diff options
Diffstat (limited to 'java')
251 files changed, 2117 insertions, 1165 deletions
diff --git a/java/compiler/impl/src/com/intellij/compiler/actions/GenerateAntBuildAction.java b/java/compiler/impl/src/com/intellij/compiler/actions/GenerateAntBuildAction.java index 8af49a55007e..f141aa002bc4 100644 --- a/java/compiler/impl/src/com/intellij/compiler/actions/GenerateAntBuildAction.java +++ b/java/compiler/impl/src/com/intellij/compiler/actions/GenerateAntBuildAction.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,10 +19,7 @@ import com.intellij.compiler.CompilerConfiguration; import com.intellij.compiler.CompilerConfigurationImpl; import com.intellij.compiler.ant.*; import com.intellij.compiler.impl.CompilerUtil; -import com.intellij.openapi.actionSystem.AnActionEvent; -import com.intellij.openapi.actionSystem.DataContext; -import com.intellij.openapi.actionSystem.PlatformDataKeys; -import com.intellij.openapi.actionSystem.Presentation; +import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.compiler.CompilerBundle; import com.intellij.openapi.progress.ProgressIndicator; @@ -105,7 +102,7 @@ public class GenerateAntBuildAction extends CompileActionBase { public void update(AnActionEvent event) { Presentation presentation = event.getPresentation(); - Project project = PlatformDataKeys.PROJECT.getData(event.getDataContext()); + Project project = CommonDataKeys.PROJECT.getData(event.getDataContext()); presentation.setEnabled(project != null); } diff --git a/java/compiler/impl/src/com/intellij/compiler/actions/ProcessAnnotationsAction.java b/java/compiler/impl/src/com/intellij/compiler/actions/ProcessAnnotationsAction.java index f33fd5fb9674..eae7060f56af 100644 --- a/java/compiler/impl/src/com/intellij/compiler/actions/ProcessAnnotationsAction.java +++ b/java/compiler/impl/src/com/intellij/compiler/actions/ProcessAnnotationsAction.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -73,7 +73,7 @@ public class ProcessAnnotationsAction extends CompileActionBase { DataContext dataContext = event.getDataContext(); presentation.setVisible(false); - Project project = PlatformDataKeys.PROJECT.getData(dataContext); + Project project = CommonDataKeys.PROJECT.getData(dataContext); if (project == null) { presentation.setEnabled(false); return; diff --git a/java/compiler/impl/src/com/intellij/compiler/make/CachedPersistentHashMap.java b/java/compiler/impl/src/com/intellij/compiler/make/CachedPersistentHashMap.java index b8b45cbe113b..324a14a6b1e2 100644 --- a/java/compiler/impl/src/com/intellij/compiler/make/CachedPersistentHashMap.java +++ b/java/compiler/impl/src/com/intellij/compiler/make/CachedPersistentHashMap.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,6 +20,7 @@ import com.intellij.util.containers.SLRUMap; import com.intellij.util.io.DataExternalizer; import com.intellij.util.io.KeyDescriptor; import com.intellij.util.io.PersistentHashMap; +import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.File; @@ -60,7 +61,7 @@ public class CachedPersistentHashMap<Key, Value> extends PersistentHashMap<Key, } @Override - protected void doAppendData(Key key, ValueDataAppender appender) throws IOException { + protected void doAppendData(Key key, @NotNull ValueDataAppender appender) throws IOException { myCache.remove(key); super.doAppendData(key, appender); } diff --git a/java/compiler/impl/src/com/intellij/compiler/options/CompilerUIConfigurable.java b/java/compiler/impl/src/com/intellij/compiler/options/CompilerUIConfigurable.java index b97a10386568..0e8f7bdaa370 100644 --- a/java/compiler/impl/src/com/intellij/compiler/options/CompilerUIConfigurable.java +++ b/java/compiler/impl/src/com/intellij/compiler/options/CompilerUIConfigurable.java @@ -20,6 +20,7 @@ import com.intellij.compiler.CompilerConfigurationImpl; import com.intellij.compiler.CompilerWorkspaceConfiguration; import com.intellij.compiler.MalformedPatternException; import com.intellij.compiler.server.BuildManager; +import com.intellij.ide.PowerSaveMode; import com.intellij.openapi.compiler.CompilerBundle; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.options.Configurable; @@ -165,6 +166,10 @@ public class CompilerUIConfigurable implements SearchableConfigurable, Configura configuration.convertPatterns(); myResourcePatternsField.setText(patternsToString(configuration.getResourceFilePatterns())); + + myEnableAutomakeLegendLabel.setText("(only works while not running / debugging" + + (PowerSaveMode.isEnabled() ? ", disabled in Power Save mode" : "") + + ")"); } private static String patternsToString(final String[] patterns) { diff --git a/java/debugger/impl/src/com/intellij/debugger/engine/AnonymousClassMethodFilter.java b/java/debugger/impl/src/com/intellij/debugger/engine/AnonymousClassMethodFilter.java index 7d78cdb258cd..7f8436b3de69 100644 --- a/java/debugger/impl/src/com/intellij/debugger/engine/AnonymousClassMethodFilter.java +++ b/java/debugger/impl/src/com/intellij/debugger/engine/AnonymousClassMethodFilter.java @@ -28,10 +28,25 @@ import org.jetbrains.annotations.Nullable; public class AnonymousClassMethodFilter extends BasicStepMethodFilter implements BreakpointStepMethodFilter{ @Nullable private final SourcePosition myBreakpointPosition; + private final int myLastStatementLine; public AnonymousClassMethodFilter(PsiMethod psiMethod) { super(psiMethod); - myBreakpointPosition = calcBreakpointPosition(psiMethod.getBody()); + SourcePosition firstStatementPosition = null; + SourcePosition lastStatementPosition = null; + final PsiCodeBlock body = psiMethod.getBody(); + if (body != null) { + final PsiStatement[] statements = body.getStatements(); + if (statements.length > 0) { + firstStatementPosition = SourcePosition.createFromElement(statements[0]); + if (firstStatementPosition != null) { + final PsiStatement lastStatement = statements[statements.length - 1]; + lastStatementPosition = SourcePosition.createFromOffset(firstStatementPosition.getFile(), lastStatement.getTextRange().getEndOffset()); + } + } + } + myBreakpointPosition = firstStatementPosition; + myLastStatementLine = lastStatementPosition != null? lastStatementPosition.getLine() : -1; } @Nullable @@ -39,16 +54,7 @@ public class AnonymousClassMethodFilter extends BasicStepMethodFilter implements return myBreakpointPosition; } - private static SourcePosition calcBreakpointPosition(final PsiCodeBlock body) { - if (body == null) { - return null; - } - final PsiStatement[] statements = body.getStatements(); - if (statements.length == 0) { - return null; - } - final PsiStatement firstStatement = statements[0]; - return SourcePosition.createFromElement(firstStatement); + public int getLastStatementLine() { + return myLastStatementLine; } - } diff --git a/java/debugger/impl/src/com/intellij/debugger/engine/BreakpointStepMethodFilter.java b/java/debugger/impl/src/com/intellij/debugger/engine/BreakpointStepMethodFilter.java index adfe975b8398..9c142ef2c0b6 100644 --- a/java/debugger/impl/src/com/intellij/debugger/engine/BreakpointStepMethodFilter.java +++ b/java/debugger/impl/src/com/intellij/debugger/engine/BreakpointStepMethodFilter.java @@ -25,4 +25,9 @@ import org.jetbrains.annotations.Nullable; public interface BreakpointStepMethodFilter extends MethodFilter{ @Nullable SourcePosition getBreakpointPosition(); + + /** + * @return a zero-based line number of the last lambda statement, or -1 if not available + */ + int getLastStatementLine(); } 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 77f8afc227c2..dc9d1e9e1ec7 100644 --- a/java/debugger/impl/src/com/intellij/debugger/engine/DebugProcessImpl.java +++ b/java/debugger/impl/src/com/intellij/debugger/engine/DebugProcessImpl.java @@ -424,8 +424,13 @@ public abstract class DebugProcessImpl implements DebugProcess { for (final StepRequest request : stepRequests) { ThreadReference threadReference = request.thread(); // [jeka] on attempt to delete a request assigned to a thread with unknown status, a JDWP error occures - if (threadReference.status() != ThreadReference.THREAD_STATUS_UNKNOWN && (stepThread == null || stepThread.equals(threadReference))) { - toDelete.add(request); + try { + if (threadReference.status() != ThreadReference.THREAD_STATUS_UNKNOWN && (stepThread == null || stepThread.equals(threadReference))) { + toDelete.add(request); + } + } + catch (IllegalThreadStateException e) { + LOG.info(e); // undocumented by JDI: may be thrown when querying thread status } } requestManager.deleteEventRequests(toDelete); diff --git a/java/debugger/impl/src/com/intellij/debugger/engine/LambdaMethodFilter.java b/java/debugger/impl/src/com/intellij/debugger/engine/LambdaMethodFilter.java index 7e4fd940c772..b1aade45d096 100644 --- a/java/debugger/impl/src/com/intellij/debugger/engine/LambdaMethodFilter.java +++ b/java/debugger/impl/src/com/intellij/debugger/engine/LambdaMethodFilter.java @@ -17,6 +17,7 @@ package com.intellij.debugger.engine; import com.intellij.debugger.SourcePosition; import com.intellij.debugger.engine.evaluation.EvaluateException; +import com.intellij.debugger.jdi.VirtualMachineProxyImpl; import com.intellij.psi.PsiCodeBlock; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiLambdaExpression; @@ -44,11 +45,11 @@ public class LambdaMethodFilter implements BreakpointStepMethodFilter{ final PsiElement body = lambda.getBody(); if (body instanceof PsiCodeBlock) { final PsiStatement[] statements = ((PsiCodeBlock)body).getStatements(); - final int statementCount = statements.length; - if (statementCount > 0) { + if (statements.length > 0) { firstStatementPosition = SourcePosition.createFromElement(statements[0]); - if (statementCount > 1) { - lastStatementPosition = SourcePosition.createFromElement(statements[statementCount - 1]); + if (firstStatementPosition != null) { + final PsiStatement lastStatement = statements[statements.length - 1]; + lastStatementPosition = SourcePosition.createFromOffset(firstStatementPosition.getFile(), lastStatement.getTextRange().getEndOffset()); } } } @@ -68,15 +69,13 @@ public class LambdaMethodFilter implements BreakpointStepMethodFilter{ return myFirstStatementPosition; } - /** - * @return a zero-based line number of the last lambda statement, or -1 if not available - */ public int getLastStatementLine() { return myLastStatementLine; } public boolean locationMatches(DebugProcessImpl process, Location location) throws EvaluateException { + final VirtualMachineProxyImpl vm = process.getVirtualMachineProxy(); final Method method = location.method(); - return method.name().startsWith(LAMBDA_METHOD_PREFIX) && method.isSynthetic(); + return method.name().startsWith(LAMBDA_METHOD_PREFIX) && (!vm.canGetSyntheticAttribute() || method.isSynthetic()); } } 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 771444af0868..570f6ba3d7b1 100644 --- a/java/debugger/impl/src/com/intellij/debugger/engine/PositionManagerImpl.java +++ b/java/debugger/impl/src/com/intellij/debugger/engine/PositionManagerImpl.java @@ -268,34 +268,33 @@ public class PositionManagerImpl implements PositionManager { private ReferenceType findNested(final ReferenceType fromClass, final int currentDepth, final PsiClass classToFind, final int requiredDepth, final SourcePosition position) { final VirtualMachineProxyImpl vmProxy = myDebugProcess.getVirtualMachineProxy(); if (fromClass.isPrepared()) { - - try { - //final int lineNumber = position.getLine() + 1; - if (currentDepth < requiredDepth) { final List<ReferenceType> nestedTypes = vmProxy.nestedTypes(fromClass); for (ReferenceType nested : nestedTypes) { final ReferenceType found = findNested(nested, currentDepth + 1, classToFind, requiredDepth, position); if (found != null) { - // check if enclosing class also has executable code at the same line, and if yes, prefer enclosing class - //return fromClass.locationsOfLine(lineNumber).isEmpty()? found : fromClass; return found; } } return null; } + final boolean canGetSynthetic = vmProxy.canGetSyntheticAttribute(); int rangeBegin = Integer.MAX_VALUE; int rangeEnd = Integer.MIN_VALUE; for (Location location : fromClass.allLineLocations()) { final int lnumber = location.lineNumber(); - if (lnumber < 1) { - continue; // should be a native method, skipping + if (lnumber <= 1) { + // should be a native method, skipping + // sometimes compiler generates location where line number is exactly 1 (e.g. GWT) + // such locations are hardly correspond to real lines in code, so skipping them too + continue; } final Method method = location.method(); - if (method == null || method.isSynthetic() || method.isBridge() || method.isObsolete()) { - continue; // do not take into account synthetic stuff + if (method == null || (canGetSynthetic && method.isSynthetic()) || method.isBridge()) { + // do not take into account synthetic stuff + continue; } final int locationLine = lnumber - 1; rangeBegin = Math.min(rangeBegin, locationLine); diff --git a/java/debugger/impl/src/com/intellij/debugger/engine/RequestHint.java b/java/debugger/impl/src/com/intellij/debugger/engine/RequestHint.java index e8bb6ccb09f3..06aac8843e49 100644 --- a/java/debugger/impl/src/com/intellij/debugger/engine/RequestHint.java +++ b/java/debugger/impl/src/com/intellij/debugger/engine/RequestHint.java @@ -56,7 +56,6 @@ public class RequestHint { private boolean myIgnoreFilters = false; private boolean myRestoreBreakpoints = false; - private final boolean mySkipThisMethod = false; public RequestHint(final ThreadReferenceProxyImpl stepThread, final SuspendContextImpl suspendContext, @NotNull MethodFilter methodFilter) { this(stepThread, suspendContext, StepRequest.STEP_INTO, methodFilter); @@ -125,7 +124,7 @@ public class RequestHint { } public int getDepth() { - return mySkipThisMethod ? StepRequest.STEP_OUT : myDepth; + return myDepth; } @Nullable diff --git a/java/debugger/impl/src/com/intellij/debugger/engine/events/SuspendContextCommandImpl.java b/java/debugger/impl/src/com/intellij/debugger/engine/events/SuspendContextCommandImpl.java index f3ad39594d3a..739c96270cca 100644 --- a/java/debugger/impl/src/com/intellij/debugger/engine/events/SuspendContextCommandImpl.java +++ b/java/debugger/impl/src/com/intellij/debugger/engine/events/SuspendContextCommandImpl.java @@ -67,16 +67,23 @@ public abstract class SuspendContextCommandImpl extends DebuggerCommandImpl { } finally{ suspendContext.myInProgress = false; - SuspendContextCommandImpl postponed = suspendContext.pollPostponedCommand(); - if (postponed != null) { - final Stack<SuspendContextCommandImpl> stack = new Stack<SuspendContextCommandImpl>(); - while (postponed != null) { - stack.push(postponed); - postponed = suspendContext.pollPostponedCommand(); + if (suspendContext.isResumed()) { + for (SuspendContextCommandImpl postponed = suspendContext.pollPostponedCommand(); postponed != null; postponed = suspendContext.pollPostponedCommand()) { + postponed.notifyCancelled(); } - final DebuggerManagerThreadImpl managerThread = suspendContext.getDebugProcess().getManagerThread(); - while (!stack.isEmpty()) { - managerThread.pushBack(stack.pop()); + } + else { + SuspendContextCommandImpl postponed = suspendContext.pollPostponedCommand(); + if (postponed != null) { + final Stack<SuspendContextCommandImpl> stack = new Stack<SuspendContextCommandImpl>(); + while (postponed != null) { + stack.push(postponed); + postponed = suspendContext.pollPostponedCommand(); + } + final DebuggerManagerThreadImpl managerThread = suspendContext.getDebugProcess().getManagerThread(); + while (!stack.isEmpty()) { + managerThread.pushBack(stack.pop()); + } } } } diff --git a/java/debugger/impl/src/com/intellij/debugger/impl/HotSwapFile.java b/java/debugger/impl/src/com/intellij/debugger/impl/HotSwapFile.java index db0a0fbba311..da6bdbcc6fa7 100644 --- a/java/debugger/impl/src/com/intellij/debugger/impl/HotSwapFile.java +++ b/java/debugger/impl/src/com/intellij/debugger/impl/HotSwapFile.java @@ -15,6 +15,8 @@ */ package com.intellij.debugger.impl; +import org.jetbrains.annotations.NotNull; + import java.io.File; /** @@ -23,9 +25,10 @@ import java.io.File; * Time: 2:23:38 PM */ public class HotSwapFile { + @NotNull final File file; - public HotSwapFile(File file) { + public HotSwapFile(@NotNull File file) { this.file = file; } } diff --git a/java/debugger/impl/src/com/intellij/debugger/impl/HotSwapManager.java b/java/debugger/impl/src/com/intellij/debugger/impl/HotSwapManager.java index b7cd3f9ef9a1..7347b430cacd 100644 --- a/java/debugger/impl/src/com/intellij/debugger/impl/HotSwapManager.java +++ b/java/debugger/impl/src/com/intellij/debugger/impl/HotSwapManager.java @@ -157,7 +157,12 @@ public class HotSwapManager extends AbstractProjectComponent { private void reloadClasses(DebuggerSession session, Map<String, HotSwapFile> classesToReload, HotSwapProgress progress) { final long newSwapTime = System.currentTimeMillis(); new ReloadClassesWorker(session, progress).reloadClasses(classesToReload); - setTimeStamp(session, newSwapTime); + if (progress.isCancelled()) { + session.setModifiedClassesScanRequired(true); + } + else { + setTimeStamp(session, newSwapTime); + } } public static Map<DebuggerSession, Map<String, HotSwapFile>> findModifiedClasses(List<DebuggerSession> sessions, Map<String, List<String>> generatedPaths) { @@ -220,7 +225,13 @@ public class HotSwapManager extends AbstractProjectComponent { swapProgress.setTitle(DebuggerBundle.message("progress.hotswap.scanning.classes")); scanClassesCommand.run(); - return swapProgress.isCancelled() ? new HashMap<DebuggerSession, Map<String, HotSwapFile>>() : modifiedClasses; + if (swapProgress.isCancelled()) { + for (DebuggerSession session : sessions) { + session.setModifiedClassesScanRequired(true); + } + return new HashMap<DebuggerSession, Map<String, HotSwapFile>>(); + } + return modifiedClasses; } public static void reloadModifiedClasses(final Map<DebuggerSession, Map<String, HotSwapFile>> modifiedClasses, final HotSwapProgress reloadClassesProgress) { @@ -240,6 +251,10 @@ public class HotSwapManager extends AbstractProjectComponent { debuggerSession, modifiedClasses.get(debuggerSession), reloadClassesProgress ); } + + protected void commandCancelled() { + debuggerSession.setModifiedClassesScanRequired(true); + } }); } diff --git a/java/debugger/impl/src/com/intellij/debugger/impl/MultiProcessCommand.java b/java/debugger/impl/src/com/intellij/debugger/impl/MultiProcessCommand.java index db146c9aabf6..9fe6b8c390ff 100644 --- a/java/debugger/impl/src/com/intellij/debugger/impl/MultiProcessCommand.java +++ b/java/debugger/impl/src/com/intellij/debugger/impl/MultiProcessCommand.java @@ -19,11 +19,11 @@ import com.intellij.debugger.engine.DebugProcessImpl; import com.intellij.debugger.engine.events.DebuggerCommandImpl; import com.intellij.openapi.util.Pair; -import java.util.ArrayList; +import java.util.LinkedList; import java.util.List; public class MultiProcessCommand implements Runnable{ - private final List<Pair<DebugProcessImpl, DebuggerCommandImpl>> myCommands = new ArrayList<Pair<DebugProcessImpl, DebuggerCommandImpl>>(); + private final List<Pair<DebugProcessImpl, DebuggerCommandImpl>> myCommands = new LinkedList<Pair<DebugProcessImpl, DebuggerCommandImpl>>(); public void run() { while(true) { @@ -40,7 +40,10 @@ public class MultiProcessCommand implements Runnable{ public void cancel() { synchronized(myCommands) { - myCommands.clear(); + while (!myCommands.isEmpty()) { + Pair<DebugProcessImpl, DebuggerCommandImpl> pair = myCommands.remove(0); + pair.getSecond().notifyCancelled(); + } } } diff --git a/java/debugger/impl/src/com/intellij/debugger/impl/ReloadClassesWorker.java b/java/debugger/impl/src/com/intellij/debugger/impl/ReloadClassesWorker.java index d8d8dd469c43..796aab701765 100644 --- a/java/debugger/impl/src/com/intellij/debugger/impl/ReloadClassesWorker.java +++ b/java/debugger/impl/src/com/intellij/debugger/impl/ReloadClassesWorker.java @@ -26,11 +26,13 @@ import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.io.FileUtil; import com.intellij.util.StringBuilderSpinAllocator; +import com.intellij.util.concurrency.Semaphore; import com.intellij.util.ui.MessageCategory; -import com.intellij.util.ui.UIUtil; import com.sun.jdi.ReferenceType; import org.jetbrains.annotations.Nullable; +import javax.swing.*; +import java.io.File; import java.io.IOException; import java.util.Collections; import java.util.HashMap; @@ -113,35 +115,44 @@ class ReloadClassesWorker { try { RedefineProcessor redefineProcessor = new RedefineProcessor(virtualMachineProxy); - int processedClassesCount = 0; - for (final String qualifiedName : modifiedClasses.keySet()) { - processedClassesCount++; + int processedEntriesCount = 0; + for (final Map.Entry<String, HotSwapFile> entry : modifiedClasses.entrySet()) { + if (redefineProcessor.getProcessedClassesCount() == 0 && myProgress.isCancelled()) { + // once at least one class has been actually reloaded, do not interrupt the whole process + break; + } + processedEntriesCount++; + final String qualifiedName = entry.getKey(); if (qualifiedName != null) { myProgress.setText(qualifiedName); - myProgress.setFraction(processedClassesCount / (double)modifiedClasses.size()); + myProgress.setFraction(processedEntriesCount / (double)modifiedClasses.size()); } - final HotSwapFile fileDescr = modifiedClasses.get(qualifiedName); - final byte[] content; try { - content = FileUtil.loadFileBytes(fileDescr.file); + redefineProcessor.processClass(qualifiedName, entry.getValue().file); } catch (IOException e) { reportProblem(qualifiedName, e); - continue; } - redefineProcessor.processClass(qualifiedName, content); } + + if (redefineProcessor.getProcessedClassesCount() == 0 && myProgress.isCancelled()) { + // once at least one class has been actually reloaded, do not interrupt the whole process + return; + } + redefineProcessor.processPending(); myProgress.setFraction(1); final int partiallyRedefinedClassesCount = redefineProcessor.getPartiallyRedefinedClassesCount(); if (partiallyRedefinedClassesCount == 0) { - myProgress.addMessage(myDebuggerSession, MessageCategory.INFORMATION, - DebuggerBundle.message("status.classes.reloaded", redefineProcessor.getProcessedClassesCount())); + myProgress.addMessage( + myDebuggerSession, MessageCategory.INFORMATION, DebuggerBundle.message("status.classes.reloaded", redefineProcessor.getProcessedClassesCount()) + ); } else { - final String message = DebuggerBundle.message("status.classes.not.all.versions.reloaded", partiallyRedefinedClassesCount, - redefineProcessor.getProcessedClassesCount()); + final String message = DebuggerBundle.message( + "status.classes.not.all.versions.reloaded", partiallyRedefinedClassesCount, redefineProcessor.getProcessedClassesCount() + ); myProgress.addMessage(myDebuggerSession, MessageCategory.WARNING, message); } @@ -153,50 +164,41 @@ class ReloadClassesWorker { processException(e); } + final Semaphore waitSemaphore = new Semaphore(); + waitSemaphore.down(); //noinspection SSBasedInspection - UIUtil.invokeAndWaitIfNeeded(new Runnable() { + SwingUtilities.invokeLater(new Runnable() { public void run() { - if (project.isDisposed()) { - return; + try { + if (!project.isDisposed()) { + final BreakpointManager breakpointManager = (DebuggerManagerEx.getInstanceEx(project)).getBreakpointManager(); + breakpointManager.reloadBreakpoints(); + debugProcess.getRequestsManager().clearWarnings(); + if (LOG.isDebugEnabled()) { + LOG.debug("requests updated"); + LOG.debug("time stamp set"); + } + myDebuggerSession.refresh(false); + } + } + catch (Throwable e) { + LOG.error(e); } - final BreakpointManager breakpointManager = (DebuggerManagerEx.getInstanceEx(project)).getBreakpointManager(); - breakpointManager.reloadBreakpoints(); - debugProcess.getRequestsManager().clearWarnings(); - if (LOG.isDebugEnabled()) { - LOG.debug("requests updated"); - LOG.debug("time stamp set"); + finally { + waitSemaphore.up(); } - myDebuggerSession.refresh(false); + } + }); - /* - debugProcess.getManagerThread().schedule(new DebuggerCommandImpl() { - protected void action() throws Exception { - try { - breakpointManager.enableBreakpoints(debugProcess); - } - catch (Exception e) { - processException(e); - } - //try { - // virtualMachineProxy.resume(); - //} - //catch (Exception e) { - // processException(e); - //} - } + waitSemaphore.waitFor(); - public Priority getPriority() { - return Priority.HIGH; - } - }); - */ + if (!project.isDisposed()) { + try { + breakpointManager.enableBreakpoints(debugProcess); + } + catch (Exception e) { + processException(e); } - }); - try { - breakpointManager.enableBreakpoints(debugProcess); - } - catch (Exception e) { - processException(e); } } @@ -233,10 +235,13 @@ class ReloadClassesWorker { myVirtualMachineProxy = virtualMachineProxy; } - public void processClass(String qualifiedName, byte[] content) throws Throwable { + public void processClass(String qualifiedName, File file) throws Throwable { final List<ReferenceType> vmClasses = myVirtualMachineProxy.classesByName(qualifiedName); - if (vmClasses.isEmpty()) return; + if (vmClasses.isEmpty()) { + return; + } + final byte[] content = FileUtil.loadFileBytes(file); if (vmClasses.size() == 1) { myRedefineMap.put(vmClasses.get(0), content); if (myRedefineMap.size() >= CLASSES_CHUNK_SIZE) { diff --git a/java/debugger/impl/src/com/intellij/debugger/jdi/VirtualMachineProxyImpl.java b/java/debugger/impl/src/com/intellij/debugger/jdi/VirtualMachineProxyImpl.java index c703680f5581..109b51ec507e 100644 --- a/java/debugger/impl/src/com/intellij/debugger/jdi/VirtualMachineProxyImpl.java +++ b/java/debugger/impl/src/com/intellij/debugger/jdi/VirtualMachineProxyImpl.java @@ -68,6 +68,8 @@ public class VirtualMachineProxyImpl implements JdiTimer, VirtualMachineProxy { canWatchFieldModification(); canPopFrames(); + virtualMachine.allClasses(); // this will cache classes inside JDI and enable faster search of classes later + List<ThreadGroupReference> groups = virtualMachine.topLevelThreadGroups(); for (ThreadGroupReference threadGroupReference : groups) { threadGroupCreated(threadGroupReference); @@ -120,10 +122,11 @@ public class VirtualMachineProxyImpl implements JdiTimer, VirtualMachineProxy { } public List<ReferenceType> allClasses() { - if (myAllClasses == null) { - myAllClasses = myVirtualMachine.allClasses(); + List<ReferenceType> allClasses = myAllClasses; + if (allClasses == null) { + myAllClasses = allClasses = myVirtualMachine.allClasses(); } - return myAllClasses; + return allClasses; } public String toString() { diff --git a/java/debugger/impl/src/com/intellij/debugger/ui/HotSwapUIImpl.java b/java/debugger/impl/src/com/intellij/debugger/ui/HotSwapUIImpl.java index 9c61c8c73fe5..71e5cfbdff5e 100644 --- a/java/debugger/impl/src/com/intellij/debugger/ui/HotSwapUIImpl.java +++ b/java/debugger/impl/src/com/intellij/debugger/ui/HotSwapUIImpl.java @@ -33,23 +33,29 @@ import com.intellij.openapi.compiler.CompilationStatusListener; import com.intellij.openapi.compiler.CompileContext; import com.intellij.openapi.compiler.CompilerManager; import com.intellij.openapi.compiler.CompilerTopics; +import com.intellij.openapi.compiler.ex.CompilerPathsEx; import com.intellij.openapi.components.ProjectComponent; +import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.Ref; +import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiDocumentManager; import com.intellij.util.PairFunction; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.messages.MessageBus; import com.intellij.util.messages.MessageBusConnection; +import gnu.trove.THashSet; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import org.jetbrains.jps.util.JpsPathUtil; import javax.swing.*; +import java.io.File; import java.util.*; import java.util.concurrent.atomic.AtomicReference; @@ -269,8 +275,7 @@ public class HotSwapUIImpl extends HotSwapUI implements ProjectComponent { return result.get(); } - private static void reloadModifiedClasses(final Map<DebuggerSession, Map<String, HotSwapFile>> modifiedClasses, - final HotSwapProgressImpl progress) { + private static void reloadModifiedClasses(final Map<DebuggerSession, Map<String, HotSwapFile>> modifiedClasses, final HotSwapProgressImpl progress) { ProgressManager.getInstance().runProcess(new Runnable() { public void run() { HotSwapManager.reloadModifiedClasses(modifiedClasses, progress); @@ -303,9 +308,17 @@ public class HotSwapUIImpl extends HotSwapUI implements ProjectComponent { private final AtomicReference<Map<String, List<String>>> myGeneratedPaths = new AtomicReference<Map<String, List<String>>>(new HashMap<String, List<String>>()); + private final THashSet<File> myOutputRoots; + + private MyCompilationStatusListener() { + myOutputRoots = new THashSet<File>(FileUtil.FILE_HASHING_STRATEGY); + for (final String path : CompilerPathsEx.getOutputPaths(ModuleManager.getInstance(myProject).getModules())) { + myOutputRoots.add(new File(path)); + } + } public void fileGenerated(String outputRoot, String relativePath) { - if (StringUtil.endsWith(relativePath, ".class")) { + if (StringUtil.endsWith(relativePath, ".class") && JpsPathUtil.isUnder(myOutputRoots, new File(outputRoot))) { // collect only classes final Map<String, List<String>> map = myGeneratedPaths.get(); List<String> paths = map.get(outputRoot); diff --git a/java/debugger/impl/src/com/intellij/debugger/ui/JavaDebuggerSupport.java b/java/debugger/impl/src/com/intellij/debugger/ui/JavaDebuggerSupport.java index 370673aaf7ed..e021d76b271b 100644 --- a/java/debugger/impl/src/com/intellij/debugger/ui/JavaDebuggerSupport.java +++ b/java/debugger/impl/src/com/intellij/debugger/ui/JavaDebuggerSupport.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,10 +22,7 @@ import com.intellij.debugger.settings.*; import com.intellij.debugger.ui.breakpoints.*; import com.intellij.ide.DataManager; import com.intellij.openapi.Disposable; -import com.intellij.openapi.actionSystem.AnAction; -import com.intellij.openapi.actionSystem.AnActionEvent; -import com.intellij.openapi.actionSystem.PlatformDataKeys; -import com.intellij.openapi.actionSystem.Presentation; +import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.markup.GutterIconRenderer; import com.intellij.openapi.editor.markup.RangeHighlighter; @@ -338,7 +335,7 @@ public class JavaDebuggerSupport extends DebuggerSupport { public static Project getCurrentProject() { //todo[nik] improve - Project project = PlatformDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext()); + Project project = CommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext()); if (project != null) { return project; } diff --git a/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/StepIntoBreakpoint.java b/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/StepIntoBreakpoint.java index afb5a684ffdd..6e39e5ac1d29 100644 --- a/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/StepIntoBreakpoint.java +++ b/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/StepIntoBreakpoint.java @@ -55,10 +55,10 @@ public class StepIntoBreakpoint extends RunToCursorBreakpoint { final SourcePosition startPosition = getSourcePosition(); List<Location> locations = positionManager.locationsOfLine(classType, startPosition); - if (locations.isEmpty() && myFilter instanceof LambdaMethodFilter) { - // sometimes first statements are mapped to some weird line number, - // so if lambda spans for more than one lines, try get some locations from these lines - final int lastLine = ((LambdaMethodFilter)myFilter).getLastStatementLine(); + if (locations.isEmpty()) { + // sometimes first statements are mapped to some weird line number, or there are no executable instructions at first statement's line + // so if lambda or method body spans for more than one lines, try get some locations from these lines + final int lastLine = myFilter.getLastStatementLine(); if (lastLine >= 0) { int nextLine = startPosition.getLine() + 1; while (nextLine <= lastLine && locations.isEmpty()) { diff --git a/java/debugger/impl/src/com/intellij/debugger/ui/impl/watch/DebuggerTree.java b/java/debugger/impl/src/com/intellij/debugger/ui/impl/watch/DebuggerTree.java index 32ace1064daf..39c2775df018 100644 --- a/java/debugger/impl/src/com/intellij/debugger/ui/impl/watch/DebuggerTree.java +++ b/java/debugger/impl/src/com/intellij/debugger/ui/impl/watch/DebuggerTree.java @@ -32,10 +32,7 @@ import com.intellij.debugger.engine.events.SuspendContextCommandImpl; import com.intellij.debugger.impl.DebuggerContextImpl; import com.intellij.debugger.impl.DebuggerSession; import com.intellij.debugger.impl.DebuggerUtilsEx; -import com.intellij.debugger.jdi.LocalVariableProxyImpl; -import com.intellij.debugger.jdi.StackFrameProxyImpl; -import com.intellij.debugger.jdi.ThreadGroupReferenceProxyImpl; -import com.intellij.debugger.jdi.ThreadReferenceProxyImpl; +import com.intellij.debugger.jdi.*; import com.intellij.debugger.settings.NodeRendererSettings; import com.intellij.debugger.settings.ThreadsViewSettings; import com.intellij.debugger.ui.breakpoints.Breakpoint; @@ -462,8 +459,10 @@ public abstract class DebuggerTree extends DebuggerTreeBase implements DataProvi final ReferenceType thisRefType = thisObjectReference.referenceType(); if (thisRefType instanceof ClassType && thisRefType.equals(location.declaringType()) && thisRefType.name().contains("$")) { // makes sense for nested classes only final ClassType clsType = (ClassType)thisRefType; + final DebugProcessImpl debugProcess = getDebuggerContext().getDebugProcess(); + final VirtualMachineProxyImpl vm = debugProcess.getVirtualMachineProxy(); for (Field field : clsType.fields()) { - if (field.isSynthetic() && StringUtil.startsWith(field.name(), FieldDescriptorImpl.OUTER_LOCAL_VAR_FIELD_PREFIX)) { + if ((!vm.canGetSyntheticAttribute() || field.isSynthetic()) && StringUtil.startsWith(field.name(), FieldDescriptorImpl.OUTER_LOCAL_VAR_FIELD_PREFIX)) { final FieldDescriptorImpl fieldDescriptor = myNodeManager.getFieldDescriptor(stackDescriptor, thisObjectReference, field); myChildren.add(myNodeManager.createNode(fieldDescriptor, evaluationContext)); } diff --git a/java/debugger/impl/src/org/jetbrains/java/debugger/breakpoints/JavaBreakpointType.java b/java/debugger/impl/src/org/jetbrains/java/debugger/breakpoints/JavaBreakpointType.java index d3e6545cced1..c2088722880b 100644 --- a/java/debugger/impl/src/org/jetbrains/java/debugger/breakpoints/JavaBreakpointType.java +++ b/java/debugger/impl/src/org/jetbrains/java/debugger/breakpoints/JavaBreakpointType.java @@ -57,7 +57,8 @@ public class JavaBreakpointType extends XLineBreakpointTypeBase { @Contract("null -> false") public static boolean doCanPutAt(@Nullable PsiFile psiFile) { - if (psiFile == null) { + // JSPX supports jvm debugging, but not in XHTML files + if (psiFile == null || psiFile.getVirtualFile().getFileType() == StdFileTypes.XHTML) { return false; } diff --git a/java/execution/openapi/src/com/intellij/execution/configurations/JavaCommandLineState.java b/java/execution/openapi/src/com/intellij/execution/configurations/JavaCommandLineState.java index e0c60ee3846d..bab671678c57 100644 --- a/java/execution/openapi/src/com/intellij/execution/configurations/JavaCommandLineState.java +++ b/java/execution/openapi/src/com/intellij/execution/configurations/JavaCommandLineState.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,7 +19,7 @@ import com.intellij.execution.ExecutionException; import com.intellij.execution.process.OSProcessHandler; import com.intellij.execution.runners.ExecutionEnvironment; import com.intellij.ide.DataManager; -import com.intellij.openapi.actionSystem.PlatformDataKeys; +import com.intellij.openapi.actionSystem.CommonDataKeys; import org.jetbrains.annotations.NotNull; @@ -49,7 +49,8 @@ public abstract class JavaCommandLineState extends CommandLineState implements J protected abstract JavaParameters createJavaParameters() throws ExecutionException; protected GeneralCommandLine createCommandLine() throws ExecutionException { - return CommandLineBuilder.createFromJavaParameters(getJavaParameters(), PlatformDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext()), true); + return CommandLineBuilder.createFromJavaParameters(getJavaParameters(), CommonDataKeys.PROJECT + .getData(DataManager.getInstance().getDataContext()), true); } public boolean shouldAddJavaProgramRunnerActions() { diff --git a/java/idea-ui/src/com/intellij/codeInsight/daemon/impl/AttachSourcesNotificationProvider.java b/java/idea-ui/src/com/intellij/codeInsight/daemon/impl/AttachSourcesNotificationProvider.java index 9e9213db43cc..5f6f18def730 100644 --- a/java/idea-ui/src/com/intellij/codeInsight/daemon/impl/AttachSourcesNotificationProvider.java +++ b/java/idea-ui/src/com/intellij/codeInsight/daemon/impl/AttachSourcesNotificationProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2012 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -72,16 +72,19 @@ public class AttachSourcesNotificationProvider extends EditorNotifications.Provi public AttachSourcesNotificationProvider(Project project, final EditorNotifications notifications) { myProject = project; myProject.getMessageBus().connect(project).subscribe(ProjectTopics.PROJECT_ROOTS, new ModuleRootAdapter() { + @Override public void rootsChanged(ModuleRootEvent event) { notifications.updateAllNotifications(); } }); } + @Override public Key<EditorNotificationPanel> getKey() { return KEY; } + @Override public EditorNotificationPanel createNotificationPanel(final VirtualFile file, FileEditor fileEditor) { if (file.getFileType() != JavaClassFileType.INSTANCE) return null; final List<LibraryOrderEntry> libraries = findOrderEntriesContainingFile(file); @@ -129,6 +132,7 @@ public class AttachSourcesNotificationProvider extends EditorNotifications.Provi } Collections.sort(actions, new Comparator<AttachSourcesProvider.AttachSourcesAction>() { + @Override public int compare(AttachSourcesProvider.AttachSourcesAction o1, AttachSourcesProvider.AttachSourcesAction o2) { return o1.getName().compareToIgnoreCase(o2.getName()); } @@ -138,6 +142,7 @@ public class AttachSourcesNotificationProvider extends EditorNotifications.Provi for (final AttachSourcesProvider.AttachSourcesAction each : actions) { panel.createActionLabel(GuiUtils.getTextWithoutMnemonicEscaping(each.getName()), new Runnable() { + @Override public void run() { if (!Comparing.equal(libraries, findOrderEntriesContainingFile(file))) { Messages.showErrorDialog(myProject, "Cannot find library for " + StringUtil.getShortName(fqn), "Error"); @@ -147,8 +152,10 @@ public class AttachSourcesNotificationProvider extends EditorNotifications.Provi panel.setText(each.getBusyText()); Runnable onFinish = new Runnable() { + @Override public void run() { SwingUtilities.invokeLater(new Runnable() { + @Override public void run() { panel.setText(ProjectBundle.message("library.sources.not.found")); } @@ -178,6 +185,7 @@ public class AttachSourcesNotificationProvider extends EditorNotifications.Provi private static void appendSources(final Library library, final VirtualFile[] files) { ApplicationManager.getApplication().runWriteAction(new Runnable() { + @Override public void run() { Library.ModifiableModel model = library.getModifiableModel(); for (VirtualFile virtualFile : files) { @@ -207,10 +215,12 @@ public class AttachSourcesNotificationProvider extends EditorNotifications.Provi myClassFile = classFile; } + @Override public String getName() { return ProjectBundle.message("module.libraries.attach.sources.immediately.button"); } + @Override public String getBusyText() { return ProjectBundle.message("library.attach.sources.action.busy.text"); } @@ -229,6 +239,7 @@ public class AttachSourcesNotificationProvider extends EditorNotifications.Provi } if (modelsToCommit.isEmpty()) return new ActionCallback.Rejected(); new WriteAction() { + @Override protected void run(final Result result) { for (Library.ModifiableModel model : modelsToCommit) { model.commit(); @@ -259,14 +270,17 @@ public class AttachSourcesNotificationProvider extends EditorNotifications.Provi myParentComponent = parentComponent; } + @Override public String getName() { return ProjectBundle.message("module.libraries.attach.sources.button"); } + @Override public String getBusyText() { return ProjectBundle.message("library.attach.sources.action.busy.text"); } + @Override public ActionCallback perform(final List<LibraryOrderEntry> libraries) { FileChooserDescriptor descriptor = FileChooserDescriptorFactory.createMultipleJavaPathDescriptor(); descriptor.setTitle(ProjectBundle.message("library.attach.sources.action")); diff --git a/java/idea-ui/src/com/intellij/codeInsight/daemon/impl/SetupSDKNotificationProvider.java b/java/idea-ui/src/com/intellij/codeInsight/daemon/impl/SetupSDKNotificationProvider.java index 604d5f7f0f78..2683d2197b15 100644 --- a/java/idea-ui/src/com/intellij/codeInsight/daemon/impl/SetupSDKNotificationProvider.java +++ b/java/idea-ui/src/com/intellij/codeInsight/daemon/impl/SetupSDKNotificationProvider.java @@ -49,6 +49,7 @@ public class SetupSDKNotificationProvider extends EditorNotifications.Provider<E public SetupSDKNotificationProvider(Project project, final EditorNotifications notifications) { myProject = project; myProject.getMessageBus().connect(project).subscribe(ProjectTopics.PROJECT_ROOTS, new ModuleRootAdapter() { + @Override public void rootsChanged(ModuleRootEvent event) { notifications.updateAllNotifications(); } @@ -81,7 +82,7 @@ public class SetupSDKNotificationProvider extends EditorNotifications.Provider<E } @NotNull - private static EditorNotificationPanel createPanel(final @NotNull Project project, final @NotNull PsiFile file) { + private static EditorNotificationPanel createPanel(@NotNull final Project project, @NotNull final PsiFile file) { final EditorNotificationPanel panel = new EditorNotificationPanel(); panel.setText(ProjectBundle.message("project.sdk.not.defined")); panel.createActionLabel(ProjectBundle.message("project.sdk.setup"), new Runnable() { diff --git a/java/idea-ui/src/com/intellij/ide/palette/impl/PaletteGroupHeader.java b/java/idea-ui/src/com/intellij/ide/palette/impl/PaletteGroupHeader.java index 72f197fa38b8..c98caefa3f75 100644 --- a/java/idea-ui/src/com/intellij/ide/palette/impl/PaletteGroupHeader.java +++ b/java/idea-ui/src/com/intellij/ide/palette/impl/PaletteGroupHeader.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -159,7 +159,7 @@ public class PaletteGroupHeader extends JCheckBox implements DataProvider { @Nullable public Object getData(String dataId) { Object data = myPaletteWindow.getData(dataId); if (data != null) return data; - Project project = PlatformDataKeys.PROJECT.getData(myPaletteWindow); + Project project = CommonDataKeys.PROJECT.getData(myPaletteWindow); return myGroup.getData(project, dataId); } diff --git a/java/idea-ui/src/com/intellij/ide/projectWizard/NewProjectWizard.java b/java/idea-ui/src/com/intellij/ide/projectWizard/NewProjectWizard.java index 5ecda308c122..290d3cd65f8f 100644 --- a/java/idea-ui/src/com/intellij/ide/projectWizard/NewProjectWizard.java +++ b/java/idea-ui/src/com/intellij/ide/projectWizard/NewProjectWizard.java @@ -35,6 +35,7 @@ public class NewProjectWizard extends AbstractProjectWizard { super("New Project", project, defaultPath); // addStep(); // addStep(new ProjectSummaryStep(myWizardContext)); + myWizardContext.setNewWizard(true); mySequence = new StepSequence(); mySequence.addCommonStep(new ProjectTypeStep(myWizardContext, this, modulesProvider)); mySequence.addCommonFinishingStep(new ProjectSettingsStep(myWizardContext), null); diff --git a/java/idea-ui/src/com/intellij/ide/projectWizard/ProjectTypeStep.java b/java/idea-ui/src/com/intellij/ide/projectWizard/ProjectTypeStep.java index 2003d991dc64..3efa81829db1 100644 --- a/java/idea-ui/src/com/intellij/ide/projectWizard/ProjectTypeStep.java +++ b/java/idea-ui/src/com/intellij/ide/projectWizard/ProjectTypeStep.java @@ -141,7 +141,7 @@ public class ProjectTypeStep extends ModuleWizardStep { }); for (ProjectCategory category : map.values()) { - myWizard.getSequence().addStepsForBuilder(myBuilders.get(category), context, modulesProvider, true); + myWizard.getSequence().addStepsForBuilder(myBuilders.get(category), context, modulesProvider); } myFrameworksPanel = new AddSupportForFrameworksPanel(Collections.<FrameworkSupportInModuleProvider>emptyList(), model, true); @@ -218,7 +218,7 @@ public class ProjectTypeStep extends ModuleWizardStep { public void updateDataModel() { ModuleBuilder builder = getSelectedBuilder(); assert builder != null; - myWizard.getSequence().addStepsForBuilder(builder, myContext, myModulesProvider, true); + myWizard.getSequence().addStepsForBuilder(builder, myContext, myModulesProvider); } @Override diff --git a/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/SelectTemplateStep.java b/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/SelectTemplateStep.java index 51296b6f41ac..e1d46ea35e30 100644 --- a/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/SelectTemplateStep.java +++ b/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/SelectTemplateStep.java @@ -43,7 +43,6 @@ import com.intellij.ui.HideableDecorator; import com.intellij.ui.IdeBorderFactory; import com.intellij.ui.components.JBLabel; import com.intellij.ui.components.JBList; -import com.intellij.util.containers.FactoryMap; import com.intellij.util.containers.MultiMap; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -94,13 +93,6 @@ public class SelectTemplateStep extends ModuleWizardStep implements SettingsStep private final StepSequence mySequence; @Nullable private ModuleWizardStep mySettingsStep; - private FactoryMap<String, ModuleWizardStep> mySettingsSteps = new FactoryMap<String, ModuleWizardStep>() { - @Nullable - @Override - protected ModuleWizardStep create(String key) { - return myModuleBuilder.modifySettingsStep(SelectTemplateStep.this); - } - }; private final ProjectTypesList myList; @@ -160,9 +152,6 @@ public class SelectTemplateStep extends ModuleWizardStep implements SettingsStep @Override public void disposeUIResources() { Disposer.dispose(myList); - for (ModuleWizardStep step : mySettingsSteps.values()) { - step.disposeUIResources(); - } } @Override @@ -184,7 +173,9 @@ public class SelectTemplateStep extends ModuleWizardStep implements SettingsStep restorePanel(myNamePathComponent, 4); restorePanel(myModulePanel, myWizardContext.isCreatingNewProject() ? 8 : 6); restorePanel(myExpertPanel, myWizardContext.isCreatingNewProject() ? 1 : 0); - createSettingsStep(); + + if (mySettingsStep != null) mySettingsStep.disposeUIResources(); + mySettingsStep = myModuleBuilder == null ? null : myModuleBuilder.modifySettingsStep(this); String description = null; if (template != null) { @@ -208,15 +199,6 @@ public class SelectTemplateStep extends ModuleWizardStep implements SettingsStep mySettingsPanel.repaint(); } - private void createSettingsStep() { - if (myModuleBuilder == null) { - mySettingsStep = null; - } - else { - mySettingsStep = mySettingsSteps.get(myModuleBuilder.getBuilderId()); - } - } - private static int restorePanel(JPanel component, int i) { int removed = 0; while (component.getComponentCount() > i) { diff --git a/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/StepSequence.java b/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/StepSequence.java index bbc9b21769f2..866bc7701394 100644 --- a/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/StepSequence.java +++ b/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/StepSequence.java @@ -55,11 +55,10 @@ public class StepSequence { public void addStepsForBuilder(@NotNull AbstractModuleBuilder builder, @NotNull WizardContext wizardContext, - @NotNull ModulesProvider modulesProvider, - boolean forNewWizard) { + @NotNull ModulesProvider modulesProvider) { String id = builder.getBuilderId(); if (!mySpecificSteps.containsKey(id)) { - mySpecificSteps.put(id, Arrays.asList(builder.createWizardSteps(wizardContext, modulesProvider, forNewWizard))); + mySpecificSteps.put(id, Arrays.asList(builder.createWizardSteps(wizardContext, modulesProvider))); } } diff --git a/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/modes/CreateFromScratchMode.java b/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/modes/CreateFromScratchMode.java index bb631ec75ede..bc10c316e6d7 100644 --- a/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/modes/CreateFromScratchMode.java +++ b/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/modes/CreateFromScratchMode.java @@ -63,7 +63,7 @@ public class CreateFromScratchMode extends WizardMode { StepSequence sequence = new StepSequence(); for (ModuleBuilder builder : builders) { - sequence.addStepsForBuilder(builder, context, modulesProvider, false); + sequence.addStepsForBuilder(builder, context, modulesProvider); } return sequence; } diff --git a/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/modes/CreateFromTemplateMode.java b/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/modes/CreateFromTemplateMode.java index acac1865a5aa..898e6243f7a5 100644 --- a/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/modes/CreateFromTemplateMode.java +++ b/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/modes/CreateFromTemplateMode.java @@ -108,7 +108,7 @@ public class CreateFromTemplateMode extends WizardMode { MultiMap<TemplatesGroup, ProjectTemplate> map = getTemplatesMap(context, true); StepSequence sequence = new StepSequence(); for (ProjectTemplate template : map.values()) { - sequence.addStepsForBuilder(template.createModuleBuilder(), context, modulesProvider, false); + sequence.addStepsForBuilder(template.createModuleBuilder(), context, modulesProvider); } mySelectTemplateStep = new SelectTemplateStep(context, sequence, map); sequence.addCommonStep(mySelectTemplateStep); diff --git a/java/idea-ui/src/com/intellij/ide/util/projectWizard/AbstractStepWithProgress.java b/java/idea-ui/src/com/intellij/ide/util/projectWizard/AbstractStepWithProgress.java index f1c4b5f146fc..1068a14f7331 100644 --- a/java/idea-ui/src/com/intellij/ide/util/projectWizard/AbstractStepWithProgress.java +++ b/java/idea-ui/src/com/intellij/ide/util/projectWizard/AbstractStepWithProgress.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -178,7 +178,7 @@ public abstract class AbstractStepWithProgress<Result> extends ModuleWizardStep if (isProgressRunning()) { final int answer = Messages.showOkCancelDialog(getComponent(), myPromptStopSearch, IdeBundle.message("title.question"), IdeBundle.message("action.continue.searching"), IdeBundle.message("action.stop.searching"), Messages.getWarningIcon()); - if (answer == 1) { // terminate + if (answer != Messages.OK) { // terminate cancelSearch(); } return false; diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/JavaContentEntryEditor.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/JavaContentEntryEditor.java index 7d3c535fcd9b..23f00c23ff45 100644 --- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/JavaContentEntryEditor.java +++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/JavaContentEntryEditor.java @@ -19,8 +19,6 @@ import com.intellij.openapi.roots.CompilerModuleExtension; import com.intellij.openapi.roots.ContentEntry; import com.intellij.openapi.roots.ExcludeFolder; import com.intellij.openapi.roots.SourceFolder; -import com.intellij.openapi.util.io.FileUtil; -import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VirtualFile; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -55,7 +53,7 @@ public abstract class JavaContentEntryEditor extends ContentEntryEditor { @Override protected ExcludeFolder doAddExcludeFolder(@NotNull final VirtualFile file) { - final boolean isCompilerOutput = isCompilerOutput(file); + final boolean isCompilerOutput = isCompilerOutput(file.getUrl()); if (isCompilerOutput) { myCompilerExtension.setExcludeOutput(true); return null; @@ -64,32 +62,26 @@ public abstract class JavaContentEntryEditor extends ContentEntryEditor { } @Override - protected void doRemoveExcludeFolder(@NotNull final ExcludeFolder excludeFolder) { - final VirtualFile file = excludeFolder.getFile(); - if (file != null) { - if (isCompilerOutput(file)) { - myCompilerExtension.setExcludeOutput(false); - } + protected void doRemoveExcludeFolder(@NotNull final String excludeRootUrl) { + if (isCompilerOutput(excludeRootUrl)) { + myCompilerExtension.setExcludeOutput(false); } - super.doRemoveExcludeFolder(excludeFolder); + super.doRemoveExcludeFolder(excludeRootUrl); } - private boolean isCompilerOutput(@NotNull final VirtualFile file) { - final VirtualFile compilerOutputPath = myCompilerExtension.getCompilerOutputPath(); - if (file.equals(compilerOutputPath)) { + private boolean isCompilerOutput(@NotNull final String fileUrl) { + if (fileUrl.equals(myCompilerExtension.getCompilerOutputUrl())) { return true; } - final VirtualFile compilerOutputPathForTests = myCompilerExtension.getCompilerOutputPathForTests(); - if (file.equals(compilerOutputPathForTests)) { + if (fileUrl.equals(myCompilerExtension.getCompilerOutputUrlForTests())) { return true; } - final String path = file.getPath(); if (myCompilerExtension.isCompilerOutputPathInherited()) { final ProjectStructureConfigurable instance = ProjectStructureConfigurable.getInstance(getModel().getModule().getProject()); - final String compilerOutput = VfsUtil.urlToPath(instance.getProjectConfig().getCompilerOutputUrl()); - if (FileUtil.pathsEqual(compilerOutput, path)) { + final String compilerOutputUrl = instance.getProjectConfig().getCompilerOutputUrl(); + if (fileUrl.equals(compilerOutputUrl)) { return true; } } diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/JavaResourceRootEditHandlerBase.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/JavaResourceRootEditHandlerBase.java index 3c2b3a205fd5..ba7778da6397 100644 --- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/JavaResourceRootEditHandlerBase.java +++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/JavaResourceRootEditHandlerBase.java @@ -38,12 +38,6 @@ public abstract class JavaResourceRootEditHandlerBase extends ModuleSourceRootEd @Nullable @Override - public String getMarkRootGroupName() { - return "Resources"; - } - - @Nullable - @Override public CustomShortcutSet getMarkRootShortcutSet() { return null; } diff --git a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/RemoveSuppressWarningAction.java b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/RemoveSuppressWarningAction.java index f8d2e8e06054..867f165b61ac 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/RemoveSuppressWarningAction.java +++ b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/RemoveSuppressWarningAction.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -123,21 +123,21 @@ public class RemoveSuppressWarningAction implements LocalQuickFix { } else { PsiComment newComment = JavaPsiFacade.getInstance(comment.getProject()).getElementFactory() - .createCommentFromText("// " + SuppressionUtil.SUPPRESS_INSPECTIONS_TAG_NAME+" "+newText, comment); + .createCommentFromText("// " + SuppressionUtilCore.SUPPRESS_INSPECTIONS_TAG_NAME +" "+newText, comment); comment.replace(newComment); } } } private void removeFromJavaDoc(PsiDocComment docComment) throws IncorrectOperationException { - PsiDocTag tag = docComment.findTagByName(SuppressionUtil.SUPPRESS_INSPECTIONS_TAG_NAME); + PsiDocTag tag = docComment.findTagByName(SuppressionUtilCore.SUPPRESS_INSPECTIONS_TAG_NAME); if (tag == null) return; String newText = removeFromElementText(tag.getDataElements()); if (newText != null && newText.isEmpty()) { tag.delete(); } else if (newText != null) { - newText = "@" + SuppressionUtil.SUPPRESS_INSPECTIONS_TAG_NAME + " " + newText; + newText = "@" + SuppressionUtilCore.SUPPRESS_INSPECTIONS_TAG_NAME + " " + newText; PsiDocTag newTag = JavaPsiFacade.getInstance(tag.getProject()).getElementFactory().createDocTagFromText(newText); tag.replace(newTag); } @@ -150,7 +150,7 @@ public class RemoveSuppressWarningAction implements LocalQuickFix { text += StringUtil.trimStart(element.getText(), "//").trim(); } text = StringUtil.trimStart(text, "@").trim(); - text = StringUtil.trimStart(text, SuppressionUtil.SUPPRESS_INSPECTIONS_TAG_NAME).trim(); + text = StringUtil.trimStart(text, SuppressionUtilCore.SUPPRESS_INSPECTIONS_TAG_NAME).trim(); List<String> ids = StringUtil.split(text, ","); int i = ArrayUtil.find(ids.toArray(), myID); if (i==-1) return null; diff --git a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/actions/SuppressAllForClassFix.java b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/actions/SuppressAllForClassFix.java index d0154dc1436e..d4abb6b235f4 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/actions/SuppressAllForClassFix.java +++ b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/actions/SuppressAllForClassFix.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,6 +19,7 @@ import com.intellij.codeInsight.FileModificationService; import com.intellij.codeInspection.InspectionsBundle; import com.intellij.codeInspection.JavaSuppressionUtil; import com.intellij.codeInspection.SuppressionUtil; +import com.intellij.codeInspection.SuppressionUtilCore; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.psi.*; @@ -83,9 +84,9 @@ public class SuppressAllForClassFix extends SuppressFix { else { PsiDocComment docComment = container.getDocComment(); if (docComment != null) { - PsiDocTag noInspectionTag = docComment.findTagByName(SuppressionUtil.SUPPRESS_INSPECTIONS_TAG_NAME); + PsiDocTag noInspectionTag = docComment.findTagByName(SuppressionUtilCore.SUPPRESS_INSPECTIONS_TAG_NAME); if (noInspectionTag != null) { - String tagText = "@" + SuppressionUtil.SUPPRESS_INSPECTIONS_TAG_NAME + " " + SuppressionUtil.ALL; + String tagText = "@" + SuppressionUtilCore.SUPPRESS_INSPECTIONS_TAG_NAME + " " + SuppressionUtil.ALL; noInspectionTag.replace(JavaPsiFacade.getInstance(project).getElementFactory().createDocTagFromText(tagText)); // todo suppress //DaemonCodeAnalyzer.getInstance(project).restart(); diff --git a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/actions/SuppressFix.java b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/actions/SuppressFix.java index 67c483e2ecdf..8715882bd37a 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/actions/SuppressFix.java +++ b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/actions/SuppressFix.java @@ -20,6 +20,7 @@ import com.intellij.codeInsight.daemon.HighlightDisplayKey; import com.intellij.codeInspection.InspectionsBundle; import com.intellij.codeInspection.JavaSuppressionUtil; import com.intellij.codeInspection.SuppressionUtil; +import com.intellij.codeInspection.SuppressionUtilCore; import com.intellij.lang.java.JavaLanguage; import com.intellij.openapi.command.undo.UndoUtil; import com.intellij.openapi.module.Module; @@ -113,19 +114,19 @@ public class SuppressFix extends AbstractBatchSuppressByNoInspectionCommentFix { PsiDocComment docComment = container.getDocComment(); PsiManager manager = PsiManager.getInstance(project); if (docComment == null) { - String commentText = "/** @" + SuppressionUtil.SUPPRESS_INSPECTIONS_TAG_NAME + " " + getID(container) + "*/"; + String commentText = "/** @" + SuppressionUtilCore.SUPPRESS_INSPECTIONS_TAG_NAME + " " + getID(container) + "*/"; docComment = JavaPsiFacade.getInstance(manager.getProject()).getElementFactory().createDocCommentFromText(commentText); PsiElement firstChild = container.getFirstChild(); container.addBefore(docComment, firstChild); } else { - PsiDocTag noInspectionTag = docComment.findTagByName(SuppressionUtil.SUPPRESS_INSPECTIONS_TAG_NAME); + PsiDocTag noInspectionTag = docComment.findTagByName(SuppressionUtilCore.SUPPRESS_INSPECTIONS_TAG_NAME); if (noInspectionTag != null) { String tagText = noInspectionTag.getText() + ", " + getID(container); noInspectionTag.replace(JavaPsiFacade.getInstance(manager.getProject()).getElementFactory().createDocTagFromText(tagText)); } else { - String tagText = "@" + SuppressionUtil.SUPPRESS_INSPECTIONS_TAG_NAME + " " + getID(container); + String tagText = "@" + SuppressionUtilCore.SUPPRESS_INSPECTIONS_TAG_NAME + " " + getID(container); docComment.add(JavaPsiFacade.getInstance(manager.getProject()).getElementFactory().createDocTagFromText(tagText)); } } diff --git a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/GenericsHighlightUtil.java b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/GenericsHighlightUtil.java index c501134afff1..687484b3399d 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/GenericsHighlightUtil.java +++ b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/GenericsHighlightUtil.java @@ -464,13 +464,38 @@ public class GenericsHighlightUtil { final PsiIdentifier classIdentifier = aClass.getNameIdentifier(); if (PsiUtil.isLanguageLevel8OrHigher(aClass) && classIdentifier != null) { - final HighlightInfo info = checkUnrelatedDefaultMethods(aClass, signaturesWithSupers, classIdentifier); + HighlightInfo info = checkUnrelatedDefaultMethods(aClass, signaturesWithSupers, classIdentifier); + if (info != null) return info; + info = checkDefaultMethodOverrideEquivalentToObjectNonPrivate(aClass, signaturesWithSupers); if (info != null) return info; } return null; } + private static HighlightInfo checkDefaultMethodOverrideEquivalentToObjectNonPrivate(PsiClass aClass, + Collection<HierarchicalMethodSignature> withSupers) { + if (aClass.isInterface()) { + for (HierarchicalMethodSignature sig : withSupers) { + final PsiMethod method = sig.getMethod(); + if (method.hasModifierProperty(PsiModifier.DEFAULT)) { + for (HierarchicalMethodSignature methodSignature : sig.getSuperSignatures()) { + final PsiClass containingClass = methodSignature.getMethod().getContainingClass(); + if (containingClass != null && CommonClassNames.JAVA_LANG_OBJECT.equals(containingClass.getQualifiedName())) { + final PsiIdentifier identifier = method.getNameIdentifier(); + LOG.assertTrue(identifier != null); + return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR) + .descriptionAndTooltip("Default method " + sig.getName() + " overrides a member of java.lang.Object") + .range(identifier) + .create(); + } + } + } + } + } + return null; + } + private static HighlightInfo checkUnrelatedDefaultMethods(PsiClass aClass, Collection<HierarchicalMethodSignature> signaturesWithSupers, PsiIdentifier classIdentifier) { @@ -485,20 +510,32 @@ public class GenericsHighlightUtil { final PsiClass superContainingClass = superMethod.getContainingClass(); if (containingClass != null && superContainingClass != null && !InheritanceUtil .isInheritorOrSelf(containingClass, superContainingClass, true)) { - if (superMethod.hasModifierProperty(PsiModifier.DEFAULT)) { - final String inheritUnrelatedDefaultsMessage = HighlightUtil.formatClass(aClass) + " inherits unrelated defaults for " + - JavaHighlightUtil.formatMethod(method) + " from types " + HighlightUtil.formatClass(containingClass) + - " and " + HighlightUtil.formatClass(superContainingClass); - return HighlightInfo - .newHighlightInfo(HighlightInfoType.ERROR).range(classIdentifier).descriptionAndTooltip(inheritUnrelatedDefaultsMessage).create(); - } - if (!aClass.hasModifierProperty(PsiModifier.ABSTRACT)) { + final boolean isDefault = superMethod.hasModifierProperty(PsiModifier.DEFAULT); + if (!aClass.hasModifierProperty(PsiModifier.ABSTRACT) && !isDefault) { final String message = JavaErrorMessages.message( aClass instanceof PsiEnumConstantInitializer ? "enum.constant.should.implement.method" : "class.must.be.abstract", HighlightUtil.formatClass(superContainingClass), JavaHighlightUtil.formatMethod(superMethod), HighlightUtil.formatClass(superContainingClass, false)); - return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(classIdentifier).descriptionAndTooltip(message).create(); + return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR) + .range(classIdentifier).descriptionAndTooltip(message) + .create(); + } + + if (isDefault || superMethod.hasModifierProperty(PsiModifier.ABSTRACT)) { + final String message = isDefault + ? " inherits unrelated defaults for " + : " inherits abstract and default for "; + final String inheritUnrelatedDefaultsMessage = HighlightUtil.formatClass(aClass) + + message + + JavaHighlightUtil.formatMethod(method) + + " from types " + + HighlightUtil.formatClass(containingClass) + + " and " + + HighlightUtil.formatClass(superContainingClass); + return HighlightInfo + .newHighlightInfo(HighlightInfoType.ERROR).range(classIdentifier).descriptionAndTooltip(inheritUnrelatedDefaultsMessage) + .create(); } } } diff --git a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightControlFlowUtil.java b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightControlFlowUtil.java index dbb380ae54e4..357c934f8f2d 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightControlFlowUtil.java +++ b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightControlFlowUtil.java @@ -318,7 +318,7 @@ public class HighlightControlFlowUtil { return null; } final PsiField anotherField = PsiTreeUtil.getTopmostParentOfType(expression, PsiField.class); - if (anotherField != null && anotherField.getContainingClass() == aClass) { + if (anotherField != null && anotherField.getContainingClass() == aClass && !field.hasModifierProperty(PsiModifier.STATIC)) { startOffset = 0; } block = null; diff --git a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightMethodUtil.java b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightMethodUtil.java index 1957844f3c59..04853941e2da 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightMethodUtil.java +++ b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightMethodUtil.java @@ -339,7 +339,7 @@ public class HighlightMethodUtil { if (resolved instanceof PsiMethod && resolveResult.isValidResult()) { TextRange fixRange = getFixRange(methodCall); highlightInfo = HighlightUtil.checkUnhandledExceptions(methodCall, fixRange); - if (highlightInfo == null && !LambdaUtil.isValidQualifier4InterfaceStaticMethodCall((PsiMethod)resolved, methodCall.getMethodExpression(), languageLevel)) { + if (highlightInfo == null && !LambdaUtil.isValidQualifier4InterfaceStaticMethodCall((PsiMethod)resolved, methodCall.getMethodExpression(), resolveResult.getCurrentFileResolveScope(), languageLevel)) { highlightInfo = HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).descriptionAndTooltip("Static method may be invoked on containing interface class only").range(fixRange).create(); } } diff --git a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightUtil.java b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightUtil.java index 12af14a61b5c..cd01d32cde50 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightUtil.java +++ b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightUtil.java @@ -289,8 +289,47 @@ public class HighlightUtil extends HighlightUtilBase { @Nullable + static HighlightInfo checkIntersectionInTypeCast(@NotNull PsiTypeCastExpression expression) { + final PsiTypeElement castTypeElement = expression.getCastType(); + if (castTypeElement == null) return null; + PsiType castType = castTypeElement.getType(); + if (isIntersection(castTypeElement, castType)) { + if (PsiUtil.isLanguageLevel8OrHigher(expression)) { + final PsiTypeElement[] conjuncts = PsiTreeUtil.getChildrenOfType(castTypeElement, PsiTypeElement.class); + if (conjuncts != null) { + final List<PsiTypeElement> conjList = new ArrayList<PsiTypeElement>(Arrays.asList(conjuncts)); + for (int i = 1; i < conjuncts.length; i++) { + final PsiTypeElement conjunct = conjuncts[i]; + final PsiType conjType = conjunct.getType(); + if (conjType instanceof PsiClassType) { + final PsiClass aClass = ((PsiClassType)conjType).resolve(); + if (aClass != null && !aClass.isInterface()) { + final HighlightInfo errorResult = HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR) + .range(conjunct) + .descriptionAndTooltip(JavaErrorMessages.message("interface.expected")).create(); + QuickFixAction.registerQuickFixAction(errorResult, new FlipIntersectionSidesFix(aClass.getName(), conjList, conjunct, castTypeElement), null); + return errorResult; + } + } + } + } + } else { + return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR) + .range(expression) + .descriptionAndTooltip("Intersection types in cast are not supported at this language level").create(); + } + } + return null; + } + + static boolean isIntersection(PsiTypeElement castTypeElement, PsiType castType) { + if (castType instanceof PsiIntersectionType) return true; + return castType instanceof PsiClassType && PsiTreeUtil.getChildrenOfType(castTypeElement, PsiTypeElement.class) != null; + } + + @Nullable static HighlightInfo checkInconvertibleTypeCast(@NotNull PsiTypeCastExpression expression) { - PsiTypeElement castTypeElement = expression.getCastType(); + final PsiTypeElement castTypeElement = expression.getCastType(); if (castTypeElement == null) return null; PsiType castType = castTypeElement.getType(); @@ -306,6 +345,7 @@ public class HighlightUtil extends HighlightUtilBase { return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(expression).descriptionAndTooltip(message).create(); } + return null; } @@ -1358,9 +1398,11 @@ public class HighlightUtil extends HighlightUtilBase { if (PsiUtil.isLanguageLevel8OrHigher(expr)) { final PsiMethod method = PsiTreeUtil.getParentOfType(expr, PsiMethod.class); if (method != null && method.hasModifierProperty(PsiModifier.DEFAULT) && qualifier == null) { - //todo[r.sh] "Add qualifier" quick fix - String description = JavaErrorMessages.message("unqualified.super.disallowed"); - return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(parent).descriptionAndTooltip(description).create(); + final String description = JavaErrorMessages.message("unqualified.super.disallowed"); + final HighlightInfo highlightInfo = + HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(parent).descriptionAndTooltip(description).create(); + QualifySuperArgumentFix.registerQuickFixAction((PsiSuperExpression)expr, highlightInfo); + return highlightInfo; } } } @@ -1420,7 +1462,7 @@ public class HighlightUtil extends HighlightUtilBase { final PsiType superType = expr.getType(); if (!(superType instanceof PsiClassType)) return false; final PsiClass superClass = ((PsiClassType)superType).resolve(); - return superClass != null && aClass.equals(superClass); + return superClass != null && aClass.equals(superClass) && PsiUtil.getEnclosingStaticElement(expr, PsiTreeUtil.getParentOfType(expr, PsiClass.class)) == null; } @NotNull diff --git a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightVisitorImpl.java b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightVisitorImpl.java index d24c311e4a53..f552a66c25ab 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightVisitorImpl.java +++ b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightVisitorImpl.java @@ -1336,6 +1336,7 @@ public class HighlightVisitorImpl extends JavaElementVisitor implements Highligh public void visitTypeCastExpression(PsiTypeCastExpression typeCast) { super.visitTypeCastExpression(typeCast); try { + if (!myHolder.hasErrorResults()) myHolder.add(HighlightUtil.checkIntersectionInTypeCast(typeCast)); if (!myHolder.hasErrorResults()) myHolder.add(HighlightUtil.checkInconvertibleTypeCast(typeCast)); } catch (IndexNotReadyException ignore) { diff --git a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/FlipIntersectionSidesFix.java b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/FlipIntersectionSidesFix.java new file mode 100644 index 000000000000..8eed99632fda --- /dev/null +++ b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/FlipIntersectionSidesFix.java @@ -0,0 +1,100 @@ +/* + * Copyright 2000-2013 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.intellij.codeInsight.daemon.impl.quickfix; + +import com.intellij.codeInsight.FileModificationService; +import com.intellij.codeInsight.intention.IntentionAction; +import com.intellij.openapi.diagnostic.Logger; +import com.intellij.openapi.editor.Editor; +import com.intellij.openapi.project.Project; +import com.intellij.openapi.util.Comparing; +import com.intellij.openapi.util.text.StringUtil; +import com.intellij.psi.*; +import com.intellij.psi.codeStyle.CodeStyleManager; +import com.intellij.util.Function; +import com.intellij.util.IncorrectOperationException; +import org.jetbrains.annotations.NotNull; + +import java.util.List; + +/** +* User: anna +* Date: 10/31/13 +*/ +public class FlipIntersectionSidesFix implements IntentionAction { + private static final Logger LOG = Logger.getInstance("#" + FlipIntersectionSidesFix.class.getName()); + private final String myClassName; + private final List<PsiTypeElement> myConjuncts; + private final PsiTypeElement myConjunct; + private final PsiTypeElement myCastTypeElement; + + public FlipIntersectionSidesFix(String className, + @NotNull List<PsiTypeElement> conjList, + PsiTypeElement conjunct, + PsiTypeElement castTypeElement) { + myClassName = className; + myConjuncts = conjList; + LOG.assertTrue(!conjList.isEmpty()); + myConjunct = conjunct; + myCastTypeElement = castTypeElement; + } + + @NotNull + @Override + public String getText() { + return "Move '" + myClassName + "' to the beginning"; + } + + @NotNull + @Override + public String getFamilyName() { + return "Move to front"; + } + + @Override + public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) { + for (PsiTypeElement typeElement : myConjuncts) { + if (!typeElement.isValid()) return false; + } + return !Comparing.strEqual(myConjunct.getText(), myConjuncts.get(0).getText()); + } + + @Override + public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException { + if (!FileModificationService.getInstance().prepareFileForWrite(file)) return; + myConjuncts.remove(myConjunct); + myConjuncts.add(0, myConjunct); + + final String intersectionTypeText = StringUtil.join(myConjuncts, new Function<PsiTypeElement, String>() { + @Override + public String fun(PsiTypeElement element) { + return element.getText(); + } + }, " & "); + final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(project); + final PsiTypeCastExpression fixedCast = + (PsiTypeCastExpression)elementFactory.createExpressionFromText("(" + intersectionTypeText + ") a", myCastTypeElement); + final PsiTypeElement fixedCastCastType = fixedCast.getCastType(); + LOG.assertTrue(fixedCastCastType != null); + final PsiElement flippedTypeElement = myCastTypeElement.replace(fixedCastCastType); + CodeStyleManager.getInstance(project).reformat(flippedTypeElement); + } + + @Override + public boolean startInWriteAction() { + return true; + } +} diff --git a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/QualifySuperArgumentFix.java b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/QualifySuperArgumentFix.java new file mode 100644 index 000000000000..0a3048f23273 --- /dev/null +++ b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/QualifySuperArgumentFix.java @@ -0,0 +1,75 @@ +/* + * Copyright 2000-2013 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Created by IntelliJ IDEA. + * User: cdr + * Date: Nov 13, 2002 + * Time: 3:26:50 PM + * To change this template use Options | File Templates. + */ +package com.intellij.codeInsight.daemon.impl.quickfix; + +import com.intellij.codeInsight.daemon.impl.HighlightInfo; +import com.intellij.openapi.util.TextRange; +import com.intellij.psi.*; +import com.intellij.psi.infos.CandidateInfo; +import com.intellij.psi.util.PsiTreeUtil; +import com.intellij.psi.util.PsiUtil; +import com.intellij.psi.util.TypeConversionUtil; +import com.intellij.refactoring.util.RefactoringChangeUtil; +import org.jetbrains.annotations.NotNull; + +import java.util.HashSet; +import java.util.Set; + +public class QualifySuperArgumentFix extends QualifyThisOrSuperArgumentFix { + public QualifySuperArgumentFix(@NotNull PsiExpression expression, @NotNull PsiClass psiClass) { + super(expression, psiClass); + } + + @Override + protected String getQualifierText() { + return "super"; + } + + @Override + protected PsiExpression getQualifier(PsiManager manager) { + return RefactoringChangeUtil.createSuperExpression(manager, myPsiClass); + } + + public static void registerQuickFixAction(@NotNull PsiSuperExpression expr, HighlightInfo highlightInfo) { + LOG.assertTrue(expr.getQualifier() == null); + final PsiClass containingClass = PsiTreeUtil.getParentOfType(expr, PsiClass.class); + if (containingClass != null && containingClass.isInterface()) { + final PsiMethodCallExpression callExpression = PsiTreeUtil.getParentOfType(expr, PsiMethodCallExpression.class); + if (callExpression != null) { + final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(callExpression.getProject()); + for (PsiClass superClass : containingClass.getSupers()) { + if (superClass.isInterface()) { + final PsiMethodCallExpression copy = (PsiMethodCallExpression)callExpression.copy(); + final PsiExpression superQualifierCopy = copy.getMethodExpression().getQualifierExpression(); + LOG.assertTrue(superQualifierCopy != null); + superQualifierCopy.delete(); + if (((PsiMethodCallExpression)elementFactory.createExpressionFromText(copy.getText(), superClass)).resolveMethod() != null) { + QuickFixAction.registerQuickFixAction(highlightInfo, new QualifySuperArgumentFix(expr, superClass)); + } + } + } + } + } + } +} diff --git a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/QualifyThisArgumentFix.java b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/QualifyThisArgumentFix.java index 4eeb1d7ee730..3b427e829771 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/QualifyThisArgumentFix.java +++ b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/QualifyThisArgumentFix.java @@ -25,6 +25,7 @@ package com.intellij.codeInsight.daemon.impl.quickfix; import com.intellij.codeInsight.daemon.impl.HighlightInfo; import com.intellij.codeInsight.intention.IntentionAction; +import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.TextRange; @@ -40,45 +41,19 @@ import org.jetbrains.annotations.NotNull; import java.util.HashSet; import java.util.Set; -public class QualifyThisArgumentFix implements IntentionAction { - private final PsiThisExpression myExpression; - private final PsiClass myPsiClass; - private String myText; - - - public QualifyThisArgumentFix(@NotNull PsiThisExpression expression, @NotNull PsiClass psiClass) { - myExpression = expression; - myPsiClass = psiClass; - } - - @Override - public boolean startInWriteAction() { - return true; - } - - @NotNull - @Override - public String getText() { - return myText; - } - - @Override - public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) { - if (!myExpression.isValid()) return false; - if (!myPsiClass.isValid()) return false; - myText = "Qualify this expression with \'" + myPsiClass.getQualifiedName() + "\'"; - return true; +public class QualifyThisArgumentFix extends QualifyThisOrSuperArgumentFix{ + public QualifyThisArgumentFix(@NotNull PsiExpression expression, @NotNull PsiClass psiClass) { + super(expression, psiClass); } - @NotNull @Override - public String getFamilyName() { - return "Qualify this"; + protected String getQualifierText() { + return "this"; } @Override - public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException { - myExpression.replace(RefactoringChangeUtil.createThisExpression(PsiManager.getInstance(project), myPsiClass)); + protected PsiExpression getQualifier(PsiManager manager) { + return RefactoringChangeUtil.createThisExpression(manager, myPsiClass); } public static void registerQuickFixAction(CandidateInfo[] candidates, PsiCall call, HighlightInfo highlightInfo, final TextRange fixRange) { diff --git a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/QualifyThisOrSuperArgumentFix.java b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/QualifyThisOrSuperArgumentFix.java new file mode 100644 index 000000000000..2ea59ccadb91 --- /dev/null +++ b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/QualifyThisOrSuperArgumentFix.java @@ -0,0 +1,88 @@ +/* + * Copyright 2000-2013 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Created by IntelliJ IDEA. + * User: cdr + * Date: Nov 13, 2002 + * Time: 3:26:50 PM + * To change this template use Options | File Templates. + */ +package com.intellij.codeInsight.daemon.impl.quickfix; + +import com.intellij.codeInsight.daemon.impl.HighlightInfo; +import com.intellij.codeInsight.intention.IntentionAction; +import com.intellij.openapi.diagnostic.Logger; +import com.intellij.openapi.editor.Editor; +import com.intellij.openapi.project.Project; +import com.intellij.openapi.util.TextRange; +import com.intellij.psi.*; +import com.intellij.psi.infos.CandidateInfo; +import com.intellij.psi.util.PsiTreeUtil; +import com.intellij.psi.util.PsiUtil; +import com.intellij.psi.util.TypeConversionUtil; +import com.intellij.refactoring.util.RefactoringChangeUtil; +import com.intellij.util.IncorrectOperationException; +import org.jetbrains.annotations.NotNull; + +import java.util.HashSet; +import java.util.Set; + +public abstract class QualifyThisOrSuperArgumentFix implements IntentionAction { + protected static final Logger LOG = Logger.getInstance("#" + QualifyThisOrSuperArgumentFix.class.getName()); + protected final PsiExpression myExpression; + protected final PsiClass myPsiClass; + private String myText; + + + public QualifyThisOrSuperArgumentFix(@NotNull PsiExpression expression, @NotNull PsiClass psiClass) { + myExpression = expression; + myPsiClass = psiClass; + } + + @Override + public boolean startInWriteAction() { + return true; + } + + @NotNull + @Override + public String getText() { + return myText; + } + + protected abstract String getQualifierText(); + protected abstract PsiExpression getQualifier(PsiManager manager); + + @Override + public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) { + if (!myExpression.isValid()) return false; + if (!myPsiClass.isValid()) return false; + myText = "Qualify " + getQualifierText() + " expression with \'" + myPsiClass.getQualifiedName() + "\'"; + return true; + } + + @NotNull + @Override + public String getFamilyName() { + return "Qualify " + getQualifierText(); + } + + @Override + public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException { + myExpression.replace(getQualifier(PsiManager.getInstance(project))); + } +} diff --git a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/QualifyWithThisFix.java b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/QualifyWithThisFix.java index cebb50c019ea..beb210744589 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/QualifyWithThisFix.java +++ b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/QualifyWithThisFix.java @@ -13,8 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.intellij.codeInsight.daemon.impl.analysis; +package com.intellij.codeInsight.daemon.impl.quickfix; +import com.intellij.codeInsight.FileModificationService; import com.intellij.codeInsight.intention.IntentionAction; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; @@ -26,7 +27,7 @@ import org.jetbrains.annotations.NotNull; /** * User: anna */ -class QualifyWithThisFix implements IntentionAction { +public class QualifyWithThisFix implements IntentionAction { private final PsiClass myContainingClass; private final PsiElement myExpression; @@ -54,6 +55,7 @@ class QualifyWithThisFix implements IntentionAction { @Override public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException { + if (!FileModificationService.getInstance().prepareFileForWrite(file)) return; final PsiThisExpression thisExpression = RefactoringChangeUtil.createThisExpression(PsiManager.getInstance(project), myContainingClass); ((PsiReferenceExpression)myExpression).setQualifierExpression(thisExpression); diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/ControlFlowAnalyzer.java b/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/ControlFlowAnalyzer.java index 3492a2b13b04..7a89381553f8 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/ControlFlowAnalyzer.java +++ b/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/ControlFlowAnalyzer.java @@ -42,7 +42,7 @@ import static com.intellij.codeInsight.ConditionChecker.Type.*; import static com.intellij.codeInspection.dataFlow.MethodContract.ValueConstraint; import static com.intellij.psi.CommonClassNames.*; -class ControlFlowAnalyzer extends JavaElementVisitor { +public class ControlFlowAnalyzer extends JavaElementVisitor { private static final Logger LOG = Logger.getInstance("#com.intellij.codeInspection.dataFlow.ControlFlowAnalyzer"); public static final String ORG_JETBRAINS_ANNOTATIONS_CONTRACT = Contract.class.getName(); private boolean myIgnoreAssertions; diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/DataFlowInspectionBase.java b/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/DataFlowInspectionBase.java index eeb81ea22292..c6314f7d9bb1 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/DataFlowInspectionBase.java +++ b/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/DataFlowInspectionBase.java @@ -111,13 +111,21 @@ public class DataFlowInspectionBase extends BaseJavaBatchLocalInspectionTool { if (method == null) return; String text = AnnotationUtil.getStringAttributeValue(annotation, null); - if (text == null) return; + if (StringUtil.isNotEmpty(text)) { + String error = checkContract(method, text); + if (error != null) { + PsiAnnotationMemberValue value = annotation.findAttributeValue(null); + assert value != null; + holder.registerProblem(value, error); + return; + } + } - String error = checkContract(method, text); - if (error != null) { - PsiAnnotationMemberValue value = annotation.findAttributeValue(null); + if (Boolean.TRUE.equals(AnnotationUtil.getBooleanAttributeValue(annotation, "pure")) && + PsiType.VOID.equals(method.getReturnType())) { + PsiAnnotationMemberValue value = annotation.findDeclaredAttributeValue("pure"); assert value != null; - holder.registerProblem(value, error); + holder.registerProblem(value, "Pure methods must return something, void is not allowed as a return type"); } } }; diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/localCanBeFinal/LocalCanBeFinal.java b/java/java-analysis-impl/src/com/intellij/codeInspection/localCanBeFinal/LocalCanBeFinal.java index 0c20acf17225..028e9b7a7e9d 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInspection/localCanBeFinal/LocalCanBeFinal.java +++ b/java/java-analysis-impl/src/com/intellij/codeInspection/localCanBeFinal/LocalCanBeFinal.java @@ -221,12 +221,14 @@ public class LocalCanBeFinal extends BaseJavaBatchLocalInspectionTool { if (body.getParent() instanceof PsiMethod && isReportParameters()) { final PsiMethod method = (PsiMethod)body.getParent(); - Collections.addAll(result, method.getParameterList().getParameters()); + if (!(method instanceof SyntheticElement)) { // e.g. JspHolderMethod + Collections.addAll(result, method.getParameterList().getParameters()); + } } for (Iterator<PsiVariable> iterator = result.iterator(); iterator.hasNext(); ) { final PsiVariable variable = iterator.next(); - if (shouldBeIgnored(variable) || !variable.isPhysical()) { + if (shouldBeIgnored(variable)) { iterator.remove(); } } diff --git a/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionData.java b/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionData.java index a9167f297091..52725a0afa77 100644 --- a/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionData.java +++ b/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionData.java @@ -429,8 +429,13 @@ public class JavaCompletionData extends JavaAwareCompletionData { } if (SUPER_OR_THIS_PATTERN.accepts(position)) { - if (!AFTER_DOT.accepts(position) || isInsideQualifierClass(position)) { - result.addElement(createKeyword(position, PsiKeyword.THIS)); + final boolean afterDot = AFTER_DOT.accepts(position); + final boolean insideQualifierClass = isInsideQualifierClass(position); + final boolean insideInheritorClass = PsiUtil.isLanguageLevel8OrHigher(position) && isInsideInheritorClass(position); + if (!afterDot || insideQualifierClass || insideInheritorClass) { + if (!afterDot || insideQualifierClass) { + result.addElement(createKeyword(position, PsiKeyword.THIS)); + } final LookupItem superItem = (LookupItem)createKeyword(position, PsiKeyword.SUPER); if (psiElement().afterLeaf(psiElement().withText("{").withSuperParent(2, psiMethod().constructor(true))).accepts(position)) { @@ -732,6 +737,25 @@ public class JavaCompletionData extends JavaAwareCompletionData { return false; } + private static boolean isInsideInheritorClass(PsiElement position) { + if (position.getParent() instanceof PsiJavaCodeReferenceElement) { + final PsiElement qualifier = ((PsiJavaCodeReferenceElement)position.getParent()).getQualifier(); + if (qualifier instanceof PsiJavaCodeReferenceElement) { + final PsiElement qualifierClass = ((PsiJavaCodeReferenceElement)qualifier).resolve(); + if (qualifierClass instanceof PsiClass && ((PsiClass)qualifierClass).isInterface()) { + PsiElement parent = position; + while ((parent = PsiTreeUtil.getParentOfType(parent, PsiClass.class, true)) != null) { + if (PsiUtil.getEnclosingStaticElement(position, (PsiClass)parent) == null && + ((PsiClass)parent).isInheritor((PsiClass)qualifierClass, true)) { + return true; + } + } + } + } + } + return false; + } + private static boolean superConstructorHasParameters(PsiMethod method) { final PsiClass psiClass = method.getContainingClass(); if (psiClass == null) { diff --git a/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionSorting.java b/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionSorting.java index 1ebc7e42cfb5..e2296e4c3d2c 100644 --- a/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionSorting.java +++ b/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionSorting.java @@ -331,7 +331,11 @@ public class JavaCompletionSorting { if (type instanceof PsiClassType) { final PsiClass psiClass = ((PsiClassType)type).resolve(); if (psiClass != null && CommonClassNames.JAVA_LANG_CLASS.equals(psiClass.getQualifiedName())) { - return GenericsUtil.eliminateWildcards(type); + PsiClassType erased = (PsiClassType)GenericsUtil.eliminateWildcards(type); + PsiType[] parameters = erased.getParameters(); + if (parameters.length == 1 && !parameters[0].equalsToText(CommonClassNames.JAVA_LANG_OBJECT)) { + return erased; + } } } return type; diff --git a/java/java-impl/src/com/intellij/codeInsight/completion/methodChains/Constants.java b/java/java-impl/src/com/intellij/codeInsight/completion/methodChains/Constants.java deleted file mode 100644 index 7a326a70d4c7..000000000000 --- a/java/java-impl/src/com/intellij/codeInsight/completion/methodChains/Constants.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.intellij.codeInsight.completion.methodChains; - -/** - * @author Dmitry Batkovich - */ -public final class Constants { - - private Constants() { - } - - /** - * magic numbers - */ - public static final int SINGLETON_MAGIC_RATIO = 100; - - public static final int SINGLETON_MAGIC_RATIO2 = 5; - - public static final int CHAIN_SEARCH_MAGIC_RATIO = 12; - -} diff --git a/java/java-impl/src/com/intellij/codeInsight/completion/methodChains/completion/MethodsChainsCompletionContributor.java b/java/java-impl/src/com/intellij/codeInsight/completion/methodChains/completion/MethodsChainsCompletionContributor.java index 8781e46630bf..9b602dc63dfa 100644 --- a/java/java-impl/src/com/intellij/codeInsight/completion/methodChains/completion/MethodsChainsCompletionContributor.java +++ b/java/java-impl/src/com/intellij/codeInsight/completion/methodChains/completion/MethodsChainsCompletionContributor.java @@ -58,11 +58,9 @@ public class MethodsChainsCompletionContributor extends CompletionContributor { protected void addCompletions(final @NotNull CompletionParameters parameters, final ProcessingContext context, final @NotNull CompletionResultSet result) { - final ChainCompletionContext completionContext = extractContext(parameters); if (completionContext == null) return; - final String targetClassQName = completionContext.getTargetQName(); final Set<String> contextTypesKeysSet = completionContext.getContextTypes(); final Set<String> contextRelevantTypes = new HashSet<String>(contextTypesKeysSet.size() + 1); @@ -73,9 +71,7 @@ public class MethodsChainsCompletionContributor extends CompletionContributor { } contextRelevantTypes.remove(targetClassQName); - //final boolean useBigrams = ApplicationManager.getApplication().isUnitTestMode() || parameters.getInvocationCount() == 3; - final boolean useBigrams = true; - final List<LookupElement> foundElements = searchForLookups(targetClassQName, contextRelevantTypes, completionContext, useBigrams); + final List<LookupElement> foundElements = searchForLookups(targetClassQName, contextRelevantTypes, completionContext); result.addAllElements(foundElements); } }); @@ -83,9 +79,8 @@ public class MethodsChainsCompletionContributor extends CompletionContributor { private static List<LookupElement> searchForLookups(final String targetClassQName, final Set<String> contextRelevantTypes, - final ChainCompletionContext completionContext, - final boolean useBigrams) { - final MethodChainsSearchService searchService = new MethodChainsSearchService(completionContext.getProject(), useBigrams); + final ChainCompletionContext completionContext) { + final MethodChainsSearchService searchService = new MethodChainsSearchService(completionContext.getProject()); final List<MethodsChain> searchResult = searchChains(targetClassQName, contextRelevantTypes, MAX_SEARCH_RESULT_SIZE, MAX_CHAIN_SIZE, completionContext, searchService); if (searchResult.size() < MAX_SEARCH_RESULT_SIZE) { diff --git a/java/java-impl/src/com/intellij/codeInsight/completion/methodChains/search/ChainsSearcher.java b/java/java-impl/src/com/intellij/codeInsight/completion/methodChains/search/ChainsSearcher.java index 660e0f7f67c3..5ecba096b7bb 100644 --- a/java/java-impl/src/com/intellij/codeInsight/completion/methodChains/search/ChainsSearcher.java +++ b/java/java-impl/src/com/intellij/codeInsight/completion/methodChains/search/ChainsSearcher.java @@ -3,9 +3,13 @@ package com.intellij.codeInsight.completion.methodChains.search; import com.intellij.codeInsight.completion.methodChains.completion.context.ChainCompletionContext; import com.intellij.compilerOutputIndex.impl.MethodIncompleteSignature; import com.intellij.compilerOutputIndex.impl.UsageIndexValue; +import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.util.Pair; +import com.intellij.psi.PsiClass; +import com.intellij.psi.PsiManager; import com.intellij.psi.PsiMethod; +import com.intellij.psi.PsiModifier; import com.intellij.util.Function; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.FactoryMap; @@ -16,7 +20,12 @@ import java.util.*; /** * @author Dmitry Batkovich */ -public class ChainsSearcher { +public final class ChainsSearcher { + private ChainsSearcher() { + } + + private static final Logger LOG = Logger.getInstance(ChainsSearcher.class); + private static final double NEXT_METHOD_IN_CHAIN_RATIO = 1.5; public static List<MethodsChain> search(final MethodChainsSearchService searchService, final String targetQName, @@ -86,7 +95,6 @@ public class ChainsSearcher { } final ResultHolder result = new ResultHolder(context); - while (!q.isEmpty()) { ProgressManager.checkCanceled(); final WeightAware<Pair<MethodIncompleteSignature, MethodsChain>> currentVertex = q.poll(); @@ -100,13 +108,13 @@ public class ChainsSearcher { result.add(currentVertex.getUnderlying().getSecond()); continue; } - final SortedSet<UsageIndexValue> bigrams = searchService.getBigram(currentVertexUnderlying.getFirst()); + final SortedSet<UsageIndexValue> nextMethods = searchService.getMethods(currentVertexUnderlying.getFirst().getOwner()); final MaxSizeTreeSet<WeightAware<MethodIncompleteSignature>> currentSignatures = new MaxSizeTreeSet<WeightAware<MethodIncompleteSignature>>(maxResultSize); - for (final UsageIndexValue indexValue : bigrams) { + for (final UsageIndexValue indexValue : nextMethods) { final MethodIncompleteSignature vertex = indexValue.getMethodIncompleteSignature(); final int occurrences = indexValue.getOccurrences(); - if (!vertex.getOwner().equals(targetQName)) { + if (vertex.isStatic() || !vertex.getOwner().equals(targetQName)) { final int vertexDistance = Math.min(currentVertexDistance, occurrences); final MethodsChain knownVertexMethodsChain = knownDistance.get(vertex); if ((knownVertexMethodsChain == null || knownVertexMethodsChain.getChainWeight() < vertexDistance)) { @@ -124,6 +132,9 @@ public class ChainsSearcher { } } } + else { + break; + } } } boolean updated = false; @@ -132,7 +143,7 @@ public class ChainsSearcher { for (final WeightAware<MethodIncompleteSignature> sign : currentSignatures) { final PsiMethod[] resolved = resolver.get(sign.getUnderlying()); if (!isBreak) { - if (sign.getWeight() * maxResultSize > currentVertex.getWeight()) { + if (sign.getWeight() * NEXT_METHOD_IN_CHAIN_RATIO > currentVertex.getWeight()) { final boolean stopChain = sign.getUnderlying().isStatic() || toSet.contains(sign.getUnderlying().getOwner()); if (stopChain) { updated = true; @@ -151,7 +162,8 @@ public class ChainsSearcher { } final MethodsChain methodsChain = currentVertexUnderlying.second.addEdge(resolved, sign.getUnderlying().getOwner(), sign.getWeight()); - if (ParametersMatcher.matchParameters(methodsChain, context).noUnmatchedAndHasMatched()) { + final ParametersMatcher.MatchResult parametersMatchResult = ParametersMatcher.matchParameters(methodsChain, context); + if (parametersMatchResult.noUnmatchedAndHasMatched() && parametersMatchResult.hasTarget()) { updated = true; q.addFirst(new WeightAware<Pair<MethodIncompleteSignature, MethodsChain>>( new Pair<MethodIncompleteSignature, MethodsChain>(sign.getUnderlying(), methodsChain), sign.getWeight())); @@ -171,8 +183,15 @@ public class ChainsSearcher { return result.getResult(); } - private static class ResultHolder { + private static MethodsChain createChainFromFirstElement(final MethodsChain chain, final PsiClass newQualifierClass) { + final String qualifiedClassName = newQualifierClass.getQualifiedName(); + if (qualifiedClassName == null) { + throw new IllegalArgumentException(); + } + return new MethodsChain(chain.getFirst(), chain.getChainWeight(), qualifiedClassName); + } + private static class ResultHolder { private final List<MethodsChain> myResult; private final ChainCompletionContext myContext; @@ -212,48 +231,67 @@ public class ChainsSearcher { } } - public List<MethodsChain> getResult() { + public List<MethodsChain> getRawResult() { return myResult; } + public List<MethodsChain> getResult() { + return findSimilar(reduceChainsSize(myResult, PsiManager.getInstance(myContext.getProject())), myContext); + } + public int size() { return myResult.size(); } - } - private static int sumWeight(MaxSizeTreeSet<WeightAware<MethodIncompleteSignature>> weightAwareSignatures) { - int weight = 0; - for (WeightAware<MethodIncompleteSignature> weightAware : weightAwareSignatures) { - weight += weightAware.getWeight(); + private static List<MethodsChain> reduceChainsSize(final List<MethodsChain> chains, final PsiManager psiManager) { + return ContainerUtil.map(chains, new Function<MethodsChain, MethodsChain>() { + @Override + public MethodsChain fun(final MethodsChain chain) { + final Iterator<PsiMethod[]> chainIterator = chain.iterator(); + if (!chainIterator.hasNext()) { + LOG.error("empty chain"); + return chain; + } + final PsiMethod[] first = chainIterator.next(); + while (chainIterator.hasNext()) { + final PsiMethod psiMethod = chainIterator.next()[0]; + if (psiMethod.hasModifierProperty(PsiModifier.STATIC)) { + continue; + } + final PsiClass current = psiMethod.getContainingClass(); + if (current == null) { + LOG.error("containing class must be not null"); + return chain; + } + final PsiMethod[] currentMethods = current.findMethodsByName(first[0].getName(), true); + if (currentMethods.length != 0) { + for (final PsiMethod f : first) { + final PsiMethod[] fSupers = f.findDeepestSuperMethods(); + final PsiMethod fSuper = fSupers.length == 0 ? first[0] : fSupers[0]; + for (final PsiMethod currentMethod : currentMethods) { + if (psiManager.areElementsEquivalent(currentMethod, fSuper)) { + return createChainFromFirstElement(chain, currentMethod.getContainingClass()); + } + for (final PsiMethod method : currentMethod.findDeepestSuperMethods()) { + if (psiManager.areElementsEquivalent(method, fSuper)) { + return createChainFromFirstElement(chain, method.getContainingClass()); + } + } + } + } + } + } + return chain; + } + }); } - return weight; - } - private static boolean doChoose(final SortedSet<UsageIndexValue> bigrams, final int currentWeight, final int maxResultSize) { - if (bigrams.size() == 1) { - return true; - } - int sumWeight = 0; - for (final UsageIndexValue bigram : bigrams) { - sumWeight += bigram.getOccurrences(); - } - if (Math.abs(sumWeight - currentWeight) < currentWeight / maxResultSize) { - return true; - } - final List<UsageIndexValue> essentialValues = new ArrayList<UsageIndexValue>(); - Integer max = null; - for (UsageIndexValue bigram : bigrams) { - if (max == null) { - max = bigram.getOccurrences(); - } - if (max / bigram.getOccurrences() > maxResultSize) { - break; - } - essentialValues.add(bigram); - if (essentialValues.size() > maxResultSize) { - return false; + private static List<MethodsChain> findSimilar(final List<MethodsChain> chains, final ChainCompletionContext context) { + final ResultHolder resultHolder = new ResultHolder(context); + for (final MethodsChain chain : chains) { + resultHolder.add(chain); } + return resultHolder.getRawResult(); } - return true; } -}
\ No newline at end of file +} diff --git a/java/java-impl/src/com/intellij/codeInsight/completion/methodChains/search/MethodChainsSearchService.java b/java/java-impl/src/com/intellij/codeInsight/completion/methodChains/search/MethodChainsSearchService.java index 2c004593929e..587945d53fea 100644 --- a/java/java-impl/src/com/intellij/codeInsight/completion/methodChains/search/MethodChainsSearchService.java +++ b/java/java-impl/src/com/intellij/codeInsight/completion/methodChains/search/MethodChainsSearchService.java @@ -1,9 +1,7 @@ package com.intellij.codeInsight.completion.methodChains.search; -import com.intellij.compilerOutputIndex.impl.MethodIncompleteSignature; import com.intellij.compilerOutputIndex.impl.MethodsUsageIndex; import com.intellij.compilerOutputIndex.impl.UsageIndexValue; -import com.intellij.compilerOutputIndex.impl.bigram.BigramMethodsUsageIndex; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiManager; import org.jetbrains.annotations.NotNull; @@ -18,14 +16,10 @@ public class MethodChainsSearchService { private final static SortedSet EMPTY_SORTED_SET = new TreeSet(); private final MethodsUsageIndex myMethodsUsageIndex; - private final BigramMethodsUsageIndex myBigramMethodsUsageIndex; private final Project myProject; - private final boolean myUseBigrams; - public MethodChainsSearchService(final Project project, final boolean useBigrams) { - myUseBigrams = useBigrams; + public MethodChainsSearchService(final Project project) { myMethodsUsageIndex = MethodsUsageIndex.getInstance(project); - myBigramMethodsUsageIndex = BigramMethodsUsageIndex.getInstance(project); myProject = project; } @@ -35,18 +29,6 @@ public class MethodChainsSearchService { @NotNull @SuppressWarnings("unchecked") - public SortedSet<UsageIndexValue> getBigram(final MethodIncompleteSignature methodIncompleteSignature) { - final TreeSet<UsageIndexValue> values = myUseBigrams - ? myBigramMethodsUsageIndex.getValues(methodIncompleteSignature) - : myMethodsUsageIndex.getValues(methodIncompleteSignature.getOwner()); - if (values != null) { - return values; - } - return EMPTY_SORTED_SET; - } - - @NotNull - @SuppressWarnings("unchecked") public SortedSet<UsageIndexValue> getMethods(final String targetQName) { final TreeSet<UsageIndexValue> value = myMethodsUsageIndex.getValues(targetQName); if (value != null) { diff --git a/java/java-impl/src/com/intellij/codeInsight/completion/methodChains/search/MethodsChain.java b/java/java-impl/src/com/intellij/codeInsight/completion/methodChains/search/MethodsChain.java index 517a1d6181b8..a4b055b7e458 100644 --- a/java/java-impl/src/com/intellij/codeInsight/completion/methodChains/search/MethodsChain.java +++ b/java/java-impl/src/com/intellij/codeInsight/completion/methodChains/search/MethodsChain.java @@ -4,13 +4,12 @@ import com.intellij.codeInsight.completion.methodChains.completion.context.Chain import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiManager; import com.intellij.psi.PsiMethod; -import com.intellij.util.containers.ContainerUtil; -import org.jetbrains.annotations.Nullable; +import com.intellij.psi.PsiParameter; +import org.jetbrains.annotations.NotNull; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; +import java.util.*; +import static com.intellij.util.containers.ContainerUtil.findAll; import static com.intellij.util.containers.ContainerUtil.reverse; /** @@ -23,27 +22,41 @@ public class MethodsChain { // chain qualifier class could be different with method.getContainingClass() private final String myQualifierClassName; + private final Set<String> myExcludedQNames; + public MethodsChain(final PsiMethod[] methods, final int weight, final String qualifierClassName) { - this(ContainerUtil.<PsiMethod[]>newArrayList(methods), weight, qualifierClassName); + this(Collections.singletonList(methods), weight, qualifierClassName, chooseParametersQNames(methods)); } - public MethodsChain(final List<PsiMethod[]> revertedPath, final int weight, final String qualifierClassName) { + private MethodsChain(final List<PsiMethod[]> revertedPath, + final int weight, + final String qualifierClassName, + final Set<String> excludedQNames) { myRevertedPath = revertedPath; myWeight = weight; myQualifierClassName = qualifierClassName; + myExcludedQNames = excludedQNames; } public int size() { return myRevertedPath.size(); } + public Set<String> getExcludedQNames() { + return myExcludedQNames; + } + public String getQualifierClassName() { return myQualifierClassName; } - @Nullable - public PsiMethod getOneOfFirst() { - return (myRevertedPath.isEmpty() || myRevertedPath.get(0).length == 0) ? null : myRevertedPath.get(myRevertedPath.size() - 1)[0]; + public Iterator<PsiMethod[]> iterator() { + return myRevertedPath.iterator(); + } + + @NotNull + public PsiMethod[] getFirst() { + return myRevertedPath.get(0); } public List<PsiMethod[]> getPath() { @@ -54,13 +67,18 @@ public class MethodsChain { return myWeight; } + @SuppressWarnings("unchecked") public MethodsChain addEdge(final PsiMethod[] psiMethods, final String newQualifierClassName, final int newWeight) { final List<PsiMethod[]> newRevertedPath = new ArrayList<PsiMethod[]>(myRevertedPath.size() + 1); newRevertedPath.addAll(myRevertedPath); newRevertedPath.add(psiMethods); - return new MethodsChain(newRevertedPath, newWeight, newQualifierClassName); + return new MethodsChain(newRevertedPath, + newWeight, + newQualifierClassName, + joinSets(myExcludedQNames, chooseParametersQNames(psiMethods))); } + @Override public String toString() { return StringUtil.join(myRevertedPath, "<-"); @@ -100,8 +118,15 @@ public class MethodsChain { : CompareResult.NOT_EQUAL; } + public enum CompareResult { + LEFT_CONTAINS_RIGHT, + RIGHT_CONTAINS_LEFT, + EQUAL, + NOT_EQUAL + } + private static boolean hasBaseMethod(final PsiMethod[] left, final PsiMethod[] right, final PsiManager psiManager) { - for (PsiMethod rightMethod : right) { + for (final PsiMethod rightMethod : right) { final PsiMethod[] rightSupers = rightMethod.findDeepestSuperMethods(); if (rightSupers.length != 0) { for (final PsiMethod leftMethod : left) { @@ -113,13 +138,26 @@ public class MethodsChain { } } } - } return false; + } + return false; } - public enum CompareResult { - LEFT_CONTAINS_RIGHT, - RIGHT_CONTAINS_LEFT, - EQUAL, - NOT_EQUAL + private static Set<String> joinSets(final Set<String>... sets) { + final Set<String> result = new HashSet<String>(); + for (final Set<String> set : sets) { + for (final String s : set) { + result.add(s); + } + } + return result; + } + + private static Set<String> chooseParametersQNames(final PsiMethod[] methods) { + final Set<String> qNames = new HashSet<String>(); + for (final PsiParameter methodParameter : methods[0].getParameterList().getParameters()) { + qNames.add(methodParameter.getType().getCanonicalText()); + } + return qNames; } + } diff --git a/java/java-impl/src/com/intellij/codeInsight/completion/methodChains/search/MethodsChainLookupRangingHelper.java b/java/java-impl/src/com/intellij/codeInsight/completion/methodChains/search/MethodsChainLookupRangingHelper.java index cd6d5516bd40..0389f76b35fb 100644 --- a/java/java-impl/src/com/intellij/codeInsight/completion/methodChains/search/MethodsChainLookupRangingHelper.java +++ b/java/java-impl/src/com/intellij/codeInsight/completion/methodChains/search/MethodsChainLookupRangingHelper.java @@ -192,7 +192,6 @@ public class MethodsChainLookupRangingHelper { if (e != null) { final LookupElement firstChainElement; if (e instanceof PsiVariable) { - hasCallingVariableInContext = true; firstChainElement = new VariableLookupItem((PsiVariable)e); } else if (e instanceof PsiMethod) { @@ -204,6 +203,7 @@ public class MethodsChainLookupRangingHelper { else { throw new AssertionError(); } + hasCallingVariableInContext = true; lookupElement = new JavaChainLookupElement(firstChainElement, createLookupElement(method, parametersMap)); } else { diff --git a/java/java-impl/src/com/intellij/codeInsight/completion/methodChains/search/ParametersMatcher.java b/java/java-impl/src/com/intellij/codeInsight/completion/methodChains/search/ParametersMatcher.java index 2c2a563cef8c..fd4d5d7c2d0b 100644 --- a/java/java-impl/src/com/intellij/codeInsight/completion/methodChains/search/ParametersMatcher.java +++ b/java/java-impl/src/com/intellij/codeInsight/completion/methodChains/search/ParametersMatcher.java @@ -8,19 +8,22 @@ import com.intellij.psi.PsiType; import org.jetbrains.annotations.NotNull; import java.util.NavigableSet; +import java.util.Set; import java.util.TreeSet; /** * @author Dmitry Batkovich */ -public class ParametersMatcher { +public final class ParametersMatcher { + + private ParametersMatcher() {} public static MatchResult matchParameters(final MethodsChain chain, final ChainCompletionContext context) { MatchResult overallResult = EMPTY; for (final PsiMethod[] methods : chain.getPath()) { final NavigableSet<MatchResult> matchResults = new TreeSet<MatchResult>(); for (final PsiMethod method : methods) { - matchResults.add(matchParameters(method, context)); + matchResults.add(matchParameters(method, context, chain.getExcludedQNames())); } final MatchResult best = matchResults.first(); overallResult = overallResult.add(best); @@ -28,30 +31,37 @@ public class ParametersMatcher { return overallResult; } - public static MatchResult matchParameters(final PsiMethod method, final ChainCompletionContext context) { + private static MatchResult matchParameters(final PsiMethod method, final ChainCompletionContext context, final Set<String> additionalExcludedNames) { int matched = 0; int unMatched = 0; + boolean hasTarget = false; for (final PsiParameter parameter : method.getParameterList().getParameters()) { final PsiType type = parameter.getType(); - if (context.contains(type.getCanonicalText()) || type instanceof PsiPrimitiveType) { + final String canonicalText = type.getCanonicalText(); + if (context.contains(canonicalText) || type instanceof PsiPrimitiveType) { matched++; } else { unMatched++; } + if (context.getTargetQName().equals(canonicalText) || additionalExcludedNames.contains(canonicalText)) { + hasTarget = true; + } } - return new MatchResult(matched, unMatched); + return new MatchResult(matched, unMatched, hasTarget); } - private static final MatchResult EMPTY = new MatchResult(0, 0); + private static final MatchResult EMPTY = new MatchResult(0, 0, false); public static class MatchResult implements Comparable<MatchResult> { private final int myMatched; private final int myUnMatched; + private final boolean myHasTarget; - private MatchResult(final int matched, final int unMatched) { + private MatchResult(final int matched, final int unMatched, final boolean hasTarget) { myMatched = matched; myUnMatched = unMatched; + myHasTarget = hasTarget; } public int getMatched() { @@ -62,8 +72,12 @@ public class ParametersMatcher { return myUnMatched; } + public boolean hasTarget() { + return myHasTarget; + } + public MatchResult add(final MatchResult other) { - return new MatchResult(getMatched() + other.getMatched(), getUnMatched() + other.getUnMatched()); + return new MatchResult(getMatched() + other.getMatched(), getUnMatched() + other.getUnMatched(), other.myHasTarget || myHasTarget); } public boolean noUnmatchedAndHasMatched() { diff --git a/java/java-impl/src/com/intellij/codeInsight/completion/methodChains/search/SearchInitializer.java b/java/java-impl/src/com/intellij/codeInsight/completion/methodChains/search/SearchInitializer.java index b89edb677836..54e6d01767e2 100644 --- a/java/java-impl/src/com/intellij/codeInsight/completion/methodChains/search/SearchInitializer.java +++ b/java/java-impl/src/com/intellij/codeInsight/completion/methodChains/search/SearchInitializer.java @@ -1,6 +1,5 @@ package com.intellij.codeInsight.completion.methodChains.search; -import com.intellij.codeInsight.completion.methodChains.Constants; import com.intellij.compilerOutputIndex.impl.MethodIncompleteSignature; import com.intellij.compilerOutputIndex.impl.UsageIndexValue; import com.intellij.psi.PsiMethod; @@ -12,6 +11,8 @@ import java.util.*; * @author Dmitry Batkovich <dmitry.batkovich@jetbrains.com> */ public class SearchInitializer { + private final static int CHAIN_SEARCH_MAGIC_RATIO = 12; + private final List<WeightAware<MethodIncompleteSignature>> myVertices; private final LinkedHashMap<MethodIncompleteSignature, MethodsChain> myChains; private final FactoryMap<MethodIncompleteSignature, PsiMethod[]> myResolver; @@ -35,7 +36,7 @@ public class SearchInitializer { if (bestOccurrences == -1) { bestOccurrences = occurrences; } - else if (bestOccurrences > occurrences * Constants.CHAIN_SEARCH_MAGIC_RATIO) { + else if (bestOccurrences > occurrences * CHAIN_SEARCH_MAGIC_RATIO) { return; } } diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/JavaAwareInspectionProfileCoverter.java b/java/java-impl/src/com/intellij/codeInsight/daemon/JavaAwareInspectionProfileCoverter.java index 5caad6166995..58e6fafa38c8 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/JavaAwareInspectionProfileCoverter.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/JavaAwareInspectionProfileCoverter.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,6 +23,7 @@ package com.intellij.codeInsight.daemon; import com.intellij.codeInspection.ModifiableModel; import com.intellij.codeInspection.ex.InspectionToolWrapper; import com.intellij.codeInspection.javaDoc.JavaDocLocalInspection; +import com.intellij.codeInspection.javaDoc.JavaDocLocalInspectionBase; import com.intellij.profile.codeInspection.InspectionProfileManager; import org.jdom.Element; import org.jetbrains.annotations.NonNls; @@ -52,7 +53,7 @@ public class JavaAwareInspectionProfileCoverter extends InspectionProfileConvert super.fillErrorLevels(profile); //javadoc attributes - final InspectionToolWrapper toolWrapper = profile.getInspectionTool(JavaDocLocalInspection.SHORT_NAME, null); + final InspectionToolWrapper toolWrapper = profile.getInspectionTool(JavaDocLocalInspectionBase.SHORT_NAME, null); JavaDocLocalInspection inspection = (JavaDocLocalInspection)toolWrapper.getTool(); inspection.myAdditionalJavadocTags = myAdditionalJavadocTags; } diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/IconLineMarkerProvider.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/IconLineMarkerProvider.java index b3ef7ca2afce..5f470553e2d9 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/IconLineMarkerProvider.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/IconLineMarkerProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,7 +50,7 @@ import java.util.*; * @author Konstantin Bulenkov */ public class IconLineMarkerProvider implements LineMarkerProvider { - private static final @NonNls String JAVAX_SWING_ICON = "javax.swing.Icon"; + @NonNls private static final String JAVAX_SWING_ICON = "javax.swing.Icon"; private static final int ICON_MAX_WEIGHT = 16; private static final int ICON_MAX_HEIGHT = 16; private static final int ICON_MAX_SIZE = 2 * 1024 * 1024; //2Kb diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/MarkerType.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/MarkerType.java index 9b2b49328533..12b1788dcea7 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/MarkerType.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/MarkerType.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2012 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -298,8 +298,8 @@ public class MarkerType { } private static class OverridingMethodsUpdater extends ListBackgroundUpdaterTask { - private PsiMethod myMethod; - private PsiElementListCellRenderer myRenderer; + private final PsiMethod myMethod; + private final PsiElementListCellRenderer myRenderer; public OverridingMethodsUpdater(PsiMethod method, PsiElementListCellRenderer renderer) { super(method.getProject(), SEARCHING_FOR_OVERRIDING_METHODS); diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateClassFromUsageBaseFix.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateClassFromUsageBaseFix.java index 1845c960f7e9..ce91467d773d 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateClassFromUsageBaseFix.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateClassFromUsageBaseFix.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,7 +44,7 @@ public abstract class CreateClassFromUsageBaseFix extends BaseIntentionAction { protected abstract String getText(String varName); - private boolean isAvailableInContext(final @NotNull PsiJavaCodeReferenceElement element) { + private boolean isAvailableInContext(@NotNull final PsiJavaCodeReferenceElement element) { PsiElement parent = element.getParent(); if (myKind == CreateClassKind.ANNOTATION) { diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateConstructorFromThisOrSuperFix.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateConstructorFromThisOrSuperFix.java index f944fc742b2a..4249e579aedf 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateConstructorFromThisOrSuperFix.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateConstructorFromThisOrSuperFix.java @@ -144,7 +144,7 @@ public abstract class CreateConstructorFromThisOrSuperFix extends CreateFromUsag PsiMethod method = (PsiMethod) methodCall.getMethodExpression().resolve(); PsiExpressionList argumentList = methodCall.getArgumentList(); List<PsiClass> classes = getTargetClasses(element); - return classes.size() > 0 && !CreateFromUsageUtils.shouldCreateConstructor(classes.get(0), argumentList, method); + return !classes.isEmpty() && !CreateFromUsageUtils.shouldCreateConstructor(classes.get(0), argumentList, method); } @Override diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateConstructorParameterFromFieldFix.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateConstructorParameterFromFieldFix.java index 2fc03f8b42ec..f47a780b599a 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateConstructorParameterFromFieldFix.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateConstructorParameterFromFieldFix.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2011 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -198,6 +198,7 @@ public class CreateConstructorParameterFromFieldFix implements IntentionAction { return finalFields.put(psiVariable, Boolean.TRUE) == null; } + @NotNull @Override public Iterator<SmartPsiElementPointer<PsiField>> iterator() { return finalFields.keySet().iterator(); diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreatePropertyFromUsageFix.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreatePropertyFromUsageFix.java index b1cf8282b263..c36c25f4b47b 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreatePropertyFromUsageFix.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreatePropertyFromUsageFix.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -82,7 +82,7 @@ public class CreatePropertyFromUsageFix extends CreateFromUsageBaseFix implement String methodName = myMethodCall.getMethodExpression().getReferenceName(); LOG.assertTrue(methodName != null); String propertyName = PropertyUtil.getPropertyName(methodName); - if (propertyName == null || propertyName.length() == 0) return false; + if (propertyName == null || propertyName.isEmpty()) return false; String getterOrSetter = null; if (methodName.startsWith(GET_PREFIX) || methodName.startsWith(IS_PREFIX)) { @@ -326,7 +326,7 @@ public class CreatePropertyFromUsageFix extends CreateFromUsageBaseFix implement JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(methodCall.getProject()); String methodName = methodCall.getMethodExpression().getReferenceName(); String propertyName = PropertyUtil.getPropertyName(methodName); - if (propertyName != null && propertyName.length() > 0) { + if (propertyName != null && !propertyName.isEmpty()) { VariableKind kind = isStatic ? VariableKind.STATIC_FIELD : VariableKind.FIELD; return codeStyleManager.propertyNameToVariableName(propertyName, kind); } diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/LocateLibraryDialog.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/LocateLibraryDialog.java index 66af7f1300c9..ebc118e3e691 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/LocateLibraryDialog.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/LocateLibraryDialog.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -52,7 +52,7 @@ public class LocateLibraryDialog extends DialogWrapper { return myResultingLibraryPath; } - public LocateLibraryDialog(Module module, String libraryPath, final @NonNls String libraryName, final String libraryDescription ) { + public LocateLibraryDialog(Module module, String libraryPath, @NonNls final String libraryName, final String libraryDescription ) { super (module.getProject(), true); setTitle ( QuickFixBundle.message("add.library.title.dialog")); @@ -108,7 +108,7 @@ public class LocateLibraryDialog extends DialogWrapper { if ( copyEnabled ) { myCopyToDir.getTextField().requestFocusInWindow(); } - setOKActionEnabled(! copyEnabled || myCopyToDir.getText().length() != 0 ); + setOKActionEnabled(! copyEnabled || !myCopyToDir.getText().isEmpty()); } @Override @@ -147,7 +147,7 @@ public class LocateLibraryDialog extends DialogWrapper { } final String dstDir = myCopyToDir.getText(); - if ( dstDir.length() == 0 ) { + if (dstDir.isEmpty()) { return null; } diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/PullAsAbstractUpFix.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/PullAsAbstractUpFix.java index c42829baafef..f079ffa1dc2d 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/PullAsAbstractUpFix.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/PullAsAbstractUpFix.java @@ -91,7 +91,7 @@ public class PullAsAbstractUpFix extends LocalQuickFixAndIntentionActionOnPsiEle collectClassesToPullUp(manager, classesToPullUp, containingClass.getExtendsListTypes()); collectClassesToPullUp(manager, classesToPullUp, containingClass.getImplementsListTypes()); - if (classesToPullUp.size() == 0) { + if (classesToPullUp.isEmpty()) { //check visibility new ExtractInterfaceHandler().invoke(project, new PsiElement[]{containingClass}, null); } @@ -154,7 +154,7 @@ public class PullAsAbstractUpFix extends LocalQuickFixAndIntentionActionOnPsiEle final LinkedHashSet<PsiClass> classesToPullUp = new LinkedHashSet<PsiClass>(); collectClassesToPullUp(manager, classesToPullUp, containingClass.getExtendsListTypes()); collectClassesToPullUp(manager, classesToPullUp, containingClass.getImplementsListTypes()); - if (classesToPullUp.size() == 0) { + if (classesToPullUp.isEmpty()) { name = "Extract method \'" + methodWithOverrides.getName() + "\' to new interface"; canBePulledUp = false; } else if (classesToPullUp.size() == 1) { diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/VariableAccessFromInnerClassFix.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/VariableAccessFromInnerClassFix.java index 131260f47cf7..98a271629093 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/VariableAccessFromInnerClassFix.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/VariableAccessFromInnerClassFix.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,6 +30,7 @@ import com.intellij.psi.codeStyle.JavaCodeStyleManager; import com.intellij.psi.controlFlow.ControlFlowUtil; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.util.PsiUtil; +import com.intellij.refactoring.util.RefactoringUtil; import com.intellij.util.IncorrectOperationException; import com.intellij.util.containers.ConcurrentWeakHashMap; import gnu.trove.THashMap; @@ -139,6 +140,7 @@ public class VariableAccessFromInnerClassFix implements IntentionAction { return finalVars.put(psiVariable, Boolean.TRUE) == null; } + @NotNull @Override public Iterator<PsiVariable> iterator() { return finalVars.keySet().iterator(); @@ -203,9 +205,13 @@ public class VariableAccessFromInnerClassFix implements IntentionAction { PsiUtil.setModifierProperty(newVariable, PsiModifier.FINAL, true); PsiElement statement = getStatementToInsertBefore(); if (statement == null) return; - statement.getParent().addBefore(copyDecl, statement); PsiExpression newExpression = factory.createExpressionFromText(newName, myVariable); replaceReferences(myClass, myVariable, newExpression); + if (RefactoringUtil.isLoopOrIf(statement.getParent())) { + RefactoringUtil.putStatementInLoopBody(copyDecl, statement.getParent(), statement); + } else { + statement.getParent().addBefore(copyDecl, statement); + } } private PsiElement getStatementToInsertBefore() { @@ -216,7 +222,7 @@ public class VariableAccessFromInnerClassFix implements IntentionAction { PsiElement statement = myClass; nextInnerClass: do { - statement = PsiUtil.getEnclosingStatement(statement); + statement = RefactoringUtil.getParentStatement(statement, false); if (statement == null || statement.getParent() == null) { return null; diff --git a/java/java-impl/src/com/intellij/codeInsight/editorActions/wordSelection/MethodOrClassSelectioner.java b/java/java-impl/src/com/intellij/codeInsight/editorActions/wordSelection/MethodOrClassSelectioner.java index ef3315da52bd..c6526f63695c 100644 --- a/java/java-impl/src/com/intellij/codeInsight/editorActions/wordSelection/MethodOrClassSelectioner.java +++ b/java/java-impl/src/com/intellij/codeInsight/editorActions/wordSelection/MethodOrClassSelectioner.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,7 +20,7 @@ import com.intellij.openapi.editor.Editor; import com.intellij.openapi.util.TextRange; import com.intellij.psi.*; import com.intellij.psi.javadoc.PsiDocComment; -import com.intellij.util.containers.CollectionFactory; +import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import java.util.Collection; @@ -40,7 +40,7 @@ public class MethodOrClassSelectioner extends BasicSelectioner { @Override public List<TextRange> select(PsiElement e, CharSequence editorText, int cursorOffset, Editor editor) { - List<TextRange> result = CollectionFactory.arrayList(e.getTextRange()); + List<TextRange> result = ContainerUtil.newArrayList(e.getTextRange()); result.addAll(expandToWholeLinesWithBlanks(editorText, e.getTextRange())); PsiElement firstChild = e.getFirstChild(); diff --git a/java/java-impl/src/com/intellij/codeInsight/highlighting/HighlightExitPointsHandlerFactory.java b/java/java-impl/src/com/intellij/codeInsight/highlighting/HighlightExitPointsHandlerFactory.java index 5b2a25e7678d..4a05420dd354 100644 --- a/java/java-impl/src/com/intellij/codeInsight/highlighting/HighlightExitPointsHandlerFactory.java +++ b/java/java-impl/src/com/intellij/codeInsight/highlighting/HighlightExitPointsHandlerFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,11 +15,11 @@ */ package com.intellij.codeInsight.highlighting; +import com.intellij.codeInsight.TargetElementUtilBase; import com.intellij.openapi.editor.Editor; -import com.intellij.psi.PsiFile; import com.intellij.psi.PsiElement; +import com.intellij.psi.PsiFile; import com.intellij.psi.PsiKeyword; -import com.intellij.codeInsight.TargetElementUtilBase; /** * @author yole diff --git a/java/java-impl/src/com/intellij/codeInsight/highlighting/HighlightImportedElementsHandler.java b/java/java-impl/src/com/intellij/codeInsight/highlighting/HighlightImportedElementsHandler.java index b51094596c4f..71e301aa91f6 100644 --- a/java/java-impl/src/com/intellij/codeInsight/highlighting/HighlightImportedElementsHandler.java +++ b/java/java-impl/src/com/intellij/codeInsight/highlighting/HighlightImportedElementsHandler.java @@ -24,14 +24,12 @@ import com.intellij.openapi.ui.popup.PopupChooserBuilder; import com.intellij.psi.*; import com.intellij.psi.util.InheritanceUtil; import com.intellij.psi.util.PsiTreeUtil; -import com.intellij.ui.ListSpeedSearch; import com.intellij.ui.components.JBList; import com.intellij.util.Consumer; import com.intellij.util.Function; import org.jetbrains.annotations.NotNull; import javax.swing.*; -import java.io.Serializable; import java.util.*; /** @@ -165,6 +163,7 @@ public class HighlightImportedElementsHandler extends HighlightUsagesHandlerBase this.myImportStatic = importStatic; } + @Override public void visitReferenceElement(PsiJavaCodeReferenceElement reference) { super.visitReferenceElement(reference); if (!myImportStatic && reference.getText().equals(reference.getQualifiedName())) { @@ -283,6 +282,7 @@ public class HighlightImportedElementsHandler extends HighlightUsagesHandlerBase static class PsiMemberComparator implements Comparator<PsiMember> { + @Override public int compare(PsiMember member1, PsiMember member2) { final String name1 = member1.getName(); if (name1 == null) { diff --git a/java/java-impl/src/com/intellij/codeInsight/highlighting/HighlightOverridingMethodsHandlerFactory.java b/java/java-impl/src/com/intellij/codeInsight/highlighting/HighlightOverridingMethodsHandlerFactory.java index 965a90b8c414..bc9c0a47ce6f 100644 --- a/java/java-impl/src/com/intellij/codeInsight/highlighting/HighlightOverridingMethodsHandlerFactory.java +++ b/java/java-impl/src/com/intellij/codeInsight/highlighting/HighlightOverridingMethodsHandlerFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,9 +15,9 @@ */ package com.intellij.codeInsight.highlighting; +import com.intellij.codeInsight.TargetElementUtilBase; import com.intellij.openapi.editor.Editor; import com.intellij.psi.*; -import com.intellij.codeInsight.TargetElementUtilBase; /** * @author yole diff --git a/java/java-impl/src/com/intellij/codeInsight/intention/impl/ConvertAbsolutePathToRelativeIntentionAction.java b/java/java-impl/src/com/intellij/codeInsight/intention/impl/ConvertAbsolutePathToRelativeIntentionAction.java index 63df5bfa1288..dfede04c9fcd 100644 --- a/java/java-impl/src/com/intellij/codeInsight/intention/impl/ConvertAbsolutePathToRelativeIntentionAction.java +++ b/java/java-impl/src/com/intellij/codeInsight/intention/impl/ConvertAbsolutePathToRelativeIntentionAction.java @@ -20,14 +20,10 @@ import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiReference; -import com.intellij.psi.impl.source.resolve.reference.impl.PsiMultiReference; import com.intellij.psi.impl.source.resolve.reference.impl.providers.FileReference; -import com.intellij.psi.impl.source.resolve.reference.impl.providers.FileReferenceOwner; import com.intellij.psi.impl.source.resolve.reference.impl.providers.FileReferenceSet; -import com.intellij.psi.impl.source.resolve.reference.impl.providers.PsiFileReference; import com.intellij.util.IncorrectOperationException; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; /** * @author spleaner @@ -41,7 +37,7 @@ public class ConvertAbsolutePathToRelativeIntentionAction extends BaseIntentionA @Override public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) { final PsiReference reference = file.findReferenceAt(editor.getCaretModel().getOffset()); - final FileReference fileReference = reference == null ? null : findFileReference(reference); + final FileReference fileReference = reference == null ? null : FileReference.findFileReference(reference); if (fileReference != null) { final FileReferenceSet set = fileReference.getFileReferenceSet(); @@ -54,26 +50,6 @@ public class ConvertAbsolutePathToRelativeIntentionAction extends BaseIntentionA return false; } - @Nullable - private static FileReference findFileReference(@NotNull final PsiReference original) { - if (original instanceof PsiMultiReference) { - final PsiMultiReference multiReference = (PsiMultiReference)original; - for (PsiReference reference : multiReference.getReferences()) { - if (reference instanceof FileReference) { - return (FileReference)reference; - } - } - } - else if (original instanceof FileReferenceOwner) { - final PsiFileReference fileReference = ((FileReferenceOwner)original).getLastFileReference(); - if (fileReference instanceof FileReference) { - return (FileReference)fileReference; - } - } - - return null; - } - @Override @NotNull public String getFamilyName() { @@ -85,7 +61,7 @@ public class ConvertAbsolutePathToRelativeIntentionAction extends BaseIntentionA if (!FileModificationService.getInstance().prepareFileForWrite(file)) return; final PsiReference reference = file.findReferenceAt(editor.getCaretModel().getOffset()); - final FileReference fileReference = reference == null ? null : findFileReference(reference); + final FileReference fileReference = reference == null ? null : FileReference.findFileReference(reference); if (fileReference != null) { final FileReference lastReference = fileReference.getFileReferenceSet().getLastReference(); if (lastReference != null) lastReference.bindToElement(lastReference.resolve(), !isConvertToRelative()); diff --git a/java/java-impl/src/com/intellij/codeInspection/javaDoc/JavaDocReferenceInspection.java b/java/java-impl/src/com/intellij/codeInspection/javaDoc/JavaDocReferenceInspection.java index 1832a6fcdc3f..29e21845a7ad 100644 --- a/java/java-impl/src/com/intellij/codeInspection/javaDoc/JavaDocReferenceInspection.java +++ b/java/java-impl/src/com/intellij/codeInspection/javaDoc/JavaDocReferenceInspection.java @@ -42,6 +42,7 @@ import com.intellij.psi.PsiJavaCodeReferenceElement; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.util.proximity.PsiProximityComparator; import com.intellij.ui.components.JBList; +import com.intellij.util.Consumer; import org.jetbrains.annotations.NotNull; import javax.swing.*; @@ -83,9 +84,9 @@ public class JavaDocReferenceInspection extends JavaDocReferenceInspectionBase { @Override public void applyFix(@NotNull final Project project, @NotNull final ProblemDescriptor descriptor) { final AsyncResult<DataContext> asyncResult = DataManager.getInstance().getDataContextFromFocus(); - asyncResult.doWhenDone(new AsyncResult.Handler<DataContext>() { + asyncResult.doWhenDone(new Consumer<DataContext>() { @Override - public void run(DataContext dataContext) { + public void consume(DataContext dataContext) { final Editor editor = CommonDataKeys.EDITOR.getData(dataContext); assert editor != null; final TextRange textRange = ((ProblemDescriptorBase)descriptor).getTextRange(); @@ -152,9 +153,9 @@ public class JavaDocReferenceInspection extends JavaDocReferenceInspectionBase { } }; final AsyncResult<DataContext> asyncResult = DataManager.getInstance().getDataContextFromFocus(); - asyncResult.doWhenDone(new AsyncResult.Handler<DataContext>() { + asyncResult.doWhenDone(new Consumer<DataContext>() { @Override - public void run(DataContext dataContext) { + public void consume(DataContext dataContext) { new PopupChooserBuilder(list). setTitle(QuickFixBundle.message("add.qualifier.original.class.chooser.title")). setItemChoosenCallback(runnable). diff --git a/java/java-impl/src/com/intellij/compilerOutputIndex/api/fs/AsmUtil.java b/java/java-impl/src/com/intellij/compilerOutputIndex/api/fs/AsmUtil.java index 315a78e69c49..0ed09484e3ad 100644 --- a/java/java-impl/src/com/intellij/compilerOutputIndex/api/fs/AsmUtil.java +++ b/java/java-impl/src/com/intellij/compilerOutputIndex/api/fs/AsmUtil.java @@ -2,11 +2,13 @@ package com.intellij.compilerOutputIndex.api.fs; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.ArrayUtil; +import com.intellij.util.containers.ContainerUtil; import org.jetbrains.asm4.Opcodes; import org.jetbrains.asm4.Type; import java.util.ArrayList; import java.util.List; +import java.util.Set; /** * @author Dmitry Batkovich <dmitry.batkovich@jetbrains.com> @@ -52,4 +54,32 @@ public final class AsmUtil implements Opcodes { private static String asJavaInnerClassQName(final String byteCodeClassQName) { return StringUtil.replaceChar(byteCodeClassQName, '$', '.'); } + + //char + //double + //float + //int + //long + //short + //boolean + //byte + //void + //Object + //String + //Class + private static final Set<String> ASM_PRIMITIVE_TYPES = ContainerUtil.newHashSet("C", "D", "F", "I", "J", "S", "Z", "B", "V", + "Ljava/lang/Object;", + "Ljava/lang/String;", + "Ljava/lang/Class;"); + + public static boolean isPrimitive(final String asmType) { + return ASM_PRIMITIVE_TYPES.contains(asmType); + } + + public static boolean isPrimitiveOrArray(final String asmType) { + if (asmType.startsWith("[")) { + return true; + } + return isPrimitive(asmType); + } } diff --git a/java/java-impl/src/com/intellij/compilerOutputIndex/api/indexer/CompilerOutputBaseIndex.java b/java/java-impl/src/com/intellij/compilerOutputIndex/api/indexer/CompilerOutputBaseIndex.java index cc315b646281..1c0231b97b11 100644 --- a/java/java-impl/src/com/intellij/compilerOutputIndex/api/indexer/CompilerOutputBaseIndex.java +++ b/java/java-impl/src/com/intellij/compilerOutputIndex/api/indexer/CompilerOutputBaseIndex.java @@ -5,10 +5,11 @@ import com.intellij.openapi.extensions.ExtensionPointName; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Factory; import com.intellij.openapi.util.Ref; +import com.intellij.openapi.util.ThrowableComputable; import com.intellij.openapi.util.io.FileUtil; -import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.indexing.*; import com.intellij.util.io.DataExternalizer; +import com.intellij.util.io.IOUtil; import com.intellij.util.io.KeyDescriptor; import com.intellij.util.io.PersistentHashMap; import org.jetbrains.asm4.tree.ClassNode; @@ -51,24 +52,32 @@ public abstract class CompilerOutputBaseIndex<K, V> { if (!IndexInfrastructure.getIndexRootDir(indexId).exists()) { rewriteIndex.set(true); } - final File storageFile = IndexInfrastructure.getStorageFile(indexId); + final File storageFile = getStorageFile(indexId); final MapIndexStorage<K, V> indexStorage = new MapIndexStorage<K, V>(storageFile, myKeyDescriptor, myValueExternalizer, 1024); index = new MapReduceIndex<K, V, ClassNode>(indexId, getIndexer(), indexStorage); index.setInputIdToDataKeysIndex(new Factory<PersistentHashMap<Integer, Collection<K>>>() { @Override public PersistentHashMap<Integer, Collection<K>> create() { - Exception failCause = null; - for (int attempts = 0; attempts < 2; attempts++) { - try { - return FileBasedIndexImpl.createIdToDataKeysIndex(indexId, myKeyDescriptor, new MemoryIndexStorage<K, V>(indexStorage)); - } - catch (IOException e) { - failCause = e; - FileUtil.delete(IndexInfrastructure.getInputIndexStorageFile(getIndexId())); - rewriteIndex.set(true); - } + try { + return IOUtil.openCleanOrResetBroken( + new ThrowableComputable<PersistentHashMap<Integer, Collection<K>>, IOException>() { + @Override + public PersistentHashMap<Integer, Collection<K>> compute() throws IOException { + return FileBasedIndexImpl.createIdToDataKeysIndex(indexId, myKeyDescriptor, new MemoryIndexStorage<K, V>(indexStorage)); + } + }, + new Runnable() { + @Override + public void run() { + FileUtil.delete(getInputIndexStorageFile(getIndexId())); + rewriteIndex.set(true); + } + } + ); + } + catch (IOException e) { + throw new RuntimeException("couldn't create index", e); } - throw new RuntimeException("couldn't create index", failCause); } }); final File versionFile = getVersionFile(indexId); @@ -144,9 +153,4 @@ public abstract class CompilerOutputBaseIndex<K, V> { protected final ID<K, V> generateIndexId(final String indexName) { return CompilerOutputIndexUtil.generateIndexId(indexName, myProject); } - - protected final ID<K, V> generateIndexId(final Class aClass) { - final String className = StringUtil.getShortName(aClass); - return generateIndexId(StringUtil.trimEnd(className, "Index")); - } } diff --git a/java/java-impl/src/com/intellij/compilerOutputIndex/api/indexer/CompilerOutputIndexFeature.java b/java/java-impl/src/com/intellij/compilerOutputIndex/api/indexer/CompilerOutputIndexFeature.java index 95e0385e471f..7a8169fc1a74 100644 --- a/java/java-impl/src/com/intellij/compilerOutputIndex/api/indexer/CompilerOutputIndexFeature.java +++ b/java/java-impl/src/com/intellij/compilerOutputIndex/api/indexer/CompilerOutputIndexFeature.java @@ -16,7 +16,6 @@ package com.intellij.compilerOutputIndex.api.indexer; import com.intellij.compilerOutputIndex.impl.MethodsUsageIndex; -import com.intellij.compilerOutputIndex.impl.bigram.BigramMethodsUsageIndex; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.util.registry.RegistryValue; import com.intellij.util.containers.ContainerUtil; @@ -31,7 +30,7 @@ import java.util.Collections; @SuppressWarnings("unchecked") public enum CompilerOutputIndexFeature { METHOD_CHAINS_COMPLETION("completion.enable.relevant.method.chain.suggestions", ContainerUtil - .<Class<? extends CompilerOutputBaseIndex>>newArrayList(BigramMethodsUsageIndex.class, MethodsUsageIndex.class)); + .<Class<? extends CompilerOutputBaseIndex>>newArrayList(MethodsUsageIndex.class)); @NotNull private final String myKey; diff --git a/java/java-impl/src/com/intellij/compilerOutputIndex/api/indexer/CompilerOutputIndexUtil.java b/java/java-impl/src/com/intellij/compilerOutputIndex/api/indexer/CompilerOutputIndexUtil.java index c096cc81a364..3ca255162ec3 100644 --- a/java/java-impl/src/com/intellij/compilerOutputIndex/api/indexer/CompilerOutputIndexUtil.java +++ b/java/java-impl/src/com/intellij/compilerOutputIndex/api/indexer/CompilerOutputIndexUtil.java @@ -11,11 +11,7 @@ public final class CompilerOutputIndexUtil { private CompilerOutputIndexUtil() {} public static <K, V> ID<K, V> generateIndexId(final String indexName, final Project project) { - return ID.create(String.format("compilerOutputIndex.%s.%d", indexName, Math.abs(project.getBasePath().hashCode()))); - } - - public static boolean isSetterOrConstructorMethodName(final String methodName) { - return MethodIncompleteSignature.CONSTRUCTOR_METHOD_NAME.equals(methodName) || methodName.startsWith("set"); - + final String hash = Integer.toHexString(project.getBasePath().hashCode()); + return ID.create(String.format("compilerOutputIndex.%s.%s", indexName, hash)); } } diff --git a/java/java-impl/src/com/intellij/compilerOutputIndex/api/indexer/CompilerOutputIndexer.java b/java/java-impl/src/com/intellij/compilerOutputIndex/api/indexer/CompilerOutputIndexer.java index d4f9927af485..fed4c02502b0 100644 --- a/java/java-impl/src/com/intellij/compilerOutputIndex/api/indexer/CompilerOutputIndexer.java +++ b/java/java-impl/src/com/intellij/compilerOutputIndex/api/indexer/CompilerOutputIndexer.java @@ -3,18 +3,16 @@ package com.intellij.compilerOutputIndex.api.indexer; import com.intellij.compilerOutputIndex.api.fs.CompilerOutputFilesUtil; import com.intellij.compilerOutputIndex.api.fs.FileVisitorService; import com.intellij.openapi.compiler.CompilationStatusAdapter; -import com.intellij.openapi.compiler.CompileContext; -import com.intellij.openapi.compiler.CompileTask; import com.intellij.openapi.compiler.CompilerManager; import com.intellij.openapi.components.AbstractProjectComponent; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.extensions.Extensions; -import com.intellij.openapi.module.Module; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.progress.Task; import com.intellij.openapi.project.Project; +import com.intellij.openapi.util.ThrowableComputable; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.registry.RegistryValue; import com.intellij.openapi.util.registry.RegistryValueListener; @@ -24,10 +22,7 @@ import com.intellij.util.containers.ConcurrentHashSet; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.indexing.ID; import com.intellij.util.indexing.IndexInfrastructure; -import com.intellij.util.io.DataExternalizer; -import com.intellij.util.io.EnumeratorStringDescriptor; -import com.intellij.util.io.PersistentEnumeratorDelegate; -import com.intellij.util.io.PersistentHashMap; +import com.intellij.util.io.*; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; @@ -159,10 +154,16 @@ public class CompilerOutputIndexer extends AbstractProjectComponent { private void doEnable() { if (myInitialized.compareAndSet(false, true)) { initTimestampIndex(); + final File storageFile = + IndexInfrastructure.getStorageFile(CompilerOutputIndexUtil.generateIndexId("compilerOutputIndexFileId.enum", myProject)); + try { - myFileEnumerator = new PersistentEnumeratorDelegate<String>( - IndexInfrastructure.getStorageFile(CompilerOutputIndexUtil.generateIndexId("compilerOutputIndexFileId.enum", myProject)), - new EnumeratorStringDescriptor(), 2048); + myFileEnumerator = IOUtil.openCleanOrResetBroken(new ThrowableComputable<PersistentEnumeratorDelegate<String>, IOException>() { + @Override + public PersistentEnumeratorDelegate<String> compute() throws IOException { + return new PersistentEnumeratorDelegate<String>(storageFile, new EnumeratorStringDescriptor(), 2048); + } + }, storageFile); } catch (IOException e) { throw new RuntimeException(e); @@ -187,29 +188,35 @@ public class CompilerOutputIndexer extends AbstractProjectComponent { } private void initTimestampIndex() { - for (int attempts = 0; attempts < 2; attempts++) { - try { - myFileTimestampsIndex = new PersistentHashMap<String, Long>(IndexInfrastructure.getStorageFile(getFileTimestampsIndexId()), - new EnumeratorStringDescriptor(), new DataExternalizer<Long>() { + final File storageFile = IndexInfrastructure.getStorageFile(getFileTimestampsIndexId()); + try { + myFileTimestampsIndex = IOUtil.openCleanOrResetBroken( + new ThrowableComputable<PersistentHashMap<String, Long>, IOException>() { @Override - public void save(final DataOutput out, final Long value) throws IOException { - out.writeLong(value); - } + public PersistentHashMap<String, Long> compute() throws IOException { + return new PersistentHashMap<String, Long>(storageFile, + new EnumeratorStringDescriptor(), new DataExternalizer<Long>() { + @Override + public void save(final DataOutput out, final Long value) throws IOException { + out.writeLong(value); + } - @Override - public Long read(final DataInput in) throws IOException { - return in.readLong(); + @Override + public Long read(final DataInput in) throws IOException { + return in.readLong(); + } + }); } - }); - } - catch (IOException e) { - FileUtil.delete(IndexInfrastructure.getIndexRootDir(getFileTimestampsIndexId())); - } - if (myFileTimestampsIndex != null) { - return; - } + }, + new Runnable() { + public void run() { + FileUtil.delete(IndexInfrastructure.getIndexRootDir(getFileTimestampsIndexId())); + } + } + ); + } catch (IOException ex) { + throw new RuntimeException("Timestamps index not initialized", ex); } - throw new RuntimeException("Timestamps index not initialized"); } public void reindex(final FileVisitorService visitorService, final @NotNull ProgressIndicator indicator) { diff --git a/java/java-impl/src/com/intellij/compilerOutputIndex/impl/ClassFileData.java b/java/java-impl/src/com/intellij/compilerOutputIndex/impl/ClassFileData.java deleted file mode 100644 index 10508d039791..000000000000 --- a/java/java-impl/src/com/intellij/compilerOutputIndex/impl/ClassFileData.java +++ /dev/null @@ -1,117 +0,0 @@ -package com.intellij.compilerOutputIndex.impl; - -import com.intellij.codeInsight.completion.methodChains.ChainCompletionStringUtil; -import com.intellij.compilerOutputIndex.api.fs.AsmUtil; -import org.jetbrains.asm4.ClassReader; -import org.jetbrains.asm4.ClassVisitor; -import org.jetbrains.asm4.MethodVisitor; -import org.jetbrains.asm4.Opcodes; -import org.jetbrains.asm4.tree.ClassNode; - -import java.util.ArrayList; -import java.util.List; - -/** - * @author Dmitry Batkovich <dmitry.batkovich@jetbrains.com> - */ -public class ClassFileData { - private final List<MethodData> myMethodDatas; - - public ClassFileData(final ClassNode classNode) { - this(classNode, true); - } - - public ClassFileData(final ClassNode classNode, final boolean checkForPrimitiveReturn) { - myMethodDatas = new ArrayList<MethodData>(); - classNode.accept(new ClassVisitor(Opcodes.ASM4) { - @Override - public MethodVisitor visitMethod(final int access, - final String name, - final String desc, - final String signature, - final String[] exceptions) { - final MethodDataAccumulator methodDataAccumulator = new MethodDataAccumulator(checkForPrimitiveReturn); - myMethodDatas.add(methodDataAccumulator.getMethodData()); - return methodDataAccumulator; - } - }); - } - - public List<MethodData> getMethodDatas() { - return myMethodDatas; - } - - public static class MethodData { - private final List<MethodInsnSignature> myMethodInsnSignatures = new ArrayList<MethodInsnSignature>(); - - private void addSign(final MethodInsnSignature signature) { - myMethodInsnSignatures.add(signature); - } - - public List<MethodInsnSignature> getMethodInsnSignatures() { - return myMethodInsnSignatures; - } - } - - private static class MethodDataAccumulator extends MethodVisitor { - private final MethodData myMethodData = new MethodData(); - private final boolean myCheckForPrimitiveReturn; - - public MethodDataAccumulator(final boolean checkForPrimitiveReturn) { - super(Opcodes.ASM4); - myCheckForPrimitiveReturn = checkForPrimitiveReturn; - } - - private MethodData getMethodData() { - return myMethodData; - } - - @Override - public void visitMethodInsn(final int opcode, final String owner, final String name, final String desc) { - if (MethodIncompleteSignature.CONSTRUCTOR_METHOD_NAME.equals(name)) { - return; - } - final String ownerClassName = AsmUtil.getQualifiedClassName(owner); - if (ChainCompletionStringUtil.isPrimitiveOrArrayOfPrimitives(ownerClassName)) { - return; - } - if (myCheckForPrimitiveReturn) { - final String returnType = AsmUtil.getReturnType(desc); - if (ChainCompletionStringUtil.isPrimitiveOrArrayOfPrimitives(returnType)) { - return; - } - } - myMethodData.addSign(new MethodInsnSignature(opcode, owner, name, desc)); - } - } - - public static class MethodInsnSignature { - private final int myOpcode; - private final String myOwner; - private final String myName; - private final String myDesc; - - private MethodInsnSignature(final int opcode, final String owner, final String name, final String desc) { - myOpcode = opcode; - myOwner = owner; - myName = name; - myDesc = desc; - } - - public int getOpcode() { - return myOpcode; - } - - public String getOwner() { - return myOwner; - } - - public String getName() { - return myName; - } - - public String getDesc() { - return myDesc; - } - } -}
\ No newline at end of file diff --git a/java/java-impl/src/com/intellij/compilerOutputIndex/impl/CompilerOutputBaseGramsIndex.java b/java/java-impl/src/com/intellij/compilerOutputIndex/impl/CompilerOutputBaseGramsIndex.java deleted file mode 100644 index b5a183a45eaf..000000000000 --- a/java/java-impl/src/com/intellij/compilerOutputIndex/impl/CompilerOutputBaseGramsIndex.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.intellij.compilerOutputIndex.impl; - -import com.google.common.collect.HashMultiset; -import com.google.common.collect.Multiset; -import com.intellij.compilerOutputIndex.api.indexer.CompilerOutputBaseIndex; -import com.intellij.openapi.project.Project; -import com.intellij.util.indexing.StorageException; -import com.intellij.util.indexing.ValueContainer; -import com.intellij.util.io.KeyDescriptor; - -import java.util.TreeSet; - -/** - * @author Dmitry Batkovich <dmitry.batkovich@jetbrains.com> - */ -public abstract class CompilerOutputBaseGramsIndex<K> extends CompilerOutputBaseIndex<K, Multiset<MethodIncompleteSignature>> { - - protected CompilerOutputBaseGramsIndex(final KeyDescriptor<K> keyDescriptor, final Project project) { - super(keyDescriptor, new GuavaHashMultiSetExternalizer<MethodIncompleteSignature>(MethodIncompleteSignature.createKeyDescriptor()), project); - } - - public TreeSet<UsageIndexValue> getValues(final K key) { - try { - final ValueContainer<Multiset<MethodIncompleteSignature>> valueContainer = myIndex.getData(key); - final Multiset<MethodIncompleteSignature> rawValues = HashMultiset.create(); - valueContainer.forEach(new ValueContainer.ContainerAction<Multiset<MethodIncompleteSignature>>() { - @Override - public boolean perform(final int id, final Multiset<MethodIncompleteSignature> values) { - for (final Multiset.Entry<MethodIncompleteSignature> entry : values.entrySet()) { - rawValues.add(entry.getElement(), entry.getCount()); - } - return true; - } - }); - return rawValuesToValues(rawValues); - } catch (StorageException e) { - throw new RuntimeException(); - } - } - - private static TreeSet<UsageIndexValue> rawValuesToValues(final Multiset<MethodIncompleteSignature> rawValues) { - final TreeSet<UsageIndexValue> values = new TreeSet<UsageIndexValue>(); - for (final Multiset.Entry<MethodIncompleteSignature> entry : rawValues.entrySet()) { - values.add(new UsageIndexValue(entry.getElement(), entry.getCount())); - } - return values; - } -} diff --git a/java/java-impl/src/com/intellij/compilerOutputIndex/impl/MethodIncompleteSignature.java b/java/java-impl/src/com/intellij/compilerOutputIndex/impl/MethodIncompleteSignature.java index ad85322f3f6a..c0904bc3e36e 100644 --- a/java/java-impl/src/com/intellij/compilerOutputIndex/impl/MethodIncompleteSignature.java +++ b/java/java-impl/src/com/intellij/compilerOutputIndex/impl/MethodIncompleteSignature.java @@ -1,5 +1,6 @@ package com.intellij.compilerOutputIndex.impl; +import com.intellij.compilerOutputIndex.api.fs.AsmUtil; import com.intellij.openapi.util.Condition; import com.intellij.psi.*; import com.intellij.psi.search.GlobalSearchScope; @@ -12,6 +13,7 @@ import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.ArrayList; +import java.util.Collections; import java.util.Comparator; import java.util.List; @@ -44,6 +46,13 @@ public class MethodIncompleteSignature { return new MethodIncompleteSignature(className, className, CONSTRUCTOR_METHOD_NAME, true); } + public MethodIncompleteSignature toExternalRepresentation() { + return new MethodIncompleteSignature(AsmUtil.getQualifiedClassName(getOwner()), + AsmUtil.getQualifiedClassName(getReturnType()), + getName(), + isStatic()); + } + @NotNull public String getOwner() { return myOwner; @@ -87,6 +96,14 @@ public class MethodIncompleteSignature { } } } + if (filtered.size() > 1) { + Collections.sort(filtered, new Comparator<PsiMethod>() { + @Override + public int compare(final PsiMethod o1, final PsiMethod o2) { + return o1.getParameterList().getParametersCount() - o2.getParameterList().getParametersCount(); + } + }); + } return filtered.toArray(new PsiMethod[filtered.size()]); } diff --git a/java/java-impl/src/com/intellij/compilerOutputIndex/impl/MethodsUsageIndex.java b/java/java-impl/src/com/intellij/compilerOutputIndex/impl/MethodsUsageIndex.java index 10061352f060..78a63bd41a17 100644 --- a/java/java-impl/src/com/intellij/compilerOutputIndex/impl/MethodsUsageIndex.java +++ b/java/java-impl/src/com/intellij/compilerOutputIndex/impl/MethodsUsageIndex.java @@ -3,32 +3,47 @@ package com.intellij.compilerOutputIndex.impl; import com.google.common.collect.HashMultiset; import com.google.common.collect.Multiset; import com.intellij.compilerOutputIndex.api.fs.AsmUtil; +import com.intellij.compilerOutputIndex.api.indexer.CompilerOutputBaseIndex; import com.intellij.compilerOutputIndex.api.indexer.CompilerOutputIndexer; import com.intellij.openapi.project.Project; +import com.intellij.openapi.roots.ModifiableRootModel; +import com.intellij.openapi.roots.ModuleRootManager; +import com.intellij.openapi.roots.ModuleRootModel; +import com.intellij.psi.*; import com.intellij.util.indexing.DataIndexer; import com.intellij.util.indexing.ID; import com.intellij.util.indexing.StorageException; +import com.intellij.util.indexing.ValueContainer; +import com.intellij.util.io.DataExternalizer; import com.intellij.util.io.EnumeratorStringDescriptor; +import com.intellij.util.io.KeyDescriptor; import org.jetbrains.annotations.NotNull; -import org.jetbrains.asm4.ClassReader; +import org.jetbrains.asm4.ClassVisitor; +import org.jetbrains.asm4.MethodVisitor; import org.jetbrains.asm4.Opcodes; +import org.jetbrains.asm4.Type; import org.jetbrains.asm4.tree.ClassNode; +import java.io.DataInput; +import java.io.DataOutput; +import java.io.IOException; import java.util.HashMap; import java.util.Map; +import java.util.TreeSet; /** * @author Dmitry Batkovich <dmitry.batkovich@jetbrains.com> */ -public class MethodsUsageIndex extends CompilerOutputBaseGramsIndex<String> { +public class MethodsUsageIndex extends CompilerOutputBaseIndex<String, Multiset<MethodIncompleteSignature>> { public static MethodsUsageIndex getInstance(final Project project) { return CompilerOutputIndexer.getInstance(project).getIndex(MethodsUsageIndex.class); } public MethodsUsageIndex(final Project project) { - super(new EnumeratorStringDescriptor(), project); + super(new EnumeratorStringDescriptor(), + new GuavaHashMultiSetExternalizer<MethodIncompleteSignature>(MethodIncompleteSignature.createKeyDescriptor()), project); } @Override @@ -38,25 +53,33 @@ public class MethodsUsageIndex extends CompilerOutputBaseGramsIndex<String> { @Override public Map<String, Multiset<MethodIncompleteSignature>> map(final ClassNode inputData) { final Map<String, Multiset<MethodIncompleteSignature>> map = new HashMap<String, Multiset<MethodIncompleteSignature>>(); - for (final ClassFileData.MethodData data : new ClassFileData(inputData).getMethodDatas()) { - for (final ClassFileData.MethodInsnSignature ms : data.getMethodInsnSignatures()) { - final String ownerClassName = AsmUtil.getQualifiedClassName(ms.getOwner()); - final String returnType = AsmUtil.getReturnType(ms.getDesc()); - if (MethodIncompleteSignature.CONSTRUCTOR_METHOD_NAME.equals(ms.getName())) { - addToIndex(map, ownerClassName, MethodIncompleteSignature.constructor(ownerClassName)); + final MethodVisitor methodVisitor = new MethodVisitor(Opcodes.ASM4) { + @Override + public void visitMethodInsn(final int opcode, final String owner, final String name, final String desc) { + final Type returnType = Type.getReturnType(desc); + if (MethodIncompleteSignature.CONSTRUCTOR_METHOD_NAME.equals(name) || + AsmUtil.isPrimitiveOrArray(returnType.getDescriptor())) { + return; } - else { - final boolean isStatic = ms.getOpcode() == Opcodes.INVOKESTATIC; - if (!ownerClassName.equals(returnType) || isStatic) { - addToIndex(map, returnType, new MethodIncompleteSignature(ownerClassName, returnType, ms.getName(), isStatic)); - } + final String returnClassName = returnType.getInternalName(); + final boolean isStatic = opcode == Opcodes.INVOKESTATIC; + if (!owner.equals(returnClassName) || isStatic) { + addToIndex(map, returnClassName, new MethodIncompleteSignature(owner, returnClassName, name, isStatic)); } } - } + }; + inputData.accept(new ClassVisitor(Opcodes.ASM4) { + @Override + public MethodVisitor visitMethod(final int access, + final String name, + final String desc, + final String signature, + final String[] exceptions) { + return methodVisitor; + } + }); return map; } - - }; } @@ -67,17 +90,46 @@ public class MethodsUsageIndex extends CompilerOutputBaseGramsIndex<String> { @Override protected int getVersion() { - return 0; + return 1; + } + + public TreeSet<UsageIndexValue> getValues(final String key) { + try { + final ValueContainer<Multiset<MethodIncompleteSignature>> valueContainer = myIndex.getData(key); + final Multiset<MethodIncompleteSignature> rawValues = HashMultiset.create(); + valueContainer.forEach(new ValueContainer.ContainerAction<Multiset<MethodIncompleteSignature>>() { + @Override + public boolean perform(final int id, final Multiset<MethodIncompleteSignature> values) { + for (final Multiset.Entry<MethodIncompleteSignature> entry : values.entrySet()) { + rawValues.add(entry.getElement(), entry.getCount()); + } + return true; + } + }); + return rawValuesToValues(rawValues); + } + catch (final StorageException e) { + throw new RuntimeException(); + } } private static void addToIndex(final Map<String, Multiset<MethodIncompleteSignature>> map, - final String key, + final String internalClassName, final MethodIncompleteSignature mi) { - Multiset<MethodIncompleteSignature> occurrences = map.get(key); + final String className = AsmUtil.getQualifiedClassName(internalClassName); + Multiset<MethodIncompleteSignature> occurrences = map.get(className); if (occurrences == null) { occurrences = HashMultiset.create(); - map.put(key, occurrences); + map.put(className, occurrences); } occurrences.add(mi); } -}
\ No newline at end of file + + private static TreeSet<UsageIndexValue> rawValuesToValues(final Multiset<MethodIncompleteSignature> rawValues) { + final TreeSet<UsageIndexValue> values = new TreeSet<UsageIndexValue>(); + for (final Multiset.Entry<MethodIncompleteSignature> entry : rawValues.entrySet()) { + values.add(new UsageIndexValue(entry.getElement().toExternalRepresentation(), entry.getCount())); + } + return values; + } +} diff --git a/java/java-impl/src/com/intellij/compilerOutputIndex/impl/bigram/Bigram.java b/java/java-impl/src/com/intellij/compilerOutputIndex/impl/bigram/Bigram.java deleted file mode 100644 index f5f4ff87a095..000000000000 --- a/java/java-impl/src/com/intellij/compilerOutputIndex/impl/bigram/Bigram.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.intellij.compilerOutputIndex.impl.bigram; - -import com.intellij.openapi.util.Pair; -import org.jetbrains.annotations.NotNull; - -/** - * @author Dmitry Batkovich <dmitry.batkovich@jetbrains.com> - */ -public class Bigram<E> extends Pair<E, E> { - public Bigram(@NotNull final E first, @NotNull final E second) { - super(first, second); - } - - public Bigram<E> swap() { - return new Bigram<E>(second, first); - } - - @Override - public String toString() { - return String.format("%s - %s", first, second); - } -} diff --git a/java/java-impl/src/com/intellij/compilerOutputIndex/impl/bigram/BigramMethodsUsageIndex.java b/java/java-impl/src/com/intellij/compilerOutputIndex/impl/bigram/BigramMethodsUsageIndex.java deleted file mode 100644 index 31bf75fef612..000000000000 --- a/java/java-impl/src/com/intellij/compilerOutputIndex/impl/bigram/BigramMethodsUsageIndex.java +++ /dev/null @@ -1,87 +0,0 @@ -package com.intellij.compilerOutputIndex.impl.bigram; - -import com.google.common.collect.HashMultiset; -import com.google.common.collect.Multiset; -import com.intellij.compilerOutputIndex.api.fs.AsmUtil; -import com.intellij.compilerOutputIndex.api.indexer.CompilerOutputIndexer; -import com.intellij.compilerOutputIndex.impl.ClassFileData; -import com.intellij.compilerOutputIndex.impl.CompilerOutputBaseGramsIndex; -import com.intellij.compilerOutputIndex.impl.MethodIncompleteSignature; -import com.intellij.compilerOutputIndex.impl.MethodIncompleteSignatureChain; -import com.intellij.openapi.project.Project; -import com.intellij.util.SmartList; -import com.intellij.util.indexing.DataIndexer; -import com.intellij.util.indexing.ID; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.asm4.ClassReader; -import org.jetbrains.asm4.Opcodes; -import org.jetbrains.asm4.tree.ClassNode; - -import java.util.*; - -/** - * @author Dmitry Batkovich <dmitry.batkovich@jetbrains.com> - */ -public class BigramMethodsUsageIndex extends CompilerOutputBaseGramsIndex<MethodIncompleteSignature> { - public static BigramMethodsUsageIndex getInstance(final Project project) { - return CompilerOutputIndexer.getInstance(project).getIndex(BigramMethodsUsageIndex.class); - } - - public BigramMethodsUsageIndex( final Project project) { - super(MethodIncompleteSignature.createKeyDescriptor(), project); - } - - @Override - protected ID<MethodIncompleteSignature, Multiset<MethodIncompleteSignature>> getIndexId() { - return generateIndexId("BigramMethodsUsage"); - } - - @Override - protected int getVersion() { - return 0; - } - - @Override - protected DataIndexer<MethodIncompleteSignature, Multiset<MethodIncompleteSignature>,ClassNode> getIndexer() { - // - // not fair way, but works fast - // - return new DataIndexer<MethodIncompleteSignature, Multiset<MethodIncompleteSignature>, ClassNode>() { - @NotNull - @Override - public Map<MethodIncompleteSignature, Multiset<MethodIncompleteSignature>> map(final ClassNode inputData) { - final Map<MethodIncompleteSignature, Multiset<MethodIncompleteSignature>> map = - new HashMap<MethodIncompleteSignature, Multiset<MethodIncompleteSignature>>(); - for (final ClassFileData.MethodData data : new ClassFileData(inputData).getMethodDatas()) { - final SimpleBigramsExtractor extractor = new SimpleBigramsExtractor(new SimpleBigramsExtractor.BigramMethodIncompleteSignatureProcessor() { - @Override - public void process(final Bigram<MethodIncompleteSignature> bigram) { - final MethodIncompleteSignature secondGram = bigram.getSecond(); - Multiset<MethodIncompleteSignature> occurrences = map.get(secondGram); - if (occurrences == null) { - occurrences = HashMultiset.create(); - map.put(secondGram, occurrences); - } - occurrences.add(bigram.getFirst()); - } - }); - for (final ClassFileData.MethodInsnSignature ms : data.getMethodInsnSignatures()) { - final List<MethodIncompleteSignature> methodInvocations = new SmartList<MethodIncompleteSignature>(); - final String ownerClassName = AsmUtil.getQualifiedClassName(ms.getOwner()); - final String returnType = AsmUtil.getReturnType(ms.getDesc()); - - if (ms.getName().equals(MethodIncompleteSignature.CONSTRUCTOR_METHOD_NAME)) { - methodInvocations.add(MethodIncompleteSignature.constructor(ownerClassName)); - } - else { - methodInvocations.add(new MethodIncompleteSignature(ownerClassName, returnType, ms.getName(), ms.getOpcode() == Opcodes.INVOKESTATIC)); - } - extractor.addChain(new MethodIncompleteSignatureChain(methodInvocations)); - } - } - return map; - } - }; - } - -} diff --git a/java/java-impl/src/com/intellij/compilerOutputIndex/impl/bigram/SimpleBigramsExtractor.java b/java/java-impl/src/com/intellij/compilerOutputIndex/impl/bigram/SimpleBigramsExtractor.java deleted file mode 100644 index d231a07e0f18..000000000000 --- a/java/java-impl/src/com/intellij/compilerOutputIndex/impl/bigram/SimpleBigramsExtractor.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.intellij.compilerOutputIndex.impl.bigram; - -import com.intellij.compilerOutputIndex.impl.MethodIncompleteSignature; -import com.intellij.compilerOutputIndex.impl.MethodIncompleteSignatureChain; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.util.*; - -/** -* @author Dmitry Batkovich -*/ -class SimpleBigramsExtractor { - private final Map<String, MethodIncompleteSignature> myHolder = new HashMap<String, MethodIncompleteSignature>(); - private final BigramMethodIncompleteSignatureProcessor myProcessor; - - public SimpleBigramsExtractor(final BigramMethodIncompleteSignatureProcessor processor) { - myProcessor = processor; - } - - public void addChain(final MethodIncompleteSignatureChain chain) { - if (chain.isEmpty()) { - return; - } - final MethodIncompleteSignature firstInvocation = chain.getFirstInvocation(); - assert firstInvocation != null; - final MethodIncompleteSignature head = firstInvocation.isStatic() ? null : myHolder.get(firstInvocation.getOwner()); - for (final Bigram<MethodIncompleteSignature> bigram : toBigrams(head, chain)) { - myProcessor.process(bigram); - } - final MethodIncompleteSignature lastInvocation = chain.getLastInvocation(); - assert lastInvocation != null; - myHolder.put(lastInvocation.getReturnType(), lastInvocation); - } - - private static Collection<Bigram<MethodIncompleteSignature>> toBigrams(final @Nullable MethodIncompleteSignature head, - final @NotNull MethodIncompleteSignatureChain chain) { - MethodIncompleteSignature currentLast = null; - if (head != null) { - currentLast = head; - } - final List<Bigram<MethodIncompleteSignature>> bigrams = new ArrayList<Bigram<MethodIncompleteSignature>>(chain.size()); - for (final MethodIncompleteSignature current : chain.list()) { - if (currentLast != null) { - bigrams.add(new Bigram<MethodIncompleteSignature>(currentLast, current)); - } - currentLast = current; - } - return bigrams; - } - - public interface BigramMethodIncompleteSignatureProcessor { - void process(Bigram<MethodIncompleteSignature> bigram); - } -} diff --git a/java/java-impl/src/com/intellij/ide/hierarchy/call/JavaCallHierarchyProvider.java b/java/java-impl/src/com/intellij/ide/hierarchy/call/JavaCallHierarchyProvider.java index 5c95175adce6..20caeb65d34f 100644 --- a/java/java-impl/src/com/intellij/ide/hierarchy/call/JavaCallHierarchyProvider.java +++ b/java/java-impl/src/com/intellij/ide/hierarchy/call/JavaCallHierarchyProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,17 +15,15 @@ */ package com.intellij.ide.hierarchy.call; -import com.intellij.ide.hierarchy.HierarchyProvider; -import com.intellij.ide.hierarchy.HierarchyBrowser; import com.intellij.ide.hierarchy.CallHierarchyBrowserBase; +import com.intellij.ide.hierarchy.HierarchyBrowser; +import com.intellij.ide.hierarchy.HierarchyProvider; import com.intellij.openapi.actionSystem.CommonDataKeys; +import com.intellij.openapi.actionSystem.DataContext; +import com.intellij.openapi.project.Project; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiMethod; import com.intellij.psi.util.PsiTreeUtil; -import com.intellij.openapi.actionSystem.DataContext; -import com.intellij.openapi.actionSystem.PlatformDataKeys; -import com.intellij.openapi.actionSystem.LangDataKeys; -import com.intellij.openapi.project.Project; import org.jetbrains.annotations.NotNull; /** @@ -34,7 +32,7 @@ import org.jetbrains.annotations.NotNull; public class JavaCallHierarchyProvider implements HierarchyProvider { @Override public PsiElement getTarget(@NotNull final DataContext dataContext) { - final Project project = PlatformDataKeys.PROJECT.getData(dataContext); + final Project project = CommonDataKeys.PROJECT.getData(dataContext); if (project == null) return null; final PsiElement element = CommonDataKeys.PSI_ELEMENT.getData(dataContext); diff --git a/java/java-impl/src/com/intellij/ide/macro/ClasspathEntryMacro.java b/java/java-impl/src/com/intellij/ide/macro/ClasspathEntryMacro.java index 5ee1126b6f09..b28334802f24 100644 --- a/java/java-impl/src/com/intellij/ide/macro/ClasspathEntryMacro.java +++ b/java/java-impl/src/com/intellij/ide/macro/ClasspathEntryMacro.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,7 +18,6 @@ package com.intellij.ide.macro; import com.intellij.ide.IdeBundle; import com.intellij.openapi.actionSystem.CommonDataKeys; import com.intellij.openapi.actionSystem.DataContext; -import com.intellij.openapi.actionSystem.PlatformDataKeys; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.vfs.VirtualFile; @@ -36,7 +35,7 @@ public final class ClasspathEntryMacro extends Macro { } public String expand(final DataContext dataContext) { - final Project project = PlatformDataKeys.PROJECT.getData(dataContext); + final Project project = CommonDataKeys.PROJECT.getData(dataContext); if (project == null) return null; final VirtualFile file = CommonDataKeys.VIRTUAL_FILE.getData(dataContext); if (file == null) return null; diff --git a/java/java-impl/src/com/intellij/openapi/module/JavaModuleType.java b/java/java-impl/src/com/intellij/openapi/module/JavaModuleType.java index 0ad4e7c99309..ade31f9e3f2d 100644 --- a/java/java-impl/src/com/intellij/openapi/module/JavaModuleType.java +++ b/java/java-impl/src/com/intellij/openapi/module/JavaModuleType.java @@ -84,17 +84,17 @@ public class JavaModuleType extends ModuleType<JavaModuleBuilder> { @NotNull @Override public ModuleWizardStep[] createWizardSteps(@NotNull final WizardContext wizardContext, @NotNull final JavaModuleBuilder moduleBuilder, - @NotNull final ModulesProvider modulesProvider, boolean forNewWizard) { + @NotNull final ModulesProvider modulesProvider) { final ProjectWizardStepFactory wizardFactory = ProjectWizardStepFactory.getInstance(); ArrayList<ModuleWizardStep> steps = new ArrayList<ModuleWizardStep>(); - if (!forNewWizard) { + if (!wizardContext.isNewWizard()) { final ModuleWizardStep supportForFrameworksStep = wizardFactory.createSupportForFrameworksStep(wizardContext, moduleBuilder, modulesProvider); if (supportForFrameworksStep != null) { steps.add(supportForFrameworksStep); } } final ModuleWizardStep[] wizardSteps = steps.toArray(new ModuleWizardStep[steps.size()]); - return ArrayUtil.mergeArrays(wizardSteps, super.createWizardSteps(wizardContext, moduleBuilder, modulesProvider, forNewWizard)); + return ArrayUtil.mergeArrays(wizardSteps, super.createWizardSteps(wizardContext, moduleBuilder, modulesProvider)); } @Nullable diff --git a/java/java-impl/src/com/intellij/openapi/roots/impl/ExcludeCompilerOutputPolicy.java b/java/java-impl/src/com/intellij/openapi/roots/impl/ExcludeCompilerOutputPolicy.java index f880d36a6b19..adbacfcd38ce 100644 --- a/java/java-impl/src/com/intellij/openapi/roots/impl/ExcludeCompilerOutputPolicy.java +++ b/java/java-impl/src/com/intellij/openapi/roots/impl/ExcludeCompilerOutputPolicy.java @@ -25,6 +25,7 @@ import com.intellij.openapi.util.Comparing; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.pointers.VirtualFilePointer; import com.intellij.openapi.util.io.FileUtil; +import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; @@ -78,14 +79,12 @@ public class ExcludeCompilerOutputPolicy implements DirectoryIndexExcludePolicy return VirtualFilePointer.EMPTY_ARRAY; } if (extension.isCompilerOutputPathInherited()) { - result.add(CompilerProjectExtension.getInstance(myProject).getCompilerOutputPointer()); + ContainerUtil.addIfNotNull(result, CompilerProjectExtension.getInstance(myProject).getCompilerOutputPointer()); } else { if (!extension.isExcludeOutput()) return VirtualFilePointer.EMPTY_ARRAY; - final VirtualFilePointer outputPath = extension.getCompilerOutputPointer(); - if (outputPath != null) result.add(outputPath); - final VirtualFilePointer outputPathForTests = extension.getCompilerOutputForTestsPointer(); - if (outputPathForTests != null) result.add(outputPathForTests); + ContainerUtil.addIfNotNull(result, extension.getCompilerOutputPointer()); + ContainerUtil.addIfNotNull(result, extension.getCompilerOutputForTestsPointer()); } return result.isEmpty() ? VirtualFilePointer.EMPTY_ARRAY : result.toArray(new VirtualFilePointer[result.size()]); } diff --git a/java/java-impl/src/com/intellij/psi/formatter/JavadocWhiteSpaceFormattingStrategy.java b/java/java-impl/src/com/intellij/psi/formatter/JavadocWhiteSpaceFormattingStrategy.java index 4f20b9225206..28ae06ea33c8 100644 --- a/java/java-impl/src/com/intellij/psi/formatter/JavadocWhiteSpaceFormattingStrategy.java +++ b/java/java-impl/src/com/intellij/psi/formatter/JavadocWhiteSpaceFormattingStrategy.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2011 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,6 +25,6 @@ import org.jetbrains.annotations.NotNull; public class JavadocWhiteSpaceFormattingStrategy extends WhiteSpaceFormattingStrategyAdapter { @Override public boolean containsWhitespacesOnly(@NotNull final ASTNode node) { - return node.getElementType() == JavaDocTokenType.DOC_COMMENT_DATA && node.textContains('\n') && node.getText().trim().length() == 0; + return node.getElementType() == JavaDocTokenType.DOC_COMMENT_DATA && node.textContains('\n') && node.getText().trim().isEmpty(); } } diff --git a/java/java-impl/src/com/intellij/psi/formatter/java/BlockContainingJavaBlock.java b/java/java-impl/src/com/intellij/psi/formatter/java/BlockContainingJavaBlock.java index 5bbd481b6e40..cb5139cdef91 100644 --- a/java/java-impl/src/com/intellij/psi/formatter/java/BlockContainingJavaBlock.java +++ b/java/java-impl/src/com/intellij/psi/formatter/java/BlockContainingJavaBlock.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,9 +38,9 @@ public class BlockContainingJavaBlock extends AbstractJavaBlock{ JavaElementType.IF_STATEMENT, JavaElementType.WHILE_STATEMENT, JavaElementType.FOR_STATEMENT ); - private final static int BEFORE_FIRST = 0; - private final static int BEFORE_BLOCK = 1; - private final static int AFTER_ELSE = 2; + private static final int BEFORE_FIRST = 0; + private static final int BEFORE_BLOCK = 1; + private static final int AFTER_ELSE = 2; private final List<Indent> myIndentsBefore = new ArrayList<Indent>(); diff --git a/java/java-impl/src/com/intellij/psi/formatter/java/CodeBlockBlock.java b/java/java-impl/src/com/intellij/psi/formatter/java/CodeBlockBlock.java index bcec4eff628e..574c93f950b5 100644 --- a/java/java-impl/src/com/intellij/psi/formatter/java/CodeBlockBlock.java +++ b/java/java-impl/src/com/intellij/psi/formatter/java/CodeBlockBlock.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2012 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,9 +36,9 @@ import java.util.ArrayList; import java.util.List; public class CodeBlockBlock extends AbstractJavaBlock { - private final static int BEFORE_FIRST = 0; - private final static int BEFORE_LBRACE = 1; - private final static int INSIDE_BODY = 2; + private static final int BEFORE_FIRST = 0; + private static final int BEFORE_LBRACE = 1; + private static final int INSIDE_BODY = 2; private final int myChildrenIndent; diff --git a/java/java-impl/src/com/intellij/psi/formatter/java/CommentWithInjectionBlock.java b/java/java-impl/src/com/intellij/psi/formatter/java/CommentWithInjectionBlock.java index 08bb1f44fb72..7e31f44230b0 100644 --- a/java/java-impl/src/com/intellij/psi/formatter/java/CommentWithInjectionBlock.java +++ b/java/java-impl/src/com/intellij/psi/formatter/java/CommentWithInjectionBlock.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2010 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,7 +30,7 @@ import java.util.List; * @author nik */ public class CommentWithInjectionBlock extends AbstractJavaBlock { - private InjectedLanguageBlockBuilder myInjectedBlockBuilder; + private final InjectedLanguageBlockBuilder myInjectedBlockBuilder; public CommentWithInjectionBlock(ASTNode node, Wrap wrap, Alignment alignment, Indent indent, CommonCodeStyleSettings settings) { super(node, wrap, alignment, indent, settings); diff --git a/java/java-impl/src/com/intellij/psi/formatter/java/DocCommentBlock.java b/java/java-impl/src/com/intellij/psi/formatter/java/DocCommentBlock.java index b65393f3a4b3..4bc6f6d2616b 100644 --- a/java/java-impl/src/com/intellij/psi/formatter/java/DocCommentBlock.java +++ b/java/java-impl/src/com/intellij/psi/formatter/java/DocCommentBlock.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,7 +39,7 @@ public class DocCommentBlock extends AbstractJavaBlock{ while (child != null) { if (child.getElementType() == JavaDocTokenType.DOC_COMMENT_START) { result.add(createJavaBlock(child, mySettings, Indent.getNoneIndent(), null, AlignmentStrategy.getNullStrategy())); - } else if (!FormatterUtil.containsWhiteSpacesOnly(child) && child.getText().trim().length() > 0){ + } else if (!FormatterUtil.containsWhiteSpacesOnly(child) && !child.getText().trim().isEmpty()){ result.add(createJavaBlock(child, mySettings, Indent.getSpaceIndent(1), null, AlignmentStrategy.getNullStrategy())); } child = child.getTreeNext(); diff --git a/java/java-impl/src/com/intellij/psi/formatter/java/ExtendsListBlock.java b/java/java-impl/src/com/intellij/psi/formatter/java/ExtendsListBlock.java index 2a5098803d01..37e49def2526 100644 --- a/java/java-impl/src/com/intellij/psi/formatter/java/ExtendsListBlock.java +++ b/java/java-impl/src/com/intellij/psi/formatter/java/ExtendsListBlock.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,6 +24,7 @@ import com.intellij.lang.ASTNode; import com.intellij.psi.codeStyle.CommonCodeStyleSettings; import com.intellij.psi.formatter.FormatterUtil; import com.intellij.psi.impl.source.tree.ElementType; +import com.intellij.psi.impl.source.tree.JavaElementType; import java.util.ArrayList; import java.util.List; @@ -78,9 +79,9 @@ public class ExtendsListBlock extends AbstractJavaBlock{ } private boolean alignList() { - if (myNode.getElementType() == ElementType.EXTENDS_LIST || myNode.getElementType() == ElementType.IMPLEMENTS_LIST) { + if (myNode.getElementType() == JavaElementType.EXTENDS_LIST || myNode.getElementType() == JavaElementType.IMPLEMENTS_LIST) { return mySettings.ALIGN_MULTILINE_EXTENDS_LIST; - } else if (myNode.getElementType() == ElementType.THROWS_LIST) { + } else if (myNode.getElementType() == JavaElementType.THROWS_LIST) { return mySettings.ALIGN_MULTILINE_THROWS_LIST; } return false; diff --git a/java/java-impl/src/com/intellij/psi/formatter/java/LabeledJavaBlock.java b/java/java-impl/src/com/intellij/psi/formatter/java/LabeledJavaBlock.java index c354bcc3de86..c3f0af11b33e 100644 --- a/java/java-impl/src/com/intellij/psi/formatter/java/LabeledJavaBlock.java +++ b/java/java-impl/src/com/intellij/psi/formatter/java/LabeledJavaBlock.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,6 +19,7 @@ import com.intellij.formatting.*; import com.intellij.formatting.alignment.AlignmentStrategy; import com.intellij.lang.ASTNode; import com.intellij.openapi.fileTypes.StdFileTypes; +import com.intellij.psi.JavaTokenType; import com.intellij.psi.codeStyle.CommonCodeStyleSettings; import com.intellij.psi.formatter.FormatterUtil; import com.intellij.psi.impl.source.tree.ElementType; @@ -45,7 +46,7 @@ public class LabeledJavaBlock extends AbstractJavaBlock{ while (child != null) { if (!FormatterUtil.containsWhiteSpacesOnly(child) && child.getTextLength() > 0){ result.add(createJavaBlock(child, mySettings, currentIndent, currentWrap, AlignmentStrategy.getNullStrategy())); - if (child.getElementType() == ElementType.COLON) { + if (child.getElementType() == JavaTokenType.COLON) { currentIndent = Indent.getNoneIndent(); currentWrap =Wrap.createWrap(WrapType.ALWAYS, true); } diff --git a/java/java-impl/src/com/intellij/psi/formatter/java/WrappingStrategy.java b/java/java-impl/src/com/intellij/psi/formatter/java/WrappingStrategy.java index 2429bc0212cc..e4d283edccb0 100644 --- a/java/java-impl/src/com/intellij/psi/formatter/java/WrappingStrategy.java +++ b/java/java-impl/src/com/intellij/psi/formatter/java/WrappingStrategy.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,6 +16,7 @@ package com.intellij.psi.formatter.java; import com.intellij.formatting.Wrap; +import com.intellij.psi.JavaTokenType; import com.intellij.psi.tree.IElementType; import com.intellij.psi.impl.source.tree.ElementType; @@ -32,7 +33,7 @@ public abstract class WrappingStrategy { return new WrappingStrategy(wrap) { @Override protected boolean shouldWrap(final IElementType type) { - return type != ElementType.COMMA && type != ElementType.SEMICOLON; + return type != JavaTokenType.COMMA && type != JavaTokenType.SEMICOLON; } }; } diff --git a/java/java-impl/src/com/intellij/psi/formatter/java/wrap/impl/JavaChildWrapArranger.java b/java/java-impl/src/com/intellij/psi/formatter/java/wrap/impl/JavaChildWrapArranger.java index 6f5fb24af9a8..52ea316861c6 100644 --- a/java/java-impl/src/com/intellij/psi/formatter/java/wrap/impl/JavaChildWrapArranger.java +++ b/java/java-impl/src/com/intellij/psi/formatter/java/wrap/impl/JavaChildWrapArranger.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2010 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -136,7 +136,7 @@ public class JavaChildWrapArranger { } if (role == ChildRole.LOOP_BODY) { final boolean dontWrap = (childType == JavaElementType.CODE_BLOCK || childType == JavaElementType.BLOCK_STATEMENT) && - settings.BRACE_STYLE == CodeStyleSettings.END_OF_LINE; + settings.BRACE_STYLE == CommonCodeStyleSettings.END_OF_LINE; return Wrap.createWrap(dontWrap ? WrapType.NONE : WrapType.NORMAL, true); } else { diff --git a/java/java-impl/src/com/intellij/psi/impl/beanProperties/CreateBeanPropertyFix.java b/java/java-impl/src/com/intellij/psi/impl/beanProperties/CreateBeanPropertyFix.java index 47618f5594ae..053a534e0c98 100644 --- a/java/java-impl/src/com/intellij/psi/impl/beanProperties/CreateBeanPropertyFix.java +++ b/java/java-impl/src/com/intellij/psi/impl/beanProperties/CreateBeanPropertyFix.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,7 +39,7 @@ import org.jetbrains.annotations.Nullable; */ public abstract class CreateBeanPropertyFix implements LocalQuickFix, IntentionAction { - private final static Logger LOG = Logger.getInstance("#com.intellij.psi.impl.beanProperties.CreateBeanPropertyFix"); + private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.beanProperties.CreateBeanPropertyFix"); private static final CreateBeanPropertyFix[] NO_FIXES = new CreateBeanPropertyFix[0]; protected final String myPropertyName; diff --git a/java/java-impl/src/com/intellij/psi/impl/file/PsiJavaDirectoryFactory.java b/java/java-impl/src/com/intellij/psi/impl/file/PsiJavaDirectoryFactory.java index e92396e00a2f..83761827f52d 100644 --- a/java/java-impl/src/com/intellij/psi/impl/file/PsiJavaDirectoryFactory.java +++ b/java/java-impl/src/com/intellij/psi/impl/file/PsiJavaDirectoryFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,7 +48,7 @@ public class PsiJavaDirectoryFactory extends PsiDirectoryFactory { final PsiPackage aPackage = JavaDirectoryService.getInstance().getPackage(directory); if (aPackage != null) { final String qualifiedName = aPackage.getQualifiedName(); - if (qualifiedName.length() > 0) return qualifiedName; + if (!qualifiedName.isEmpty()) return qualifiedName; if (presentable) { return PsiBundle.message("default.package.presentation") + " (" + directory.getVirtualFile().getPresentableUrl() + ")"; } diff --git a/java/java-impl/src/com/intellij/psi/impl/light/LightMethodBuilder.java b/java/java-impl/src/com/intellij/psi/impl/light/LightMethodBuilder.java index 70e7b8415990..d568db62854f 100644 --- a/java/java-impl/src/com/intellij/psi/impl/light/LightMethodBuilder.java +++ b/java/java-impl/src/com/intellij/psi/impl/light/LightMethodBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2012 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -46,9 +46,9 @@ public class LightMethodBuilder extends LightElement implements PsiMethod, Origi private final String myName; private Computable<PsiType> myReturnType; private final PsiModifierList myModifierList; - private PsiParameterList myParameterList; - private PsiTypeParameterList myTypeParameterList; - private PsiReferenceList myThrowsList; + private final PsiParameterList myParameterList; + private final PsiTypeParameterList myTypeParameterList; + private final PsiReferenceList myThrowsList; private Icon myBaseIcon; private PsiClass myContainingClass; private boolean myConstructor; diff --git a/java/java-impl/src/com/intellij/psi/impl/search/AnnotatedPackagesSearcher.java b/java/java-impl/src/com/intellij/psi/impl/search/AnnotatedPackagesSearcher.java index c1b65eccdccf..8e52d775a846 100644 --- a/java/java-impl/src/com/intellij/psi/impl/search/AnnotatedPackagesSearcher.java +++ b/java/java-impl/src/com/intellij/psi/impl/search/AnnotatedPackagesSearcher.java @@ -86,7 +86,7 @@ public class AnnotatedPackagesSearcher implements QueryExecutor<PsiPackage, Anno GlobalSearchScope infoFiles = useScope instanceof GlobalSearchScope ? ((GlobalSearchScope)useScope).intersectWith(infoFilesFilter) : infoFilesFilter; - final boolean[] wantmore = new boolean[]{true}; + final boolean[] wantmore = {true}; helper.processAllFilesWithWord(annotationShortName, infoFiles, new Processor<PsiFile>() { @Override public boolean process(final PsiFile psiFile) { diff --git a/java/java-impl/src/com/intellij/psi/impl/search/JavaIndexPatternBuilder.java b/java/java-impl/src/com/intellij/psi/impl/search/JavaIndexPatternBuilder.java index f404c401ae6f..50005842b25e 100644 --- a/java/java-impl/src/com/intellij/psi/impl/search/JavaIndexPatternBuilder.java +++ b/java/java-impl/src/com/intellij/psi/impl/search/JavaIndexPatternBuilder.java @@ -32,7 +32,7 @@ import org.jetbrains.annotations.Nullable; */ public class JavaIndexPatternBuilder implements IndexPatternBuilder { public static final TokenSet XML_DATA_CHARS = TokenSet.create(XmlTokenType.XML_DATA_CHARACTERS); - public static final TokenSet XML_COMMENT_BIT_SET = TokenSet.create(XmlElementType.XML_COMMENT_CHARACTERS); + public static final TokenSet XML_COMMENT_BIT_SET = TokenSet.create(XmlTokenType.XML_COMMENT_CHARACTERS); @Override @Nullable diff --git a/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/ImportsFormatter.java b/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/ImportsFormatter.java index aaf5f98540e2..4e81caef937b 100644 --- a/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/ImportsFormatter.java +++ b/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/ImportsFormatter.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,8 +39,8 @@ public class ImportsFormatter extends XmlRecursiveElementVisitor { private final FormattingDocumentModelImpl myDocumentModel; private final CommonCodeStyleSettings.IndentOptions myIndentOptions; - private static final @NonNls String PAGE_DIRECTIVE = "page"; - private static final @NonNls String IMPORT_ATT = "import"; + @NonNls private static final String PAGE_DIRECTIVE = "page"; + @NonNls private static final String IMPORT_ATT = "import"; private final PostFormatProcessorHelper myPostProcessor; @@ -134,7 +134,7 @@ public class ImportsFormatter extends XmlRecursiveElementVisitor { private static ASTNode findValueToken(final ASTNode node) { ASTNode child = node.getFirstChildNode(); while (child != null){ - if (child.getElementType() == XmlElementType.XML_ATTRIBUTE_VALUE_TOKEN) return child; + if (child.getElementType() == XmlTokenType.XML_ATTRIBUTE_VALUE_TOKEN) return child; child = child.getTreeNext(); } return null; diff --git a/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/JavaCodeStyleManagerImpl.java b/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/JavaCodeStyleManagerImpl.java index 7c257dd8c83a..3056eccd9291 100644 --- a/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/JavaCodeStyleManagerImpl.java +++ b/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/JavaCodeStyleManagerImpl.java @@ -779,7 +779,7 @@ public class JavaCodeStyleManagerImpl extends JavaCodeStyleManager { String prefix = getPrefixByVariableKind(variableKind); String name = propertyName; - if (name.length() > 0 && prefix.length() > 0 && !StringUtil.endsWithChar(prefix, '_')) { + if (!name.isEmpty() && !prefix.isEmpty() && !StringUtil.endsWithChar(prefix, '_')) { name = Character.toUpperCase(name.charAt(0)) + name.substring(1); } name = prefix + name + getSuffixByVariableKind(variableKind); diff --git a/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/PsiBasedFormatterModelWithShiftIndentInside.java b/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/PsiBasedFormatterModelWithShiftIndentInside.java index 2eb7c78ca525..9782b5630500 100644 --- a/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/PsiBasedFormatterModelWithShiftIndentInside.java +++ b/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/PsiBasedFormatterModelWithShiftIndentInside.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,6 +35,7 @@ import com.intellij.psi.formatter.PsiBasedFormattingModel; import com.intellij.psi.impl.source.tree.TreeUtil; import com.intellij.psi.tree.IElementType; import com.intellij.psi.xml.XmlElementType; +import com.intellij.psi.xml.XmlTokenType; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; @@ -84,7 +85,7 @@ public class PsiBasedFormatterModelWithShiftIndentInside extends PsiBasedFormatt if(type == TokenType.WHITE_SPACE) { final String text = prevNode.getText(); - final @NonNls String cdataStartMarker = "<![CDATA["; + @NonNls final String cdataStartMarker = "<![CDATA["; final int cdataPos = text.indexOf(cdataStartMarker); if (cdataPos != -1 && whiteSpace.indexOf(cdataStartMarker) == -1) { whiteSpace = DocumentBasedFormattingModel.mergeWsWithCdataMarker(whiteSpace, text, cdataPos); @@ -95,8 +96,8 @@ public class PsiBasedFormatterModelWithShiftIndentInside extends PsiBasedFormatt type = prevNode != null ? prevNode.getElementType():null; } - final @NonNls String cdataEndMarker = "]]>"; - if(type == XmlElementType.XML_CDATA_END && whiteSpace.indexOf(cdataEndMarker) == -1) { + @NonNls final String cdataEndMarker = "]]>"; + if(type == XmlTokenType.XML_CDATA_END && whiteSpace.indexOf(cdataEndMarker) == -1) { final ASTNode at = findElementAt(prevNode.getStartOffset()); if (at != null && at.getPsi() instanceof PsiWhiteSpace) { diff --git a/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/ShiftIndentInsideHelper.java b/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/ShiftIndentInsideHelper.java index f975f622407e..158e8b60cd2d 100644 --- a/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/ShiftIndentInsideHelper.java +++ b/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/ShiftIndentInsideHelper.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -113,7 +113,7 @@ public class ShiftIndentInsideHelper { leafOffset = getStartOffset(element, leaf); } else { - if (newSpace.length() > 0) { + if (!newSpace.isEmpty()) { LeafElement newLeaf = ASTFactory.whitespace(newSpace); next.getTreeParent().addChild(newLeaf, next); } @@ -129,7 +129,7 @@ public class ShiftIndentInsideHelper { } String leafText = leaf.getText(); String newLeafText = leafText.substring(0, startOffset) + newSpace + leafText.substring(endOffset); - if (newLeafText.length() > 0) { + if (!newLeafText.isEmpty()) { LeafElement newLeaf = Factory.createSingleLeafElement(leaf.getElementType(), newLeafText,charTableByTree, SharedImplUtil.getManagerByTree(leaf)); if (leaf.getTreeParent() != null) { leaf.getTreeParent().replaceChild(leaf, newLeaf); diff --git a/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/javadoc/JDComment.java b/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/javadoc/JDComment.java index 740b77cb2228..0d51c0d2111f 100644 --- a/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/javadoc/JDComment.java +++ b/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/javadoc/JDComment.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,11 +43,11 @@ public class JDComment { } protected static boolean isNull(@Nullable String s) { - return s == null || s.trim().length() == 0; + return s == null || s.trim().isEmpty(); } protected static boolean isNull(@Nullable List<?> l) { - return l == null || l.size() == 0; + return l == null || l.isEmpty(); } public void setMultiLine(boolean value) { diff --git a/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/javadoc/JDMethodComment.java b/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/javadoc/JDMethodComment.java index 0059b2f1274f..e541b0714c5b 100644 --- a/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/javadoc/JDMethodComment.java +++ b/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/javadoc/JDMethodComment.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,7 +39,7 @@ public class JDMethodComment extends JDParamListOwnerComment { super.generateSpecial(prefix, sb); if (myReturnTag != null) { - if (myFormatter.getSettings().JD_KEEP_EMPTY_RETURN || myReturnTag.trim().length() != 0) { + if (myFormatter.getSettings().JD_KEEP_EMPTY_RETURN || !myReturnTag.trim().isEmpty()) { JDTag tag = JDTag.RETURN; sb.append(prefix); sb.append(tag.getWithEndWhitespace()); diff --git a/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/javadoc/JDParser.java b/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/javadoc/JDParser.java index 7220876dc0e9..05e359137e72 100644 --- a/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/javadoc/JDParser.java +++ b/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/javadoc/JDParser.java @@ -73,7 +73,7 @@ public class JDParser { for (int i = 0; i < size; i++) { String line = l.get(i); line = line.trim(); - if (line.length() > 0) { + if (!line.isEmpty()) { if (line.charAt(0) == '*') { if ((markers.get(i)).booleanValue()) { if (line.length() > 1 && line.charAt(1) == ' ') { @@ -95,7 +95,7 @@ public class JDParser { String tag = null; for (int i = 0; i <= size; i++) { String line = i == size ? null : l.get(i); - if (i == size || line.length() > 0) { + if (i == size || !line.isEmpty()) { if (i == size || line.charAt(0) == '@') { if (tag == null) { comment.setDescription(sb.toString()); @@ -157,7 +157,7 @@ public class JDParser { private List<String> toArray(@Nullable String s, @NotNull String separators, @Nullable List<Boolean> markers) { if (s == null) return null; s = s.trim(); - if (s.length() == 0) return null; + if (s.isEmpty()) return null; boolean p2nl = markers != null && mySettings.JD_P_AT_EMPTY_LINES; List<String> list = new ArrayList<String>(); StringTokenizer st = new StringTokenizer(s, separators, true); @@ -232,7 +232,7 @@ public class JDParser { String seq = pair.getFirst(); boolean isMarked = pair.getSecond(); - if (seq.length() == 0) { + if (seq.isEmpty()) { // keep empty lines list.add(""); continue; @@ -514,9 +514,9 @@ public class JDParser { boolean insidePreTag = false; for (int i = 0; i < list.size(); i++) { String line = list.get(i); - if (line.length() == 0 && !mySettings.JD_KEEP_EMPTY_LINES) continue; + if (line.isEmpty() && !mySettings.JD_KEEP_EMPTY_LINES) continue; if (i != 0) sb.append(prefix); - if (line.length() == 0 && mySettings.JD_P_AT_EMPTY_LINES && !insidePreTag) { + if (line.isEmpty() && mySettings.JD_P_AT_EMPTY_LINES && !insidePreTag) { if (myLanguageLevel.isAtLeast(LanguageLevel.JDK_1_8)) { //Self-closing elements are not allowed for javadoc tool from JDK8 sb.append(P_START_TAG); diff --git a/java/java-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/FilePathReferenceProvider.java b/java/java-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/FilePathReferenceProvider.java index c23cf728f500..4ca7694dfd5b 100644 --- a/java/java-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/FilePathReferenceProvider.java +++ b/java/java-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/FilePathReferenceProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -53,7 +53,7 @@ public class FilePathReferenceProvider extends PsiReferenceProvider { String text, int offset, final boolean soft, - final @NotNull Module... forModules) { + @NotNull final Module... forModules) { return new FileReferenceSet(text, element, offset, this, true, myEndingSlashNotAllowed) { @@ -75,7 +75,7 @@ public class FilePathReferenceProvider extends PsiReferenceProvider { @Override public boolean absoluteUrlNeedsStartSlash() { final String s = getPathString(); - return s != null && s.length() > 0 && s.charAt(0) == '/'; + return s != null && !s.isEmpty() && s.charAt(0) == '/'; } @Override diff --git a/java/java-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/JavaClassReference.java b/java/java-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/JavaClassReference.java index c4024838e8af..5e4e42e66410 100644 --- a/java/java-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/JavaClassReference.java +++ b/java/java-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/JavaClassReference.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2011 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -518,7 +518,6 @@ public class JavaClassReference extends GenericReference implements PsiJavaRefer return list; } - @NotNull public void processSubclassVariants(@NotNull PsiPackage context, @NotNull String[] extendClasses, Consumer<LookupElement> result) { GlobalSearchScope packageScope = PackageScope.packageScope(context, true); GlobalSearchScope scope = myJavaClassReferenceSet.getProvider().getScope(getElement().getProject()); diff --git a/java/java-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/JavaClassReferenceProvider.java b/java/java-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/JavaClassReferenceProvider.java index ebc7ec1de80c..6e9e92dc4ff9 100644 --- a/java/java-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/JavaClassReferenceProvider.java +++ b/java/java-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/JavaClassReferenceProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -61,7 +61,7 @@ public class JavaClassReferenceProvider extends GenericReferenceProvider impleme private boolean myAllowEmpty; - private ParameterizedCachedValueProvider<List<PsiElement>, Project> myProvider = new ParameterizedCachedValueProvider<List<PsiElement>, Project>() { + private final ParameterizedCachedValueProvider<List<PsiElement>, Project> myProvider = new ParameterizedCachedValueProvider<List<PsiElement>, Project>() { @Override public CachedValueProvider.Result<List<PsiElement>> compute(Project project) { final List<PsiElement> psiPackages = new ArrayList<PsiElement>(); diff --git a/java/java-impl/src/com/intellij/psi/impl/source/tree/injected/MyTestInjector.java b/java/java-impl/src/com/intellij/psi/impl/source/tree/injected/MyTestInjector.java index 2876f7611a15..5139b49efc16 100644 --- a/java/java-impl/src/com/intellij/psi/impl/source/tree/injected/MyTestInjector.java +++ b/java/java-impl/src/com/intellij/psi/impl/source/tree/injected/MyTestInjector.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -293,7 +293,7 @@ public class MyTestInjector { if (!method.hasModifierProperty(PsiModifier.NATIVE) || !method.hasModifierProperty(PsiModifier.PUBLIC)) return; String paramList = ""; for (PsiParameter parameter : method.getParameterList().getParameters()) { - if (paramList.length()!=0) paramList += ","; + if (!paramList.isEmpty()) paramList += ","; paramList += parameter.getName(); } @NonNls String header = "function " + method.getName() + "("+paramList+") {"; diff --git a/java/java-impl/src/com/intellij/psi/search/scope/packageSet/PatternPackageSetParserExtension.java b/java/java-impl/src/com/intellij/psi/search/scope/packageSet/PatternPackageSetParserExtension.java index d009798075b2..0b46bfee4f0f 100644 --- a/java/java-impl/src/com/intellij/psi/search/scope/packageSet/PatternPackageSetParserExtension.java +++ b/java/java-impl/src/com/intellij/psi/search/scope/packageSet/PatternPackageSetParserExtension.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -54,7 +54,7 @@ public class PatternPackageSetParserExtension implements PackageSetParserExtensi scope = PatternPackageSet.SCOPE_PROBLEM; } else if (PatternPackageSet.SCOPE_LIBRARY.equals(id)) { scope = PatternPackageSet.SCOPE_LIBRARY; - } else if (id.trim().length() > 0) { + } else if (!id.trim().isEmpty()) { scope = null; } final CharSequence buf = lexer.getBufferSequence(); diff --git a/java/java-impl/src/com/intellij/refactoring/introduceparameterobject/IntroduceParameterObjectUsageViewDescriptor.java b/java/java-impl/src/com/intellij/refactoring/introduceparameterobject/IntroduceParameterObjectUsageViewDescriptor.java index 31e8fd0b4646..87dc870bebe8 100644 --- a/java/java-impl/src/com/intellij/refactoring/introduceparameterobject/IntroduceParameterObjectUsageViewDescriptor.java +++ b/java/java-impl/src/com/intellij/refactoring/introduceparameterobject/IntroduceParameterObjectUsageViewDescriptor.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,6 +20,7 @@ import com.intellij.psi.PsiMethod; import com.intellij.refactoring.RefactorJBundle; import com.intellij.refactoring.psi.MyUsageViewUtil; import com.intellij.refactoring.ui.UsageViewDescriptorAdapter; +import org.jetbrains.annotations.NotNull; class IntroduceParameterObjectUsageViewDescriptor extends UsageViewDescriptorAdapter { @@ -30,6 +31,7 @@ class IntroduceParameterObjectUsageViewDescriptor extends UsageViewDescriptorAda this.method = method; } + @NotNull public PsiElement[] getElements() { return new PsiElement[]{method}; } diff --git a/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/JavaMoveClassesOrPackagesHandler.java b/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/JavaMoveClassesOrPackagesHandler.java index 905e3713197c..8719d9a45209 100644 --- a/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/JavaMoveClassesOrPackagesHandler.java +++ b/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/JavaMoveClassesOrPackagesHandler.java @@ -43,6 +43,7 @@ import com.intellij.refactoring.util.RadioUpDownListener; import com.intellij.refactoring.util.RefactoringUtil; import com.intellij.util.IncorrectOperationException; import com.intellij.util.containers.HashSet; +import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; @@ -138,12 +139,19 @@ public class JavaMoveClassesOrPackagesHandler extends MoveHandlerDelegate { if (targetContainer instanceof PsiDirectory) { if (CommonRefactoringUtil.checkReadOnlyStatusRecursively(project, Arrays.asList(adjustedElements), true)) { if (!packageHasMultipleDirectoriesInModule(project, (PsiDirectory)targetContainer)) { - new MoveClassesOrPackagesToNewDirectoryDialog((PsiDirectory)targetContainer, adjustedElements, callback).show(); + createMoveClassesOrPackagesToNewDirectoryDialog((PsiDirectory)targetContainer, adjustedElements, callback).show(); return; } } } - MoveClassesOrPackagesImpl.doMove(project, adjustedElements, targetContainer, callback); + doMoveWithMoveClassesDialog(project, adjustedElements, targetContainer, callback); + } + + protected void doMoveWithMoveClassesDialog(final Project project, + PsiElement[] adjustedElements, + PsiElement initialTargetElement, + final MoveCallback moveCallback) { + MoveClassesOrPackagesImpl.doMove(project, adjustedElements, initialTargetElement, moveCallback); } private static void moveDirectoriesLibrariesSafe(Project project, @@ -173,6 +181,13 @@ public class JavaMoveClassesOrPackagesHandler extends MoveHandlerDelegate { } } + @NotNull + protected DialogWrapper createMoveClassesOrPackagesToNewDirectoryDialog(@NotNull final PsiDirectory directory, + PsiElement[] elementsToMove, + final MoveCallback moveCallback) { + return new MoveClassesOrPackagesToNewDirectoryDialog(directory, elementsToMove, moveCallback); + } + private static void moveAsDirectory(Project project, PsiElement targetContainer, final MoveCallback callback, @@ -445,7 +460,7 @@ public class JavaMoveClassesOrPackagesHandler extends MoveHandlerDelegate { if (adjustedElements == null) { return true; } - MoveClassesOrPackagesImpl.doMove(project, adjustedElements, initialTargetElement, null); + doMoveWithMoveClassesDialog(project, adjustedElements, initialTargetElement, null); return true; } return false; diff --git a/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/MoveClassesOrPackagesToNewDirectoryDialog.java b/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/MoveClassesOrPackagesToNewDirectoryDialog.java index 4d1792cb9ee3..de16039b99b2 100644 --- a/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/MoveClassesOrPackagesToNewDirectoryDialog.java +++ b/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/MoveClassesOrPackagesToNewDirectoryDialog.java @@ -191,6 +191,19 @@ public class MoveClassesOrPackagesToNewDirectoryDialog extends DialogWrapper { return myDestDirectoryField.getTextField(); } + //for scala plugin + @NotNull + protected MoveClassesOrPackagesProcessor createMoveClassesOrPackagesProcessor(Project project, + PsiElement[] elements, + @NotNull final MoveDestination moveDestination, + boolean searchInComments, + boolean searchInNonJavaFiles, + MoveCallback moveCallback) { + + return new MoveClassesOrPackagesProcessor(project, elements, moveDestination, + searchInComments, searchInNonJavaFiles, moveCallback); + } + protected void performRefactoring(Project project, PsiDirectory directory, PsiPackage aPackage, boolean searchInComments, boolean searchForTextOccurences) { @@ -205,9 +218,9 @@ public class MoveClassesOrPackagesToNewDirectoryDialog extends DialogWrapper { ? factory.createSourceFolderPreservingMoveDestination(aPackage.getQualifiedName()) : factory.createSourceRootMoveDestination(aPackage.getQualifiedName(), sourceRoot); - MoveClassesOrPackagesProcessor processor = new MoveClassesOrPackagesProcessor(myDirectory.getProject(), myElementsToMove, destination, - searchInComments, searchForTextOccurences, - myMoveCallback); + MoveClassesOrPackagesProcessor processor = createMoveClassesOrPackagesProcessor(myDirectory.getProject(), myElementsToMove, destination, + searchInComments, searchForTextOccurences, myMoveCallback); + if (processor.verifyValidPackageName()) { processor.setPrepareSuccessfulSwingThreadCallback(new Runnable() { @Override diff --git a/java/java-impl/src/com/intellij/refactoring/removemiddleman/RemoveMiddlemanUsageViewDescriptor.java b/java/java-impl/src/com/intellij/refactoring/removemiddleman/RemoveMiddlemanUsageViewDescriptor.java index 4874b64f5ff7..c3bc67e81771 100644 --- a/java/java-impl/src/com/intellij/refactoring/removemiddleman/RemoveMiddlemanUsageViewDescriptor.java +++ b/java/java-impl/src/com/intellij/refactoring/removemiddleman/RemoveMiddlemanUsageViewDescriptor.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,6 +39,7 @@ class RemoveMiddlemanUsageViewDescriptor implements UsageViewDescriptor { return RefactorJBundle.message("remove.middleman.field.header"); } + @NotNull public PsiElement[] getElements() { return new PsiElement[]{field}; } diff --git a/java/java-impl/src/com/intellij/refactoring/wrapreturnvalue/WrapReturnValueUsageViewDescriptor.java b/java/java-impl/src/com/intellij/refactoring/wrapreturnvalue/WrapReturnValueUsageViewDescriptor.java index 7ee4cfb3329a..409f50fd504e 100644 --- a/java/java-impl/src/com/intellij/refactoring/wrapreturnvalue/WrapReturnValueUsageViewDescriptor.java +++ b/java/java-impl/src/com/intellij/refactoring/wrapreturnvalue/WrapReturnValueUsageViewDescriptor.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,6 +34,7 @@ class WrapReturnValueUsageViewDescriptor implements UsageViewDescriptor { this.method = method; } + @NotNull public PsiElement[] getElements(){ return new PsiElement[]{method}; } diff --git a/java/java-impl/src/com/intellij/testIntegration/createTest/CreateTestDialog.java b/java/java-impl/src/com/intellij/testIntegration/createTest/CreateTestDialog.java index 1185d60a7971..fe2b896499b3 100644 --- a/java/java-impl/src/com/intellij/testIntegration/createTest/CreateTestDialog.java +++ b/java/java-impl/src/com/intellij/testIntegration/createTest/CreateTestDialog.java @@ -40,6 +40,7 @@ import com.intellij.openapi.roots.ModuleRootManager; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.Pair; +import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; import com.intellij.refactoring.PackageWrapper; @@ -215,13 +216,47 @@ public class CreateTestDialog extends DialogWrapper { updateMethodsTable(); } + private boolean isSuperclassSelectedManually() { + String superClass = mySuperClassField.getText(); + if (StringUtil.isEmptyOrSpaces(superClass)) { + return false; + } + + for (TestFramework framework : TestFramework.EXTENSION_NAME.getExtensions()) { + if (superClass.equals(framework.getDefaultSuperClass())) { + return false; + } + } + + return true; + } + private void onLibrarySelected(TestFramework descriptor) { - String text = CodeInsightBundle.message("intention.create.test.dialog.library.not.found", descriptor.getName()); - myFixLibraryLabel.setText(text); - myFixLibraryPanel.setVisible(!descriptor.isLibraryAttached(myTargetModule)); + if (descriptor.isLibraryAttached(myTargetModule)) { + myFixLibraryPanel.setVisible(false); + } + else { + myFixLibraryPanel.setVisible(true); + String text = CodeInsightBundle.message("intention.create.test.dialog.library.not.found", descriptor.getName()); + myFixLibraryLabel.setText(text); + + myFixLibraryButton.setVisible(descriptor.getLibraryPath() != null); + } String superClass = descriptor.getDefaultSuperClass(); - mySuperClassField.appendItem(superClass == null ? "" : superClass); + + if (isSuperclassSelectedManually()) { + if (superClass != null) { + String currentSuperClass = mySuperClassField.getText(); + mySuperClassField.appendItem(superClass); + mySuperClassField.setText(currentSuperClass); + } + } + else { + mySuperClassField.appendItem(StringUtil.notNullize(superClass)); + mySuperClassField.getChildComponent().setSelectedItem(StringUtil.notNullize(superClass)); + } + mySelectedFramework = descriptor; } @@ -524,7 +559,10 @@ public class CreateTestDialog extends DialogWrapper { dialog.showDialog(); PsiClass aClass = dialog.getSelected(); if (aClass != null) { - mySuperClassField.setText(aClass.getQualifiedName()); + String superClass = aClass.getQualifiedName(); + + mySuperClassField.appendItem(superClass); + mySuperClassField.getChildComponent().setSelectedItem(superClass); } } } diff --git a/java/java-impl/src/com/intellij/usageView/JavaUsageViewDescriptionProvider.java b/java/java-impl/src/com/intellij/usageView/JavaUsageViewDescriptionProvider.java index c31d9a5f5aaf..76b4e50f1680 100644 --- a/java/java-impl/src/com/intellij/usageView/JavaUsageViewDescriptionProvider.java +++ b/java/java-impl/src/com/intellij/usageView/JavaUsageViewDescriptionProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,12 +18,14 @@ package com.intellij.usageView; import com.intellij.psi.*; import com.intellij.psi.util.PsiFormatUtil; import com.intellij.lang.LangBundle; +import com.intellij.psi.util.PsiFormatUtilBase; import org.jetbrains.annotations.NotNull; /** * @author yole */ public class JavaUsageViewDescriptionProvider implements ElementDescriptionProvider { + @Override public String getElementDescription(@NotNull final PsiElement element, @NotNull final ElementDescriptionLocation location) { if (location instanceof UsageViewShortNameLocation) { if (element instanceof PsiThrowStatement) { @@ -53,7 +55,7 @@ public class JavaUsageViewDescriptionProvider implements ElementDescriptionProvi else if (element instanceof PsiMethod) { PsiMethod psiMethod = (PsiMethod)element; return PsiFormatUtil.formatMethod(psiMethod, PsiSubstitutor.EMPTY, - PsiFormatUtil.SHOW_NAME | PsiFormatUtil.SHOW_PARAMETERS, PsiFormatUtil.SHOW_TYPE); + PsiFormatUtilBase.SHOW_NAME | PsiFormatUtilBase.SHOW_PARAMETERS, PsiFormatUtilBase.SHOW_TYPE); } } diff --git a/java/java-impl/src/com/intellij/usages/impl/rules/ClassGroupingRule.java b/java/java-impl/src/com/intellij/usages/impl/rules/ClassGroupingRule.java index 3f4864ef6ffd..4dc906ea9d3e 100644 --- a/java/java-impl/src/com/intellij/usages/impl/rules/ClassGroupingRule.java +++ b/java/java-impl/src/com/intellij/usages/impl/rules/ClassGroupingRule.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,7 +20,6 @@ import com.intellij.navigation.NavigationItemFileStatus; import com.intellij.openapi.actionSystem.CommonDataKeys; import com.intellij.openapi.actionSystem.DataKey; import com.intellij.openapi.actionSystem.DataSink; -import com.intellij.openapi.actionSystem.LangDataKeys; import com.intellij.openapi.actionSystem.TypeSafeDataProvider; import com.intellij.openapi.util.Iconable; import com.intellij.openapi.vcs.FileStatus; @@ -181,7 +180,7 @@ public class ClassGroupingRule implements UsageGroupingRule { } @Override - public int compareTo(UsageGroup usageGroup) { + public int compareTo(@NotNull UsageGroup usageGroup) { return getText(null).compareToIgnoreCase(usageGroup.getText(null)); } diff --git a/java/java-impl/src/com/intellij/usages/impl/rules/ImportFilteringRule.java b/java/java-impl/src/com/intellij/usages/impl/rules/ImportFilteringRule.java index f3ecf42415e9..ce6ce08d4293 100644 --- a/java/java-impl/src/com/intellij/usages/impl/rules/ImportFilteringRule.java +++ b/java/java-impl/src/com/intellij/usages/impl/rules/ImportFilteringRule.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2010 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,6 +29,7 @@ import org.jetbrains.annotations.NotNull; * Date: Jan 17, 2005 */ public class ImportFilteringRule extends com.intellij.usages.rules.ImportFilteringRule { + @Override public boolean isVisible(@NotNull Usage usage) { if (usage instanceof PsiElementUsage) { final PsiElement psiElement = ((PsiElementUsage)usage).getElement(); diff --git a/java/java-impl/src/com/intellij/usages/impl/rules/JavaClassGroupRuleProvider.java b/java/java-impl/src/com/intellij/usages/impl/rules/JavaClassGroupRuleProvider.java index bf8561c9913a..82b156c59385 100644 --- a/java/java-impl/src/com/intellij/usages/impl/rules/JavaClassGroupRuleProvider.java +++ b/java/java-impl/src/com/intellij/usages/impl/rules/JavaClassGroupRuleProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,6 +23,7 @@ import com.intellij.openapi.project.Project; * @author yole */ public class JavaClassGroupRuleProvider implements FileStructureGroupRuleProvider { + @Override public UsageGroupingRule getUsageGroupingRule(final Project project) { return new ClassGroupingRule(); } diff --git a/java/java-impl/src/com/intellij/usages/impl/rules/JavaMethodGroupRuleProvider.java b/java/java-impl/src/com/intellij/usages/impl/rules/JavaMethodGroupRuleProvider.java index 3ed6d3dafaa8..6ab324fcaa9c 100644 --- a/java/java-impl/src/com/intellij/usages/impl/rules/JavaMethodGroupRuleProvider.java +++ b/java/java-impl/src/com/intellij/usages/impl/rules/JavaMethodGroupRuleProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,6 +23,7 @@ import com.intellij.openapi.project.Project; * @author yole */ public class JavaMethodGroupRuleProvider implements FileStructureGroupRuleProvider { + @Override public UsageGroupingRule getUsageGroupingRule(final Project project) { return new MethodGroupingRule(); } diff --git a/java/java-impl/src/com/intellij/usages/impl/rules/JavaUsageTypeProvider.java b/java/java-impl/src/com/intellij/usages/impl/rules/JavaUsageTypeProvider.java index 7cdf805178d0..445a8aab14a2 100644 --- a/java/java-impl/src/com/intellij/usages/impl/rules/JavaUsageTypeProvider.java +++ b/java/java-impl/src/com/intellij/usages/impl/rules/JavaUsageTypeProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,6 +35,7 @@ import java.util.Set; * @author yole */ public class JavaUsageTypeProvider implements UsageTypeProviderEx { + @Override public UsageType getUsageType(final PsiElement element) { return getUsageType(element, UsageTarget.EMPTY_ARRAY); } diff --git a/java/java-impl/src/com/intellij/usages/impl/rules/MethodGroupingRule.java b/java/java-impl/src/com/intellij/usages/impl/rules/MethodGroupingRule.java index 4eaa3cccd850..496703dd354f 100644 --- a/java/java-impl/src/com/intellij/usages/impl/rules/MethodGroupingRule.java +++ b/java/java-impl/src/com/intellij/usages/impl/rules/MethodGroupingRule.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2011 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,7 +20,6 @@ import com.intellij.navigation.NavigationItemFileStatus; import com.intellij.openapi.actionSystem.CommonDataKeys; import com.intellij.openapi.actionSystem.DataKey; import com.intellij.openapi.actionSystem.DataSink; -import com.intellij.openapi.actionSystem.LangDataKeys; import com.intellij.openapi.actionSystem.TypeSafeDataProvider; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; @@ -159,7 +158,7 @@ public class MethodGroupingRule implements UsageGroupingRule { } @Override - public int compareTo(UsageGroup usageGroup) { + public int compareTo(@NotNull UsageGroup usageGroup) { if (!(usageGroup instanceof MethodUsageGroup)) { LOG.error("MethodUsageGroup expected but " + usageGroup.getClass() + " found"); } diff --git a/java/java-impl/src/com/intellij/usages/impl/rules/NonJavaFileGroupRuleProvider.java b/java/java-impl/src/com/intellij/usages/impl/rules/NonJavaFileGroupRuleProvider.java index 5b56f973985a..41ccee880de4 100644 --- a/java/java-impl/src/com/intellij/usages/impl/rules/NonJavaFileGroupRuleProvider.java +++ b/java/java-impl/src/com/intellij/usages/impl/rules/NonJavaFileGroupRuleProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,6 +23,7 @@ import com.intellij.openapi.project.Project; * @author yole */ public class NonJavaFileGroupRuleProvider implements FileStructureGroupRuleProvider { + @Override public UsageGroupingRule getUsageGroupingRule(final Project project) { return new NonJavaFileGroupingRule(project); } diff --git a/java/java-impl/src/com/intellij/usages/impl/rules/PackageGroupingRule.java b/java/java-impl/src/com/intellij/usages/impl/rules/PackageGroupingRule.java index 510ae816a14a..960e6180a7c7 100644 --- a/java/java-impl/src/com/intellij/usages/impl/rules/PackageGroupingRule.java +++ b/java/java-impl/src/com/intellij/usages/impl/rules/PackageGroupingRule.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,7 +18,6 @@ package com.intellij.usages.impl.rules; import com.intellij.openapi.actionSystem.CommonDataKeys; import com.intellij.openapi.actionSystem.DataKey; import com.intellij.openapi.actionSystem.DataSink; -import com.intellij.openapi.actionSystem.LangDataKeys; import com.intellij.openapi.actionSystem.TypeSafeDataProvider; import com.intellij.openapi.project.Project; import com.intellij.openapi.vcs.FileStatus; @@ -42,6 +41,7 @@ public class PackageGroupingRule extends DirectoryGroupingRule { super(project); } + @Override protected UsageGroup getGroupForFile(final VirtualFile dir) { PsiDirectory psiDirectory = PsiManager.getInstance(myProject).findDirectory(dir); if (psiDirectory != null) { @@ -60,44 +60,53 @@ public class PackageGroupingRule extends DirectoryGroupingRule { update(); } + @Override public void update() { if (isValid()) { myIcon = myPackage.getIcon(0); } } + @Override public Icon getIcon(boolean isOpen) { return myIcon; } + @Override @NotNull public String getText(UsageView view) { return myPackage.getQualifiedName(); } + @Override public FileStatus getFileStatus() { if (!isValid()) return null; PsiDirectory[] dirs = myPackage.getDirectories(); return dirs.length == 1 ? FileStatusManager.getInstance(myProject).getStatus(dirs[0].getVirtualFile()) : null; } + @Override public boolean isValid() { return myPackage.isValid(); } + @Override public void navigate(boolean focus) throws UnsupportedOperationException { myPackage.navigate(focus); } + @Override public boolean canNavigate() { return myPackage.canNavigate(); } + @Override public boolean canNavigateToSource() { return false; } - public int compareTo(UsageGroup usageGroup) { + @Override + public int compareTo(@NotNull UsageGroup usageGroup) { return getText(null).compareToIgnoreCase(usageGroup.getText(null)); } @@ -112,6 +121,7 @@ public class PackageGroupingRule extends DirectoryGroupingRule { return myPackage.hashCode(); } + @Override public void calcData(final DataKey key, final DataSink sink) { if (!isValid()) return; if (CommonDataKeys.PSI_ELEMENT == key) { diff --git a/java/java-psi-api/src/com/intellij/psi/LambdaUtil.java b/java/java-psi-api/src/com/intellij/psi/LambdaUtil.java index f5980c4f8757..484460760a56 100644 --- a/java/java-psi-api/src/com/intellij/psi/LambdaUtil.java +++ b/java/java-psi-api/src/com/intellij/psi/LambdaUtil.java @@ -362,7 +362,7 @@ public class LambdaUtil { } final PsiParameter[] lambdaParams = lambdaExpression.getParameterList().getParameters(); if (lambdaParams.length != methodParameters.length) return false; - final boolean[] independent = new boolean[]{true}; + final boolean[] independent = {true}; final PsiMethod interfaceMethod = getFunctionalInterfaceMethod(functionalInterfaceType); if (interfaceMethod == null) return false; final TypeParamsChecker paramsChecker = new TypeParamsChecker(lambdaExpression); @@ -662,12 +662,12 @@ public class LambdaUtil { public static boolean isValidQualifier4InterfaceStaticMethodCall(@NotNull PsiMethod method, @NotNull PsiReferenceExpression methodReferenceExpression, - @NotNull LanguageLevel languageLevel) { + @Nullable PsiElement scope, @NotNull LanguageLevel languageLevel) { if (languageLevel.isAtLeast(LanguageLevel.JDK_1_8)) { final PsiExpression qualifierExpression = methodReferenceExpression.getQualifierExpression(); final PsiClass containingClass = method.getContainingClass(); if (containingClass != null && containingClass.isInterface() && method.hasModifierProperty(PsiModifier.STATIC)) { - return qualifierExpression == null && PsiTreeUtil.isAncestor(containingClass, methodReferenceExpression, true)|| + return qualifierExpression == null && (scope instanceof PsiImportStaticStatement || PsiTreeUtil.isAncestor(containingClass, methodReferenceExpression, true))|| qualifierExpression instanceof PsiReferenceExpression && ((PsiReferenceExpression)qualifierExpression).resolve() == containingClass; } } diff --git a/java/java-psi-api/src/com/intellij/psi/PsiDisjunctionType.java b/java/java-psi-api/src/com/intellij/psi/PsiDisjunctionType.java index da0ecbe9d625..4b25ff574980 100644 --- a/java/java-psi-api/src/com/intellij/psi/PsiDisjunctionType.java +++ b/java/java-psi-api/src/com/intellij/psi/PsiDisjunctionType.java @@ -62,7 +62,7 @@ public class PsiDisjunctionType extends PsiType { @NotNull public static PsiType createDisjunction(@NotNull List<PsiType> types, @NotNull PsiManager psiManager) { - assert types.size() > 0; + assert !types.isEmpty(); return types.size() == 1 ? types.get(0) : new PsiDisjunctionType(types, psiManager); } diff --git a/java/java-psi-api/src/com/intellij/psi/PsiIntersectionType.java b/java/java-psi-api/src/com/intellij/psi/PsiIntersectionType.java index 5cdc217c5a98..9b0f7083f520 100644 --- a/java/java-psi-api/src/com/intellij/psi/PsiIntersectionType.java +++ b/java/java-psi-api/src/com/intellij/psi/PsiIntersectionType.java @@ -15,8 +15,10 @@ */ package com.intellij.psi; +import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.util.TypeConversionUtil; +import com.intellij.util.Function; import gnu.trove.THashSet; import org.jetbrains.annotations.NotNull; @@ -97,7 +99,12 @@ public class PsiIntersectionType extends PsiType { @Override public String getPresentableText() { - return myConjuncts[0].getPresentableText(); + return StringUtil.join(myConjuncts, new Function<PsiType, String>() { + @Override + public String fun(PsiType psiType) { + return psiType.getPresentableText(); + } + }, " & "); } @Override diff --git a/java/java-psi-api/src/com/intellij/psi/PsiMethodReferenceExpression.java b/java/java-psi-api/src/com/intellij/psi/PsiMethodReferenceExpression.java index 1df1441e2ad4..f65ee0e8bdd8 100644 --- a/java/java-psi-api/src/com/intellij/psi/PsiMethodReferenceExpression.java +++ b/java/java-psi-api/src/com/intellij/psi/PsiMethodReferenceExpression.java @@ -37,4 +37,9 @@ public interface PsiMethodReferenceExpression extends PsiReferenceExpression { PsiType getFunctionalInterfaceType(); boolean isExact(); + + /** + * @return true if reference is of form ClassType::new + */ + boolean isConstructor(); } diff --git a/java/java-psi-api/src/com/intellij/psi/PsiMethodReferenceUtil.java b/java/java-psi-api/src/com/intellij/psi/PsiMethodReferenceUtil.java index df72de732a5d..9bbb84e83020 100644 --- a/java/java-psi-api/src/com/intellij/psi/PsiMethodReferenceUtil.java +++ b/java/java-psi-api/src/com/intellij/psi/PsiMethodReferenceUtil.java @@ -131,7 +131,10 @@ public class PsiMethodReferenceUtil { if (resolve instanceof PsiClass) { containingClass = (PsiClass)resolve; substitutor = resolveResult.getSubstitutor(); - return new QualifierResolveResult(containingClass, substitutor, true); + final boolean isRawSubst = !methodReferenceExpression.isConstructor() && + PsiTreeUtil.isAncestor(containingClass, methodReferenceExpression, true) && + PsiUtil.isRawSubstitutor(containingClass, substitutor); + return new QualifierResolveResult(containingClass, isRawSubst ? PsiSubstitutor.EMPTY : substitutor, true); } } } @@ -191,7 +194,7 @@ public class PsiMethodReferenceUtil { if (resolve instanceof PsiMethod) { final MethodSignature signature1 = method.getSignature(LambdaUtil.getSubstitutor(method, resolveResult)); PsiSubstitutor subst = PsiSubstitutor.EMPTY; - subst = subst.putAll(qualifierResolveResult.getSubstitutor()); + subst = subst.putAll(TypeConversionUtil.getSuperClassSubstitutor(((PsiMethod)resolve).getContainingClass(), qualifierResolveResult.getContainingClass(), qualifierResolveResult.getSubstitutor())); subst = subst.putAll(result.getSubstitutor()); final MethodSignature signature2 = ((PsiMethod)resolve).getSignature(subst); diff --git a/java/java-psi-api/src/com/intellij/psi/util/ClassUtil.java b/java/java-psi-api/src/com/intellij/psi/util/ClassUtil.java index ef0e9cfad666..bf860cf47937 100644 --- a/java/java-psi-api/src/com/intellij/psi/util/ClassUtil.java +++ b/java/java-psi-api/src/com/intellij/psi/util/ClassUtil.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,7 +42,7 @@ public class ClassUtil { if (className == null){ return null; } - if (qualifiedName == null || qualifiedName.length() == 0){ + if (qualifiedName == null || qualifiedName.isEmpty()){ return className; } return qualifiedName + "." + extractClassName(className); @@ -120,7 +120,7 @@ public class ClassUtil { public static PsiClass findNonQualifiedClassByIndex(final String indexName, @NotNull final PsiClass containingClass, final boolean jvmCompatible) { String prefix = getDigitPrefix(indexName); - final int idx = prefix.length() > 0 ? Integer.parseInt(prefix) : -1; + final int idx = !prefix.isEmpty() ? Integer.parseInt(prefix) : -1; final String name = prefix.length() < indexName.length() ? indexName.substring(prefix.length()) : null; final PsiClass[] result = new PsiClass[1]; containingClass.accept(new JavaRecursiveElementVisitor() { diff --git a/java/java-psi-api/src/com/intellij/psi/util/TypeConversionUtil.java b/java/java-psi-api/src/com/intellij/psi/util/TypeConversionUtil.java index 51e2fdf0341f..6cb6931d0e15 100644 --- a/java/java-psi-api/src/com/intellij/psi/util/TypeConversionUtil.java +++ b/java/java-psi-api/src/com/intellij/psi/util/TypeConversionUtil.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2012 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -179,7 +179,15 @@ public class TypeConversionUtil { } return false; } - else if (toType instanceof PsiIntersectionType) return false; + else if (toType instanceof PsiIntersectionType) { + if (fromType instanceof PsiClassType && ((PsiClassType)fromType).getLanguageLevel().isAtLeast(LanguageLevel.JDK_1_8)) { + for (PsiType conjunct : ((PsiIntersectionType)toType).getConjuncts()) { + if (!isNarrowingReferenceConversionAllowed(fromType, conjunct)) return false; + } + return true; + } + return false; + } if (fromType instanceof PsiDisjunctionType) { return isNarrowingReferenceConversionAllowed(((PsiDisjunctionType)fromType).getLeastUpperBound(), toType); @@ -950,6 +958,7 @@ public class TypeConversionUtil { else { //isSuper if (rightWildcard.isSuper()) { final Boolean assignable = ourGuard.doPreventingRecursion(rightWildcard, true, new NotNullComputable<Boolean>() { + @NotNull @Override public Boolean compute() { return isAssignable(rightWildcard.getBound(), leftBound, allowUncheckedConversion); diff --git a/java/java-psi-impl/src/com/intellij/codeInsight/BaseExternalAnnotationsManager.java b/java/java-psi-impl/src/com/intellij/codeInsight/BaseExternalAnnotationsManager.java index cfd59f5e0a02..9c9b2fa2b743 100644 --- a/java/java-psi-impl/src/com/intellij/codeInsight/BaseExternalAnnotationsManager.java +++ b/java/java-psi-impl/src/com/intellij/codeInsight/BaseExternalAnnotationsManager.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2012 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,7 +28,6 @@ import com.intellij.pom.java.LanguageLevel; import com.intellij.psi.*; import com.intellij.psi.impl.source.*; import com.intellij.psi.util.PsiFormatUtil; -import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.Function; import com.intellij.util.IncorrectOperationException; import com.intellij.util.SmartList; diff --git a/java/java-psi-impl/src/com/intellij/codeInsight/highlighting/JavaHighlightUsagesDescriptionProvider.java b/java/java-psi-impl/src/com/intellij/codeInsight/highlighting/JavaHighlightUsagesDescriptionProvider.java index b09181c1a5da..765db7903e62 100644 --- a/java/java-psi-impl/src/com/intellij/codeInsight/highlighting/JavaHighlightUsagesDescriptionProvider.java +++ b/java/java-psi-impl/src/com/intellij/codeInsight/highlighting/JavaHighlightUsagesDescriptionProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,9 +15,9 @@ */ package com.intellij.codeInsight.highlighting; +import com.intellij.lang.LangBundle; import com.intellij.psi.*; import com.intellij.psi.util.PsiFormatUtil; -import com.intellij.lang.LangBundle; import com.intellij.psi.util.PsiFormatUtilBase; import org.jetbrains.annotations.NotNull; diff --git a/java/java-psi-impl/src/com/intellij/codeInsight/javadoc/JavaDocInfoGenerator.java b/java/java-psi-impl/src/com/intellij/codeInsight/javadoc/JavaDocInfoGenerator.java index 0591b8f27d47..ea5a668221af 100644 --- a/java/java-psi-impl/src/com/intellij/codeInsight/javadoc/JavaDocInfoGenerator.java +++ b/java/java-psi-impl/src/com/intellij/codeInsight/javadoc/JavaDocInfoGenerator.java @@ -1661,7 +1661,7 @@ public class JavaDocInfoGenerator { return length; } - if (type instanceof PsiDisjunctionType) { + if (type instanceof PsiDisjunctionType || type instanceof PsiIntersectionType) { if (!generateLink) { final String text = StringUtil.escapeXml(type.getCanonicalText()); buffer.append(text); @@ -1669,9 +1669,17 @@ public class JavaDocInfoGenerator { } else { int length = 0; - for (PsiType psiType : ((PsiDisjunctionType)type).getDisjunctions()) { + final String separator = type instanceof PsiDisjunctionType ? " | " : " & "; + final List<PsiType> componentTypes; + if (type instanceof PsiIntersectionType) { + componentTypes = Arrays.asList(((PsiIntersectionType)type).getConjuncts()); + } + else { + componentTypes = ((PsiDisjunctionType)type).getDisjunctions(); + } + for (PsiType psiType : componentTypes) { if (length > 0) { - buffer.append(" | "); + buffer.append(separator); length += 3; } length += generateType(buffer, psiType, context, generateLink); diff --git a/java/java-psi-impl/src/com/intellij/core/CoreJavaFileManager.java b/java/java-psi-impl/src/com/intellij/core/CoreJavaFileManager.java index dd3904097351..f769a60876ca 100644 --- a/java/java-psi-impl/src/com/intellij/core/CoreJavaFileManager.java +++ b/java/java-psi-impl/src/com/intellij/core/CoreJavaFileManager.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2011 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,7 +49,7 @@ public class CoreJavaFileManager implements JavaFileManager { @Override public PsiPackage findPackage(@NotNull String packageName) { final List<VirtualFile> files = findDirectoriesByPackageName(packageName); - if (files.size() > 0) { + if (!files.isEmpty()) { return new PsiPackageImpl(myPsiManager, packageName); } return null; diff --git a/java/java-psi-impl/src/com/intellij/psi/controlFlow/ConditionalGoToInstruction.java b/java/java-psi-impl/src/com/intellij/psi/controlFlow/ConditionalGoToInstruction.java index 4b1bd8f66e54..5332fff79289 100644 --- a/java/java-psi-impl/src/com/intellij/psi/controlFlow/ConditionalGoToInstruction.java +++ b/java/java-psi-impl/src/com/intellij/psi/controlFlow/ConditionalGoToInstruction.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,7 +28,7 @@ public class ConditionalGoToInstruction extends ConditionalBranchingInstruction } public String toString() { - final @NonNls String sRole = "["+role.toString()+"]"; + @NonNls final String sRole = "["+role.toString()+"]"; return "COND_GOTO " + sRole + " " + offset; } diff --git a/java/java-psi-impl/src/com/intellij/psi/controlFlow/ControlFlowUtil.java b/java/java-psi-impl/src/com/intellij/psi/controlFlow/ControlFlowUtil.java index e9b8cf98ecce..c6f57a53ddd8 100644 --- a/java/java-psi-impl/src/com/intellij/psi/controlFlow/ControlFlowUtil.java +++ b/java/java-psi-impl/src/com/intellij/psi/controlFlow/ControlFlowUtil.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -369,7 +369,8 @@ public class ControlFlowUtil { return offset; } - public static final Class[] DEFAULT_EXIT_STATEMENTS_CLASSES = new Class[]{PsiReturnStatement.class, PsiBreakStatement.class, PsiContinueStatement.class}; + public static final Class[] DEFAULT_EXIT_STATEMENTS_CLASSES = + {PsiReturnStatement.class, PsiBreakStatement.class, PsiContinueStatement.class}; private static PsiStatement findStatement(ControlFlow flow, int offset) { PsiElement element = flow.getElement(offset); @@ -675,7 +676,7 @@ public class ControlFlowUtil { } public static Object[] getAllWorldProblemsAtOnce(final ControlFlow flow) { - InstructionClientVisitor[] visitors = new InstructionClientVisitor[]{ + InstructionClientVisitor[] visitors = { new ReturnPresentClientVisitor(flow), new UnreachableStatementClientVisitor(flow), new ReadBeforeWriteClientVisitor(flow, true), @@ -1249,7 +1250,7 @@ public class ControlFlowUtil { // map of variable->PsiReferenceExpressions for all read before written variables for this point and below in control flow private final CopyOnWriteList[] readVariables; private final ControlFlow myFlow; - private boolean localVariablesOnly; + private final boolean localVariablesOnly; public ReadBeforeWriteClientVisitor(ControlFlow flow, boolean localVariablesOnly) { myFlow = flow; diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/PsiImplUtil.java b/java/java-psi-impl/src/com/intellij/psi/impl/PsiImplUtil.java index 48c9d63aa059..365c5e66d6c1 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/PsiImplUtil.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/PsiImplUtil.java @@ -345,6 +345,7 @@ public class PsiImplUtil { if (annotationType instanceof PsiClass) { return findApplicableTarget((PsiClass)annotationType, types); } + if (annotationType == null) return null; } } diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/compiled/ClsClassImpl.java b/java/java-psi-impl/src/com/intellij/psi/impl/compiled/ClsClassImpl.java index 60e343b188e7..2005641364e8 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/compiled/ClsClassImpl.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/compiled/ClsClassImpl.java @@ -336,7 +336,7 @@ public class ClsClassImpl extends ClsMemberImpl<PsiClassStub<?>> implements PsiE List<PsiMethod> methods = getOwnMethods(); List<PsiClass> classes = getOwnInnerClasses(); - if (fields.size() > 0) { + if (!fields.isEmpty()) { goNextLine(newIndentLevel, buffer); for (int i = 0; i < fields.size(); i++) { @@ -365,8 +365,8 @@ public class ClsClassImpl extends ClsMemberImpl<PsiClassStub<?>> implements PsiE buffer.append(";"); } - if (methods.size() > 0) { - if (isEnum() || fields.size() > 0) { + if (!methods.isEmpty()) { + if (isEnum() || !fields.isEmpty()) { buffer.append('\n'); } goNextLine(newIndentLevel, buffer); @@ -381,7 +381,7 @@ public class ClsClassImpl extends ClsMemberImpl<PsiClassStub<?>> implements PsiE } } - if (classes.size() > 0) { + if (!classes.isEmpty()) { if (fields.size() + methods.size() > 0) { buffer.append('\n'); } diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/compiled/ClsFileImpl.java b/java/java-psi-impl/src/com/intellij/psi/impl/compiled/ClsFileImpl.java index 6191dc22dcb0..85c897641e60 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/compiled/ClsFileImpl.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/compiled/ClsFileImpl.java @@ -315,7 +315,7 @@ public class ClsFileImpl extends ClsRepositoryPsiElement<PsiClassHolderFileStub> @NotNull public LanguageLevel getSourceLanguageLevel() { final List stubs = getStub().getChildrenStubs(); - return stubs.size() > 0 ? ((PsiClassStub<?>)stubs.get(0)).getLanguageLevel() : LanguageLevel.HIGHEST; + return !stubs.isEmpty() ? ((PsiClassStub<?>)stubs.get(0)).getLanguageLevel() : LanguageLevel.HIGHEST; } @Override diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/compiled/ClsParsingUtil.java b/java/java-psi-impl/src/com/intellij/psi/impl/compiled/ClsParsingUtil.java index 5113ed4d1fff..d4b10331797d 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/compiled/ClsParsingUtil.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/compiled/ClsParsingUtil.java @@ -133,8 +133,11 @@ public class ClsParsingUtil { return new ClsPrefixExpressionImpl(parent, operation, literal); } if (expr instanceof PsiClassObjectAccessExpression) { - final String canonicalClassText = ((PsiClassObjectAccessExpression)expr).getOperand().getType().getCanonicalText(); - return new ClsClassObjectAccessExpressionImpl(parent, canonicalClassText); + String exprText = expr.getText(); + if (StringUtil.endsWith(exprText, ".class")) { + String classText = exprText.substring(0, exprText.length() - 6); + return new ClsClassObjectAccessExpressionImpl(parent, classText); + } } if (expr instanceof PsiReferenceExpression) { return new ClsReferenceExpressionImpl(parent, (PsiReferenceExpression)expr); @@ -159,7 +162,7 @@ public class ClsParsingUtil { } } - LOG.error("Unable to compute expression value: " + expr); + LOG.error("Unable to compute expression value: " + expr + " [" + expr.getText() + "]"); return null; } diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/java/stubs/JavaClassElementType.java b/java/java-psi-impl/src/com/intellij/psi/impl/java/stubs/JavaClassElementType.java index 8d6000647162..a389245410df 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/java/stubs/JavaClassElementType.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/java/stubs/JavaClassElementType.java @@ -120,7 +120,7 @@ public abstract class JavaClassElementType extends JavaStubElementType<PsiClassS if (name != null) { if (parentStub instanceof PsiJavaFileStub) { final String pkg = ((PsiJavaFileStub)parentStub).getPackageName(); - if (pkg.length() > 0) qualifiedName = pkg + '.' + name; else qualifiedName = name; + if (!pkg.isEmpty()) qualifiedName = pkg + '.' + name; else qualifiedName = name; } else if (parentStub instanceof PsiClassStub) { final String parentFqn = ((PsiClassStub)parentStub).getQualifiedName(); diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/java/stubs/JavaMethodElementType.java b/java/java-psi-impl/src/com/intellij/psi/impl/java/stubs/JavaMethodElementType.java index 2d13eb9c8c20..dc35c3b380bf 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/java/stubs/JavaMethodElementType.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/java/stubs/JavaMethodElementType.java @@ -92,7 +92,7 @@ public abstract class JavaMethodElementType extends JavaStubElementType<PsiMetho } else if (type == JavaElementType.PARAMETER_LIST) { final List<LighterASTNode> params = LightTreeUtil.getChildrenOfType(tree, child, JavaElementType.PARAMETER); - if (params.size() > 0) { + if (!params.isEmpty()) { final LighterASTNode pType = LightTreeUtil.firstChildOfType(tree, params.get(params.size() - 1), JavaElementType.TYPE); if (pType != null) { isVarArgs = (LightTreeUtil.firstChildOfType(tree, pType, JavaTokenType.ELLIPSIS) != null); diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/java/stubs/impl/PsiImportStatementStubImpl.java b/java/java-psi-impl/src/com/intellij/psi/impl/java/stubs/impl/PsiImportStatementStubImpl.java index 6a217d3466c0..1de00bfc002d 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/java/stubs/impl/PsiImportStatementStubImpl.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/java/stubs/impl/PsiImportStatementStubImpl.java @@ -38,8 +38,8 @@ public class PsiImportStatementStubImpl extends StubBase<PsiImportStatementBase> private final StringRef myText; private SoftReference<PsiJavaCodeReferenceElement> myReference = null; - private final static int ON_DEMAND = 0x01; - private final static int STATIC = 0x02; + private static final int ON_DEMAND = 0x01; + private static final int STATIC = 0x02; public PsiImportStatementStubImpl(final StubElement parent, final String text, final byte flags) { this(parent, StringRef.fromString(text), flags); diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/light/LightTypeParameterListBuilder.java b/java/java-psi-impl/src/com/intellij/psi/impl/light/LightTypeParameterListBuilder.java index 41e3a42d994e..e54dcddcc16d 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/light/LightTypeParameterListBuilder.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/light/LightTypeParameterListBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2011 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -51,7 +51,7 @@ public class LightTypeParameterListBuilder extends LightElement implements PsiTy @Override public PsiTypeParameter[] getTypeParameters() { if (cached == null) { - if (myParameters.size() == 0) { + if (myParameters.isEmpty()) { cached = PsiTypeParameter.EMPTY_ARRAY; } else { diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/PsiJavaCodeReferenceElementImpl.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/PsiJavaCodeReferenceElementImpl.java index 103b828b1873..70de663a3e06 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/source/PsiJavaCodeReferenceElementImpl.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/PsiJavaCodeReferenceElementImpl.java @@ -584,7 +584,7 @@ public class PsiJavaCodeReferenceElementImpl extends CompositePsiElement impleme PsiModifierList modifierList = PsiImplUtil.findNeighbourModifierList(this); if (modifierList != null) { List<PsiAnnotation> typeAnnotations = PsiImplUtil.getTypeUseAnnotations(modifierList); - if (typeAnnotations != null && typeAnnotations.size() > 0) { + if (typeAnnotations != null && !typeAnnotations.isEmpty()) { annotations.addAll(typeAnnotations); } } diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/PsiJavaFileBaseImpl.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/PsiJavaFileBaseImpl.java index 47a1b8e3f159..dd88a17396c9 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/source/PsiJavaFileBaseImpl.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/PsiJavaFileBaseImpl.java @@ -121,7 +121,7 @@ public abstract class PsiJavaFileBaseImpl extends PsiFileImpl implements PsiJava final PsiPackageStatement packageStatement = getPackageStatement(); final PsiElementFactory factory = JavaPsiFacade.getInstance(getProject()).getElementFactory(); if (packageStatement != null) { - if (packageName.length() > 0) { + if (!packageName.isEmpty()) { final PsiJavaCodeReferenceElement reference = packageStatement.getPackageReference(); reference.replace(factory.createReferenceFromText(packageName, packageStatement)); } @@ -130,7 +130,7 @@ public abstract class PsiJavaFileBaseImpl extends PsiFileImpl implements PsiJava } } else { - if (packageName.length() > 0) { + if (!packageName.isEmpty()) { addBefore(factory.createPackageStatement(packageName), getFirstChild()); } } diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/PsiTypeElementImpl.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/PsiTypeElementImpl.java index cc46b4bd5cd0..a747e0357505 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/source/PsiTypeElementImpl.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/PsiTypeElementImpl.java @@ -138,14 +138,14 @@ public class PsiTypeElementImpl extends CompositePsiElement implements PsiTypeEl if (PsiUtil.isJavaToken(child, JavaTokenType.AND)) { List<PsiType> types = collectTypes(); - assert types.size() > 0 : this; + assert !types.isEmpty() : this; type = PsiIntersectionType.createIntersection(types); break; } if (PsiUtil.isJavaToken(child, JavaTokenType.OR)) { List<PsiType> types = collectTypes(); - assert types.size() > 0 : this; + assert !types.isEmpty() : this; type = PsiDisjunctionType.createDisjunction(types, getManager()); break; } @@ -161,7 +161,7 @@ public class PsiTypeElementImpl extends CompositePsiElement implements PsiTypeEl if (left instanceof PsiModifierList) { List<PsiAnnotation> annotations = PsiImplUtil.getTypeUseAnnotations((PsiModifierList)left); - if (annotations != null && annotations.size() > 0) { + if (annotations != null && !annotations.isEmpty()) { list.addAll(annotations); } break; diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/javadoc/PsiDocMethodOrFieldRef.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/javadoc/PsiDocMethodOrFieldRef.java index a104ac21c353..4c3ad50c2259 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/source/javadoc/PsiDocMethodOrFieldRef.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/javadoc/PsiDocMethodOrFieldRef.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -176,7 +176,7 @@ public class PsiDocMethodOrFieldRef extends CompositePsiElement implements PsiDo final String[] typeStrings = child.getText().split("[, ]"); //avoid param types list parsing hmm method(paramType1, paramType2, ...) -> typeElement1, identifier2, ... if (typeStrings != null) { for (String type : typeStrings) { - if (type.length() > 0) { + if (!type.isEmpty()) { types.add(type); } } @@ -189,7 +189,7 @@ public class PsiDocMethodOrFieldRef extends CompositePsiElement implements PsiDo @Nullable private PsiClass getScope(){ - if (getFirstChildNode().getElementType() == ElementType.DOC_REFERENCE_HOLDER) { + if (getFirstChildNode().getElementType() == JavaDocElementType.DOC_REFERENCE_HOLDER) { final PsiElement firstChildPsi = SourceTreeToPsiMap.treeElementToPsi(getFirstChildNode().getFirstChildNode()); if (firstChildPsi instanceof PsiJavaCodeReferenceElement) { PsiJavaCodeReferenceElement referenceElement = (PsiJavaCodeReferenceElement)firstChildPsi; @@ -312,7 +312,7 @@ public class PsiDocMethodOrFieldRef extends CompositePsiElement implements PsiDo } final PsiElement child = getFirstChild(); - if (containingClass != null && child != null && child.getNode().getElementType() == ElementType.DOC_REFERENCE_HOLDER) { + if (containingClass != null && child != null && child.getNode().getElementType() == JavaDocElementType.DOC_REFERENCE_HOLDER) { final PsiJavaCodeReferenceElement referenceElement = (PsiJavaCodeReferenceElement) child.getFirstChild(); assert referenceElement != null; referenceElement.bindToElement(containingClass); diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/javadoc/SeeDocTagInfo.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/javadoc/SeeDocTagInfo.java index 0b2d6a0123bb..287afdc18f6d 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/source/javadoc/SeeDocTagInfo.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/javadoc/SeeDocTagInfo.java @@ -17,6 +17,7 @@ package com.intellij.psi.impl.source.javadoc; import com.intellij.pom.java.LanguageLevel; import com.intellij.psi.*; +import com.intellij.psi.impl.source.tree.JavaElementType; import com.intellij.psi.util.PsiUtil; import com.intellij.psi.impl.source.SourceTreeToPsiMap; import com.intellij.psi.impl.source.tree.ElementType; @@ -36,7 +37,7 @@ import java.util.List; class SeeDocTagInfo implements JavadocTagInfo { private final String myName; private final boolean myInline; - private static final @NonNls String LINKPLAIN_TAG = "linkplain"; + @NonNls private static final String LINKPLAIN_TAG = "linkplain"; public SeeDocTagInfo(@NonNls String name, boolean isInline) { myName = name; @@ -106,7 +107,7 @@ class SeeDocTagInfo implements JavadocTagInfo { PsiDocMethodOrFieldRef methodRef = (PsiDocMethodOrFieldRef) place.getParent(); final IElementType firstChildType = methodRef.getFirstChildNode().getElementType(); - if (firstChildType == ElementType.JAVA_CODE_REFERENCE || firstChildType == ElementType.REFERENCE_EXPRESSION) { + if (firstChildType == JavaElementType.JAVA_CODE_REFERENCE || firstChildType == JavaElementType.REFERENCE_EXPRESSION) { PsiJavaCodeReferenceElement referenceElement = (PsiJavaCodeReferenceElement) SourceTreeToPsiMap.treeElementToPsi(methodRef.getFirstChildNode()); final PsiElement element = referenceElement.resolve(); if (element instanceof PsiClass) { diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/ClassResolverProcessor.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/ClassResolverProcessor.java index a9135d7102e0..b0eb406f2aef 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/ClassResolverProcessor.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/ClassResolverProcessor.java @@ -32,7 +32,7 @@ import java.util.List; public class ClassResolverProcessor extends BaseScopeProcessor implements NameHint, ElementClassHint { private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.source.resolve.ClassResolverProcessor"); - private static final String[] DEFAULT_PACKAGES = new String[]{CommonClassNames.DEFAULT_PACKAGE}; + private static final String[] DEFAULT_PACKAGES = {CommonClassNames.DEFAULT_PACKAGE}; private final String myClassName; private final PsiElement myPlace; diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/StaticImportResolveProcessor.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/StaticImportResolveProcessor.java index f7adb3545e57..335969987d41 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/StaticImportResolveProcessor.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/StaticImportResolveProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2011 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -57,7 +57,7 @@ public class StaticImportResolveProcessor extends BaseScopeProcessor implements } private static boolean checkDomination(final PsiMember candidate, final List<JavaResolveResult> results) { - if (results.size() > 0) { + if (!results.isEmpty()) { for (ListIterator<JavaResolveResult> i = results.listIterator(results.size()); i.hasPrevious();) { final Domination domination = dominates(candidate, (PsiMember)i.previous().getElement()); if (domination == Domination.DOMINATED_BY) { diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/FunctionalInterfaceParameterizationUtil.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/FunctionalInterfaceParameterizationUtil.java index ae9627f3c185..d82f5303629e 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/FunctionalInterfaceParameterizationUtil.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/FunctionalInterfaceParameterizationUtil.java @@ -38,7 +38,6 @@ public class FunctionalInterfaceParameterizationUtil { } return false; } - LOG.error("Unexpected type: " + classType); return false; } diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/InferenceIncorporationPhase.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/InferenceIncorporationPhase.java index 9a0866f8eddc..455d448ba641 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/InferenceIncorporationPhase.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/InferenceIncorporationPhase.java @@ -15,6 +15,7 @@ */ package com.intellij.psi.impl.source.resolve.graphInference; +import com.intellij.psi.CommonClassNames; import com.intellij.psi.PsiType; import com.intellij.psi.impl.source.resolve.graphInference.constraints.ConstraintFormula; import com.intellij.psi.impl.source.resolve.graphInference.constraints.SubtypingConstraint; @@ -26,7 +27,7 @@ import java.util.List; * User: anna */ public class InferenceIncorporationPhase { - private InferenceSession mySession; + private final InferenceSession mySession; public InferenceIncorporationPhase(InferenceSession session) { mySession = session; @@ -146,7 +147,7 @@ public class InferenceIncorporationPhase { final boolean properType = mySession.isProperType(upperBound); for (PsiType eqBound : eqBounds) { if (properType && mySession.isProperType(eqBound)) continue; - if (!upperBound.equals(eqBound)) { + if (!upperBound.equals(eqBound) && !upperBound.equalsToText(CommonClassNames.JAVA_LANG_OBJECT)) { addConstraint(new SubtypingConstraint(upperBound, eqBound, true)); } } diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/InferenceSession.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/InferenceSession.java index 0d013030ed05..27a949b84495 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/InferenceSession.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/InferenceSession.java @@ -37,7 +37,7 @@ import java.util.*; public class InferenceSession { private static final Logger LOG = Logger.getInstance("#" + InferenceSession.class.getName()); - private Map<PsiTypeParameter, InferenceVariable> myInferenceVariables = new LinkedHashMap<PsiTypeParameter, InferenceVariable>(); + private final Map<PsiTypeParameter, InferenceVariable> myInferenceVariables = new LinkedHashMap<PsiTypeParameter, InferenceVariable>(); private final List<ConstraintFormula> myConstraints = new ArrayList<ConstraintFormula>(); private PsiSubstitutor mySiteSubstitutor; @@ -219,6 +219,9 @@ public class InferenceSession { } } + for (InferenceVariable inferenceVariable : myInferenceVariables.values()) { + inferenceVariable.ignoreInstantiation(); + } mySiteSubstitutor = resolveBounds(myInferenceVariables.values(), mySiteSubstitutor, true); for (InferenceVariable inferenceVariable : myInferenceVariables.values()) { @@ -419,8 +422,8 @@ public class InferenceSession { PsiType bound = null; for (PsiType eqBound : eqBounds) { if (eqBound == null) continue; + if (bound != null && !isProperType(eqBound)) continue; bound = acceptBoundsWithRecursiveDependencies(typeParameter, eqBound, substitutor); - if (bound != null) break; } if (bound != null) { if (bound instanceof PsiCapturedWildcardType && eqBounds.size() > 1) { @@ -445,14 +448,18 @@ public class InferenceSession { } else if (acceptObject || upperBounds.size() > 1 || !upperBounds.get(0).equalsToText(CommonClassNames.JAVA_LANG_OBJECT)) { PsiType glb = null; - for (PsiType upperBound : upperBounds) { - upperBound = acceptBoundsWithRecursiveDependencies(typeParameter, upperBound, substitutor); - if (isProperType(upperBound, false)) { - if (glb == null) { - glb = upperBound; - } - else { - glb = GenericsUtil.getGreatestLowerBound(glb, upperBound); + if (isThrowable(upperBounds)) { + glb = PsiType.getJavaLangRuntimeException(myManager, GlobalSearchScope.allScope(myManager.getProject())); + } else { + for (PsiType upperBound : upperBounds) { + upperBound = acceptBoundsWithRecursiveDependencies(typeParameter, upperBound, substitutor); + if (isProperType(upperBound, false)) { + if (glb == null) { + glb = upperBound; + } + else { + glb = GenericsUtil.getGreatestLowerBound(glb, upperBound); + } } } } @@ -473,6 +480,20 @@ public class InferenceSession { return substitutor; } + private static boolean isThrowable(List<PsiType> upperBounds) { + boolean commonThrowable = false; + for (PsiType upperBound : upperBounds) { + if (upperBound.equalsToText(CommonClassNames.JAVA_LANG_OBJECT)) continue; + if (upperBound.equalsToText(CommonClassNames.JAVA_LANG_EXCEPTION) || + upperBound.equalsToText(CommonClassNames.JAVA_LANG_THROWABLE)) { + commonThrowable = true; + } else { + return false; + } + } + return commonThrowable; + } + private PsiType acceptBoundsWithRecursiveDependencies(PsiTypeParameter typeParameter, PsiType bound, PsiSubstitutor substitutor) { if (!isProperType(bound)) { final PsiSubstitutor subst = PsiUtil.resolveClassInType(bound) != typeParameter ? substitutor.put(typeParameter, null) : substitutor; diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/InferenceVariable.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/InferenceVariable.java index 593194354b7d..f8dc21008af4 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/InferenceVariable.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/InferenceVariable.java @@ -29,8 +29,8 @@ public class InferenceVariable { return myParameter; } - private Map<InferenceBound, List<PsiType>> myBounds = new HashMap<InferenceBound, List<PsiType>>(); - private PsiTypeParameter myParameter; + private final Map<InferenceBound, List<PsiType>> myBounds = new HashMap<InferenceBound, List<PsiType>>(); + private final PsiTypeParameter myParameter; private PsiType myInstantiation = PsiType.NULL; public InferenceVariable(PsiTypeParameter parameter) { diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/InferenceVariablesOrder.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/InferenceVariablesOrder.java index 817002a1aa16..397f84b2ab1a 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/InferenceVariablesOrder.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/InferenceVariablesOrder.java @@ -78,7 +78,7 @@ public class InferenceVariablesOrder { public static class InferenceGraphNode<T> { private final List<T> myValue = new ArrayList<T>(); - private Set<InferenceGraphNode<T>> myDependencies = new HashSet<InferenceGraphNode<T>>(); + private final Set<InferenceGraphNode<T>> myDependencies = new HashSet<InferenceGraphNode<T>>(); private int index = -1; private int lowlink; diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/PsiPolyExpressionUtil.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/PsiPolyExpressionUtil.java index e5cda246efbf..d03959af447a 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/PsiPolyExpressionUtil.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/PsiPolyExpressionUtil.java @@ -76,7 +76,7 @@ public class PsiPolyExpressionUtil { if (isInAssignmentOrInvocationContext(expression) && ((PsiCallExpression)expression).getTypeArguments().length == 0) { if (method != null) { final Set<PsiTypeParameter> typeParameters = new HashSet<PsiTypeParameter>(Arrays.asList(method.getTypeParameters())); - if (typeParameters.size() > 0) { + if (!typeParameters.isEmpty()) { final PsiType returnType = method.getReturnType(); if (returnType != null) { return mentionsTypeParameters(returnType, typeParameters); diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/constraints/ExpressionCompatibilityConstraint.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/constraints/ExpressionCompatibilityConstraint.java index 14e0a37dfab0..7ef2a7250030 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/constraints/ExpressionCompatibilityConstraint.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/constraints/ExpressionCompatibilityConstraint.java @@ -31,7 +31,7 @@ import java.util.*; * User: anna */ public class ExpressionCompatibilityConstraint extends InputOutputConstraintFormula { - private PsiExpression myExpression; + private final PsiExpression myExpression; private PsiType myT; public ExpressionCompatibilityConstraint(@NotNull PsiExpression expression, @NotNull PsiType type) { @@ -81,7 +81,7 @@ public class ExpressionCompatibilityConstraint extends InputOutputConstraintForm final PsiMethod method = ((PsiCallExpression)myExpression).resolveMethod(); PsiType returnType = null; InferenceSession callSession = null; - if (method != null) { + if (method != null && !method.isConstructor()) { returnType = method.getReturnType(); final PsiParameter[] parameters = method.getParameterList().getParameters(); if (returnType != null) { diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/constraints/PsiMethodReferenceCompatibilityConstraint.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/constraints/PsiMethodReferenceCompatibilityConstraint.java index ee7bb924c555..faafe26c437b 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/constraints/PsiMethodReferenceCompatibilityConstraint.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/constraints/PsiMethodReferenceCompatibilityConstraint.java @@ -104,8 +104,8 @@ public class PsiMethodReferenceCompatibilityConstraint implements ConstraintForm constraints.add(new TypeCompatibilityConstraint(GenericsUtil.eliminateWildcards(returnType), psiSubstitutor.substitute(applicableMethodReturnType))); } else if (applicableMember instanceof PsiClass || applicableMember instanceof PsiMethod && ((PsiMethod)applicableMember).isConstructor()) { final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(applicableMember.getProject()); - final PsiClassType classType = elementFactory.createType(qualifierResolveResult.getContainingClass(), PsiSubstitutor.EMPTY); - constraints.add(new TypeCompatibilityConstraint(GenericsUtil.eliminateWildcards(returnType), psiSubstitutor.substitute(classType))); + final PsiClassType classType = elementFactory.createType(qualifierResolveResult.getContainingClass(), psiSubstitutor); + constraints.add(new TypeCompatibilityConstraint(GenericsUtil.eliminateWildcards(returnType), classType)); } } return true; diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/constraints/SubtypingConstraint.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/constraints/SubtypingConstraint.java index baaba043ec8e..cfda8a0f0e36 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/constraints/SubtypingConstraint.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/constraints/SubtypingConstraint.java @@ -29,7 +29,7 @@ import java.util.List; public class SubtypingConstraint implements ConstraintFormula { private PsiType myS; private PsiType myT; - private boolean myIsRefTypes; + private final boolean myIsRefTypes; public SubtypingConstraint(PsiType t, PsiType s, boolean isRefTypes) { myT = t; @@ -148,13 +148,14 @@ public class SubtypingConstraint implements ConstraintFormula { if (myS instanceof PsiWildcardType) { return inferenceVariable != null && inferenceVariable.isCaptured(); } else { - if (inferenceVariable != null) { - inferenceVariable.addBound(myS, InferenceBound.EQ); + final InferenceVariable inferenceVariableS = session.getInferenceVariable(myS); + if (inferenceVariableS != null) { + inferenceVariableS.addBound(myT, InferenceBound.EQ); return true; } - inferenceVariable = session.getInferenceVariable(myS); + if (inferenceVariable != null) { - inferenceVariable.addBound(myT, InferenceBound.EQ); + inferenceVariable.addBound(myS, InferenceBound.EQ); return true; } constraints.add(new SubtypingConstraint(myT, myS, true)); diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/SourceUtil.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/SourceUtil.java index 5e0865e0ec45..1380b68b9213 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/SourceUtil.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/SourceUtil.java @@ -47,7 +47,7 @@ public class SourceUtil { public void visitLeaf(LeafElement leaf) { if (!REF_FILTER.contains(leaf.getElementType())) { String leafText = leaf.getText(); - if (buffer.length() > 0 && leafText.length() > 0 && Character.isJavaIdentifierPart(leafText.charAt(0))) { + if (buffer.length() > 0 && !leafText.isEmpty() && Character.isJavaIdentifierPart(leafText.charAt(0))) { char lastInBuffer = buffer.charAt(buffer.length() - 1); if (lastInBuffer == '?' || Character.isJavaIdentifierPart(lastInBuffer)) { buffer.append(" "); diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/FieldElement.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/FieldElement.java index db0d189b72f8..bba320dee8b0 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/FieldElement.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/FieldElement.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,7 +29,7 @@ import org.jetbrains.annotations.NotNull; public class FieldElement extends CompositeElement{ public FieldElement() { - super(Constants.FIELD); + super(JavaElementType.FIELD); } protected FieldElement(@NotNull IElementType type) { diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/MethodElement.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/MethodElement.java index 048ae975beb1..31fb4bca8833 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/MethodElement.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/MethodElement.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2012 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -46,7 +46,7 @@ public class MethodElement extends CompositeElement implements Constants { @Override public TreeElement addInternal(TreeElement first, ASTNode last, ASTNode anchor, Boolean before) { - if (first == last && first.getElementType() == ElementType.CODE_BLOCK){ + if (first == last && first.getElementType() == JavaElementType.CODE_BLOCK){ ASTNode semicolon = findChildByRole(ChildRole.CLOSING_SEMICOLON); if (semicolon != null){ deleteChildInternal(semicolon); diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiBlockStatementImpl.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiBlockStatementImpl.java index b1dae5402eef..dbea6fd60fd8 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiBlockStatementImpl.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiBlockStatementImpl.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,6 +21,7 @@ import com.intellij.psi.JavaElementVisitor; import com.intellij.psi.PsiBlockStatement; import com.intellij.psi.PsiCodeBlock; import com.intellij.psi.PsiElementVisitor; +import com.intellij.psi.impl.source.tree.JavaElementType; import com.intellij.psi.tree.ChildRoleBase; import com.intellij.psi.impl.source.Constants; import com.intellij.psi.impl.source.tree.ChildRole; @@ -31,7 +32,7 @@ public class PsiBlockStatementImpl extends CompositePsiElement implements PsiBlo private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.source.tree.java.PsiBlockStatementImpl"); public PsiBlockStatementImpl() { - super(Constants.BLOCK_STATEMENT); + super(JavaElementType.BLOCK_STATEMENT); } @Override @@ -48,14 +49,14 @@ public class PsiBlockStatementImpl extends CompositePsiElement implements PsiBlo return null; case ChildRole.BLOCK: - return findChildByType(Constants.CODE_BLOCK); + return findChildByType(JavaElementType.CODE_BLOCK); } } @Override public int getChildRole(ASTNode child) { LOG.assertTrue(child.getTreeParent() == this); - if (child.getElementType() == Constants.CODE_BLOCK) { + if (child.getElementType() == JavaElementType.CODE_BLOCK) { return ChildRole.BLOCK; } else { diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiEmptyExpressionImpl.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiEmptyExpressionImpl.java index 1cbe8457fbe4..93f802863217 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiEmptyExpressionImpl.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiEmptyExpressionImpl.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,11 +20,12 @@ import com.intellij.psi.PsiElementVisitor; import com.intellij.psi.PsiExpression; import com.intellij.psi.PsiType; import com.intellij.psi.impl.source.Constants; +import com.intellij.psi.impl.source.tree.JavaElementType; import org.jetbrains.annotations.NotNull; public class PsiEmptyExpressionImpl extends ExpressionPsiElement implements PsiExpression{ public PsiEmptyExpressionImpl() { - super(Constants.EMPTY_EXPRESSION); + super(JavaElementType.EMPTY_EXPRESSION); } @Override diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiEmptyStatementImpl.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiEmptyStatementImpl.java index 40566a32ae9c..eb9661930cd0 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiEmptyStatementImpl.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiEmptyStatementImpl.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,11 +20,12 @@ import com.intellij.psi.PsiElementVisitor; import com.intellij.psi.PsiEmptyStatement; import com.intellij.psi.impl.source.Constants; import com.intellij.psi.impl.source.tree.CompositePsiElement; +import com.intellij.psi.impl.source.tree.JavaElementType; import org.jetbrains.annotations.NotNull; public class PsiEmptyStatementImpl extends CompositePsiElement implements PsiEmptyStatement { public PsiEmptyStatementImpl() { - super(Constants.EMPTY_STATEMENT); + super(JavaElementType.EMPTY_STATEMENT); } @Override diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiIdentifierImpl.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiIdentifierImpl.java index e6d5d03fba5f..4627c70ef330 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiIdentifierImpl.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiIdentifierImpl.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,7 +25,7 @@ import org.jetbrains.annotations.NotNull; public class PsiIdentifierImpl extends LeafPsiElement implements PsiIdentifier, PsiJavaToken { public PsiIdentifierImpl(CharSequence text) { - super(Constants.IDENTIFIER, text); + super(JavaTokenType.IDENTIFIER, text); } @Override diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiMethodReferenceExpressionImpl.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiMethodReferenceExpressionImpl.java index f82cf73733aa..eb4d501cdad0 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiMethodReferenceExpressionImpl.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiMethodReferenceExpressionImpl.java @@ -82,7 +82,7 @@ public class PsiMethodReferenceExpressionImpl extends PsiReferenceExpressionBase if (element instanceof PsiIdentifier) { methods = containingClass.findMethodsByName(element.getText(), false); } - else if (element instanceof PsiKeyword && PsiKeyword.NEW.equals(element.getText())) { + else if (isConstructor()) { methods = containingClass.getConstructors(); if (methods.length == 0) { //default constructor return containingClass; @@ -299,7 +299,7 @@ public class PsiMethodReferenceExpressionImpl extends PsiReferenceExpressionBase if (containingClass != null) { final PsiElement element = getReferenceNameElement(); - final boolean isConstructor = element instanceof PsiKeyword && PsiKeyword.NEW.equals(element.getText()); + final boolean isConstructor = isConstructor(); if (element instanceof PsiIdentifier || isConstructor) { if (isConstructor && (containingClass.isEnum() || containingClass.hasModifierProperty(PsiModifier.ABSTRACT))) { return JavaResolveResult.EMPTY_ARRAY; @@ -325,7 +325,7 @@ public class PsiMethodReferenceExpressionImpl extends PsiReferenceExpressionBase final PsiClassType returnType = JavaPsiFacade.getElementFactory(project).createType(containingClass, isRawSubst ? PsiSubstitutor.EMPTY : substitutor); - substitutor = LambdaUtil.inferFromReturnType(typeParameters, returnType, interfaceMethodReturnType, substitutor, languageLevel, + substitutor = LambdaUtil.inferFromReturnType(typeParameters, returnType, GenericsUtil.eliminateWildcards(interfaceMethodReturnType), substitutor, languageLevel, project); if (containingClass.getConstructors().length == 0) { @@ -421,8 +421,8 @@ public class PsiMethodReferenceExpressionImpl extends PsiReferenceExpressionBase psiSubstitutor = psiSubstitutor.putAll(substitutor); } return LambdaUtil.inferFromReturnType(method.getTypeParameters(), - psiSubstitutor.substitute(method.getReturnType()), - interfaceMethodReturnType, + method.getReturnType(), + GenericsUtil.eliminateWildcards(interfaceMethodReturnType), psiSubstitutor, languageLevel, getProject()); } @@ -471,7 +471,7 @@ public class PsiMethodReferenceExpressionImpl extends PsiReferenceExpressionBase final PsiMethod psiMethod = ((MethodCandidateInfo)conflict).getElement(); if (psiMethod == null) continue; PsiSubstitutor subst = PsiSubstitutor.EMPTY; - subst = subst.putAll(mySubstitutor); + subst = subst.putAll(TypeConversionUtil.getSuperClassSubstitutor(psiMethod.getContainingClass(), myQualifierResolveResult.getContainingClass(), mySubstitutor)); subst = subst.putAll(conflict.getSubstitutor()); final PsiType[] signatureParameterTypes2 = psiMethod.getSignature(subst).getParameterTypes(); @@ -534,6 +534,9 @@ public class PsiMethodReferenceExpressionImpl extends PsiReferenceExpressionBase @Override public CandidateInfo resolveConflict(@NotNull List<CandidateInfo> conflicts) { + checkSameSignatures(conflicts); + if (conflicts.size() == 1) return conflicts.get(0); + checkAccessStaticLevels(conflicts, true); if (conflicts.size() == 1) return conflicts.get(0); @@ -571,4 +574,10 @@ public class PsiMethodReferenceExpressionImpl extends PsiReferenceExpressionBase } } } + + @Override + public boolean isConstructor() { + final PsiElement element = getReferenceNameElement(); + return element instanceof PsiKeyword && PsiKeyword.NEW.equals(element.getText()); + } } diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiPostfixExpressionImpl.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiPostfixExpressionImpl.java index e2aeb4c13e09..059d8bc57acd 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiPostfixExpressionImpl.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiPostfixExpressionImpl.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2011 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,6 +20,7 @@ import com.intellij.openapi.diagnostic.Logger; import com.intellij.psi.*; import com.intellij.psi.impl.source.Constants; import com.intellij.psi.impl.source.tree.ChildRole; +import com.intellij.psi.impl.source.tree.JavaElementType; import com.intellij.psi.tree.IElementType; import com.intellij.psi.tree.ChildRoleBase; import org.jetbrains.annotations.NotNull; @@ -28,7 +29,7 @@ public class PsiPostfixExpressionImpl extends ExpressionPsiElement implements Ps private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.source.tree.java.PsiPostfixExpressionImpl"); public PsiPostfixExpressionImpl() { - super(Constants.POSTFIX_EXPRESSION); + super(JavaElementType.POSTFIX_EXPRESSION); } @Override diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiReferenceExpressionImpl.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiReferenceExpressionImpl.java index 932bec004fb5..639574933136 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiReferenceExpressionImpl.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiReferenceExpressionImpl.java @@ -477,7 +477,7 @@ public class PsiReferenceExpressionImpl extends PsiReferenceExpressionBase imple @Override public boolean isAcceptable(Object element, @Nullable PsiElement context) { return LambdaUtil.isValidQualifier4InterfaceStaticMethodCall((PsiMethod)element, PsiReferenceExpressionImpl.this, - PsiUtil.getLanguageLevel(PsiReferenceExpressionImpl.this)); + null, PsiUtil.getLanguageLevel(PsiReferenceExpressionImpl.this)); } @Override diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/TypeParameterElement.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/TypeParameterElement.java index f1f89583f9d0..4eb53de83de6 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/TypeParameterElement.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/TypeParameterElement.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,7 +29,7 @@ public class TypeParameterElement extends CompositeElement { private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.source.tree.java.TypeParameterElement"); public TypeParameterElement() { - super(ElementType.TYPE_PARAMETER); + super(JavaElementType.TYPE_PARAMETER); } @Override diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/TypeParameterExtendsBoundsListElement.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/TypeParameterExtendsBoundsListElement.java index b79c45be9bf0..bdc51157690c 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/TypeParameterExtendsBoundsListElement.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/TypeParameterExtendsBoundsListElement.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -103,7 +103,7 @@ public class TypeParameterExtendsBoundsListElement extends CompositeElement impl if (elType == AND) { return ChildRole.AMPERSAND_IN_BOUNDS_LIST; } - else if (elType == ElementType.JAVA_CODE_REFERENCE) { + else if (elType == JavaElementType.JAVA_CODE_REFERENCE) { return ChildRole.BASE_CLASS_REFERENCE; } else if (elType == JavaTokenType.EXTENDS_KEYWORD) { diff --git a/java/java-psi-impl/src/com/intellij/psi/presentation/java/ClassPresentationProvider.java b/java/java-psi-impl/src/com/intellij/psi/presentation/java/ClassPresentationProvider.java index 5eb8a5d667c6..12b234d83451 100644 --- a/java/java-psi-impl/src/com/intellij/psi/presentation/java/ClassPresentationProvider.java +++ b/java/java-psi-impl/src/com/intellij/psi/presentation/java/ClassPresentationProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2011 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -45,7 +45,7 @@ public class ClassPresentationProvider implements ItemPresentationProvider<PsiCl if (file instanceof PsiClassOwner) { PsiClassOwner classOwner = (PsiClassOwner)file; String packageName = classOwner.getPackageName(); - if (packageName.length() == 0) return null; + if (packageName.isEmpty()) return null; return "(" + packageName + ")"; } return null; diff --git a/java/java-psi-impl/src/com/intellij/psi/presentation/java/JavaPresentationUtil.java b/java/java-psi-impl/src/com/intellij/psi/presentation/java/JavaPresentationUtil.java index 862cd97d5d70..69dcc967a298 100644 --- a/java/java-psi-impl/src/com/intellij/psi/presentation/java/JavaPresentationUtil.java +++ b/java/java-psi-impl/src/com/intellij/psi/presentation/java/JavaPresentationUtil.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,6 +22,7 @@ import com.intellij.openapi.editor.colors.TextAttributesKey; import com.intellij.openapi.util.Iconable; import com.intellij.psi.*; import com.intellij.psi.util.PsiFormatUtil; +import com.intellij.psi.util.PsiFormatUtilBase; import com.intellij.psi.util.PsiTreeUtil; import org.jetbrains.annotations.Nullable; @@ -37,8 +38,8 @@ public class JavaPresentationUtil { public String getPresentableText() { return PsiFormatUtil.formatMethod( psiMethod, - PsiSubstitutor.EMPTY, PsiFormatUtil.SHOW_NAME | PsiFormatUtil.SHOW_PARAMETERS, - PsiFormatUtil.SHOW_TYPE + PsiSubstitutor.EMPTY, PsiFormatUtilBase.SHOW_NAME | PsiFormatUtilBase.SHOW_PARAMETERS, + PsiFormatUtilBase.SHOW_TYPE ); } diff --git a/java/java-psi-impl/src/com/intellij/psi/scope/conflictResolvers/JavaMethodsConflictResolver.java b/java/java-psi-impl/src/com/intellij/psi/scope/conflictResolvers/JavaMethodsConflictResolver.java index ba7097f2ff0d..084ad32c5d56 100644 --- a/java/java-psi-impl/src/com/intellij/psi/scope/conflictResolvers/JavaMethodsConflictResolver.java +++ b/java/java-psi-impl/src/com/intellij/psi/scope/conflictResolvers/JavaMethodsConflictResolver.java @@ -201,7 +201,7 @@ public class JavaMethodsConflictResolver implements PsiConflictResolver{ } } - private void checkSameSignatures(@NotNull List<CandidateInfo> conflicts) { + protected void checkSameSignatures(@NotNull List<CandidateInfo> conflicts) { // candidates should go in order of class hierarchy traversal // in order for this to work Map<MethodSignature, CandidateInfo> signatures = new THashMap<MethodSignature, CandidateInfo>(conflicts.size()); @@ -381,7 +381,7 @@ public class JavaMethodsConflictResolver implements PsiConflictResolver{ boolean toFilter = false; for (CandidateInfo conflict : conflicts) { ProgressManager.checkCanceled(); - final @MethodCandidateInfo.ApplicabilityLevelConstant int level = preferVarargs((MethodCandidateInfo)conflict); + @MethodCandidateInfo.ApplicabilityLevelConstant final int level = preferVarargs((MethodCandidateInfo)conflict); if (maxApplicabilityLevel > 0 && maxApplicabilityLevel != level) { toFilter = true; } diff --git a/java/java-tests/testData/codeInsight/completion/keywords/super3.java b/java/java-tests/testData/codeInsight/completion/keywords/super3.java new file mode 100644 index 000000000000..10d1e47b1329 --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/keywords/super3.java @@ -0,0 +1,25 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +interface Super +{ + default void method() {} +} + +interface Sub extends Super { + default void foo() { + Super.<caret> + } +}
\ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/completion/keywords/super3_after.java b/java/java-tests/testData/codeInsight/completion/keywords/super3_after.java new file mode 100644 index 000000000000..c8906286bc28 --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/keywords/super3_after.java @@ -0,0 +1,25 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +interface Super +{ + default void method() {} +} + +interface Sub extends Super { + default void foo() { + Super.super + } +}
\ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/completion/keywords/super4.java b/java/java-tests/testData/codeInsight/completion/keywords/super4.java new file mode 100644 index 000000000000..028a4dffa5d8 --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/keywords/super4.java @@ -0,0 +1,25 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +interface Super +{ + default void method() {} +} + +interface Sub extends Super { + static void foo() { + Super.<caret> + } +}
\ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/completion/methodChains/testOneChainContainsOther2/TestCompletion.java b/java/java-tests/testData/codeInsight/completion/methodChains/testOneChainContainsOther2/TestCompletion.java new file mode 100644 index 000000000000..886a65422cdd --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/methodChains/testOneChainContainsOther2/TestCompletion.java @@ -0,0 +1,20 @@ +interface PsiManager { + +} +interface PsiElement { + PsiManager getManager(); +} +interface PsiClass extends PsiElement { +} +interface PsiMethod extends PsiElement { + PsiClass getContainingClass(); +} +interface PsiMethodCallExpression extends PsiElement { + PsiMethod resolveMethod(); +} +public class TestCompletion { + + public void method() { + PsiManager m = <caret> + } +} diff --git a/java/java-tests/testData/codeInsight/completion/methodChains/testOneChainContainsOther2/TestIndex.java b/java/java-tests/testData/codeInsight/completion/methodChains/testOneChainContainsOther2/TestIndex.java new file mode 100644 index 000000000000..d5de1bcf74e1 --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/methodChains/testOneChainContainsOther2/TestIndex.java @@ -0,0 +1,24 @@ +public class TestIndex { + + public void statMethod(PsiMethodCallExpression e) { + e.resolveMethod().getContainingClass().getManager(); + e.resolveMethod().getContainingClass().getManager(); + e.resolveMethod().getContainingClass().getManager(); + e.resolveMethod().getContainingClass().getManager(); + e.resolveMethod().getContainingClass().getManager(); + } +} +interface PsiManager { + +} +interface PsiElement { + PsiManager getManager(); +} +interface PsiClass extends PsiElement { +} +interface PsiMethod extends PsiElement { + PsiClass getContainingClass(); +} +interface PsiMethodCallExpression extends PsiElement { + PsiMethod resolveMethod(); +} diff --git a/java/java-tests/testData/codeInsight/completion/smartTypeSorting/PreferLocalWildcardClassOverObject.java b/java/java-tests/testData/codeInsight/completion/smartTypeSorting/PreferLocalWildcardClassOverObject.java new file mode 100644 index 000000000000..d7a3c52db5ea --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/smartTypeSorting/PreferLocalWildcardClassOverObject.java @@ -0,0 +1,11 @@ +class Foo { + + static void bar(Class<?> type) { + + } + + public static void main(String[] args) { + Class<?> type; + bar(<caret>); + } +}
\ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/FinalFieldInit.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/FinalFieldInit.java index a86c0b310882..8f09a701701a 100644 --- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/FinalFieldInit.java +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/FinalFieldInit.java @@ -239,4 +239,14 @@ class IDEA100237 { final int qux = <error descr="Variable 'bar' might not have been initialized">bar</error>.hashCode() + 1; }; } +} + +class StaticInitializerUsedInAnotherStaticField { + private static final int ENUMERATION_CACHE_SIZE; + + static { + ENUMERATION_CACHE_SIZE = 0; + } + + private static final int ourEnumerationCacheConstant = ENUMERATION_CACHE_SIZE; }
\ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting8/CastToIntersection.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting8/CastToIntersection.java new file mode 100644 index 000000000000..66affa9cde79 --- /dev/null +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting8/CastToIntersection.java @@ -0,0 +1,11 @@ +import java.io.Serializable; + +public class FooBar1 { + { + Object x = null; + Object y = (CharSequence & Serializable) x; + Object y2 = (CharSequence & Integer) x; + Object y3 = (Integer & CharSequence) x; + <error descr="Incompatible types. Found: 'java.lang.CharSequence & java.io.Serializable', required: 'int'">int y1 = (CharSequence & Serializable) x;</error> + } +} diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting8/IDEA94011.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting8/IDEA94011.java index d9ac64f95819..0dd027c949c0 100644 --- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting8/IDEA94011.java +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting8/IDEA94011.java @@ -10,7 +10,7 @@ class Test { public void test(Set<MyConsumer> set) { @SuppressWarnings("unchecked") - Map<Parent, MyConsumer<Parent>> map = create<error descr="'create(java.util.Set<Test.MyConsumer<Test.Parent>>)' in 'Test' cannot be applied to '(java.util.Set<Test.MyConsumer>)'">(set)</error>; + <error descr="Incompatible types. Found: 'java.util.Map<Test.Parent,Test.MyConsumer>', required: 'java.util.Map<Test.Parent,Test.MyConsumer<Test.Parent>>'">Map<Parent, MyConsumer<Parent>> map = create(set);</error> } diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/highlighting/ReturnTypeCompatibility.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/highlighting/ReturnTypeCompatibility.java index a922039b3933..2dce3147cd4a 100644 --- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/highlighting/ReturnTypeCompatibility.java +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/highlighting/ReturnTypeCompatibility.java @@ -25,7 +25,7 @@ class ReturnTypeIncompatibility { } public static void main(String[] args) { - call<error descr="Ambiguous method call: both 'ReturnTypeIncompatibility.call(I1<Integer>)' and 'ReturnTypeIncompatibility.call(I2<String>)' match">(i-> {return i;})</error>; + call<error descr="Ambiguous method call: both 'ReturnTypeIncompatibility.call(I1<Integer>)' and 'ReturnTypeIncompatibility.call(I2<String & Integer>)' match">(i-> {return i;})</error>; } } diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/interfaceMethods/DefaultMethodOverrideEquivalentObject.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/interfaceMethods/DefaultMethodOverrideEquivalentObject.java new file mode 100644 index 000000000000..ea14af2900ce --- /dev/null +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/interfaceMethods/DefaultMethodOverrideEquivalentObject.java @@ -0,0 +1,5 @@ +interface A { + default String <error descr="Default method toString overrides a member of java.lang.Object">toString</error>() { + return ""; + } +}
\ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/interfaceMethods/DefaultSupersInStaticContext.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/interfaceMethods/DefaultSupersInStaticContext.java new file mode 100644 index 000000000000..10c717296f46 --- /dev/null +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/interfaceMethods/DefaultSupersInStaticContext.java @@ -0,0 +1,13 @@ +interface Super +{ + default void method() + { + System.out.println("Super.method()"); + } +} + +interface Sub extends Super { + static void foo() { + <error descr="'Super' is not an enclosing class">Super.super</error>.method(); + } +} diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/interfaceMethods/NotInheritFromUnrelatedDefault.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/interfaceMethods/NotInheritFromUnrelatedDefault.java index cfc1ee7abec4..79f310bdbde6 100644 --- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/interfaceMethods/NotInheritFromUnrelatedDefault.java +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/interfaceMethods/NotInheritFromUnrelatedDefault.java @@ -12,4 +12,17 @@ interface SecondParent { class <error descr="Class 'SecondParent' must either be declared abstract or implement abstract method 'doSomething()' in 'SecondParent'">FirstSon</error> implements FirstParent, SecondParent {} -<error descr="Class 'SecondSon' must either be declared abstract or implement abstract method 'doSomething()' in 'SecondParent'">class SecondSon implements SecondParent, FirstParent</error> {}
\ No newline at end of file +<error descr="Class 'SecondSon' must either be declared abstract or implement abstract method 'doSomething()' in 'SecondParent'">class SecondSon implements SecondParent, FirstParent</error> {} + +interface A { + default int foo() { + return 1; + } +} + +interface B { + abstract int foo(); +} + +interface <error descr="C inherits abstract and default for foo() from types A and B">C</error> extends A, B { +} diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/changeTypeArgs/afterSuperType.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/changeTypeArgs/afterSuperType.java index 337708e8fb14..85e4d69968a2 100644 --- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/changeTypeArgs/afterSuperType.java +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/changeTypeArgs/afterSuperType.java @@ -1,6 +1,6 @@ import java.io.Serializable; -// "Change type arguments to <Serializable>" "true" +// "Change type arguments to <Serializable & Comparable<? extends Serializable & Comparable<? extends Comparable<?>>>>" "true" class Generic<E> { Generic(E arg, E arg1) { } diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/changeTypeArgs/beforeSuperType.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/changeTypeArgs/beforeSuperType.java index 1b6580752258..782196410955 100644 --- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/changeTypeArgs/beforeSuperType.java +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/changeTypeArgs/beforeSuperType.java @@ -1,4 +1,4 @@ -// "Change type arguments to <Serializable>" "true" +// "Change type arguments to <Serializable & Comparable<? extends Serializable & Comparable<? extends Comparable<?>>>>" "true" class Generic<E> { Generic(E arg, E arg1) { } diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/flipIntersection/after1.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/flipIntersection/after1.java new file mode 100644 index 000000000000..f07cf3847bda --- /dev/null +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/flipIntersection/after1.java @@ -0,0 +1,7 @@ +// "Move 'Number' to the beginning" "true" +class C { + { + Object x = null; + Object y2 = (Number & CharSequence) x; + } +} diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/flipIntersection/before1.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/flipIntersection/before1.java new file mode 100644 index 000000000000..38380bc0c315 --- /dev/null +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/flipIntersection/before1.java @@ -0,0 +1,7 @@ +// "Move 'Number' to the beginning" "true" +class C { + { + Object x = null; + Object y2 = (CharSequence & Num<caret>ber) x; + } +} diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/flipIntersection/before2.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/flipIntersection/before2.java new file mode 100644 index 000000000000..34f28f2733f3 --- /dev/null +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/flipIntersection/before2.java @@ -0,0 +1,7 @@ +// "Move 'Number' to the beginning" "false" +class C { + { + Object x = null; + Object y2 = (Number & Num<caret>ber) x; + } +} diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/mustBeFinal/afterLoop.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/mustBeFinal/afterLoop.java new file mode 100644 index 000000000000..69e9f8c34d40 --- /dev/null +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/mustBeFinal/afterLoop.java @@ -0,0 +1,17 @@ +// "Copy 'i' to temp final variable" "true" +class ParamTypeBug { + private static String strings[] = new String[]{ "a", "b", "c" }; + + public static void main(final String ... args){ + if (args.length == 1){ + for(int i = 0; i < strings.length; i++) { + final int finalI = i; + new Thread(){ + public void run(){ + new String(strings[finalI]); + } + }.start(); + } + } + } +} diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/mustBeFinal/beforeLoop.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/mustBeFinal/beforeLoop.java new file mode 100644 index 000000000000..770526f55f29 --- /dev/null +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/mustBeFinal/beforeLoop.java @@ -0,0 +1,15 @@ +// "Copy 'i' to temp final variable" "true" +class ParamTypeBug { + private static String strings[] = new String[]{ "a", "b", "c" }; + + public static void main(final String ... args){ + if (args.length == 1){ + for(int i = 0; i < strings.length; i++) + new Thread(){ + public void run(){ + new String(strings[<caret>i]); + } + }.start(); + } + } +} diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/qualifyThis/afterDefaultInInterface.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/qualifyThis/afterDefaultInInterface.java new file mode 100644 index 000000000000..7c4c1c064588 --- /dev/null +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/qualifyThis/afterDefaultInInterface.java @@ -0,0 +1,14 @@ +// "Qualify super expression with 'Super'" "true" +interface Super +{ + default void method() + { + System.out.println("Super.method()"); + } +} + +interface Sub extends Super { + default void foo() { + Super.super.method(); + } +}
\ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/qualifyThis/beforeDefaultInInterface.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/qualifyThis/beforeDefaultInInterface.java new file mode 100644 index 000000000000..c4ea300498ca --- /dev/null +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/qualifyThis/beforeDefaultInInterface.java @@ -0,0 +1,14 @@ +// "Qualify super expression with 'Super'" "true" +interface Super +{ + default void method() + { + System.out.println("Super.method()"); + } +} + +interface Sub extends Super { + default void foo() { + <caret>super.method(); + } +}
\ No newline at end of file diff --git a/java/java-tests/testData/compileServer/incremental/fieldProperties/intNonStaticConstantChange.log b/java/java-tests/testData/compileServer/incremental/fieldProperties/intNonStaticConstantChange.log new file mode 100644 index 000000000000..6785cb00a98b --- /dev/null +++ b/java/java-tests/testData/compileServer/incremental/fieldProperties/intNonStaticConstantChange.log @@ -0,0 +1,12 @@ +Cleaning output files: +out/production/IntNonStaticConstantChange/Server.class +End of files +Compiling files: +src/Server.java +End of files +Cleaning output files: +out/production/IntNonStaticConstantChange/Client.class +End of files +Compiling files: +src/Client.java +End of files diff --git a/java/java-tests/testData/compileServer/incremental/fieldProperties/intNonStaticConstantChange/Server.java.new b/java/java-tests/testData/compileServer/incremental/fieldProperties/intNonStaticConstantChange/Server.java.new new file mode 100644 index 000000000000..6bf139a9035b --- /dev/null +++ b/java/java-tests/testData/compileServer/incremental/fieldProperties/intNonStaticConstantChange/Server.java.new @@ -0,0 +1,3 @@ +class Server { + final int var = 500; +}
\ No newline at end of file diff --git a/java/java-tests/testData/compileServer/incremental/fieldProperties/intNonStaticConstantChange/src/Client.java b/java/java-tests/testData/compileServer/incremental/fieldProperties/intNonStaticConstantChange/src/Client.java new file mode 100644 index 000000000000..3a73a3fb1795 --- /dev/null +++ b/java/java-tests/testData/compileServer/incremental/fieldProperties/intNonStaticConstantChange/src/Client.java @@ -0,0 +1,5 @@ +class Client { + public static void main(String[] args) { + System.out.println(new Server().var); + } +}
\ No newline at end of file diff --git a/java/java-tests/testData/compileServer/incremental/fieldProperties/intNonStaticConstantChange/src/Server.java b/java/java-tests/testData/compileServer/incremental/fieldProperties/intNonStaticConstantChange/src/Server.java new file mode 100644 index 000000000000..123c7e6b0a13 --- /dev/null +++ b/java/java-tests/testData/compileServer/incremental/fieldProperties/intNonStaticConstantChange/src/Server.java @@ -0,0 +1,3 @@ +class Server { + final int var = 100; +}
\ No newline at end of file diff --git a/java/java-tests/testData/inspection/dataFlow/fixture/ContractAnnotation.java b/java/java-tests/testData/inspection/dataFlow/fixture/ContractAnnotation.java index a5c27dd21749..3d97047e240e 100644 --- a/java/java-tests/testData/inspection/dataFlow/fixture/ContractAnnotation.java +++ b/java/java-tests/testData/inspection/dataFlow/fixture/ContractAnnotation.java @@ -46,4 +46,7 @@ public class AssertIsNotNull { @Contract(<warning descr="Method takes 2 parameters, while contract clause number 1 expects 1">"null -> _"</warning>) void wrongParameterCount(Object a, boolean b) {} + + @Contract(pure=<warning descr="Pure methods must return something, void is not allowed as a return type">true</warning>) + void voidPureMethod() {} } diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/AddAnnotationFixTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/AddAnnotationFixTest.java index f404fa152d0d..231a0cd45c0a 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/AddAnnotationFixTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/AddAnnotationFixTest.java @@ -1,4 +1,20 @@ /* + * Copyright 2000-2013 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* * User: anna * Date: 27-Jun-2007 */ @@ -85,7 +101,7 @@ public class AddAnnotationFixTest extends UsefulTestCase { addLibrary("/content/anno"); } - private void addLibrary(final @NotNull String... annotationsDirs) { + private void addLibrary(@NotNull final String... annotationsDirs) { ApplicationManager.getApplication().runWriteAction(new Runnable() { @Override public void run() { diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/GenerateCreateUITest.java b/java/java-tests/testSrc/com/intellij/codeInsight/GenerateCreateUITest.java index 683a22a5863f..ef3f470d7938 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/GenerateCreateUITest.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/GenerateCreateUITest.java @@ -17,7 +17,6 @@ package com.intellij.codeInsight; import com.intellij.codeInsight.generation.actions.GenerateCreateUIAction; import com.intellij.psi.PsiClass; -import com.intellij.psi.PsiElement; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.testFramework.LightCodeInsightTestCase; diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/completion/HippieCompletionTest.groovy b/java/java-tests/testSrc/com/intellij/codeInsight/completion/HippieCompletionTest.groovy index 16ca708560a6..ab9ea13a425d 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/completion/HippieCompletionTest.groovy +++ b/java/java-tests/testSrc/com/intellij/codeInsight/completion/HippieCompletionTest.groovy @@ -113,6 +113,21 @@ class Foo { ''' } + public void "test complete variable name in string literal"() { + myFixture.configureByText "a.java", ''' +class Xoo { + String foobar = "foo<caret>"; +} +''' + complete() + myFixture.checkResult ''' +class Xoo { + String foobar = "foobar<caret>"; +} +''' + + } + private void complete() { myFixture.performEditorAction(IdeActions.ACTION_HIPPIE_COMPLETION) } diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/completion/JavaAutoPopupTest.groovy b/java/java-tests/testSrc/com/intellij/codeInsight/completion/JavaAutoPopupTest.groovy index 052442f9a61e..04a73243dd91 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/completion/JavaAutoPopupTest.groovy +++ b/java/java-tests/testSrc/com/intellij/codeInsight/completion/JavaAutoPopupTest.groovy @@ -116,7 +116,7 @@ class JavaAutoPopupTest extends CompletionAutoPopupTestCase { } """) type "r" - assertContains "iterable", "iter" + myFixture.assertPreferredCompletionItems 1, "iter", "iterable" type '\b' assertContains "iterable" @@ -131,7 +131,7 @@ class JavaAutoPopupTest extends CompletionAutoPopupTestCase { assertContains "iterable" type "r" - assertContains "iterable", "iter" + myFixture.assertPreferredCompletionItems 1, "iter", "iterable" } public void testExplicitSelectionShouldSurvive() { @@ -151,7 +151,7 @@ class JavaAutoPopupTest extends CompletionAutoPopupTestCase { assertEquals 'iterable2', lookup.currentItem.lookupString type "r" - myFixture.assertPreferredCompletionItems 2, "iterable", "iter", 'iterable2' + myFixture.assertPreferredCompletionItems 2, "iter", "iterable", 'iterable2' } @@ -172,7 +172,7 @@ class JavaAutoPopupTest extends CompletionAutoPopupTestCase { assertEquals 'iterable2', lookup.currentItem.lookupString type "r" - myFixture.assertPreferredCompletionItems 2, "iterable", "iter", 'iterable2' + myFixture.assertPreferredCompletionItems 2, "iter", "iterable", 'iterable2' } @@ -1305,7 +1305,7 @@ class Foo { type 'e' myFixture.assertPreferredCompletionItems 0, 'itera', 'itex' type 'r' - myFixture.assertPreferredCompletionItems 0, 'itera', 'iter' + myFixture.assertPreferredCompletionItems 1, 'iter', 'itera' type '\b' myFixture.assertPreferredCompletionItems 0, 'itera', 'itex' } @@ -1544,9 +1544,9 @@ class Foo { } ''' type 'tpl' - myFixture.assertPreferredCompletionItems 0, 'tplMn', 'tpl' + myFixture.assertPreferredCompletionItems 1, 'tpl', 'tplMn' - LookupElementPresentation p = LookupElementPresentation.renderElement(myFixture.lookupElements[1]) + LookupElementPresentation p = LookupElementPresentation.renderElement(myFixture.lookupElements[0]) assert p.itemText == 'tpl' assert !p.tailText def tabKeyPresentation = KeyEvent.getKeyText(TemplateSettings.TAB_CHAR as int) diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/completion/KeywordCompletionTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/completion/KeywordCompletionTest.java index 55fe8231723e..6b9cff3f6149 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/completion/KeywordCompletionTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/completion/KeywordCompletionTest.java @@ -90,6 +90,8 @@ public class KeywordCompletionTest extends LightCompletionTestCase { public void testCatchFinally() throws Exception { doTest(2, "catch", "finally"); } public void testSuper1() throws Exception { doTest(1, "super"); } public void testSuper2() throws Exception { doTest(0, "super"); } + public void testSuper3() throws Exception { doTest(true); } + public void testSuper4() throws Exception { doTest(0, "class"); } public void testContinue() throws Exception { doTest(false); } public void testThrowsOnSeparateLine() throws Exception { doTest(false); } public void testDefaultInAnno() throws Exception { doTest(false); } diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/completion/MethodChainsCompletionTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/completion/MethodChainsCompletionTest.java index 78d3b1dad87a..f52ec11a844c 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/completion/MethodChainsCompletionTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/completion/MethodChainsCompletionTest.java @@ -66,6 +66,10 @@ public class MethodChainsCompletionTest extends AbstractCompilerAwareTest { assertAdvisorLookupElementEquals("p.getBaseDir", 0, 8, 1, 0, assertOneElement(doCompletion())); } + public void testOneChainContainsOther2() { + assertLookupElementStringEquals(assertOneElement(doCompletion()), "getManager"); + } + public void testTwoVariablesWithOneTypeOrSuperType() { assertAdvisorLookupElementEquals("c.getProject", 0, 4, 1, 0, assertOneElement(doCompletion())); } diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/completion/SmartTypeCompletionOrderingTest.groovy b/java/java-tests/testSrc/com/intellij/codeInsight/completion/SmartTypeCompletionOrderingTest.groovy index 11784200fef5..195a1a8854c9 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/completion/SmartTypeCompletionOrderingTest.groovy +++ b/java/java-tests/testSrc/com/intellij/codeInsight/completion/SmartTypeCompletionOrderingTest.groovy @@ -317,6 +317,9 @@ public class SmartTypeCompletionOrderingTest extends CompletionSortingTestCase { public void testGetWildcardLogger() { checkPreferredItems 0, 'Foo.class', 'forName' } + public void testPreferLocalWildcardClassOverObject() { + checkPreferredItems 0, 'type', 'Object.class' + } @Override protected String getBasePath() { diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/DiamondSuite.java b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/DiamondSuite.java index 2c0723587623..80870c246655 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/DiamondSuite.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/DiamondSuite.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2011 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,7 +17,8 @@ package com.intellij.codeInsight.daemon; import com.intellij.codeInsight.daemon.quickFix.ChangeNewOperatorTypeTest; import com.intellij.codeInsight.daemon.quickFix.Simplify2DiamondInspectionsTest; -import com.intellij.refactoring.*; +import com.intellij.refactoring.IntroduceParameterTest; +import com.intellij.refactoring.IntroduceVariableTest; import junit.framework.Test; import junit.framework.TestSuite; diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/HighlightStressTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/HighlightStressTest.java index f97b791f9ff4..2e5b38890e56 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/HighlightStressTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/HighlightStressTest.java @@ -226,6 +226,7 @@ public class HighlightStressTest extends LightDaemonAnalyzerTestCase { } final String text = imports + "\n class X {{\n" + usages + "}}"; ApplicationManager.getApplication().runWriteAction(new Runnable() { + @Override public void run() { getEditor().getDocument().setText(text); } diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/LightAdvHighlightingJdk7Test.java b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/LightAdvHighlightingJdk7Test.java index edd3fb0026be..03e81dd85c5a 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/LightAdvHighlightingJdk7Test.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/LightAdvHighlightingJdk7Test.java @@ -15,7 +15,7 @@ */ package com.intellij.codeInsight.daemon; -import com.intellij.ExtensionPoints; +import com.intellij.ToolExtensionPoints; import com.intellij.codeInsight.daemon.impl.HighlightInfo; import com.intellij.codeInspection.LocalInspectionTool; import com.intellij.codeInspection.compiler.JavacQuirksInspection; @@ -106,7 +106,7 @@ public class LightAdvHighlightingJdk7Test extends LightDaemonAnalyzerTestCase { } public void testDynamicallyAddIgnoredAnnotations() throws Exception { - ExtensionPoint<EntryPoint> point = Extensions.getRootArea().getExtensionPoint(ExtensionPoints.DEAD_CODE_TOOL); + ExtensionPoint<EntryPoint> point = Extensions.getRootArea().getExtensionPoint(ToolExtensionPoints.DEAD_CODE_TOOL); EntryPoint extension = new EntryPoint() { @NotNull @Override public String getDisplayName() { return "duh"; } @Override public boolean isEntryPoint(RefElement refElement, PsiElement psiElement) { return false; } diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/LightAdvHighlightingTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/LightAdvHighlightingTest.java index c4d120404060..37b9c4ccc392 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/LightAdvHighlightingTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/LightAdvHighlightingTest.java @@ -389,6 +389,6 @@ public class LightAdvHighlightingTest extends LightDaemonAnalyzerTestCase { public void testInsane() throws IOException { configureFromFileText("x.java", "class X { \nxxxx\n }"); List<HighlightInfo> infos = highlightErrors(); - assertTrue(infos.size() != 0); + assertTrue(!infos.isEmpty()); } } diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/RehighlightingTest.groovy b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/RehighlightingTest.groovy index 34b9f752f563..860be8b52666 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/RehighlightingTest.groovy +++ b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/RehighlightingTest.groovy @@ -1,5 +1,5 @@ /* - * Copyright 2000-2011 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,9 +15,8 @@ */ package com.intellij.codeInsight.daemon -import com.intellij.testFramework.fixtures.JavaCodeInsightFixtureTestCase import com.intellij.openapi.application.ApplicationManager - +import com.intellij.testFramework.fixtures.JavaCodeInsightFixtureTestCase /** * @author peter */ diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/Interface8MethodsHighlightingTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/Interface8MethodsHighlightingTest.java index f2e23bd2fe50..57a4d726a8dc 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/Interface8MethodsHighlightingTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/Interface8MethodsHighlightingTest.java @@ -31,6 +31,10 @@ public class Interface8MethodsHighlightingTest extends LightDaemonAnalyzerTestCa public void testCyclicSubstitutor() { doTest(false, false); } public void testThisAccessibility() { doTest(false, false); } public void testStaticMethodCalls() { doTest(false, false); } + public void testDefaultMethodOverrideEquivalentObject() { doTest(false, false); } + public void testDefaultSupersInStaticContext() { + doTest(false, false); + } private void doTest() { doTest(false, false); diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/Normal8CompletionTest.groovy b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/Normal8CompletionTest.groovy index 9c45a5ecd539..ddd15947a768 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/Normal8CompletionTest.groovy +++ b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/Normal8CompletionTest.groovy @@ -13,13 +13,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.intellij.codeInsight.daemon.lambda; - -import com.intellij.JavaTestUtil; -import com.intellij.codeInsight.completion.LightFixtureCompletionTestCase; -import com.intellij.testFramework.LightProjectDescriptor; -import org.jetbrains.annotations.NotNull; +package com.intellij.codeInsight.daemon.lambda +import com.intellij.JavaTestUtil +import com.intellij.codeInsight.completion.LightFixtureCompletionTestCase +import com.intellij.testFramework.LightProjectDescriptor +import org.jetbrains.annotations.NotNull /** * User: anna */ diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/AssignFieldFromParameterTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/AssignFieldFromParameterTest.java index 8e1ca1935635..40370435d99f 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/AssignFieldFromParameterTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/AssignFieldFromParameterTest.java @@ -1,8 +1,23 @@ +/* + * Copyright 2000-2013 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.intellij.codeInsight.daemon.quickFix; +import com.intellij.codeInsight.daemon.LightIntentionActionTestCase; import com.intellij.psi.codeStyle.CodeStyleSettings; import com.intellij.psi.codeStyle.CodeStyleSettingsManager; -import com.intellij.codeInsight.daemon.LightIntentionActionTestCase; import org.jdom.Element; /** diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/FixAllAnnotatorQuickfixTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/FixAllAnnotatorQuickfixTest.java index abeeec2b083a..b22bceca13c6 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/FixAllAnnotatorQuickfixTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/FixAllAnnotatorQuickfixTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2012 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,7 +21,9 @@ package com.intellij.codeInsight.daemon.quickFix; import com.intellij.codeInsight.intention.IntentionAction; -import com.intellij.codeInspection.*; +import com.intellij.codeInspection.DefaultHighlightVisitorBasedInspection; +import com.intellij.codeInspection.LocalQuickFix; +import com.intellij.codeInspection.ProblemDescriptor; import com.intellij.lang.Language; import com.intellij.lang.LanguageAnnotators; import com.intellij.lang.annotation.Annotation; diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/FlipIntersectionTypesTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/FlipIntersectionTypesTest.java new file mode 100644 index 000000000000..ddd8ce49bc9a --- /dev/null +++ b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/FlipIntersectionTypesTest.java @@ -0,0 +1,28 @@ +/* + * Copyright 2000-2013 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.intellij.codeInsight.daemon.quickFix; + +public class FlipIntersectionTypesTest extends LightQuickFixTestCase { + public void test() throws Exception { + doAllTests(); + } + + @Override + protected String getBasePath() { + return "/codeInsight/daemonCodeAnalyzer/quickFix/flipIntersection"; + } +} + diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/I18nQuickFixTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/I18nQuickFixTest.java index d55341d7af7e..9a9a3c66644d 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/I18nQuickFixTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/I18nQuickFixTest.java @@ -1,6 +1,20 @@ +/* + * Copyright 2000-2013 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.intellij.codeInsight.daemon.quickFix; -import com.intellij.codeInsight.daemon.quickFix.LightQuickFix15TestCase; import com.intellij.codeInspection.LocalInspectionTool; import com.intellij.codeInspection.i18n.I18nInspection; import com.intellij.openapi.util.Comparing; diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/I18nizeTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/I18nizeTest.java index 31e385d27694..099a7f4d3f0e 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/I18nizeTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/I18nizeTest.java @@ -1,3 +1,18 @@ +/* + * Copyright 2000-2013 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.intellij.codeInsight.daemon.quickFix; import com.intellij.codeInspection.i18n.I18nQuickFixHandler; @@ -32,7 +47,7 @@ public class I18nizeTest extends LightCodeInsightTestCase { action.update(event); @NonNls String afterFile = getBasePath() + "/after" + getTestName(false) + "." + ext; boolean afterFileExists = new File(PathManagerEx.getTestDataPath() + afterFile).exists(); - I18nQuickFixHandler handler = action.getHandler(event); + I18nQuickFixHandler handler = I18nizeAction.getHandler(event); try { if (handler != null) { handler.checkApplicability(getFile(), getEditor()); diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/highlighting/HighlightUsagesHandlerTest.groovy b/java/java-tests/testSrc/com/intellij/codeInsight/highlighting/HighlightUsagesHandlerTest.groovy index 885b336ba0ad..02d52a54da24 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/highlighting/HighlightUsagesHandlerTest.groovy +++ b/java/java-tests/testSrc/com/intellij/codeInsight/highlighting/HighlightUsagesHandlerTest.groovy @@ -1,12 +1,26 @@ -package com.intellij.codeInsight.highlighting; +/* + * Copyright 2000-2013 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.intellij.codeInsight.highlighting import com.intellij.JavaTestUtil import com.intellij.codeInsight.daemon.impl.IdentifierHighlighterPassFactory import com.intellij.codeInspection.sillyAssignment.SillyAssignmentInspection -import com.intellij.lang.annotation.HighlightSeverity; -import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase; -import org.jetbrains.annotations.NonNls; - +import com.intellij.lang.annotation.HighlightSeverity +import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase +import org.jetbrains.annotations.NonNls /** * @author cdr */ diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/intention/AddImportActionTest.groovy b/java/java-tests/testSrc/com/intellij/codeInsight/intention/AddImportActionTest.groovy index d06f12251a77..14486f7b4cad 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/intention/AddImportActionTest.groovy +++ b/java/java-tests/testSrc/com/intellij/codeInsight/intention/AddImportActionTest.groovy @@ -167,6 +167,22 @@ class Test { Collection<caret> c; } ''' + } + + public void testUnresolvedAnnotatedQualifiedImport() { + myFixture.configureByText 'a.java', ''' +class Test { + @Nullable Collection<caret> c; +} +''' + importClass(); + myFixture.checkResult '''import java.util.Collection; + +class Test { + @Nullable + Collection<caret> c; +} +''' } private def importClass() { diff --git a/java/java-tests/testSrc/com/intellij/codeInspection/DataFlowInspectionTest.java b/java/java-tests/testSrc/com/intellij/codeInspection/DataFlowInspectionTest.java index f8707d97f9e3..02dcfc0072b3 100644 --- a/java/java-tests/testSrc/com/intellij/codeInspection/DataFlowInspectionTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInspection/DataFlowInspectionTest.java @@ -40,12 +40,6 @@ public class DataFlowInspectionTest extends LightCodeInsightFixtureTestCase { } @Override - protected void setUp() throws Exception { - super.setUp(); - myFixture.addClass("package org.jetbrains.annotations; public @interface Contract { String value(); }"); - } - - @Override protected String getTestDataPath() { return JavaTestUtil.getJavaTestDataPath() + "/inspection/dataFlow/fixture/"; } diff --git a/java/java-tests/testSrc/com/intellij/find/FindManagerTest.java b/java/java-tests/testSrc/com/intellij/find/FindManagerTest.java index 562e1dd80f24..a7c477a52541 100644 --- a/java/java-tests/testSrc/com/intellij/find/FindManagerTest.java +++ b/java/java-tests/testSrc/com/intellij/find/FindManagerTest.java @@ -476,6 +476,8 @@ public class FindManagerTest extends DaemonAnalyzerTestCase { findModel.setRegularExpressions(true); FindManagerTestUtils.runFindForwardAndBackward(findManager, findModel, text); + + FindManagerTestUtils.runFindForwardAndBackward(findManager, findModel, text, "groovy"); } public void testFindInCommentsProperlyWorksWithOffsets() throws Exception{ diff --git a/java/java-tests/testSrc/com/intellij/navigation/ChooseByNameTest.groovy b/java/java-tests/testSrc/com/intellij/navigation/ChooseByNameTest.groovy index d6c4e81bd6e4..5deabbd30fd8 100644 --- a/java/java-tests/testSrc/com/intellij/navigation/ChooseByNameTest.groovy +++ b/java/java-tests/testSrc/com/intellij/navigation/ChooseByNameTest.groovy @@ -167,6 +167,15 @@ class Intf { assert getPopupElements(new GotoSymbolModel2(project), 'bar.goo.zzzZzz') == [method] } + public void "test line and column suffix"() { + def c = myFixture.addClass("package foo; class Bar {}") + assert getPopupElements(new GotoClassModel2(project), 'Bar') == [c] + assert getPopupElements(new GotoClassModel2(project), 'Bar:2') == [c] + assert getPopupElements(new GotoClassModel2(project), 'Bar:2:3') == [c] + assert getPopupElements(new GotoClassModel2(project), 'Bar:[2:3]') == [c] + assert getPopupElements(new GotoClassModel2(project), 'Bar:[2,3]') == [c] + } + private List<Object> getPopupElements(ChooseByNameModel model, String text) { return getPopupElements(createPopup(model), text) } diff --git a/java/java-tests/testSrc/com/intellij/openapi/roots/impl/DirectoryIndexTest.java b/java/java-tests/testSrc/com/intellij/openapi/roots/impl/DirectoryIndexTest.java index 4325dcab1623..d86fd6b2f32a 100644 --- a/java/java-tests/testSrc/com/intellij/openapi/roots/impl/DirectoryIndexTest.java +++ b/java/java-tests/testSrc/com/intellij/openapi/roots/impl/DirectoryIndexTest.java @@ -220,10 +220,15 @@ public class DirectoryIndexTest extends IdeaTestCase { public void testDirsByPackageName() { checkPackage("", true, myFileLibSrc, myFileLibCls, mySrcDir1, myTestSrc1, myResDir, myTestResDir, myLibSrcDir, myLibClsDir, mySrcDir2); checkPackage("", false, myFileLibCls, mySrcDir1, myTestSrc1, myResDir, myTestResDir, myLibClsDir, mySrcDir2); + checkPackage("pack1", true, myPack1Dir); checkPackage("pack1", false, myPack1Dir); + checkPackage("pack2", true, myPack2Dir); checkPackage("pack2", false, myPack2Dir); + + checkPackage(".pack2", false); + checkPackage(".pack2", true); } public void testCreateDir() throws Exception { @@ -503,16 +508,17 @@ public class DirectoryIndexTest extends IdeaTestCase { checkInfo(myModule1Dir, myModule, true, false, "", null, myModule); checkInfo(mySrcDir1, myModule, true, false, "", JavaSourceRootType.SOURCE, myModule); - - //todo this looks strange and inconsistent: the same library classes and sources have different order entries + checkInfo(myLibDir, myModule, true, false, "lib", null, myModule); checkInfo(myLibClsDir, myModule, true, false, "", null, myModule2, myModule3); + + //myModule is included into order entries instead of myModule2 because classes root for libraries dominates on source roots checkInfo(myLibSrcDir, myModule, true, true, "", null, myModule, myModule3); checkInfo(myResDir, myModule, true, false, "", JavaResourceRootType.RESOURCE, myModule); - //todo uncomment or replace with another assertion about library-excluded dir inside module content - //checkInfoNull(myExcludedLibSrcDir); + checkInfo(myExcludedLibSrcDir, null, true, false, "lib.src.exc", null, myModule3, myModule); + checkInfo(myExcludedLibClsDir, null, true, false, "lib.cls.exc", null, myModule3); } @@ -547,10 +553,10 @@ public class DirectoryIndexTest extends IdeaTestCase { assertEquals(packageName, fileIndex.getPackageNameByDirectory(dir)); } - assertEquals(modulesOfOrderEntries.length, info.getOrderEntries().length); + assertEquals(Arrays.toString(info.getOrderEntries()), modulesOfOrderEntries.length, info.getOrderEntries().length); for (Module aModule : modulesOfOrderEntries) { OrderEntry found = info.findOrderEntryWithOwnerModule(aModule); - assertNotNull(found); + assertNotNull("not found: " + aModule, found); } } diff --git a/java/java-tests/testSrc/com/intellij/patterns/VirtualFilePatternsTest.groovy b/java/java-tests/testSrc/com/intellij/patterns/VirtualFilePatternsTest.groovy new file mode 100644 index 000000000000..18d5622132b6 --- /dev/null +++ b/java/java-tests/testSrc/com/intellij/patterns/VirtualFilePatternsTest.groovy @@ -0,0 +1,31 @@ +/* + * Copyright 2000-2013 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.intellij.patterns +import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase +/** + * @author peter + */ +public class VirtualFilePatternsTest extends LightCodeInsightFixtureTestCase { + + public void testWithSuperParent() { + def file = myFixture.addFileToProject("foo/bar.txt", "").virtualFile + assert PlatformPatterns.virtualFile().withSuperParent(1, PlatformPatterns.virtualFile().withName("foo")).accepts(file) + assert !PlatformPatterns.virtualFile().withSuperParent(1, PlatformPatterns.virtualFile().withName("bar")).accepts(file) + assert !PlatformPatterns.virtualFile().withSuperParent(2, PlatformPatterns.virtualFile().withName("bar")).accepts(file) + assert !PlatformPatterns.virtualFile().withSuperParent(10, PlatformPatterns.virtualFile().withName("bar")).accepts(file) + assert !PlatformPatterns.virtualFile().withSuperParent(10, PlatformPatterns.virtualFile().withName("foo")).accepts(file) + } +} diff --git a/java/java-tests/testSrc/com/intellij/psi/ClsRepositoryUseTest.java b/java/java-tests/testSrc/com/intellij/psi/ClsRepositoryUseTest.java index 22a3b81138e1..ea6614e41d0f 100644 --- a/java/java-tests/testSrc/com/intellij/psi/ClsRepositoryUseTest.java +++ b/java/java-tests/testSrc/com/intellij/psi/ClsRepositoryUseTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2012 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,7 +19,6 @@ import com.intellij.ide.highlighter.JavaFileType; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ex.PathManagerEx; import com.intellij.openapi.diagnostic.Logger; -import com.intellij.openapi.projectRoots.impl.JavaSdkImpl; import com.intellij.openapi.roots.ModuleRootModificationUtil; import com.intellij.openapi.roots.OrderRootType; import com.intellij.openapi.util.io.FileUtil; @@ -555,7 +554,7 @@ public class ClsRepositoryUseTest extends PsiTestCase { assertEquals("java.util.Map.Entry", setTypeResolveResultElement.getQualifiedName()); final PsiTypeParameter[] typeParameters = setTypeResolveResultElement.getTypeParameters(); assertEquals(2, typeParameters.length); - PsiType[] mapParams = new PsiType[]{ + PsiType[] mapParams = { setTypeResolveResult.getSubstitutor().substitute(typeParameters[0]), setTypeResolveResult.getSubstitutor().substitute(typeParameters[1]) }; diff --git a/java/java-tests/testSrc/com/intellij/psi/GenericsTestCase.java b/java/java-tests/testSrc/com/intellij/psi/GenericsTestCase.java index 11c14e49e443..a9ca3405cb4b 100644 --- a/java/java-tests/testSrc/com/intellij/psi/GenericsTestCase.java +++ b/java/java-tests/testSrc/com/intellij/psi/GenericsTestCase.java @@ -1,3 +1,18 @@ +/* + * Copyright 2000-2013 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.intellij.psi; import com.intellij.openapi.application.ApplicationManager; @@ -23,7 +38,7 @@ public abstract class GenericsTestCase extends PsiTestCase { protected void setupGenericSampleClasses() { final String commonPath = PathManagerEx.getTestDataPath().replace(File.separatorChar, '/') + "/psi/types/src"; - final VirtualFile[] commonRoot = new VirtualFile[] { null }; + final VirtualFile[] commonRoot = { null }; ApplicationManager.getApplication().runWriteAction(new Runnable() { @Override public void run() { diff --git a/java/java-tests/testSrc/com/intellij/psi/MiscPsiTest.java b/java/java-tests/testSrc/com/intellij/psi/MiscPsiTest.java index 2a89e218cded..6e58fee905ed 100644 --- a/java/java-tests/testSrc/com/intellij/psi/MiscPsiTest.java +++ b/java/java-tests/testSrc/com/intellij/psi/MiscPsiTest.java @@ -1,3 +1,18 @@ +/* + * Copyright 2000-2013 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.intellij.psi; import com.intellij.openapi.application.ApplicationManager; @@ -44,7 +59,7 @@ public class MiscPsiTest extends LightCodeInsightFixtureTestCase { public void testCopyBinaryFile() throws Exception{ VirtualFile vFile = myFixture.addFileToProject("Test.xxx", "").getVirtualFile(); - final byte[] bytes = new byte[]{12,34,56,78,90,45,83,0x22,(byte)0xff, (byte)0xff, (byte)0xff, (byte)0xee}; + final byte[] bytes = {12,34,56,78,90,45,83,0x22,(byte)0xff, (byte)0xff, (byte)0xff, (byte)0xee}; vFile.setBinaryContent(bytes); VirtualFile vDir = myFixture.getTempDirFixture().findOrCreateDir("dir"); diff --git a/java/java-tests/testSrc/com/intellij/psi/formatter/java/JavaFormatterInEditorTest.java b/java/java-tests/testSrc/com/intellij/psi/formatter/java/JavaFormatterInEditorTest.java index de3e88e4e6c1..7355feba87e3 100644 --- a/java/java-tests/testSrc/com/intellij/psi/formatter/java/JavaFormatterInEditorTest.java +++ b/java/java-tests/testSrc/com/intellij/psi/formatter/java/JavaFormatterInEditorTest.java @@ -23,13 +23,13 @@ import org.jetbrains.annotations.NotNull; import java.io.IOException; /** - * Is intended to test formatting in editor behavior, i.e. check how formatting affects things like caret position, selection etc. - * + * Is intended to test formatting in editor behavior, i.e. check how formatting affects things like caret position, selection etc. + * * @author Denis Zhdanov * @since 6/1/11 6:17 PM */ public class JavaFormatterInEditorTest extends LightPlatformCodeInsightTestCase { - + public void testCaretPositionOnLongLineWrapping() throws IOException { // Inspired by IDEA-70242 getCurrentCodeStyleSettings().getCommonSettings(JavaLanguage.INSTANCE).WRAP_LONG_LINES = true; @@ -39,7 +39,7 @@ public class JavaFormatterInEditorTest extends LightPlatformCodeInsightTestCase "\n" + "class <caret>Test {\n" + "}", - + "import static java.util.concurrent\n" + " .atomic.AtomicInteger.*;\n" + "\n" + @@ -47,10 +47,59 @@ public class JavaFormatterInEditorTest extends LightPlatformCodeInsightTestCase "}" ); } - + + public void testCaretPositionPreserved_WhenOnSameLineWithWhiteSpacesOnly() throws IOException { + String text = "class Test {\n" + + " void test() {\n" + + " <caret>\n" + + " }\n" + + "}"; + doTest(text, text); + + String before = "class Test {\n" + + " void test() {\n" + + " <caret> \n" + + " }\n" + + "}"; + doTest(before, text); + } + + public void testCaretPositionPreserved_WhenSomeFormattingNeeded() throws IOException { + String before = "public class Test {\n" + + " int a;\n" + + " \n" + + " public static void main(String[] args) {\n" + + " <caret>\n" + + " }\n" + + "\n" + + " static final long j = 2;\n" + + "}"; + String after = "public class Test {\n" + + " int a;\n" + + "\n" + + " public static void main(String[] args) {\n" + + " <caret>\n" + + " }\n" + + "\n" + + " static final long j = 2;\n" + + "}"; + doTest(before, after); + + before = "public class Test {\n" + + " int a;\n" + + " \n" + + " public static void main(String[] args) {\n" + + " <caret> \n" + + " }\n" + + "\n" + + " static final long j = 2;\n" + + "}"; + doTest(before, after); + } + public void doTest(@NotNull String before, @NotNull String after) throws IOException { configureFromFileText(getTestName(false) + ".java", before); CodeStyleManager.getInstance(getProject()).reformatText(getFile(), 0, getEditor().getDocument().getTextLength()); checkResultByText(after); } -} +}
\ No newline at end of file diff --git a/java/java-tests/testSrc/com/intellij/psi/impl/file/impl/InvalidateClassFileTest.java b/java/java-tests/testSrc/com/intellij/psi/impl/file/impl/InvalidateClassFileTest.java index 94b1648bf5ae..85558dcf6ac4 100644 --- a/java/java-tests/testSrc/com/intellij/psi/impl/file/impl/InvalidateClassFileTest.java +++ b/java/java-tests/testSrc/com/intellij/psi/impl/file/impl/InvalidateClassFileTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2012 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -60,7 +60,7 @@ public class InvalidateClassFileTest extends PsiTestCase { PsiClass clazz = getJavaFacade().findClass("Clazz", GlobalSearchScope.allScope(myProject)); assertNotNull(clazz); - final boolean[] notified = new boolean[] {false}; + final boolean[] notified = {false}; final PsiTreeChangeAdapter listener = new PsiTreeChangeAdapter() { @Override public void childRemoved(@NotNull PsiTreeChangeEvent event) { diff --git a/java/jdkAnnotations/java/util/concurrent/annotations.xml b/java/jdkAnnotations/java/util/concurrent/annotations.xml index 4ffdf78dc769..762c68bde315 100644 --- a/java/jdkAnnotations/java/util/concurrent/annotations.xml +++ b/java/jdkAnnotations/java/util/concurrent/annotations.xml @@ -271,9 +271,6 @@ <item name="java.util.concurrent.ScheduledExecutorService java.util.concurrent.ScheduledFuture<V> schedule(java.util.concurrent.Callable<V>, long, java.util.concurrent.TimeUnit) 2"> <annotation name="org.jetbrains.annotations.NotNull" /> </item> - <item name="java.util.concurrent.ThreadFactory java.lang.Thread newThread(java.lang.Runnable)"> - <annotation name="org.jetbrains.annotations.NotNull" /> - </item> <item name="java.util.concurrent.ThreadFactory java.lang.Thread newThread(java.lang.Runnable) 0"> <annotation name="org.jetbrains.annotations.NotNull" /> </item> diff --git a/java/jsp-spi/src/com/intellij/psi/impl/source/jsp/JspContextManager.java b/java/jsp-spi/src/com/intellij/psi/impl/source/jsp/JspContextManager.java index 21d1701b096d..5f877f46a0cd 100644 --- a/java/jsp-spi/src/com/intellij/psi/impl/source/jsp/JspContextManager.java +++ b/java/jsp-spi/src/com/intellij/psi/impl/source/jsp/JspContextManager.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,12 +37,15 @@ public abstract class JspContextManager { public abstract void setContextFile(@NotNull PsiFile file, @Nullable BaseJspFile contextFile); - public abstract @Nullable + @Nullable + public abstract BaseJspFile getContextFile(@NotNull PsiFile file); - public abstract @Nullable JspFile getConfiguredContextFile(@NotNull PsiFile file); + @Nullable + public abstract JspFile getConfiguredContextFile(@NotNull PsiFile file); - public @NotNull + @NotNull + public BaseJspFile getRootContextFile(@NotNull BaseJspFile file) { BaseJspFile rootContext = file; HashSet<BaseJspFile> recursionPreventer = new HashSet<BaseJspFile>(); diff --git a/java/jsp-spi/src/com/intellij/psi/impl/source/jsp/JspManager.java b/java/jsp-spi/src/com/intellij/psi/impl/source/jsp/JspManager.java index 46d04cde530f..3fb2155d4b6a 100644 --- a/java/jsp-spi/src/com/intellij/psi/impl/source/jsp/JspManager.java +++ b/java/jsp-spi/src/com/intellij/psi/impl/source/jsp/JspManager.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -59,7 +59,7 @@ public abstract class JspManager implements IBaseJspManager { public abstract List<Pair<String,String>> getAvailableFunctions(@NotNull final JspFile context); @Nullable - public abstract String getPrefixForNamespace(@NotNull String namespaceUri, final @NotNull JspFile context); + public abstract String getPrefixForNamespace(@NotNull String namespaceUri, @NotNull final JspFile context); @Nullable public abstract String getDefaultPrefix(@NotNull XmlFile taglibFile); diff --git a/java/mockJDK-1.7/jre/lib/annotations.jar b/java/mockJDK-1.7/jre/lib/annotations.jar Binary files differindex c1e4afba8bee..72aa54c908ed 100644 --- a/java/mockJDK-1.7/jre/lib/annotations.jar +++ b/java/mockJDK-1.7/jre/lib/annotations.jar diff --git a/java/openapi/src/com/intellij/ide/util/projectWizard/JavaModuleBuilder.java b/java/openapi/src/com/intellij/ide/util/projectWizard/JavaModuleBuilder.java index d20b1bac8bc0..3184488e0a33 100644 --- a/java/openapi/src/com/intellij/ide/util/projectWizard/JavaModuleBuilder.java +++ b/java/openapi/src/com/intellij/ide/util/projectWizard/JavaModuleBuilder.java @@ -91,8 +91,8 @@ public class JavaModuleBuilder extends ModuleBuilder implements SourcePathsBuild } @Override - public ModuleWizardStep[] createWizardSteps(@NotNull WizardContext wizardContext, @NotNull ModulesProvider modulesProvider, boolean forNewWizard) { - return getModuleType().createWizardSteps(wizardContext, this, modulesProvider, forNewWizard); + public ModuleWizardStep[] createWizardSteps(@NotNull WizardContext wizardContext, @NotNull ModulesProvider modulesProvider) { + return getModuleType().createWizardSteps(wizardContext, this, modulesProvider); } public void setupRootModel(ModifiableRootModel rootModel) throws ConfigurationException { diff --git a/java/openapi/src/com/intellij/openapi/roots/libraries/JarVersionDetectionUtil.java b/java/openapi/src/com/intellij/openapi/roots/libraries/JarVersionDetectionUtil.java index f92d61b29096..2e5472ee3443 100644 --- a/java/openapi/src/com/intellij/openapi/roots/libraries/JarVersionDetectionUtil.java +++ b/java/openapi/src/com/intellij/openapi/roots/libraries/JarVersionDetectionUtil.java @@ -26,13 +26,13 @@ import com.intellij.openapi.vfs.VirtualFile; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.jar.Attributes; import java.util.jar.JarFile; import java.util.jar.Manifest; -import java.util.zip.ZipEntry; public class JarVersionDetectionUtil { private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.roots.libraries.JarVersionDetectionUtil"); @@ -106,5 +106,28 @@ public class JarVersionDetectionUtil { } return null; } + + private static String getJarAttribute(@NotNull File jar, @NotNull String attributeName, @Nullable String entryName) throws IOException { + JarFile runJar = new JarFile(jar); + try { + Attributes attributes = entryName == null ? runJar.getManifest().getMainAttributes() : runJar.getManifest().getAttributes(entryName); + return attributes.getValue(attributeName); + } + finally { + runJar.close(); + } + } + + public static String getBundleVersion(@NotNull File jar) throws IOException { + return getJarAttribute(jar, "Bundle-Version", null); + } + + public static String getImplementationVersion(@NotNull File jar) throws IOException { + return getJarAttributeVersion(jar, Attributes.Name.IMPLEMENTATION_VERSION, null); + } + + public static String getJarAttributeVersion(@NotNull File jar, @NotNull Attributes.Name attributeName, @Nullable String entryName) throws IOException { + return getJarAttribute(jar, attributeName.toString(), entryName); + } } diff --git a/java/openapi/src/com/intellij/psi/search/scope/packageSet/PatternPackageSet.java b/java/openapi/src/com/intellij/psi/search/scope/packageSet/PatternPackageSet.java index 7950e60f1a81..363a57cd805b 100644 --- a/java/openapi/src/com/intellij/psi/search/scope/packageSet/PatternPackageSet.java +++ b/java/openapi/src/com/intellij/psi/search/scope/packageSet/PatternPackageSet.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -51,7 +51,7 @@ public class PatternPackageSet extends PatternBasedPackageSet { myModulePatternText = modulePattern; Pattern mmgp = null; Pattern mmp = null; - if (modulePattern == null || modulePattern.length() == 0) { + if (modulePattern == null || modulePattern.isEmpty()) { mmp = null; } else { diff --git a/java/testFramework/src/com/intellij/codeInsight/CodeInsightTestCase.java b/java/testFramework/src/com/intellij/codeInsight/CodeInsightTestCase.java index 1cd7d069dc20..142b66c3f78d 100644 --- a/java/testFramework/src/com/intellij/codeInsight/CodeInsightTestCase.java +++ b/java/testFramework/src/com/intellij/codeInsight/CodeInsightTestCase.java @@ -419,6 +419,7 @@ public abstract class CodeInsightTestCase extends PsiTestCase { protected void setupCursorAndSelection(final Editor editor) { ApplicationManager.getApplication().runWriteAction(new Runnable() { + @Override public void run() { Document document = editor.getDocument(); final String text = document.getText(); |