Merge remote-tracking branch 'origin/master'

This commit is contained in:
Ekaterina Tuzova
2015-02-24 19:03:02 +03:00
410 changed files with 6122 additions and 3881 deletions
+1 -1
View File
@@ -151,7 +151,7 @@ if [ "$IS_EAP" = "true" ]; then
OS_NAME=`echo $OS_TYPE | "$TR" '[:upper:]' '[:lower:]'`
AGENT_LIB="yjpagent-$OS_NAME$BITS"
if [ -r "$IDE_BIN_HOME/lib$AGENT_LIB.so" ]; then
AGENT="-agentlib:$AGENT_LIB=disablej2ee,disablealloc,delay=10000,sessionname=@@system_selector@@"
AGENT="-agentlib:$AGENT_LIB=disablealloc,delay=10000,sessionname=@@system_selector@@"
fi
fi
+9
View File
@@ -784,6 +784,8 @@ binding.setVariable("buildMacZip", { String zipRoot, String zipPath, List paths,
exclude(name: "bin/fsnotifier")
exclude(name: "bin/restarter")
exclude(name: "MacOS/*")
exclude(name: "build.txt")
exclude(name: "NOTICE.txt")
extraBins.each {
exclude(name: it)
}
@@ -804,6 +806,13 @@ binding.setVariable("buildMacZip", { String zipRoot, String zipPath, List paths,
}
}
allPaths.each {
zipfileset(dir: it, prefix: "$zipRoot/Resources") {
include(name: "build.txt")
include(name: "NOTICE.txt")
}
}
zipfileset(file: "$macPath/bin/idea.properties", prefix: "$zipRoot/bin")
}
})
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2014 JetBrains s.r.o.
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -142,11 +142,11 @@ public class CompilerConfigurationImpl extends CompilerConfiguration implements
Element state = new Element("state");
XmlSerializer.serializeInto(myState, state, new SkipDefaultValuesSerializationFilters() {
@Override
protected boolean accepts(@NotNull Accessor accessor, @NotNull Object bean, @Nullable Object beanValue) {
public boolean accepts(@NotNull Accessor accessor, @NotNull Object bean) {
if (myState.compilerWasSpecified && "DEFAULT_COMPILER".equals(accessor.getName())) {
return true;
}
return super.accepts(accessor, bean, beanValue);
return super.accepts(accessor, bean);
}
});
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2014 JetBrains s.r.o.
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -93,6 +93,7 @@ import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;
import io.netty.util.internal.ThreadLocalRandom;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.ide.PooledThreadExecutor;
@@ -999,6 +1000,9 @@ public class BuildManager implements ApplicationComponent{
cmdLine.addParameter("-Didea.case.sensitive.fs=" + isFSCaseSensitive);
}
// this will make netty initialization faster on some systems
cmdLine.addParameter("-Dio.netty.initialSeedUniquifier=" + ThreadLocalRandom.getInitialSeedUniquifier());
boolean isProfilingMode = false;
final String additionalOptions = config.COMPILER_PROCESS_ADDITIONAL_VM_OPTIONS;
if (!StringUtil.isEmpty(additionalOptions)) {
@@ -1013,7 +1017,7 @@ public class BuildManager implements ApplicationComponent{
}
if (isProfilingMode) {
cmdLine.addParameter("-agentlib:yjpagent=disablej2ee,disablealloc,delay=10000,sessionname=ExternalBuild");
cmdLine.addParameter("-agentlib:yjpagent=disablealloc,delay=10000,sessionname=ExternalBuild");
}
// debugging
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2014 JetBrains s.r.o.
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -29,13 +29,11 @@ import com.intellij.lang.annotation.AnnotationSession;
import com.intellij.lang.annotation.ExternalAnnotator;
import com.intellij.lang.annotation.HighlightSeverity;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ReadAction;
import com.intellij.openapi.application.ReadActionProcessor;
import com.intellij.openapi.application.Result;
import com.intellij.openapi.compiler.*;
import com.intellij.openapi.compiler.options.ExcludesConfiguration;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.vfs.VirtualFile;
@@ -143,41 +141,41 @@ public class InspectionValidatorWrapper implements Validator {
return ProcessingItem.EMPTY_ARRAY;
}
final ExcludesConfiguration excludesConfiguration = ValidationConfiguration.getExcludedEntriesConfiguration(project);
final List<ProcessingItem> items = new ReadAction<List<ProcessingItem>>() {
@Override
protected void run(final Result<List<ProcessingItem>> result) {
final CompileScope compileScope = context.getCompileScope();
if (!myValidator.isAvailableOnScope(compileScope)) return;
final List<ProcessingItem> items =
DumbService.getInstance(project).runReadActionInSmartMode(new Computable<List<ProcessingItem>>() {
@Override
public List<ProcessingItem> compute() {
final CompileScope compileScope = context.getCompileScope();
if (!myValidator.isAvailableOnScope(compileScope)) return null;
final ArrayList<ProcessingItem> items = new ArrayList<ProcessingItem>();
final ArrayList<ProcessingItem> items = new ArrayList<ProcessingItem>();
final Processor<VirtualFile> processor = new ReadActionProcessor<VirtualFile>() {
@Override
public boolean processInReadAction(VirtualFile file) {
if (!file.isValid()) {
return true;
}
if (myCompilerManager.isExcludedFromCompilation(file) ||
excludesConfiguration.isExcluded(file)) {
return true;
}
final Module module = context.getModuleByFile(file);
if (module != null) {
final PsiFile psiFile = myPsiManager.findFile(file);
if (psiFile != null) {
items.add(new MyValidatorProcessingItem(psiFile));
final Processor<VirtualFile> processor = new Processor<VirtualFile>() {
@Override
public boolean process(VirtualFile file) {
if (!file.isValid()) {
return true;
}
}
return true;
}
};
ContainerUtil.process(myValidator.getFilesToProcess(myPsiManager.getProject(), context), processor);
result.setResult(items);
}
}.execute().getResultObject();
if (myCompilerManager.isExcludedFromCompilation(file) ||
excludesConfiguration.isExcluded(file)) {
return true;
}
final Module module = context.getModuleByFile(file);
if (module != null) {
final PsiFile psiFile = myPsiManager.findFile(file);
if (psiFile != null) {
items.add(new MyValidatorProcessingItem(psiFile));
}
}
return true;
}
};
ContainerUtil.process(myValidator.getFilesToProcess(myPsiManager.getProject(), context), processor);
return items;
}
});
if (items == null) return ProcessingItem.EMPTY_ARRAY;
return items.toArray(new ProcessingItem[items.size()]);
@@ -1,34 +0,0 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.debugger.actions;
import com.intellij.debugger.impl.DebuggerContextImpl;
import com.intellij.debugger.ui.impl.watch.DebuggerTreeNodeImpl;
import com.intellij.diff.DiffDialogHints;
import com.intellij.diff.DiffManager;
import com.intellij.diff.DiffRequestFactory;
import com.intellij.diff.requests.DiffRequest;
import com.intellij.openapi.project.Project;
/**
* @author Jeka
*/
public class CompareValueWithClipboardAction extends BaseValueAction {
protected void processText(final Project project, final String text, DebuggerTreeNodeImpl node, DebuggerContextImpl debuggerContext) {
DiffRequest request = DiffRequestFactory.getInstance().createClipboardVsValue(text);
DiffManager.getInstance().showDiff(project, request);
}
}
@@ -1,32 +0,0 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.debugger.actions;
import com.intellij.debugger.impl.DebuggerContextImpl;
import com.intellij.debugger.ui.impl.watch.DebuggerTreeNodeImpl;
import com.intellij.openapi.ide.CopyPasteManager;
import com.intellij.openapi.project.Project;
import java.awt.datatransfer.StringSelection;
/*
* @author Jeka
*/
public class CopyValueAction extends BaseValueAction {
protected void processText(final Project project, final String text, DebuggerTreeNodeImpl node, DebuggerContextImpl debuggerContext) {
CopyPasteManager.getInstance().setContents(new StringSelection(text));
}
}
@@ -1,51 +0,0 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.debugger.actions;
import com.intellij.debugger.ui.DebuggerPanelsManager;
import com.intellij.debugger.ui.impl.MainWatchPanel;
import com.intellij.debugger.ui.impl.watch.DebuggerTreeNodeImpl;
import com.intellij.debugger.ui.impl.watch.WatchItemDescriptor;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.project.Project;
/**
* User: lex
* Date: Sep 26, 2003
* Time: 8:34:01 PM
*/
public class EditWatchAction extends DebuggerAction {
public void actionPerformed(final AnActionEvent e) {
final DebuggerTreeNodeImpl selectedNode = getSelectedNode(e.getDataContext());
if(selectedNode == null || !(selectedNode.getDescriptor() instanceof WatchItemDescriptor)) return;
Project project = CommonDataKeys.PROJECT.getData(e.getDataContext());
MainWatchPanel watchPanel = DebuggerPanelsManager.getInstance(project).getWatchPanel();
if(watchPanel != null) {
watchPanel.editNode(selectedNode);
}
}
public void update(AnActionEvent e) {
final DebuggerTreeNodeImpl selectedNode = getSelectedNode(e.getDataContext());
e.getPresentation().setVisible(selectedNode != null && selectedNode.getDescriptor() instanceof WatchItemDescriptor);
}
};
@@ -1,43 +0,0 @@
/*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Class NewWatchAction
* @author Jeka
*/
package com.intellij.debugger.actions;
import com.intellij.debugger.ui.DebuggerPanelsManager;
import com.intellij.debugger.ui.impl.MainWatchPanel;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.project.Project;
import org.jetbrains.annotations.NotNull;
public class NewWatchAction extends DebuggerAction {
public void actionPerformed(final AnActionEvent e) {
getWatchPanel(e).newWatch();
}
@Override
public void update(@NotNull AnActionEvent e) {
e.getPresentation().setEnabled(getWatchPanel(e) != null);
}
private static MainWatchPanel getWatchPanel(AnActionEvent e) {
Project project = e.getProject();
return project != null ? DebuggerPanelsManager.getInstance(project).getWatchPanel() : null;
}
}
@@ -1,46 +0,0 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.debugger.actions;
import com.intellij.debugger.ui.impl.watch.DebuggerTree;
import com.intellij.debugger.ui.impl.watch.DebuggerTreeNodeImpl;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.Presentation;
import java.util.Enumeration;
/**
* User: lex
* Date: Sep 26, 2003
* Time: 6:24:44 PM
*/
public class RemoveAllWatchesAction extends RemoveWatchAction {
protected DebuggerTreeNodeImpl[] getNodesToDelete(AnActionEvent e) {
DebuggerTree tree = getTree(e.getDataContext());
if(tree == null) return null;
DebuggerTreeNodeImpl root = (DebuggerTreeNodeImpl)tree.getModel().getRoot();
DebuggerTreeNodeImpl [] result = new DebuggerTreeNodeImpl[root.getChildCount()];
int i = 0;
for(Enumeration enumeration = root.children(); enumeration.hasMoreElements(); i++) {
DebuggerTreeNodeImpl node = (DebuggerTreeNodeImpl)enumeration.nextElement();
result[i] = node;
}
return result;
}
protected void updatePresentation(Presentation presentation, int watchesCount) {
}
}
@@ -1,68 +0,0 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.debugger.actions;
import com.intellij.debugger.ui.impl.MainWatchPanel;
import com.intellij.debugger.ui.impl.watch.DebuggerTreeNodeImpl;
import com.intellij.debugger.ui.impl.watch.WatchItemDescriptor;
import com.intellij.debugger.DebuggerBundle;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.Presentation;
import java.util.ArrayList;
public class RemoveWatchAction extends DebuggerAction {
protected DebuggerTreeNodeImpl[] getNodesToDelete(AnActionEvent e) {
DebuggerTreeNodeImpl[] selectedNodes = getSelectedNodes(e.getDataContext());
if(selectedNodes == null) return null;
ArrayList<DebuggerTreeNodeImpl> selectedWatches = new ArrayList<DebuggerTreeNodeImpl>();
for (int i = 0; i < selectedNodes.length; i++) {
if(selectedNodes[i].getDescriptor() instanceof WatchItemDescriptor) {
selectedWatches.add(selectedNodes[i]);
}
}
return selectedWatches.toArray(new DebuggerTreeNodeImpl[selectedWatches.size()]);
}
public void actionPerformed(AnActionEvent e) {
DebuggerTreeNodeImpl [] nodes = getNodesToDelete(e);
if (nodes == null || nodes.length == 0) return;
MainWatchPanel watchPanel = (MainWatchPanel)getPanel(e.getDataContext());
for (int i = 0; i < nodes.length; i++) {
DebuggerTreeNodeImpl node = nodes[i];
watchPanel.getWatchTree().removeWatch(node);
}
}
protected void updatePresentation(Presentation presentation, int watchesCount) {
presentation.setText(DebuggerBundle.message("action.remove.watch.text", watchesCount));
}
public void update(AnActionEvent event) {
Presentation presentation = event.getPresentation();
DebuggerTreeNodeImpl[] nodes = getNodesToDelete(event);
if (nodes != null && nodes.length > 0) {
presentation.setEnabled(true);
}
else {
presentation.setEnabled(false);
}
updatePresentation(presentation, nodes != null? nodes.length : 0);
}
}
@@ -1,38 +0,0 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.debugger.actions;
import com.intellij.debugger.DebuggerManagerEx;
import com.intellij.debugger.impl.DebuggerSession;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.project.Project;
import com.intellij.xdebugger.impl.actions.DebuggerActionHandler;
import org.jetbrains.annotations.NotNull;
public class ShowExecutionPointActionHandler extends DebuggerActionHandler {
public void perform(@NotNull final Project project, final AnActionEvent event) {
final DebuggerSession session = (DebuggerManagerEx.getInstanceEx(project)).getContext().getDebuggerSession();
if (session != null) {
session.showExecutionPoint();
}
}
public boolean isEnabled(@NotNull final Project project, final AnActionEvent event) {
DebuggerSession debuggerSession = (DebuggerManagerEx.getInstanceEx(project)).getContext().getDebuggerSession();
return debuggerSession != null && debuggerSession.isPaused() &&
debuggerSession.getContextManager().getContext().getSuspendContext().getThread() != null;
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2014 JetBrains s.r.o.
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,6 +21,7 @@ import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.Presentation;
import com.intellij.openapi.actionSystem.ToggleAction;
import com.intellij.xdebugger.impl.XDebuggerUtilImpl;
import org.jetbrains.annotations.NotNull;
/**
* @author egor
@@ -36,10 +37,10 @@ public class ShowLibraryFramesAction extends ToggleAction {
}
@Override
public void update(final AnActionEvent e) {
public void update(@NotNull final AnActionEvent e) {
super.update(e);
final Presentation presentation = e.getPresentation();
final boolean shouldShow = !(Boolean)presentation.getClientProperty(SELECTED_PROPERTY);
final boolean shouldShow = !Boolean.TRUE.equals(presentation.getClientProperty(SELECTED_PROPERTY));
presentation.setText(shouldShow ? ourTextWhenShowIsOn : ourTextWhenShowIsOff);
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2014 JetBrains s.r.o.
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -1098,7 +1098,7 @@ public abstract class DebugProcessImpl extends UserDataHolderBase implements Deb
throw (RuntimeException)exception[0];
}
else {
LOG.assertTrue(false);
LOG.error("Unexpected exception " + exception[0]);
}
}
@@ -137,11 +137,7 @@ public class JavaDebugProcess extends XDebugProcess {
myNodeManager = new NodeManagerImpl(session.getProject(), null) {
@Override
public DebuggerTreeNodeImpl createNode(final NodeDescriptor descriptor, EvaluationContext evaluationContext) {
// value gathered here is required for correct renderers work. e.g. array renderer
//((NodeDescriptorImpl)descriptor).setContext((EvaluationContextImpl)evaluationContext);
final DebuggerTreeNodeImpl node = new DebuggerTreeNodeImpl(null, descriptor);
//((NodeDescriptorImpl)descriptor).updateRepresentation((EvaluationContextImpl)evaluationContext, DescriptorLabelListener.DUMMY_LISTENER);
return node;
return new DebuggerTreeNodeImpl(null, descriptor);
}
@Override
@@ -322,7 +318,6 @@ public class JavaDebugProcess extends XDebugProcess {
public void registerAdditionalActions(@NotNull DefaultActionGroup leftToolbar, @NotNull DefaultActionGroup topToolbar, @NotNull DefaultActionGroup settings) {
Constraints beforeRunner = new Constraints(Anchor.BEFORE, "Runner.Layout");
leftToolbar.add(Separator.getInstance(), beforeRunner);
//leftToolbar.add(ActionManager.getInstance().getAction(DebuggerActions.EXPORT_THREADS), beforeRunner);
leftToolbar.add(ActionManager.getInstance().getAction(DebuggerActions.DUMP_THREADS), beforeRunner);
leftToolbar.add(Separator.getInstance(), beforeRunner);
@@ -339,10 +334,10 @@ public class JavaDebugProcess extends XDebugProcess {
}
@Override
public void update(final AnActionEvent e) {
public void update(@NotNull final AnActionEvent e) {
super.update(e);
final Presentation presentation = e.getPresentation();
final boolean autoModeEnabled = (Boolean)presentation.getClientProperty(SELECTED_PROPERTY);
final boolean autoModeEnabled = Boolean.TRUE.equals(presentation.getClientProperty(SELECTED_PROPERTY));
presentation.setText(autoModeEnabled ? "All-Variables Mode" : "Auto-Variables Mode");
}
@@ -374,10 +369,10 @@ public class JavaDebugProcess extends XDebugProcess {
}
@Override
public void update(final AnActionEvent e) {
public void update(@NotNull final AnActionEvent e) {
super.update(e);
final Presentation presentation = e.getPresentation();
final boolean watchValues = (Boolean)presentation.getClientProperty(SELECTED_PROPERTY);
final boolean watchValues = Boolean.TRUE.equals(presentation.getClientProperty(SELECTED_PROPERTY));
DebugProcessImpl process = getCurrentDebugProcess(e.getProject());
final String actionText = watchValues ? myMyTextDisable : myTextEnable;
if (process == null || process.canGetMethodReturnValue()) {
@@ -46,4 +46,9 @@ public class DisableGC implements Evaluator{
public Modifier getModifier() {
return myDelegate.getModifier();
}
@Override
public String toString() {
return "NoGC -> " + myDelegate;
}
}
@@ -952,11 +952,10 @@ public class EvaluatorBuilderImpl implements EvaluatorBuilder {
}
if (qualifier instanceof PsiReferenceExpression && ((PsiReferenceExpression)qualifier).resolve() instanceof PsiClass) {
// this is a call to a 'static' method
if (contextClass == null && type == null) {
throwEvaluateException(DebuggerBundle.message("evaluation.error.qualifier.type.unknown", qualifier.getText()));
// this is a call to a 'static' method but class is not available, try to evaluate by qname
if (contextClass == null) {
contextClass = JVMNameUtil.getJVMRawText(((PsiReferenceExpression)qualifier).getQualifiedName());
}
assert contextClass != null;
objectEvaluator = new TypeEvaluator(contextClass);
}
else {
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -66,4 +66,9 @@ class LiteralEvaluator implements Evaluator {
throw EvaluateExceptionUtil
.createEvaluateException(DebuggerBundle.message("evaluation.error.unknown.expression.type", myExpectedType));
}
@Override
public String toString() {
return myValue.toString();
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -156,4 +156,9 @@ class LocalVariableEvaluator implements Evaluator {
}
return modifier;
}
@Override
public String toString() {
return myLocalVariableName;
}
}
@@ -211,4 +211,9 @@ public class MethodEvaluator implements Evaluator {
}
return null;
}
@Override
public String toString() {
return "call " + myMethodName;
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -84,6 +84,21 @@ public class StackFrameProxyImpl extends JdiProxy implements StackFrameProxy {
throw new EvaluateException(error.getMessage(), error);
}
@Override
public boolean isValid() {
if (!super.isValid()) {
return false;
}
try {
if (myStackFrame != null) {
myStackFrame.location(); //extra check if jdi frame is valid
}
return true;
} catch (InvalidStackFrameException e) {
return false;
}
}
@Override
protected void clearCaches() {
DebuggerManagerThreadImpl.assertIsManagerThread();
@@ -35,10 +35,8 @@ import java.util.Map;
@State(
name = "DebuggerSettings",
storages = {
@Storage(
file = StoragePathMacros.APP_CONFIG + "/other.xml"
)}
defaultStateAsResource = true,
storages = @Storage(file = StoragePathMacros.APP_CONFIG + "/other.xml")
)
public class DebuggerSettings implements Cloneable, PersistentStateComponent<Element> {
private static final Logger LOG = Logger.getInstance(DebuggerSettings.class);
@@ -287,7 +287,6 @@ public class DebuggerSessionTab extends DebuggerSessionTabBase implements Dispos
}
leftToolbar.addSeparator();
//addAction(leftToolbar, DebuggerActions.EXPORT_THREADS);
addAction(leftToolbar, DebuggerActions.DUMP_THREADS);
leftToolbar.addSeparator();
@@ -523,10 +522,10 @@ public class DebuggerSessionTab extends DebuggerSessionTabBase implements Dispos
}
@Override
public void update(final AnActionEvent e) {
public void update(@NotNull final AnActionEvent e) {
super.update(e);
final Presentation presentation = e.getPresentation();
final boolean autoModeEnabled = (Boolean)presentation.getClientProperty(SELECTED_PROPERTY);
final boolean autoModeEnabled = Boolean.TRUE.equals(presentation.getClientProperty(SELECTED_PROPERTY));
presentation.setText(autoModeEnabled ? "All-Variables Mode" : "Auto-Variables Mode");
}
@@ -558,10 +557,10 @@ public class DebuggerSessionTab extends DebuggerSessionTabBase implements Dispos
}
@Override
public void update(final AnActionEvent e) {
public void update(@NotNull final AnActionEvent e) {
super.update(e);
final Presentation presentation = e.getPresentation();
final boolean watchValues = (Boolean)presentation.getClientProperty(SELECTED_PROPERTY);
final boolean watchValues = Boolean.TRUE.equals(presentation.getClientProperty(SELECTED_PROPERTY));
final DebugProcessImpl process = getDebugProcess();
final String actionText = watchValues ? myMyTextDisable : myTextEnable;
if (process != null && process.canGetMethodReturnValue()) {
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -710,10 +710,10 @@ public class FramesPanel extends UpdatableDebuggerView implements DataProvider {
}
@Override
public void update(final AnActionEvent e) {
public void update(@NotNull final AnActionEvent e) {
super.update(e);
final Presentation presentation = e.getPresentation();
final boolean shouldShow = !(Boolean)presentation.getClientProperty(SELECTED_PROPERTY);
final boolean shouldShow = !Boolean.TRUE.equals(presentation.getClientProperty(SELECTED_PROPERTY));
presentation.setText(shouldShow ? ourTextWhenShowIsOn : ourTextWhenShowIsOff);
}
@@ -307,7 +307,10 @@ public abstract class SourcePosition implements Navigatable{
}
public static SourcePosition createFromElement(PsiElement element) {
final PsiElement navigationElement = element.getNavigationElement();
ApplicationManager.getApplication().assertReadAccessAllowed();
PsiElement navigationElement = element.getNavigationElement();
final SmartPsiElementPointer<PsiElement> pointer =
SmartPointerManager.getInstance(navigationElement.getProject()).createSmartPsiElementPointer(navigationElement);
final PsiFile psiFile;
if (JspPsiUtil.isInJspFile(navigationElement)) {
psiFile = JspPsiUtil.getJspFile(navigationElement);
@@ -318,12 +321,19 @@ public abstract class SourcePosition implements Navigatable{
return new SourcePositionCache(psiFile) {
@Override
protected PsiElement calcPsiElement() {
return navigationElement;
ApplicationManager.getApplication().assertReadAccessAllowed();
return pointer.getElement();
}
@Override
protected int calcOffset() {
return navigationElement.getTextOffset();
return ApplicationManager.getApplication().runReadAction(new Computable<Integer>() {
@Override
public Integer compute() {
PsiElement elem = pointer.getElement();
return elem != null ? elem.getTextOffset() : -1;
}
});
}
};
}
@@ -67,7 +67,7 @@ public class InternetAttachSourceProvider implements AttachSourcesProvider {
@NotNull
@Override
public Collection<AttachSourcesAction> getActions(List<LibraryOrderEntry> orderEntries, final PsiFile psiFile) {
VirtualFile jar = getJarByPsiFile(psiFile);
final VirtualFile jar = getJarByPsiFile(psiFile);
if (jar == null) return Collections.emptyList();
final String jarName = jar.getNameWithoutExtension();
@@ -145,7 +145,7 @@ public class InternetAttachSourceProvider implements AttachSourcesProvider {
SourceSearcher[] searchers = {new MavenCentralSourceSearcher(), new SonatypeSourceSearcher()};
for (SourceSearcher searcher : searchers) {
try {
artifactUrl = searcher.findSourceJar(indicator, artifactId, version);
artifactUrl = searcher.findSourceJar(indicator, artifactId, version, jar);
}
catch (SourceSearchException e) {
LOG.warn(e);
@@ -86,20 +86,20 @@ public class IncreaseLanguageLevelFix implements IntentionAction {
LOG.assertTrue(virtualFile != null);
final Module module = ModuleUtilCore.findModuleForFile(virtualFile, project);
final LanguageLevel moduleLevel = module == null ? null : LanguageLevelModuleExtensionImpl.getInstance(module).getLanguageLevel();
if (moduleLevel != null && isLanguageLevelAcceptable(project, module, myLevel)) {
final ModifiableRootModel rootModel = ModuleRootManager.getInstance(module).getModifiableModel();
rootModel.getModuleExtension(LanguageLevelModuleExtension.class).setLanguageLevel(myLevel);
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
if (moduleLevel != null && isLanguageLevelAcceptable(project, module, myLevel)) {
final ModifiableRootModel rootModel = ModuleRootManager.getInstance(module).getModifiableModel();
rootModel.getModuleExtension(LanguageLevelModuleExtension.class).setLanguageLevel(myLevel);
rootModel.commit();
}
});
}
else {
LanguageLevelProjectExtension.getInstance(project).setLanguageLevel(myLevel);
ProjectRootManagerEx.getInstanceEx(project).makeRootsChange(EmptyRunnable.INSTANCE, false, true);
}
else {
LanguageLevelProjectExtension.getInstance(project).setLanguageLevel(myLevel);
ProjectRootManagerEx.getInstanceEx(project).makeRootsChange(EmptyRunnable.INSTANCE, false, true);
}
}
});
}
@Nullable
@@ -263,13 +263,14 @@ public class LambdaCanBeMethodReferenceInspection extends BaseJavaBatchLocalInsp
if (element instanceof PsiMethodCallExpression) {
final PsiMethodCallExpression methodCall = (PsiMethodCallExpression)element;
final PsiMethod psiMethod = methodCall.resolveMethod();
JavaResolveResult result = methodCall.resolveMethodGenerics();
final PsiMethod psiMethod = (PsiMethod)result.getElement();
if (psiMethod == null) {
return null;
}
final PsiReferenceExpression methodExpression = methodCall.getMethodExpression();
final String qualifierByMethodCall = getQualifierTextByMethodCall(methodCall, functionalInterfaceType, parameters, psiMethod);
final String qualifierByMethodCall = getQualifierTextByMethodCall(methodCall, functionalInterfaceType, parameters, psiMethod, result.getSubstitutor());
if (qualifierByMethodCall != null) {
return qualifierByMethodCall + "::" + ((PsiMethodCallExpression)element).getTypeArgumentList().getText() + methodExpression.getReferenceName();
}
@@ -324,7 +325,8 @@ public class LambdaCanBeMethodReferenceInspection extends BaseJavaBatchLocalInsp
private static String getQualifierTextByMethodCall(final PsiMethodCallExpression methodCall,
final PsiType functionalInterfaceType,
final PsiParameter[] parameters,
final PsiMethod psiMethod) {
final PsiMethod psiMethod,
final PsiSubstitutor substitutor) {
final PsiExpression qualifierExpression = methodCall.getMethodExpression().getQualifierExpression();
@@ -332,7 +334,7 @@ public class LambdaCanBeMethodReferenceInspection extends BaseJavaBatchLocalInsp
LOG.assertTrue(containingClass != null);
if (qualifierExpression != null) {
boolean isReceiverType = PsiMethodReferenceUtil.isReceiverType(functionalInterfaceType, containingClass, psiMethod);
boolean isReceiverType = PsiMethodReferenceUtil.isReceiverType(PsiMethodReferenceUtil.getFirstParameterType(functionalInterfaceType, methodCall), containingClass, substitutor);
return isReceiverType ? composeReceiverQualifierText(parameters, psiMethod, containingClass, qualifierExpression)
: qualifierExpression.getText();
}
@@ -422,7 +424,6 @@ public class LambdaCanBeMethodReferenceInspection extends BaseJavaBatchLocalInsp
if (lambdaExpression == null) return;
PsiType functionalInterfaceType = lambdaExpression.getFunctionalInterfaceType();
if (functionalInterfaceType == null || !functionalInterfaceType.isValid()) return;
String functionalTypeText = functionalInterfaceType.getCanonicalText();
final String methodRefText = createMethodReferenceText(element, functionalInterfaceType,
lambdaExpression.getParameterList().getParameters());
@@ -106,7 +106,7 @@ public class CodeInsightUtil {
if (parent == null) return PsiElement.EMPTY_ARRAY;
while (true) {
if (parent instanceof PsiStatement) {
if (!(element1 instanceof PsiComment || element2 instanceof PsiComment)) {
if (!(element1 instanceof PsiComment)) {
parent = parent.getParent();
}
break;
@@ -37,9 +37,11 @@ import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.util.Consumer;
import com.intellij.util.SmartList;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import java.util.Set;
import static com.intellij.patterns.PsiJavaPatterns.psiClass;
import static com.intellij.patterns.PsiJavaPatterns.psiElement;
@@ -117,26 +119,52 @@ public class JavaClassNameCompletionContributor extends CompletionContributor {
final boolean pkgContext = JavaCompletionUtil.inSomePackage(insertedElement);
AllClassesGetter.processJavaClasses(parameters, matcher, filterByScope, new Consumer<PsiClass>() {
@Override
public void consume(PsiClass psiClass) {
if (filter.isAcceptable(psiClass, insertedElement)) {
if (!inJavaContext) {
consumer.consume(AllClassesGetter.createLookupItem(psiClass, AllClassesGetter.TRY_SHORTENING));
} else {
for (JavaPsiClassReferenceElement element : createClassLookupItems(psiClass, afterNew,
JavaClassNameInsertHandler.JAVA_CLASS_INSERT_HANDLER, new Condition<PsiClass>() {
@Override
public void consume(PsiClass psiClass) {
processClass(psiClass, ContainerUtil.<PsiClass>newHashSet(), "");
}
private void processClass(PsiClass psiClass, Set<PsiClass> visited, String prefix) {
if (!visited.add(psiClass)) return;
boolean isInnerClass = StringUtil.isNotEmpty(prefix);
if (isInnerClass && isProcessedIndependently(psiClass)) {
return;
}
if (filter.isAcceptable(psiClass, insertedElement)) {
if (!inJavaContext) {
JavaPsiClassReferenceElement element = AllClassesGetter.createLookupItem(psiClass, AllClassesGetter.TRY_SHORTENING);
element.setLookupString(prefix + element.getLookupString());
consumer.consume(element);
} else {
for (JavaPsiClassReferenceElement element : createClassLookupItems(psiClass, afterNew,
JavaClassNameInsertHandler.JAVA_CLASS_INSERT_HANDLER, new Condition<PsiClass>() {
@Override
public boolean value(PsiClass psiClass) {
return filter.isAcceptable(psiClass, insertedElement) &&
AllClassesGetter.isAcceptableInContext(insertedElement, psiClass, filterByScope, pkgContext);
}
})) {
consumer.consume(element);
}
element.setLookupString(prefix + element.getLookupString());
consumer.consume(element);
}
}
} else {
String name = psiClass.getName();
if (name != null) {
for (PsiClass innerClass : psiClass.getInnerClasses()) {
processClass(innerClass, visited, prefix + name + ".");
}
}
}
});
}
private boolean isProcessedIndependently(PsiClass psiClass) {
String innerName = psiClass.getName();
return innerName != null && matcher.prefixMatches(innerName);
}
});
}
static LookupElement highlightIfNeeded(JavaPsiClassReferenceElement element, CompletionParameters parameters) {
@@ -664,7 +664,20 @@ public class GenerateMembersUtil {
}
}
result = (PsiMethod)CodeStyleManager.getInstance(project).reformat(result);
PropertyUtil.annotateWithNullableStuff(field, result);
PsiModifierListOwner listOwner = null;
if (templatesManager instanceof GetterTemplatesManager) {
listOwner = result;
}
else {
final PsiParameter[] parameters = result.getParameterList().getParameters();
if (parameters.length == 1) {
listOwner = parameters[0];
}
}
if (listOwner != null) {
PropertyUtil.annotateWithNullableStuff(field, listOwner);
}
return generatePrototype(field, result);
}
@@ -5,7 +5,7 @@ static void ##
#else
$classname ##
#end
set$StringUtil.capitalizeWithJavaBeanConvention($StringUtil.sanitizeJavaIdentifier($field.name))($field.type $paramName) {
set$StringUtil.capitalizeWithJavaBeanConvention($StringUtil.sanitizeJavaIdentifier($helper.getPropertyName($field, $project)))($field.type $paramName) {
#if ($field.name == $paramName)
#if (!$field.modifierStatic)
this.##
@@ -3,7 +3,7 @@ public ##
static ##
#end
$field.type ##
#set($name = $StringUtil.capitalizeWithJavaBeanConvention($StringUtil.sanitizeJavaIdentifier($field.name)))
#set($name = $StringUtil.capitalizeWithJavaBeanConvention($StringUtil.sanitizeJavaIdentifier($helper.getPropertyName($field, $project))))
#if ($field.boolean)
#if ($StringUtil.startsWithIgnoreCase($name, 'is'))
#set($name = $StringUtil.decapitalize($name))
@@ -3,7 +3,7 @@ public ##
#if($field.modifierStatic)
static ##
#end
void set$StringUtil.capitalizeWithJavaBeanConvention($StringUtil.sanitizeJavaIdentifier($field.name))($field.type $paramName) {
void set$StringUtil.capitalizeWithJavaBeanConvention($StringUtil.sanitizeJavaIdentifier($helper.getPropertyName($field, $project)))($field.type $paramName) {
#if ($field.name == $paramName)
#if (!$field.modifierStatic)
this.##
@@ -40,7 +40,9 @@ import com.intellij.openapi.ui.popup.PopupChooserBuilder;
import com.intellij.openapi.util.Computable;
import com.intellij.psi.*;
import com.intellij.psi.search.searches.ClassInheritorsSearch;
import com.intellij.psi.util.MethodSignatureUtil;
import com.intellij.psi.util.PsiUtilCore;
import com.intellij.psi.util.TypeConversionUtil;
import com.intellij.ui.components.JBList;
import com.intellij.util.IncorrectOperationException;
@@ -180,7 +182,9 @@ public class ImplementAbstractMethodHandler {
ArrayList<PsiClass> list = new ArrayList<PsiClass>();
for (PsiClass inheritor : ClassInheritorsSearch.search(psiClass, true)) {
if (!inheritor.isInterface()) {
PsiMethod method = inheritor.findMethodBySignature(myMethod, true);
final PsiSubstitutor classSubstitutor = TypeConversionUtil.getClassSubstitutor(psiClass, inheritor, PsiSubstitutor.EMPTY);
LOG.assertTrue(classSubstitutor != null);
PsiMethod method = MethodSignatureUtil.findMethodBySignature(inheritor, myMethod.getSignature(classSubstitutor), true);
if (method == null || !method.getContainingClass().equals(psiClass)) continue;
list.add(inheritor);
}
@@ -2,6 +2,7 @@ package com.intellij.jarFinder;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.vfs.VirtualFile;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.xpath.XPath;
@@ -21,13 +22,19 @@ public class MavenCentralSourceSearcher extends SourceSearcher {
@Override
protected String findSourceJar(@NotNull ProgressIndicator indicator,
@NotNull String artifactId,
@NotNull String version) throws SourceSearchException {
@NotNull String version,
@NotNull VirtualFile classesJar) throws SourceSearchException {
try {
indicator.setText("Connecting to https://search.maven.org");
indicator.checkCanceled();
String url = "https://search.maven.org/solrsearch/select?rows=3&wt=xml&q=a:%22" + artifactId + "%22%20AND%20v:%22" + version + "%22%20AND%20l:%22sources%22";
String url = "https://search.maven.org/solrsearch/select?rows=3&wt=xml&q=";
final String groupId = findMavenGroupId(classesJar, artifactId);
if (groupId != null) {
url += "g:%22" + groupId + "%22%20AND%20";
}
url += "a:%22" + artifactId + "%22%20AND%20v:%22" + version + "%22%20AND%20l:%22sources%22";
@SuppressWarnings("unchecked")
List<Element> artifactList = (List<Element>)XPath.newInstance("/response/result/doc/str[@name='g']").selectNodes(readDocumentCancelable(indicator, url));
if (artifactList.isEmpty()) {
@@ -2,6 +2,7 @@ package com.intellij.jarFinder;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.vfs.VirtualFile;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.xpath.XPath;
@@ -19,7 +20,10 @@ public class SonatypeSourceSearcher extends SourceSearcher {
@Nullable
@Override
public String findSourceJar(@NotNull final ProgressIndicator indicator, @NotNull String artifactId, @NotNull String version)
public String findSourceJar(@NotNull final ProgressIndicator indicator,
@NotNull String artifactId,
@NotNull String version,
@NotNull VirtualFile classesJar)
throws SourceSearchException {
try {
indicator.setIndeterminate(true);
@@ -28,6 +32,11 @@ public class SonatypeSourceSearcher extends SourceSearcher {
indicator.checkCanceled();
String url = "https://oss.sonatype.org/service/local/lucene/search?collapseresults=true&c=sources&a=" + artifactId + "&v=" + version;
String groupId = findMavenGroupId(classesJar, artifactId);
if(groupId != null) {
url += ("&g=" + groupId);
}
List<Element> artifactList = (List<Element>)XPath.newInstance("/searchNGResponse/data/artifact").selectNodes(readDocumentCancelable(indicator, url));
if (artifactList.isEmpty()) {
return null;
@@ -50,7 +59,7 @@ public class SonatypeSourceSearcher extends SourceSearcher {
return null;
}
String groupId = element.getChildTextTrim("groupId");
groupId = element.getChildTextTrim("groupId");
String repositoryId = artifactHintList.get(0).getChildTextTrim("repositoryId");
return "https://oss.sonatype.org/service/local/artifact/maven/redirect?r=" +
@@ -2,6 +2,10 @@ package com.intellij.jarFinder;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.util.JDOMUtil;
import com.intellij.openapi.util.io.StreamUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.io.HttpRequests;
import org.jdom.Document;
import org.jdom.JDOMException;
@@ -9,19 +13,43 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
/**
* @author Sergey Evdokimov
*/
public abstract class SourceSearcher {
private static final String MAVEN_POM_ENTRY_PREFIX = "META-INF/maven/";
/**
* @param indicator
* @param artifactId
* @param version
* @return groupId of found artifact and url.
* @return url of found artifact
*/
@Nullable
protected abstract String findSourceJar(@NotNull final ProgressIndicator indicator, @NotNull String artifactId, @NotNull String version) throws SourceSearchException;
protected String findSourceJar(@NotNull final ProgressIndicator indicator, @NotNull String artifactId, @NotNull String version)
throws SourceSearchException {
return null;
}
/**
* @param indicator
* @param artifactId
* @param version
* @param classesJar classes jar
* @return url of found artifact
*/
@Nullable
protected String findSourceJar(@NotNull final ProgressIndicator indicator,
@NotNull String artifactId,
@NotNull String version,
@NotNull VirtualFile classesJar) throws SourceSearchException {
return findSourceJar(indicator, artifactId, version);
}
@NotNull
protected static Document readDocumentCancelable(final ProgressIndicator indicator, String url) throws IOException {
@@ -39,6 +67,34 @@ public abstract class SourceSearcher {
}
});
}
@Nullable
protected static String findMavenGroupId(@NotNull VirtualFile classesJar, String artifactId) {
try {
JarFile jarFile = new JarFile(VfsUtilCore.virtualToIoFile(classesJar));
try {
final Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
final String name = entry.getName();
if (StringUtil.startsWith(name, MAVEN_POM_ENTRY_PREFIX) && StringUtil.endsWith(name, "/" + artifactId + "/pom.xml")) {
final int index = name.indexOf('/', MAVEN_POM_ENTRY_PREFIX.length());
return index != -1 ? name.substring(MAVEN_POM_ENTRY_PREFIX.length(), index) : null;
}
}
}
finally {
try {
jarFile.close();
}
catch (IOException ignore) {
}
}
}
catch (IOException ignore) {
}
return null;
}
}
class SourceSearchException extends Exception {
@@ -28,6 +28,7 @@ import com.intellij.psi.PsiJavaFile;
import com.intellij.psi.codeStyle.JavaCodeStyleManager;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* @author max
@@ -44,7 +45,10 @@ public class JavaImportOptimizer implements ImportOptimizer {
Project project = file.getProject();
final PsiImportList newImportList = JavaCodeStyleManager.getInstance(project).prepareOptimizeImportsResult((PsiJavaFile)file);
if (newImportList == null) return EmptyRunnable.getInstance();
return new Runnable() {
return new CollectingInfoRunnable() {
private int myImportListLengthDiff = 0;
@Override
public void run() {
try {
@@ -55,12 +59,23 @@ public class JavaImportOptimizer implements ImportOptimizer {
}
final PsiImportList oldImportList = ((PsiJavaFile)file).getImportList();
assert oldImportList != null;
int importsBefore = oldImportList.getAllImportStatements().length;
oldImportList.replace(newImportList);
myImportListLengthDiff = importsBefore - newImportList.getAllImportStatements().length;
}
catch (IncorrectOperationException e) {
LOG.error(e);
}
}
@Nullable
@Override
public String getUserNotificationInfo() {
if (myImportListLengthDiff > 0) {
return "removed " + myImportListLengthDiff + " import" + (myImportListLengthDiff > 1 ? "s" : "");
}
return null;
}
};
}
@@ -1,19 +1,34 @@
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.psi.impl.source.resolve.reference.impl.providers;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiPackage;
import com.intellij.psi.impl.source.resolve.reference.impl.providers.PackageReferenceSet;
import com.intellij.util.PatternUtil;
import com.intellij.util.Processor;
import org.jetbrains.annotations.Nullable;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.regex.Pattern;
public class PatternPackageReferenceSet extends PackageReferenceSet {
public PatternPackageReferenceSet(String packageName, PsiElement element, int startInElement) {
super(packageName, element, startInElement);
}
@@ -24,7 +39,7 @@ public class PatternPackageReferenceSet extends PackageReferenceSet {
if (packageName.contains("*")) {
final Pattern pattern = PatternUtil.fromMask(packageName);
final Set<PsiPackage> packages = new HashSet<PsiPackage>();
final Set<PsiPackage> packages = new LinkedHashSet<PsiPackage>();
processSubPackages(context, new Processor<PsiPackage>() {
@Override
@@ -39,13 +54,13 @@ public class PatternPackageReferenceSet extends PackageReferenceSet {
return packages;
}
else {
return super.resolvePackageName(context, packageName);
}
return super.resolvePackageName(context, packageName);
}
protected static boolean processSubPackages(final PsiPackage pkg, final Processor<PsiPackage> processor) {
protected static boolean processSubPackages(final PsiPackage pkg, final Processor<PsiPackage> processor) {
if (!processor.process(pkg)) return false;
for (final PsiPackage aPackage : pkg.getSubPackages()) {
if (!processSubPackages(aPackage, processor)) return false;
}
@@ -203,8 +203,8 @@ public class CreateTestDialog extends DialogWrapper {
}.registerCustomShortcutSet(new CustomShortcutSet(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, InputEvent.SHIFT_DOWN_MASK)),
myTargetPackageField.getChildComponent());
myGenerateBeforeBox = new JCheckBox("setUp/@Before");
myGenerateAfterBox = new JCheckBox("tearDown/@After");
myGenerateBeforeBox = new JCheckBox(CodeInsightBundle.message("intention.create.test.dialog.setUp"));
myGenerateAfterBox = new JCheckBox(CodeInsightBundle.message("intention.create.test.dialog.tearDown"));
myShowInheritedMethodsBox = new JCheckBox(CodeInsightBundle.message("intention.create.test.dialog.show.inherited"));
myShowInheritedMethodsBox.addActionListener(new ActionListener() {
@@ -411,7 +411,9 @@ public class CreateTestDialog extends DialogWrapper {
constr.gridy = gridy++;
constr.gridx = 0;
constr.weightx = 0;
panel.add(new JLabel(CodeInsightBundle.message("intention.create.test.dialog.select.methods")), constr);
final JLabel membersLabel = new JLabel(CodeInsightBundle.message("intention.create.test.dialog.select.methods"));
membersLabel.setLabelFor(myMethodsTable);
panel.add(membersLabel, constr);
constr.gridx = 1;
constr.weightx = 1;
@@ -30,10 +30,10 @@ public class PsiMethodReferenceUtil {
public static final Logger LOG = Logger.getInstance("#" + PsiMethodReferenceUtil.class.getName());
public static boolean hasReceiver(PsiType[] parameterTypes, QualifierResolveResult qualifierResolveResult, PsiMethodReferenceExpression methodRef) {
if (parameterTypes.length > 0 &&
if (parameterTypes.length > 0 &&
!methodRef.isConstructor() &&
isReceiverType(parameterTypes[0], qualifierResolveResult.getContainingClass(), qualifierResolveResult.getSubstitutor()) &&
isStaticallyReferenced(methodRef)) {
isStaticallyReferenced(methodRef) &&
isReceiverType(parameterTypes[0], qualifierResolveResult.getContainingClass(), qualifierResolveResult.getSubstitutor())) {
return true;
}
return false;
@@ -46,7 +46,7 @@ public class PsiMethodReferenceUtil {
LOG.assertTrue(containingClass != null);
PsiSubstitutor subst = result.getSubstitutor();
PsiClass qContainingClass = getQualifierResolveResult(expression).getContainingClass();
if (qContainingClass != null && isReceiverType(functionalInterfaceType, containingClass, (PsiMethod)resolve)) {
if (qContainingClass != null && isReceiverType(getFirstParameterType(functionalInterfaceType, expression), qContainingClass, subst)) {
subst = TypeConversionUtil.getClassSubstitutor(containingClass, qContainingClass, subst);
LOG.assertTrue(subst != null);
}
@@ -202,53 +202,27 @@ public class PsiMethodReferenceUtil {
return true;
}
public static boolean isReceiverType(@Nullable PsiClass aClass, @Nullable PsiClass containingClass) {
return InheritanceUtil.isInheritorOrSelf(aClass, containingClass, true);
}
public static boolean isReceiverType(PsiType receiverType, @Nullable PsiClass containingClass, PsiSubstitutor psiSubstitutor) {
if (containingClass != null) {
receiverType = getExpandedType(receiverType, containingClass);
//if P1, ..., Pn is not empty and P1 is a subtype of ReferenceType, then the method reference expression is treated as
// if it were a method invocation expression with argument expressions of types P2, ...,Pn.
public static boolean isReceiverType(@Nullable PsiType receiverType, PsiClass containingClass, PsiSubstitutor psiSubstitutor) {
if (receiverType == null) {
return false;
}
final PsiClassType.ClassResolveResult resolveResult = PsiUtil.resolveGenericsClassInType(receiverType);
final PsiClass receiverClass = resolveResult.getElement();
if (receiverClass != null && isReceiverType(receiverClass, containingClass)) {
if (emptyOrRaw(containingClass, psiSubstitutor)) {
return true;
}
final PsiSubstitutor derivedSubstitutor = TypeConversionUtil.getClassSubstitutor(containingClass, receiverClass, psiSubstitutor);
return derivedSubstitutor != null && TypeConversionUtil.isAssignable(JavaPsiFacade.getElementFactory(containingClass.getProject()).createType(containingClass, derivedSubstitutor), receiverType);
}
return false;
return TypeConversionUtil.isAssignable(JavaPsiFacade.getElementFactory(containingClass.getProject()).createType(containingClass, psiSubstitutor),
getExpandedType(receiverType, containingClass));
}
private static boolean emptyOrRaw(PsiClass containingClass, PsiSubstitutor psiSubstitutor) {
return PsiUtil.isRawSubstitutor(containingClass, psiSubstitutor) ||
psiSubstitutor.getSubstitutionMap().isEmpty();
}
public static boolean isReceiverType(PsiType functionalInterfaceType, PsiClass containingClass, @Nullable PsiMethod referencedMethod) {
public static PsiType getFirstParameterType(PsiType functionalInterfaceType, PsiElement context) {
final PsiClassType.ClassResolveResult resolveResult = PsiUtil.resolveGenericsClassInType(functionalInterfaceType);
final MethodSignature function = LambdaUtil.getFunction(resolveResult.getElement());
if (function != null) {
final int interfaceMethodParamsLength = function.getParameterTypes().length;
if (interfaceMethodParamsLength > 0) {
final PsiType firstParamType = resolveResult.getSubstitutor().substitute(function.getParameterTypes()[0]);
boolean isReceiver = isReceiverType(firstParamType,
containingClass, PsiUtil.resolveGenericsClassInType(firstParamType).getSubstitutor());
if (isReceiver) {
if (referencedMethod == null){
if (interfaceMethodParamsLength == 1) return true;
return false;
}
if (referencedMethod.getParameterList().getParametersCount() != interfaceMethodParamsLength - 1) {
return false;
}
return true;
}
PsiType type = resolveResult.getSubstitutor().substitute(function.getParameterTypes()[0]);
return type != null ? PsiUtil.captureToplevelWildcards(type, context) : null;
}
}
return false;
return null;
}
private static PsiType getExpandedType(PsiType type, @NotNull PsiElement typeElement) {
@@ -312,17 +312,17 @@ public class MethodCandidateInfo extends CandidateInfo{
public static CurrentCandidateProperties getCurrentMethod(PsiElement context) {
if (isOverloadCheck()) {
ourOverloadGuard.prohibitResultCaching(ourOverloadGuard.currentStack().get(0));
}
final Map<PsiElement, CurrentCandidateProperties> currentMethodCandidates = CURRENT_CANDIDATE.get();
return currentMethodCandidates != null ? currentMethodCandidates.get(context) : null;
}
public static void updateSubstitutor(PsiElement context, PsiSubstitutor newSubstitutor) {
final Map<PsiElement, CurrentCandidateProperties> currentMethodCandidates = CURRENT_CANDIDATE.get();
if (currentMethodCandidates != null) {
final CurrentCandidateProperties properties = currentMethodCandidates.get(context);
if (properties != null) {
properties.setSubstitutor(newSubstitutor);
}
CurrentCandidateProperties candidateProperties = getCurrentMethod(context);
if (candidateProperties != null) {
candidateProperties.setSubstitutor(newSubstitutor);
}
}
@@ -403,6 +403,7 @@ public class TypeConversionUtil {
final PsiClass class1 = PsiUtil.resolveClassInType(typeArg1);
if (class1 instanceof PsiTypeParameter) {
for (PsiType type : class1.getExtendsListTypes()) {
type = substitutor1.substitute(type);
if (TypesDistinctProver.provablyDistinct(type, typeArg2) && !isAssignable(type, typeArg2)) return false;
}
}
@@ -262,7 +262,13 @@ public class TypesDistinctProver {
final PsiType boundBound = ((PsiWildcardType)bound).getBound();
if (boundBound != null && !boundBound.equals(type)) {
final PsiClass psiClass = PsiUtil.resolveClassInClassTypeOnly(boundBound);
return psiClass == null || !(((PsiWildcardType)bound).isExtends() && possibleClasses.contains(psiClass));
if (psiClass == null) {
return true;
}
if (psiClass instanceof PsiTypeParameter) {
return try2ProveTypeParameterDistinct(type, psiClass);
}
return !(((PsiWildcardType)bound).isExtends() && possibleClasses.contains(psiClass));
}
return false;
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2014 JetBrains s.r.o.
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -41,10 +41,13 @@ import com.intellij.psi.impl.LanguageConstantExpressionEvaluator;
import com.intellij.psi.impl.PsiExpressionEvaluator;
import com.intellij.psi.impl.compiled.ClassFileStubBuilder;
import com.intellij.psi.impl.file.PsiPackageImplementationHelper;
import com.intellij.psi.impl.search.MethodSuperSearcher;
import com.intellij.psi.impl.source.tree.CoreJavaASTFactory;
import com.intellij.psi.impl.source.tree.PlainTextASTFactory;
import com.intellij.psi.presentation.java.*;
import com.intellij.psi.search.searches.SuperMethodsSearch;
import com.intellij.psi.stubs.BinaryFileStubBuilders;
import com.intellij.util.QueryExecutor;
import org.jetbrains.annotations.NotNull;
/**
@@ -98,6 +101,8 @@ public class JavaCoreApplicationEnvironment extends CoreApplicationEnvironment {
}
});
registerApplicationExtensionPoint(SuperMethodsSearch.EP_NAME, QueryExecutor.class);
addExtension(SuperMethodsSearch.EP_NAME, new MethodSuperSearcher());
}
@SuppressWarnings("MethodMayBeStatic") // overridden in upsource
@@ -852,6 +852,7 @@ public class ControlFlowUtil {
private static PsiReferenceExpression findReferenceTo(PsiElement element, PsiVariable variable) {
if (element instanceof PsiReferenceExpression
&& !((PsiReferenceExpression)element).isQualified()
&& ((PsiReferenceExpression)element).resolve() == variable) {
return (PsiReferenceExpression)element;
}
@@ -20,6 +20,7 @@ import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.ProgressIndicatorProvider;
import com.intellij.openapi.roots.FileIndexFacade;
import com.intellij.openapi.util.*;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.psi.*;
@@ -711,6 +712,10 @@ public class PsiClassImplUtil {
@Nullable
public static PsiClassType correctType(PsiClassType originalType, final GlobalSearchScope resolveScope) {
if (!Registry.is("java.correct.class.type.by.place.resolve.scope")) {
return originalType;
}
final PsiClassType.ClassResolveResult originalResolveResult = originalType.resolveGenerics();
PsiClass superClass = originalResolveResult.getElement();
if (superClass == null) {
@@ -746,7 +751,7 @@ public class PsiClassImplUtil {
}
});
if (substitute == null) return null;
substitutor = substitutor.put(typeParameters[i], substitute);
}
}
@@ -83,4 +83,14 @@ public class LightFieldBuilder extends LightVariableBuilder<LightFieldBuilder> i
public PsiClass getContainingClass() {
return myContainingClass;
}
@Override
public boolean isEquivalentTo(PsiElement another) {
if (!(another instanceof PsiField)) return false;
if (!((PsiField)another).getName().equals(getName())) return false;
if (hasModifierProperty(PsiModifier.STATIC) != ((PsiField)another).hasModifierProperty(PsiModifier.STATIC)) return false;
final PsiClass containingClass = getContainingClass();
final PsiClass anotherClass = ((PsiField)another).getContainingClass();
return containingClass == null && anotherClass == null || getManager().areElementsEquivalent(containingClass, anotherClass);
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2014 JetBrains s.r.o.
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,10 +18,12 @@ package com.intellij.psi.impl.source.resolve.graphInference.constraints;
import com.intellij.codeInsight.ExceptionUtil;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.util.Condition;
import com.intellij.psi.*;
import com.intellij.psi.impl.source.resolve.graphInference.InferenceSession;
import com.intellij.psi.impl.source.resolve.graphInference.InferenceVariable;
import com.intellij.psi.impl.source.resolve.graphInference.PsiPolyExpressionUtil;
import com.intellij.psi.util.InheritanceUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.psi.util.TypeConversionUtil;
import com.intellij.util.Function;
@@ -45,7 +47,7 @@ public class CheckedExceptionCompatibilityConstraint extends InputOutputConstrai
}
@Override
public boolean reduce(InferenceSession session, List<ConstraintFormula> constraints) {
public boolean reduce(final InferenceSession session, List<ConstraintFormula> constraints) {
if (!PsiPolyExpressionUtil.isPolyExpression(myExpression)) {
return true;
}
@@ -111,7 +113,12 @@ public class CheckedExceptionCompatibilityConstraint extends InputOutputConstrai
}
});
if (exceptions != null) {
thrownTypes.addAll(exceptions);
thrownTypes.addAll(ContainerUtil.filter(exceptions, new Condition<PsiClassType>() {
@Override
public boolean value(PsiClassType type) {
return session.isProperType(type) && InheritanceUtil.isInheritor(type, CommonClassNames.JAVA_LANG_EXCEPTION);
}
}));
}
}
} else {
@@ -169,7 +176,7 @@ public class CheckedExceptionCompatibilityConstraint extends InputOutputConstrai
private static boolean isAddressed(List<PsiType> expectedThrownTypes, PsiType thrownType) {
for (PsiType expectedThrownType : expectedThrownTypes) {
if (TypeConversionUtil.isAssignable(expectedThrownType, thrownType)) {
if (TypeConversionUtil.isAssignable(TypeConversionUtil.erasure(thrownType), expectedThrownType)) {
return true;
}
}
@@ -20,7 +20,6 @@ import com.intellij.lang.ASTNode;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.psi.*;
import com.intellij.psi.impl.PsiImplUtil;
import com.intellij.psi.impl.source.resolve.graphInference.FunctionalInterfaceParameterizationUtil;
@@ -480,7 +479,7 @@ public class PsiMethodReferenceExpressionImpl extends PsiReferenceExpressionBase
PsiClass qContainingClass = PsiMethodReferenceUtil.getQualifierResolveResult(this).getContainingClass();
if (qContainingClass != null && containingClass != null &&
PsiMethodReferenceUtil.isReceiverType(left, containingClass, (PsiMethod)resolve)) {
PsiMethodReferenceUtil.isReceiverType(PsiMethodReferenceUtil.getFirstParameterType(left, this), qContainingClass, subst)) {
subst = TypeConversionUtil.getClassSubstitutor(containingClass, qContainingClass, subst);
LOG.assertTrue(subst != null);
}
@@ -0,0 +1,14 @@
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
int a = 3;
int b = 3;
}
}
@@ -0,0 +1,17 @@
import java.lang.String;
import java.util.List;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.HashSet;
public class Test {
public static void main(String[] args) {
<selection>List<String> list = new ArrayList<String>();
int a = 3;</selection>
int b = 3;
}
}
@@ -0,0 +1,11 @@
public class Test {
int a = 2;
int b = 3;
public void run() {
int myFirst = 12;
}
}
@@ -0,0 +1,11 @@
public class Test {
<selection>int a = 2;
int b = 3;</selection>
public void run() {
int myFirst = 12;
}
}
@@ -0,0 +1,11 @@
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
}
}
@@ -0,0 +1,14 @@
import java.lang.String;
import java.util.List;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.HashSet;
public class Test {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
}
}
@@ -0,0 +1,10 @@
public class Test {
public int a = 3;
public void test() {
int c = 3;
}
}
@@ -0,0 +1,10 @@
public class Test {
public int a = 3;
public void test() {
int c = 3;
}
}
@@ -0,0 +1,11 @@
final class MyModule {
@Target({FIELD,PARAMETER,METHOD})
@Retention(RUNTIME)
public static @interface Dependency { }
}
final class SomeService {
SomeService(@My<caret>) {
}
}
@@ -0,0 +1,11 @@
final class MyModule {
@Target({FIELD,PARAMETER,METHOD})
@Retention(RUNTIME)
public static @interface Dependency { }
}
final class SomeService {
SomeService(@MyModule.Dependency<caret>) {
}
}
@@ -0,0 +1,7 @@
import java.util.List;
abstract class Test implements List<Test> {
private <T extends List<T>> T foo() {
return (T)this;
}
}
@@ -0,0 +1,18 @@
abstract class Test {
interface Selection<A> {}
interface CriteriaQuery<T> {
void select(Selection<? extends T> selection);
}
private <N> void foo(CriteriaQuery<N> criteria, Selection<String[]> array) {
criteria.select((Selection<? extends N>)array);
}
private <N extends Integer> void foo1(CriteriaQuery<N> criteria, Selection<String[]> array) {
criteria.select(<error descr="Inconvertible types; cannot cast 'Test.Selection<java.lang.String[]>' to 'Test.Selection<? extends N>'">(Selection<? extends N>)array</error>);
}
private <N extends Integer> void foo2(CriteriaQuery<N> criteria, Selection<Object> array) {
criteria.select(<error descr="Inconvertible types; cannot cast 'Test.Selection<java.lang.Object>' to 'Test.Selection<? extends N>'">(Selection<? extends N>)array</error>);
}
}
@@ -0,0 +1,18 @@
import java.util.concurrent.Future;
class TypeInferenceBug
{
public interface Callback<V> {
void done(V value);
}
public static <V> void addCallback(Future<V> future, Callback<? super V> callback) {}
public static <T> Callback<T> createCallback() {
return value -> {};
}
public static void bind(Future<?> future) {
addCallback(future, createCallback());
}
}
@@ -0,0 +1,17 @@
import java.util.Comparator;
class Test {
private final int x;
public Test(int x) {
this.x = x;
}
public static final Comparator<Test> comparator = (o1, o2) -> {
if (o1.x == o2.x) {
}
<error descr="'Test.this' cannot be referenced from a static context">this</error>.x != o2.x;
return 0;
};
}
@@ -0,0 +1,38 @@
import java.io.IOException;
class Test {
interface B<K, E extends Throwable> {
K l(K k) throws E;
}
<R> void bar(B<R, IOException> b) {}
<E extends Exception, T> T baz(T l) throws E {
return null;
}
{
bar(l -> baz(l));
bar(this::baz);
}
}
class Test1 {
interface B<K, E extends Throwable> {
K l(K k) throws E;
}
<R> void bar(B<R, IOException> b) {}
class MyEx extends Exception{}
<E extends MyEx, T> T baz(T l) throws E {
return null;
}
{
bar(l -> baz<error descr="'baz(java.lang.Object)' in 'Test1' cannot be applied to '(<lambda parameter>)'">(l)</error>);
bar(<error descr="Unhandled exception: Test1.MyEx">this::baz</error>);
}
}
@@ -0,0 +1,28 @@
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.function.Function;
class Test {
static class Base {
public BigDecimal getTotal() {
return null;
}
}
public static void foo(List<? extends Base> list, List<Base> list1) {
System.out.println(add(list, Base::getTotal));
list1.forEach(Base::getTotal);
}
public static <T> BigDecimal add(Collection<T> objectsThatHaveBigDecimals, Function<T, ? extends BigDecimal> functionToGet) {
return objectsThatHaveBigDecimals == null ? null : objectsThatHaveBigDecimals.stream().map(functionToGet).reduce(null, Test::add);
}
public static BigDecimal add(BigDecimal... sequence) {
return null;
}
}
@@ -0,0 +1,43 @@
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collector;
class Test {
public static final <T> Collector<T, AtomicReference<T>, Optional<T>> toSingleton() {
return Collector.of(
AtomicReference::new,
(ref, v) -> {
if (!ref.compareAndSet(null, v) && v != null) {
throw new IllegalStateException("There is only one elvis.");
}
},
(left, right) -> setOrFail(left, right.get()),
ref -> Optional.of(ref.get())
);
}
public static final <T> Collector<T, AtomicReference<T>, Optional<T>> toSingleton1() {
return Collector.of(
AtomicReference::new,
(ref, v) -> setOrFail(ref, v),
(left, right) -> setOrFail(left, right.get()),
ref -> Optional.of(ref.get())
);
}
public static final <T> Collector<T, AtomicReference<T>, Optional<T>> toSingleton2() {
return Collector.of(
AtomicReference::new,
Test::setOrFail,
(left, right) -> setOrFail(left, right.get()),
ref -> Optional.of(ref.get())
);
}
private static final <T> AtomicReference<T> setOrFail(AtomicReference<T> ref, T v) {
if (!ref.compareAndSet(null, v) && v != null) {
throw new IllegalStateException("There is only one elvis.");
}
return ref;
}
}
@@ -0,0 +1,9 @@
import java.util.Collection;
import java.util.function.ToIntFunction;
import java.util.stream.Collectors;
class Test {
public static <T> int sum(Collection<? extends T> collection, ToIntFunction<? super T> mapper) {
return collection.stream().collect(Collectors.summingInt(mapper));
}
}
@@ -0,0 +1,21 @@
import java.util.*;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import static java.util.stream.Collectors.counting;
import static java.util.stream.Collectors.groupingBy;
abstract class Token {
private static B<Long> getMode(Optional<Map.Entry<Integer, Long>> max){
return max
.flatMap(e -> Optional.of(new B<>(Long.valu<ref>eOf(e.getValue().longValue()))))
.get();
}
static class B<K> {
public B(K k) {}
}
}
@@ -0,0 +1,20 @@
// "Implement method 'foo'" "true"
abstract class A<T> {
abstract String foo(T t);
}
class B extends A<String> {
@Override
String foo(String s1) {
return null;
}
}
class ABC extends A<Integer> {
@Override
String foo(Integer integer) {
return null;
}
}
@@ -0,0 +1,15 @@
// "Implement method 'foo'" "true"
abstract class A<T> {
abstract String f<caret>oo(T t);
}
class B extends A<String> {
@Override
String foo(String s1) {
return null;
}
}
class ABC extends A<Integer> {}
@@ -20,6 +20,9 @@ import com.intellij.codeInsight.generation.GenerateSetterHandler
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.codeStyle.CodeStyleSettings
import com.intellij.psi.codeStyle.CodeStyleSettingsManager
import com.intellij.psi.codeStyle.JavaCodeStyleManager
import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase
import com.intellij.util.ui.UIUtil
import com.siyeh.ig.style.UnqualifiedFieldAccessInspection
@@ -70,6 +73,34 @@ class Foo {
'''
}
public void "test strip field prefix"() {
def settings = CodeStyleSettingsManager.getInstance(getProject()).currentSettings
String oldPrefix = settings.FIELD_NAME_PREFIX
try {
settings.FIELD_NAME_PREFIX = "my"
myFixture.configureByText 'a.java', '''
class Foo {
String myName;
<caret>
}
'''
generateGetter()
myFixture.checkResult '''
class Foo {
String myName;
public String getName() {
return myName;
}
}
'''
}
finally {
settings.FIELD_NAME_PREFIX = oldPrefix
}
}
public void "test qualified this"() {
myFixture.enableInspections(UnqualifiedFieldAccessInspection.class)
myFixture.configureByText 'a.java', '''
@@ -91,6 +122,38 @@ class Foo {
'''
}
public void "test nullable stuff"() {
myFixture.addClass("package org.jetbrains.annotations;\n" +
"public @interface NotNull {}")
myFixture.configureByText 'a.java', '''
class Foo {
@org.jetbrains.annotations.NotNull
private String myName;
<caret>
}
'''
generateGetter()
generateSetter()
myFixture.checkResult '''import org.jetbrains.annotations.NotNull;
class Foo {
@org.jetbrains.annotations.NotNull
private String myName;
public void setMyName(@NotNull String myName) {
this.myName = myName;
}
@NotNull
public String getMyName() {
return myName;
}
}
'''
}
private void generateGetter() {
WriteCommandAction.runWriteCommandAction(getProject(), {
new GenerateGetterHandler() {
@@ -25,7 +25,7 @@ import com.intellij.testFramework.fixtures.JavaCodeInsightFixtureTestCase
*/
class MultipleModuleHighlightingTest extends JavaCodeInsightFixtureTestCase {
@Bombed(day = 1, month = Calendar.MARCH)
@Bombed(day = 1, month = Calendar.APRIL)
public void "test use original place classpath for reference type resolving"() {
addTwoModules()
@@ -60,7 +60,7 @@ class Class3 {
myFixture.checkHighlighting()
}
@Bombed(day = 1, month = Calendar.MARCH)
@Bombed(day = 1, month = Calendar.APRIL)
public void "test use original place classpath for new expression type resolving"() {
addTwoModules()
@@ -316,14 +316,9 @@ class AdditionalEventInfo {
}
}
class MockReformatFileSettings implements LayoutCodeOptions {
private boolean myProcessWholeFile;
private boolean myProcessDirectories;
private boolean myRearrange;
private boolean myIncludeSubdirs;
class MockReformatFileSettings implements ReformatFilesOptions {
private boolean myOptimizeImports;
private boolean myProcessOnlyChangedText;
private boolean myIsOK = true;
private boolean myIncludeSubdirs;
@Nullable
@Override
@@ -338,33 +333,13 @@ class MockReformatFileSettings implements LayoutCodeOptions {
}
@Override
public boolean isProcessWholeFile() {
return myProcessWholeFile;
}
MockReformatFileSettings setProcessWholeFile(boolean processWholeFile) {
myProcessWholeFile = processWholeFile;
return this;
public TextRangeType getTextRangeType() {
return TextRangeType.WHOLE_FILE;
}
@Override
public boolean isProcessDirectory() {
return myProcessDirectories;
}
MockReformatFileSettings setProcessDirectory(boolean processDirectories) {
myProcessDirectories = processDirectories;
return this;
}
@Override
public boolean isRearrangeEntries() {
return myRearrange;
}
@Override
public boolean isIncludeSubdirectories() {
return myIncludeSubdirs;
public boolean isRearrangeCode() {
return false;
}
@Override
@@ -378,23 +353,6 @@ class MockReformatFileSettings implements LayoutCodeOptions {
return this;
}
@Override
public boolean isProcessOnlyChangedText() {
return myProcessOnlyChangedText;
}
@NotNull
MockReformatFileSettings setProcessOnlyChangedText(boolean processOnlyChangedText) {
myProcessOnlyChangedText = processOnlyChangedText;
return this;
}
@NotNull
MockReformatFileSettings setRearrange(boolean rearrange) {
myRearrange = rearrange;
return this;
}
@NotNull
MockReformatFileSettings setIncludeSubdirs(boolean includeSubdirs) {
myIncludeSubdirs = includeSubdirs;
@@ -16,106 +16,90 @@
package com.intellij.codeInsight.actions;
import com.intellij.JavaTestUtil;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vcs.FilePath;
import com.intellij.openapi.vcs.VcsException;
import com.intellij.openapi.vcs.changes.Change;
import com.intellij.openapi.vcs.changes.ContentRevision;
import com.intellij.openapi.vcs.history.VcsRevisionNumber;
import com.intellij.psi.PsiFile;
import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import com.intellij.testFramework.fixtures.LightPlatformCodeInsightFixtureTestCase;
public class ReformatCodeActionInEditorTest extends LightCodeInsightFixtureTestCase {
import static com.intellij.codeInsight.actions.TextRangeType.*;
public class ReformatCodeActionInEditorTest extends LightPlatformCodeInsightFixtureTestCase {
@Override
protected String getTestDataPath() {
return JavaTestUtil.getJavaTestDataPath() + "/actions/reformatFileInEditor/";
}
public void doTest(@NotNull ReformatFilesOptions options) {
setOptions(options);
String before = null;
if (options.isProcessOnlyChangedText()) {
myFixture.configureByFile(getTestName(true) + "_revision.java");
PsiFile file = myFixture.getFile();
Document document = myFixture.getDocument(file);
before = document.getText();
}
myFixture.configureByFile(getTestName(true) + "_before.java");
if (before != null) {
myFixture.getFile().putUserData(FormatChangedTextUtil.TEST_REVISION_CONTENT, before);
}
final String actionId = IdeActions.ACTION_EDITOR_REFORMAT;
AnAction action = ActionManager.getInstance().getAction(actionId);
AnActionEvent event = createEventFor(action, getProject(), myFixture.getEditor());
action.actionPerformed(event);
myFixture.checkResultByFile(getTestName(true) + "_after.java");
}
@Override
public void tearDown() throws Exception {
myFixture.getFile().putUserData(FormatChangedTextUtil.TEST_REVISION_CONTENT, null);
super.tearDown();
}
protected AnActionEvent createEventFor(@NotNull AnAction action, @NotNull final Project project, @NotNull final Editor editor) {
return new AnActionEvent(null, new DataContext() {
@Nullable
@Override
public Object getData(@NonNls String dataId) {
if (CommonDataKeys.PROJECT.is(dataId)) return project;
if (CommonDataKeys.EDITOR.is(dataId)) return editor;
return null;
}
}, "", action.getTemplatePresentation(), ActionManager.getInstance(), 0);
public void doTest(LayoutCodeOptions options) {
CharSequence revisionContent = null;
if (options.getTextRangeType() == VCS_CHANGED_TEXT) {
myFixture.configureByFile(getTestName(true) + "_revision.java");
PsiFile file = myFixture.getFile();
Document document = myFixture.getDocument(file);
revisionContent = document.getCharsSequence();
}
myFixture.configureByFile(getTestName(true) + "_before.java");
if (revisionContent != null) {
myFixture.getFile().putUserData(FormatChangedTextUtil.TEST_REVISION_CONTENT, revisionContent);
}
FileInEditorProcessor processor = new FileInEditorProcessor(myFixture.getFile(), myFixture.getEditor(), options);
processor.processCode();
myFixture.checkResultByFile(getTestName(true) + "_after.java");
}
protected void setOptions(ReformatFilesOptions options) {
ReformatCodeAction.setTestOptions(options);
public void testSelectionReformat() {
doTest(new ReformatCodeRunOptions(SELECTED_TEXT));
}
public void testWholeFileReformat() {
doTest(new ReformatCodeRunOptions(WHOLE_FILE));
}
public void testWholeFileReformatAndOptimize() {
doTest(new ReformatCodeRunOptions(WHOLE_FILE).setOptimizeImports(true));
}
public void testSelectedTextAndOptimizeImports() {
doTest(new ReformatCodeRunOptions(SELECTED_TEXT).setOptimizeImports(true));
}
public void testFormatWholeFile() {
doTest(new MockReformatFileSettings().setProcessWholeFile(true));
doTest(new ReformatCodeRunOptions(WHOLE_FILE));
}
public void testFormatOptimizeWholeFile() {
doTest(new MockReformatFileSettings().setProcessWholeFile(true).setOptimizeImports(true));
doTest(new ReformatCodeRunOptions(WHOLE_FILE).setOptimizeImports(true));
}
public void testFormatOptimizeRearrangeWholeFile() {
doTest(new MockReformatFileSettings().setProcessWholeFile(true).setOptimizeImports(true).setRearrange(true));
doTest(new ReformatCodeRunOptions(WHOLE_FILE).setOptimizeImports(true).setRearrangeCode(true));
}
public void testFormatSelection() {
doTest(new MockReformatFileSettings().setProcessWholeFile(false));
doTest(new ReformatCodeRunOptions(SELECTED_TEXT));
}
public void testFormatRearrangeSelection() {
doTest(new MockReformatFileSettings().setProcessWholeFile(false).setRearrange(true));
doTest(new ReformatCodeRunOptions(SELECTED_TEXT).setRearrangeCode(true));
}
public void testFormatVcsChanges() {
doTest(new MockReformatFileSettings().setProcessOnlyChangedText(true));
doTest(new ReformatCodeRunOptions(VCS_CHANGED_TEXT));
}
public void testFormatOptimizeVcsChanges() {
doTest(new MockReformatFileSettings().setProcessOnlyChangedText(true).setOptimizeImports(true));
doTest(new ReformatCodeRunOptions(VCS_CHANGED_TEXT).setOptimizeImports(true));
}
public void testFormatOptimizeRearrangeVcsChanges() {
doTest(new MockReformatFileSettings().setProcessOnlyChangedText(true).setOptimizeImports(true).setRearrange(true));
doTest(new ReformatCodeRunOptions(VCS_CHANGED_TEXT).setOptimizeImports(true).setRearrangeCode(true));
}
}
@@ -35,35 +35,10 @@ public class ReformatCodeActionTest extends AbstractLayoutCodeProcessorTest {
public void testReformatAndOptimizeMultipleFiles() throws IOException {
List<PsiFile> files = createTestFiles(getTempRootDirectory(), classNames);
injectMockDialogFlags(new MockReformatFileSettings().setOptimizeImports(true));
performReformatActionOnSelectedFiles(files);
checkFormationAndImportsOptimizationFor(files);
}
public void testReformatSingleSelectedFile() throws IOException {
List<PsiFile> files = createTestFiles(getTempRootDirectory(), classNames);
PsiFile fileToReformat = files.get(0);
List<PsiFile> shouldNotBeFormatted = files.subList(1, files.size());
injectMockDialogFlags(new MockReformatFileSettings().setOptimizeImports(true));
performReformatActionOnSelectedFile(fileToReformat);
checkFormationAndImportsOptimizationFor(Arrays.asList(fileToReformat));
checkNoProcessingWasPerformedOn(shouldNotBeFormatted);
}
public void testReformatAndOptimizeFileFromEditor() throws IOException {
List<PsiFile> files = createTestFiles(getTempRootDirectory(), classNames);
injectMockDialogFlags(new MockReformatFileSettings().setOptimizeImports(true));
PsiFile fileToFormat = files.get(0);
List<PsiFile> shouldNotBeFormatted = files.subList(1, files.size());
performReformatActionOnFileInEditor(fileToFormat);
checkFormationAndImportsOptimizationFor(Arrays.asList(fileToFormat));
checkNoProcessingWasPerformedOn(shouldNotBeFormatted);
}
public void testOptimizeAndReformatOnlySelectedFiles() throws IOException {
List<PsiFile> files = createTestFiles(getTempRootDirectory(), classNames);
List<PsiFile> forProcessing = ContainerUtil.newArrayList(files.get(0), files.get(1));
@@ -77,28 +52,6 @@ public class ReformatCodeActionTest extends AbstractLayoutCodeProcessorTest {
checkNoProcessingWasPerformedOn(noProcessing);
}
public void testOptimizeAndReformatAllFilesInDirectoryIncludeSubdirs() throws IOException {
TestFileStructure fileStructure = getThreeLevelDirectoryStructure();
injectMockDialogFlags(new MockReformatFileSettings().setOptimizeImports(true).setProcessDirectory(true).setIncludeSubdirs(true));
PsiFile fileInEditor = fileStructure.getFilesAtLevel(2).get(0);
List<PsiFile> shouldNotBeFormatted = fileStructure.getFilesAtLevel(1);
performReformatActionOnFileInEditor(fileInEditor);
checkFormationAndImportsOptimizationFor(fileStructure.getFilesAtLevel(2), fileStructure.getFilesAtLevel(3));
checkNoProcessingWasPerformedOn(shouldNotBeFormatted);
}
public void testOptimizeAndReformatAllFilesInDirectoryExcludeSubdirs() throws IOException {
TestFileStructure fileStructure = getThreeLevelDirectoryStructure();
injectMockDialogFlags(new MockReformatFileSettings().setOptimizeImports(true).setIncludeSubdirs(false));
performReformatActionOnSelectedFiles(fileStructure.getFilesAtLevel(2));
checkFormationAndImportsOptimizationFor(fileStructure.getFilesAtLevel(2));
checkNoProcessingWasPerformedOn(fileStructure.getFilesAtLevel(1), fileStructure.getFilesAtLevel(3));
}
public void testOptimizeAndReformatInModule() throws IOException {
Module module = createModuleWithSourceRoot("newModule");
VirtualFile srcDir = ModuleRootManager.getInstance(module).getSourceRoots()[0];
@@ -109,26 +62,4 @@ public class ReformatCodeActionTest extends AbstractLayoutCodeProcessorTest {
checkFormationAndImportsOptimizationFor(files);
}
private TestFileStructure getThreeLevelDirectoryStructure() throws IOException {
TestFileStructure fileStructure = new TestFileStructure(getModule(), getTempRootDirectory());
fileStructure.createDirectoryAndMakeItCurrent("dir");
addFilesToCurrentDirectory(fileStructure);
fileStructure.createDirectoryAndMakeItCurrent("innerDir");
addFilesToCurrentDirectory(fileStructure);
fileStructure.createDirectoryAndMakeItCurrent("innerInnerDir");
addFilesToCurrentDirectory(fileStructure);
return fileStructure;
}
private void addFilesToCurrentDirectory(TestFileStructure fileStructure) throws IOException {
for (int i = 0; i < 5; i++) {
String className = "Test" + i;
fileStructure.addTestFile("Test" + i + ".java", getUntouchedJavaSourceForTotalProcessing(className));
}
}
}
@@ -932,6 +932,7 @@ public class ListUtils {
public void testTabReplacesMethodNameWithLocalVariableName() throws Throwable { doTest('\t'); }
public void testMethodParameterAnnotationClass() throws Throwable { doTest(); }
public void testInnerAnnotation() { doTest('\n'); }
public void testPrimitiveCastOverwrite() throws Throwable { doTest '\t' }
public void testClassReferenceInFor() throws Throwable { doTest ' ' }
public void testClassReferenceInFor2() throws Throwable { doTest ' ' }
@@ -455,6 +455,14 @@ public class GenericsHighlightingTest extends LightDaemonAnalyzerTestCase {
doTest(LanguageLevel.JDK_1_7, JavaSdkVersion.JDK_1_7, false);
}
public void testCastConversionToTypeParameter() throws Exception {
doTest(LanguageLevel.JDK_1_7, JavaSdkVersion.JDK_1_7, false);
}
public void testTypeDistinctProverForWildcardAndTypeParameter() throws Exception {
doTest(LanguageLevel.JDK_1_7, JavaSdkVersion.JDK_1_7, false);
}
public void testJavaUtilCollections_NoVerify() throws Exception {
PsiClass collectionsClass = getJavaFacade().findClass("java.util.Collections", GlobalSearchScope.moduleWithLibrariesScope(getModule()));
assertNotNull(collectionsClass);
@@ -16,7 +16,6 @@
package com.intellij.codeInsight.daemon.lambda;
import com.intellij.JavaTestUtil;
import com.intellij.idea.Bombed;
import com.intellij.psi.*;
import com.intellij.psi.search.searches.FunctionalExpressionSearch;
import com.intellij.psi.search.searches.ReferencesSearch;
@@ -25,7 +24,6 @@ import com.intellij.testFramework.LightProjectDescriptor;
import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase;
import org.jetbrains.annotations.NotNull;
import java.util.Calendar;
import java.util.Collection;
public class FindFunctionalInterfaceTest extends LightCodeInsightFixtureTestCase {
@@ -263,6 +263,10 @@ public class GraphInferenceHighlightingTest extends LightDaemonAnalyzerTestCase
doTest();
}
public void testIDEA134277() throws Exception {
doTest();
}
private void doTest() throws Exception {
doTest(false);
}
@@ -0,0 +1,55 @@
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInsight.daemon.lambda;
import com.intellij.codeInsight.daemon.LightDaemonAnalyzerTestCase;
import com.intellij.codeInspection.deadCode.UnusedDeclarationInspection;
import com.intellij.openapi.projectRoots.JavaSdkVersion;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.testFramework.IdeaTestUtil;
import org.jetbrains.annotations.NonNls;
public class Java8RegressionTest extends LightDaemonAnalyzerTestCase {
@NonNls static final String BASE_PATH = "/codeInsight/daemonCodeAnalyzer/lambda/regression";
@Override
protected void setUp() throws Exception {
super.setUp();
enableInspectionTool(new UnusedDeclarationInspection());
}
public void testIDEA136856() throws Exception {
doTest();
}
public void testIDEA136887() throws Exception {
doTest();
}
private void doTest() {
doTest(false);
}
private void doTest(boolean warnings) {
IdeaTestUtil.setTestVersion(JavaSdkVersion.JDK_1_8, getModule(), getTestRootDisposable());
doTest(BASE_PATH + "/" + getTestName(false) + ".java", warnings, false);
}
@Override
protected Sdk getProjectJDK() {
return IdeaTestUtil.getMockJdk18();
}
}
@@ -32,6 +32,7 @@ public class LambdaHighlightingTest extends LightDaemonAnalyzerTestCase {
public void testStaticAccess() { doTest(); }
public void testEffectiveFinal() { doTest(); }
public void testFieldInitializedUsedInLambda() {doTest();}
public void testReassignUsedVars() { doTest(); }
public void testLambdaContext() { doTest(); }
public void testReturnTypeCompatibility() { doTest(); }
@@ -80,7 +80,6 @@ public class NewLambdaHighlightingTest extends LightDaemonAnalyzerTestCase {
public void testLiftedIntersectionType() { doTest(); }
public void testInferenceFromReturnStatements() { doTest(); }
public void testDownUpThroughLambdaReturnStatements() { doTest(); }
@Bombed(year = 2015, month = Calendar.MARCH, day = 30)
public void testIDEA124547() { doTest(); }
public void testIDEA118362() { doTest(); }
public void testIDEA126056() { doTest(); }
@@ -139,11 +138,14 @@ public class NewLambdaHighlightingTest extends LightDaemonAnalyzerTestCase {
doTest();
}
@Bombed(year = 2015, month = Calendar.MARCH, day = 30)
public void testCheckedExceptionsConstraintsSubstitutions() throws Exception {
doTest();
}
public void testCheckedExceptionsConstraintsSubstitutions1() throws Exception {
doTest();
}
public void testCheckedExceptionsConstraintsSubstitutionsDeepInBody() throws Exception {
doTest();
}
@@ -168,7 +170,6 @@ public class NewLambdaHighlightingTest extends LightDaemonAnalyzerTestCase {
doTest();
}
@Bombed(year = 2015, month = Calendar.MARCH, day = 30)
public void testIDEA127124() throws Exception {
doTest();
}
@@ -19,15 +19,12 @@ import com.intellij.codeInsight.daemon.LightDaemonAnalyzerTestCase;
import com.intellij.codeInspection.LocalInspectionTool;
import com.intellij.codeInspection.deadCode.UnusedDeclarationInspection;
import com.intellij.codeInspection.uncheckedWarnings.UncheckedWarningLocalInspection;
import com.intellij.idea.Bombed;
import com.intellij.openapi.projectRoots.JavaSdkVersion;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.testFramework.IdeaTestUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import java.util.Calendar;
public class NewMethodRefHighlightingTest extends LightDaemonAnalyzerTestCase {
@NonNls static final String BASE_PATH = "/codeInsight/daemonCodeAnalyzer/lambda/newMethodRef";
@@ -373,7 +370,6 @@ public class NewMethodRefHighlightingTest extends LightDaemonAnalyzerTestCase {
doTest();
}
@Bombed(year = 2015, month = Calendar.MARCH, day = 30)
public void testIDEA132379() throws Exception {
doTest();
}
@@ -386,6 +382,10 @@ public class NewMethodRefHighlightingTest extends LightDaemonAnalyzerTestCase {
doTest(false);
}
public void testSecondSearchIfFirstParameterIsASubtypeOfReferenceTypeFromExpressionDeclaration() throws Exception {
doTest();
}
private void doTest() {
doTest(false);
}
@@ -21,6 +21,7 @@ import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.roots.LanguageLevelProjectExtension;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.psi.*;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.testFramework.IdeaTestUtil;
import com.intellij.testFramework.ResolveTestCase;
@@ -30,6 +31,14 @@ public class TypeInference18Test extends ResolveTestCase {
doTest();
}
public void testSecondConflictResolution() throws Exception {
PsiReference ref = configureByFile("/codeInsight/daemonCodeAnalyzer/lambda/resolve/" + getTestName(false) + ".java");
assertNotNull(ref);
PsiMethodCallExpression methodCallExpression = PsiTreeUtil.getParentOfType(ref.getElement(), PsiMethodCallExpression.class);
assertNotNull(methodCallExpression);
assertNotNull(methodCallExpression.resolveMethod());
}
private LanguageLevel myOldLanguageLevel;
@Override
@@ -365,6 +365,19 @@ public class FindManagerTest extends DaemonAnalyzerTestCase {
assertSize(1, findUsages(findModel));
}
public void testNonSourceContent() throws Exception {
VirtualFile root = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(createTempDirectory());
PsiTestUtil.addContentRoot(myModule, root);
createFile(myModule, root, "A.txt", "goo doo");
FindModel findModel = FindManagerTestUtils.configureFindModel("goo");
findModel.setProjectScope(false);
findModel.setModuleName(myModule.getName());
assertSize(1, findUsages(findModel));
}
public void testReplaceRegexp() {
FindModel findModel = new FindModel();
findModel.setStringToFind("bug_(?=here)");
@@ -537,6 +550,7 @@ public class FindManagerTest extends DaemonAnalyzerTestCase {
findModel.setFromCursor(false);
findModel.setGlobal(true);
findModel.setMultipleFiles(true);
findModel.setCustomScope(true);
ThrowableRunnable test = new ThrowableRunnable() {
@Override
@@ -573,6 +587,7 @@ public class FindManagerTest extends DaemonAnalyzerTestCase {
VirtualFile file = tempDirFixture.createFile("a.txt", "foo bar foo");
FindModel findModel = FindManagerTestUtils.configureFindModel("foo");
findModel.setWholeWordsOnly(true);
findModel.setCustomScope(true);
findModel.setCustomScope(new LocalSearchScope(PsiManager.getInstance(myProject).findFile(file)));
assertSize(2, findUsages(findModel));
}
@@ -446,7 +446,8 @@ public class JavaStructuralSearchProfile extends StructuralSearchProfile {
ParameterInfo nameInfo = builder.findParameterization(name);
ParameterInfo typeInfo = builder.findParameterization(type);
if (nameInfo != null && typeInfo != null && !(parameter.getParent() instanceof PsiCatchSection)) {
final PsiElement scope = parameter.getDeclarationScope();
if (nameInfo != null && typeInfo != null && !(scope instanceof PsiCatchSection) && !(scope instanceof PsiForeachStatement)) {
nameInfo.setArgumentContext(false);
typeInfo.setArgumentContext(false);
typeInfo.setMethodParameterContext(true);
@@ -1205,9 +1205,10 @@ public class JavaMatchingVisitor extends JavaElementVisitor {
public void visitIfStatement(final PsiIfStatement if1) {
final PsiIfStatement if2 = (PsiIfStatement)myMatchingVisitor.getElement();
final PsiStatement elseBranch = if1.getElseBranch();
myMatchingVisitor.setResult(myMatchingVisitor.match(if1.getCondition(), if2.getCondition()) &&
compareBody(if1.getThenBranch(), if2.getThenBranch()) &&
compareBody(if1.getElseBranch(), if2.getElseBranch()));
(elseBranch == null || compareBody(elseBranch, if2.getElseBranch())));
}
@Override
@@ -84,7 +84,7 @@ public class CompileScopeImpl extends CompileScope {
@Override
public boolean isAffected(BuildTarget<?> target, @NotNull File file) {
if (myFiles.isEmpty()) {//optimization
return true;
return isAffected(target);
}
final Set<File> files = myFiles.get(target);
return files != null && files.contains(file);
Binary file not shown.
@@ -60,7 +60,7 @@ public class HighlightDisplayLevel {
*/
@Deprecated
public static final HighlightDisplayLevel INFO = new HighlightDisplayLevel(HighlightSeverity.INFO, DO_NOT_SHOW.getIcon());
public static final HighlightDisplayLevel WEAK_WARNING = new HighlightDisplayLevel(HighlightSeverity.WEAK_WARNING, DO_NOT_SHOW.getIcon());
public static final HighlightDisplayLevel WEAK_WARNING = new HighlightDisplayLevel(HighlightSeverity.WEAK_WARNING, createIconByKey(CodeInsightColors.WEAK_WARNING_ATTRIBUTES));
public static final HighlightDisplayLevel NON_SWITCHABLE_ERROR = new HighlightDisplayLevel(HighlightSeverity.ERROR);
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2014 JetBrains s.r.o.
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,10 +13,10 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInsight.daemon;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.util.xmlb.annotations.OptionTag;
import com.intellij.util.xmlb.annotations.Transient;
public class DaemonCodeAnalyzerSettings {
@@ -26,9 +26,9 @@ public class DaemonCodeAnalyzerSettings {
public boolean NEXT_ERROR_ACTION_GOES_TO_ERRORS_FIRST = true;
public int AUTOREPARSE_DELAY = 300;
public boolean SHOW_ADD_IMPORT_HINTS = true;
protected boolean myShowAddImportHints = true;
public String NO_AUTO_IMPORT_PATTERN = "[a-z].?";
public boolean SUPPRESS_WARNINGS = true;
protected boolean mySuppressWarnings = true;
public boolean SHOW_METHOD_SEPARATORS = false;
public int ERROR_STRIPE_MARK_MIN_HEIGHT = 2;
public boolean SHOW_SMALL_ICONS_IN_GUTTER = true;
@@ -38,21 +38,21 @@ public class DaemonCodeAnalyzerSettings {
return false;
}
@Transient
@OptionTag(value = "SHOW_ADD_IMPORT_HINTS")
public boolean isImportHintEnabled() {
return SHOW_ADD_IMPORT_HINTS;
return myShowAddImportHints;
}
public void setImportHintEnabled(boolean isImportHintEnabled) {
SHOW_ADD_IMPORT_HINTS = isImportHintEnabled;
myShowAddImportHints = isImportHintEnabled;
}
@Transient
@OptionTag(value = "SUPPRESS_WARNINGS")
public boolean isSuppressWarnings() {
return SUPPRESS_WARNINGS;
return mySuppressWarnings;
}
public void setSuppressWarnings(boolean suppressWarnings) {
SUPPRESS_WARNINGS = suppressWarnings;
mySuppressWarnings = suppressWarnings;
}
}
@@ -20,7 +20,6 @@ import com.intellij.idea.Main;
import com.intellij.openapi.application.PathManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.util.ArrayUtil;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.lang.UrlClassLoader;
import com.intellij.util.text.StringTokenizer;
@@ -28,13 +27,10 @@ import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.*;
import java.util.regex.Pattern;
/**
@@ -55,14 +51,14 @@ public class BootstrapClassLoaderUtil extends ClassUtilCore {
public static ClassLoader initClassLoader(boolean updatePlugins) throws MalformedURLException {
PathManager.loadProperties();
List<URL> classpath = new ArrayList<URL>();
Collection<URL> classpath = new LinkedHashSet<URL>();
addParentClasspath(classpath);
addIDEALibraries(classpath);
addAdditionalClassPath(classpath);
UrlClassLoader.Builder builder = UrlClassLoader.build()
.urls(filterClassPath(classpath))
.allowLock()
.urls(filterClassPath(new ArrayList<URL>(classpath)))
.allowLock(false)
.usePersistentClasspathIndexForLocalClassDirectories()
.useCache();
if (Boolean.valueOf(System.getProperty(PROPERTY_ALLOW_BOOTSTRAP_RESOURCES, "true"))) {
@@ -85,68 +81,35 @@ public class BootstrapClassLoaderUtil extends ClassUtilCore {
return newClassLoader;
}
private static List<URL> filterClassPath(List<URL> classpathElements) {
String ignoreProperty = System.getProperty(PROPERTY_IGNORE_CLASSPATH);
if (ignoreProperty != null) {
Pattern pattern = Pattern.compile(ignoreProperty);
for (Iterator<URL> i = classpathElements.iterator(); i.hasNext(); ) {
String url = i.next().toExternalForm();
if (pattern.matcher(url).matches()) {
i.remove();
}
}
}
return classpathElements;
}
private static void addParentClasspath(List<URL> classpathElements) throws MalformedURLException {
private static void addParentClasspath(Collection<URL> classpath) throws MalformedURLException {
List<URLClassLoader> loaders = new ArrayList<URLClassLoader>(2);
for (ClassLoader loader = BootstrapClassLoaderUtil.class.getClassLoader(); loader != null; loader = loader.getParent()) {
if (loader instanceof URLClassLoader) {
ContainerUtil.addAll(classpathElements, ((URLClassLoader)loader).getURLs());
loaders.add(0, (URLClassLoader)loader);
}
else {
String loaderName = loader.getClass().getName();
try {
Class<?> antClassLoaderClass = Class.forName("org.apache.tools.ant.AntClassLoader");
if (antClassLoaderClass.isInstance(loader) ||
"org.apache.tools.ant.AntClassLoader".equals(loaderName) ||
"org.apache.tools.ant.loader.AntClassLoader2".equals(loaderName)) {
String classpath = (String)antClassLoaderClass
.getDeclaredMethod("getClasspath", ArrayUtil.EMPTY_CLASS_ARRAY)
.invoke(loader, ArrayUtil.EMPTY_OBJECT_ARRAY);
StringTokenizer tokenizer = new StringTokenizer(classpath, File.separator, false);
while (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
classpathElements.add(new File(token).toURI().toURL());
}
}
else {
getLogger().warn("Unknown class loader: " + loaderName);
}
}
catch (ClassCastException e) { getLogger().warn("Unknown class loader '" + loaderName + "'", e); }
catch (ClassNotFoundException e) { getLogger().warn("Unknown class loader '" + loaderName + "'", e); }
catch (NoSuchMethodException e) { getLogger().warn("Unknown class loader '" + loaderName + "'", e); }
catch (IllegalAccessException e) { getLogger().warn("Unknown class loader '" + loaderName + "'", e); }
catch (InvocationTargetException e) { getLogger().warn("Unknown class loader '" + loaderName + "'", e); }
getLogger().warn("Unknown class loader: " + loader.getClass().getName());
}
}
for (URLClassLoader loader : loaders) {
ContainerUtil.addAll(classpath, loader.getURLs());
}
}
private static void addIDEALibraries(List<URL> classpathElements) throws MalformedURLException {
private static void addIDEALibraries(Collection<URL> classpath) throws MalformedURLException {
Class<BootstrapClassLoaderUtil> aClass = BootstrapClassLoaderUtil.class;
String selfRoot = PathManager.getResourceRoot(aClass, "/" + aClass.getName().replace('.', '/') + ".class");
assert selfRoot != null;
URL selfRootUrl = new File(selfRoot).getAbsoluteFile().toURI().toURL();
classpathElements.add(selfRootUrl);
classpath.add(selfRootUrl);
File libFolder = new File(PathManager.getLibPath());
addLibraries(classpathElements, libFolder, selfRootUrl);
addLibraries(classpathElements, new File(libFolder, "ext"), selfRootUrl);
addLibraries(classpathElements, new File(libFolder, "ant/lib"), selfRootUrl);
addLibraries(classpath, libFolder, selfRootUrl);
addLibraries(classpath, new File(libFolder, "ext"), selfRootUrl);
addLibraries(classpath, new File(libFolder, "ant/lib"), selfRootUrl);
}
private static void addLibraries(List<URL> classPath, File fromDir, URL selfRootUrl) throws MalformedURLException {
private static void addLibraries(Collection<URL> classPath, File fromDir, URL selfRootUrl) throws MalformedURLException {
File[] files = fromDir.listFiles();
if (files == null) return;
@@ -160,16 +123,30 @@ public class BootstrapClassLoaderUtil extends ClassUtilCore {
}
}
private static void addAdditionalClassPath(List<URL> classPath) {
private static void addAdditionalClassPath(Collection<URL> classpath) {
try {
StringTokenizer tokenizer = new StringTokenizer(System.getProperty(PROPERTY_ADDITIONAL_CLASSPATH, ""), File.pathSeparator, false);
while (tokenizer.hasMoreTokens()) {
String pathItem = tokenizer.nextToken();
classPath.add(new File(pathItem).toURI().toURL());
classpath.add(new File(pathItem).toURI().toURL());
}
}
catch (MalformedURLException e) {
getLogger().error(e);
}
}
private static List<URL> filterClassPath(List<URL> classpath) {
String ignoreProperty = System.getProperty(PROPERTY_IGNORE_CLASSPATH);
if (ignoreProperty != null) {
Pattern pattern = Pattern.compile(ignoreProperty);
for (Iterator<URL> i = classpath.iterator(); i.hasNext(); ) {
String url = i.next().toExternalForm();
if (pattern.matcher(url).matches()) {
i.remove();
}
}
}
return classpath;
}
}
@@ -17,8 +17,6 @@ package com.intellij.openapi.editor.markup;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.JDOMExternalizable;
import com.intellij.openapi.util.WriteExternalException;
import org.intellij.lang.annotations.JdkConstants;
import org.jdom.Element;
import org.jetbrains.annotations.Contract;
@@ -30,7 +28,7 @@ import java.awt.*;
/**
* Defines the visual representation (colors and effects) of text.
*/
public class TextAttributes implements JDOMExternalizable, Cloneable {
public class TextAttributes implements Cloneable {
private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.editor.markup.TextAttributes");
public static final TextAttributes ERASE_MARKER = new TextAttributes();
@@ -77,7 +75,7 @@ public class TextAttributes implements JDOMExternalizable, Cloneable {
myEnforcedDefaults = enforced;
}
public TextAttributes(@NotNull Element element) throws InvalidDataException {
public TextAttributes(@NotNull Element element) {
readExternal(element);
}
@@ -191,14 +189,20 @@ public class TextAttributes implements JDOMExternalizable, Cloneable {
return myAttrs.hashCode();
}
@Override
public void readExternal(Element element) throws InvalidDataException {
myAttrs = AttributesFlyweight.create(element);
if (isEmpty()) myEnforcedDefaults = true;
public void readExternal(Element element) {
try {
myAttrs = AttributesFlyweight.create(element);
}
catch (InvalidDataException e) {
throw new RuntimeException(e);
}
if (isEmpty()) {
myEnforcedDefaults = true;
}
}
@Override
public void writeExternal(Element element) throws WriteExternalException {
public void writeExternal(Element element) {
myAttrs.writeExternal(element);
}
@@ -27,7 +27,7 @@ import java.io.IOException;
/**
* @author yole
*/
public abstract class BaseSchemeProcessor<T extends ExternalizableScheme> implements SchemeProcessor<T> {
public abstract class BaseSchemeProcessor<T extends ExternalizableScheme> implements SchemeProcessor<T>, SchemeExtensionProvider {
@Override
public void initScheme(@NotNull T scheme) {
}
@@ -75,4 +75,15 @@ public abstract class BaseSchemeProcessor<T extends ExternalizableScheme> implem
public State getState(@NotNull T scheme) {
return shouldBeSaved(scheme) ? State.POSSIBLY_CHANGED : State.NON_PERSISTENT;
}
@Override
public boolean isUpgradeNeeded() {
return false;
}
@NotNull
@Override
public String getSchemeExtension() {
return ".xml";
}
}
@@ -15,94 +15,43 @@
*/
package com.intellij.openapi.options;
import com.intellij.util.ThrowableConvertor;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
public interface SchemesManager <T extends Scheme, E extends ExternalizableScheme>{
SchemesManager EMPTY = new SchemesManager(){
@Override
@NotNull
public Collection loadSchemes() {
return Collections.emptySet();
}
public abstract class SchemesManager<T extends Scheme, E extends ExternalizableScheme> {
@NotNull
public abstract Collection<E> loadSchemes();
@Override
public void addNewScheme(@NotNull final Scheme scheme, final boolean replaceExisting) {
}
public abstract void addNewScheme(@NotNull T scheme, final boolean replaceExisting);
@Override
public void clearAllSchemes() {
}
@Override
@NotNull
public List getAllSchemes() {
return Collections.emptyList();
}
@Override
public Scheme findSchemeByName(@NotNull String schemeName) {
return null;
}
@Override
public void save() {
}
@Override
public void setCurrentSchemeName(String schemeName) {
}
@Override
public Scheme getCurrentScheme() {
return null;
}
@Override
public void removeScheme(@NotNull Scheme scheme) {
}
@Override
@NotNull
public Collection getAllSchemeNames() {
return Collections.emptySet();
}
@Override
public File getRootDirectory() {
return null;
}
};
public abstract void clearAllSchemes();
@NotNull
Collection<E> loadSchemes();
void addNewScheme(@NotNull T scheme, final boolean replaceExisting);
void clearAllSchemes();
@NotNull
List<T> getAllSchemes();
public abstract List<T> getAllSchemes();
@Nullable
T findSchemeByName(@NotNull String schemeName);
public abstract T findSchemeByName(@NotNull String schemeName);
void save();
public abstract void save();
void setCurrentSchemeName(@Nullable String schemeName);
public abstract void setCurrentSchemeName(@Nullable String schemeName);
@Nullable
T getCurrentScheme();
public abstract T getCurrentScheme();
void removeScheme(@NotNull T scheme);
public abstract void removeScheme(@NotNull T scheme);
@NotNull
Collection<String> getAllSchemeNames();
public abstract Collection<String> getAllSchemeNames();
File getRootDirectory();
public abstract File getRootDirectory();
public void loadBundledScheme(@NotNull String resourceName, @NotNull Object requestor, @NotNull ThrowableConvertor<Element, T, Throwable> convertor) {
}
}
@@ -1,45 +0,0 @@
/*
* 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.openapi.options;
import org.jetbrains.annotations.NotNull;
@Deprecated
public class SharedScheme<E extends ExternalizableScheme> {
private final String myUserName;
private final String myDescription;
private final E myScheme;
public SharedScheme(@NotNull String userName, final String description, @NotNull E scheme) {
myUserName = userName;
myDescription = description;
myScheme = scheme;
}
@NotNull
public String getUserName() {
return myUserName;
}
public String getDescription() {
return myDescription;
}
@NotNull
public E getScheme() {
return myScheme;
}
}

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