CPP-16098 - Lags during inplace rename typing

- call `commitDocument` explicitly in cases when `calculateQuickResult` can redirect it's calculation to heavy `calculateResult`

GitOrigin-RevId: 41f0c47c57f4528d7d7a25208024ec28bb8c2e12
This commit is contained in:
Vladimir Plyashkun
2019-05-03 01:38:12 +03:00
committed by intellij-monorepo-bot
parent dc1a52762e
commit e3ca319824
279 changed files with 2826 additions and 3487 deletions
+3 -3
View File
@@ -1,12 +1,12 @@
<component name="libraryTable">
<library name="completion-ranking-java" type="repository">
<properties maven-id="org.jetbrains.intellij.deps.completion.ranking:java:0.0.3" />
<properties include-transitive-deps="false" maven-id="org.jetbrains.intellij.deps.completion:completion-ranking-java:0.0.6" />
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/org/jetbrains/intellij/deps/completion/ranking/java/0.0.3/java-0.0.3.jar!/" />
<root url="jar://$MAVEN_REPOSITORY$/org/jetbrains/intellij/deps/completion/completion-ranking-java/0.0.6/completion-ranking-java-0.0.6.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/org/jetbrains/intellij/deps/completion/ranking/java/0.0.3/java-0.0.3-sources.jar!/" />
<root url="jar://$MAVEN_REPOSITORY$/org/jetbrains/intellij/deps/completion/completion-ranking-java/0.0.6/completion-ranking-java-0.0.6-sources.jar!/" />
</SOURCES>
</library>
</component>
+12
View File
@@ -0,0 +1,12 @@
<component name="libraryTable">
<library name="completion-ranking-python" type="repository">
<properties include-transitive-deps="false" maven-id="org.jetbrains.intellij.deps.completion:completion-ranking-python:0.0.2" />
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/org/jetbrains/intellij/deps/completion/completion-ranking-python/0.0.2/completion-ranking-python-0.0.2.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/org/jetbrains/intellij/deps/completion/completion-ranking-python/0.0.2/completion-ranking-python-0.0.2-sources.jar!/" />
</SOURCES>
</library>
</component>
+3 -3
View File
@@ -1,12 +1,12 @@
<component name="libraryTable">
<library name="jediterm-pty" type="repository">
<properties include-transitive-deps="false" maven-id="org.jetbrains.jediterm:jediterm-pty:2.14" />
<properties include-transitive-deps="false" maven-id="org.jetbrains.jediterm:jediterm-pty:2.15" />
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/org/jetbrains/jediterm/jediterm-pty/2.14/jediterm-pty-2.14.jar!/" />
<root url="jar://$MAVEN_REPOSITORY$/org/jetbrains/jediterm/jediterm-pty/2.15/jediterm-pty-2.15.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/org/jetbrains/jediterm/jediterm-pty/2.14/jediterm-pty-2.14-sources.jar!/" />
<root url="jar://$MAVEN_REPOSITORY$/org/jetbrains/jediterm/jediterm-pty/2.15/jediterm-pty-2.15-sources.jar!/" />
</SOURCES>
</library>
</component>
@@ -49,9 +49,8 @@ public enum ArtifactKind {
}
return null;
}
@NotNull
public static EnumSet<ArtifactKind> kindsOf(boolean sources, boolean javadoc) {
public static EnumSet<ArtifactKind> kindsOf(boolean sources, boolean javadoc, String... artifactPackaging) {
EnumSet<ArtifactKind> result = EnumSet.noneOf(ArtifactKind.class);
if (sources) {
result.add(SOURCES);
@@ -59,6 +58,17 @@ public enum ArtifactKind {
if (javadoc) {
result.add(JAVADOC);
}
if (artifactPackaging.length == 0 || artifactPackaging.length == 1 && artifactPackaging[0] == null) {
result.add(ARTIFACT);
}
else {
for (String packaging : artifactPackaging) {
final ArtifactKind artifact = find(ARTIFACT.getClassifier(), packaging);
if (artifact != null) {
result.add(artifact);
}
}
}
return result;
}
}
@@ -20,7 +20,6 @@ import com.intellij.openapi.compiler.Compiler;
import com.intellij.openapi.compiler.CompilerBundle;
import com.intellij.openapi.compiler.CompilerManager;
import com.intellij.openapi.compiler.Validator;
import com.intellij.openapi.compiler.generic.GenericCompiler;
import com.intellij.openapi.compiler.options.ExcludedEntriesConfigurable;
import com.intellij.openapi.compiler.options.ExcludesConfiguration;
import com.intellij.openapi.fileChooser.FileChooserDescriptor;
@@ -159,13 +158,7 @@ public class ValidationConfigurable implements SearchableConfigurable, Configura
private List<Compiler> getValidators() {
final CompilerManager compilerManager = CompilerManager.getInstance(myProject);
final List<Compiler> validators = new SmartList<>(compilerManager.getCompilers(Validator.class));
for (GenericCompiler compiler : compilerManager.getCompilers(GenericCompiler.class)) {
if (compiler.getOrderPlace() == GenericCompiler.CompileOrderPlace.VALIDATING) {
validators.add(compiler);
}
}
return validators;
return new SmartList<>(compilerManager.getCompilers(Validator.class));
}
@Override
@@ -1,42 +0,0 @@
/*
* Copyright 2000-2010 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.compiler.generic;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
/**
* @deprecated this class is part of the old deprecated build infrastructure; plug into the external build process instead (see {@link org.jetbrains.jps.builders.BuildTarget})
*/
@Deprecated
@ApiStatus.ScheduledForRemoval(inVersion = "192.0")
public abstract class BuildTarget {
public static final BuildTarget DEFAULT = new BuildTarget() {
@NotNull
@Override
public String getId() {
return "<default>";
}
};
@NotNull
public abstract String getId();
@Override
public String toString() {
return "Build Target: " + getId();
}
}
@@ -1,44 +0,0 @@
/*
* Copyright 2000-2010 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.compiler.generic;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
/**
* @deprecated this class is part of the old deprecated build infrastructure; plug into the external build process instead (see {@link org.jetbrains.jps.builders.BuildTarget})
*/
@Deprecated
@ApiStatus.ScheduledForRemoval(inVersion = "192.0")
public abstract class CompileItem<Key, SourceState, OutputState> {
@NotNull
public abstract Key getKey();
public abstract boolean isSourceUpToDate(@NotNull SourceState state);
@NotNull
public abstract SourceState computeSourceState();
public abstract boolean isOutputUpToDate(@NotNull OutputState state);
@NotNull
public abstract OutputState computeOutputState();
public boolean isExcluded() {
return false;
}
}
@@ -1,48 +0,0 @@
/*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.compiler.generic;
import com.intellij.util.io.DataExternalizer;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
/**
* @deprecated this class is part of the old deprecated build infrastructure; plug into the external build process instead (see {@link org.jetbrains.jps.builders.BuildTarget})
*/
@Deprecated
@ApiStatus.ScheduledForRemoval(inVersion = "192.0")
public class DummyPersistentState {
public static final DummyPersistentState INSTANCE = new DummyPersistentState();
public static final DataExternalizer<DummyPersistentState> EXTERNALIZER = new DummyPersistentStateExternalizer();
private DummyPersistentState() {
}
private static class DummyPersistentStateExternalizer implements DataExternalizer<DummyPersistentState> {
@Override
public void save(@NotNull DataOutput out, DummyPersistentState value) throws IOException {
}
@Override
public DummyPersistentState read(@NotNull DataInput in) throws IOException {
return INSTANCE;
}
}
}
@@ -1,76 +0,0 @@
/*
* Copyright 2000-2010 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.compiler.generic;
import com.intellij.openapi.compiler.CompileContext;
import com.intellij.openapi.compiler.CompileScope;
import com.intellij.openapi.compiler.Compiler;
import com.intellij.util.io.DataExternalizer;
import com.intellij.util.io.EnumeratorStringDescriptor;
import com.intellij.util.io.KeyDescriptor;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
/**
* @deprecated this class is part of the old deprecated build infrastructure; plug into the external build process instead
* (see {@link org.jetbrains.jps.incremental.TargetBuilder})
*/
@Deprecated
@ApiStatus.ScheduledForRemoval(inVersion = "192.0")
public abstract class GenericCompiler<Key, SourceState, OutputState> implements Compiler {
protected static final KeyDescriptor<String> STRING_KEY_DESCRIPTOR = EnumeratorStringDescriptor.INSTANCE;
private final String myId;
private final int myVersion;
private final CompileOrderPlace myOrderPlace;
protected GenericCompiler(@NotNull String id, int version, @NotNull CompileOrderPlace orderPlace) {
myId = id;
myVersion = version;
myOrderPlace = orderPlace;
}
@NotNull
public abstract KeyDescriptor<Key> getItemKeyDescriptor();
@NotNull
public abstract DataExternalizer<SourceState> getSourceStateExternalizer();
@NotNull
public abstract DataExternalizer<OutputState> getOutputStateExternalizer();
@NotNull
public abstract GenericCompilerInstance<?, ? extends CompileItem<Key, SourceState, OutputState>, Key, SourceState, OutputState> createInstance(@NotNull CompileContext context);
public final String getId() {
return myId;
}
public final int getVersion() {
return myVersion;
}
@Override
public boolean validateConfiguration(CompileScope scope) {
return true;
}
public CompileOrderPlace getOrderPlace() {
return myOrderPlace;
}
public enum CompileOrderPlace {
CLASS_INSTRUMENTING, CLASS_POST_PROCESSING, PACKAGING, VALIDATING
}
}
@@ -1,52 +0,0 @@
/*
* Copyright 2000-2010 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.compiler.generic;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
/**
* @deprecated this class is part of the old deprecated build infrastructure; plug into the external build process instead
* (see {@link org.jetbrains.jps.incremental.TargetBuilder})
*/
@Deprecated
@ApiStatus.ScheduledForRemoval(inVersion = "192.0")
public class GenericCompilerCacheState<Key, SourceState, OutputState> {
private final Key myKey;
private final SourceState mySourceState;
private final OutputState myOutputState;
public GenericCompilerCacheState(@NotNull Key key, @NotNull SourceState sourceState, @NotNull OutputState outputState) {
myKey = key;
mySourceState = sourceState;
myOutputState = outputState;
}
@NotNull
public Key getKey() {
return myKey;
}
@NotNull
public SourceState getSourceState() {
return mySourceState;
}
@NotNull
public OutputState getOutputState() {
return myOutputState;
}
}
@@ -1,65 +0,0 @@
/*
* Copyright 2000-2010 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.compiler.generic;
import com.intellij.openapi.compiler.CompileContext;
import com.intellij.openapi.project.Project;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.util.List;
/**
* @deprecated this class is part of the old deprecated build infrastructure; plug into the external build process instead
* (see {@link org.jetbrains.jps.incremental.TargetBuilder})
*/
@Deprecated
@ApiStatus.ScheduledForRemoval(inVersion = "192.0")
public abstract class GenericCompilerInstance<T extends BuildTarget, Item extends CompileItem<Key, SourceState, OutputState>, Key, SourceState, OutputState> {
protected final CompileContext myContext;
protected GenericCompilerInstance(CompileContext context) {
myContext = context;
}
protected Project getProject() {
return myContext.getProject();
}
@NotNull
public abstract List<T> getAllTargets();
@NotNull
public abstract List<T> getSelectedTargets();
public abstract void processObsoleteTarget(@NotNull String targetId, @NotNull List<GenericCompilerCacheState<Key, SourceState, OutputState>> obsoleteItems);
@NotNull
public abstract List<Item> getItems(@NotNull T target);
public abstract void processItems(@NotNull T target, @NotNull List<? extends GenericCompilerProcessingItem<Item, SourceState, OutputState>> changedItems, @NotNull List<GenericCompilerCacheState<Key, SourceState, OutputState>> obsoleteItems,
@NotNull OutputConsumer<? super Item> consumer);
public interface OutputConsumer<Item extends CompileItem<?,?,?>> {
void addFileToRefresh(@NotNull File file);
void addDirectoryToRefresh(@NotNull File dir);
void addProcessedItem(@NotNull Item sourceItem);
}
}
@@ -1,52 +0,0 @@
/*
* Copyright 2000-2010 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.compiler.generic;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* @deprecated this class is part of the old deprecated build infrastructure; plug into the external build process instead (see {@link org.jetbrains.jps.builders.BuildTarget})
*/
@Deprecated
@ApiStatus.ScheduledForRemoval(inVersion = "192.0")
public class GenericCompilerProcessingItem<Item extends CompileItem<?, SourceState, OutputState>, SourceState, OutputState> {
private final Item myItem;
private final SourceState myCachedSourceState;
private final OutputState myCachedOutputState;
public GenericCompilerProcessingItem(@NotNull Item item, @Nullable SourceState cachedSourceState, @Nullable OutputState cachedOutputState) {
myItem = item;
myCachedSourceState = cachedSourceState;
myCachedOutputState = cachedOutputState;
}
@NotNull
public Item getItem() {
return myItem;
}
@Nullable
public SourceState getCachedSourceState() {
return myCachedSourceState;
}
@Nullable
public OutputState getCachedOutputState() {
return myCachedOutputState;
}
}
@@ -1,89 +0,0 @@
/*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.compiler.generic;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileManager;
import com.intellij.util.io.DataExternalizer;
import com.intellij.util.io.IOUtil;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/**
* @deprecated this class is part of the old deprecated build infrastructure; plug into the external build process instead (see {@link org.jetbrains.jps.builders.BuildTarget})
*/
@Deprecated
@ApiStatus.ScheduledForRemoval(inVersion = "192.0")
public class VirtualFileWithDependenciesState {
public static final DataExternalizer<VirtualFileWithDependenciesState> EXTERNALIZER = new VirtualFileWithDependenciesExternalizer();
private final long mySourceTimestamp;
private final Map<String, Long> myDependencies = new HashMap<>();
public VirtualFileWithDependenciesState(long sourceTimestamp) {
mySourceTimestamp = sourceTimestamp;
}
public void addDependency(@NotNull VirtualFile file) {
myDependencies.put(file.getUrl(), file.getTimeStamp());
}
public boolean isUpToDate(@NotNull VirtualFile sourceFile) {
if (sourceFile.getTimeStamp() != mySourceTimestamp) {
return false;
}
VirtualFileManager manager = VirtualFileManager.getInstance();
for (Map.Entry<String, Long> entry : myDependencies.entrySet()) {
final VirtualFile file = manager.findFileByUrl(entry.getKey());
if (file == null || file.getTimeStamp() != entry.getValue()) {
return false;
}
}
return true;
}
private static class VirtualFileWithDependenciesExternalizer implements DataExternalizer<VirtualFileWithDependenciesState> {
@Override
public void save(@NotNull DataOutput out, VirtualFileWithDependenciesState value) throws IOException {
out.writeLong(value.mySourceTimestamp);
final Map<String, Long> dependencies = value.myDependencies;
out.writeInt(dependencies.size());
for (Map.Entry<String, Long> entry : dependencies.entrySet()) {
IOUtil.writeUTF(out, entry.getKey());
out.writeLong(entry.getValue());
}
}
@Override
public VirtualFileWithDependenciesState read(@NotNull DataInput in) throws IOException {
final VirtualFileWithDependenciesState state = new VirtualFileWithDependenciesState(in.readLong());
int size = in.readInt();
while (size-- > 0) {
final String url = IOUtil.readUTF(in);
final long timestamp = in.readLong();
state.myDependencies.put(url, timestamp);
}
return state;
}
}
}
@@ -1,47 +0,0 @@
/*
* Copyright 2000-2016 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.task.impl;
import com.intellij.packaging.artifacts.Artifact;
import com.intellij.task.ArtifactBuildTask;
import com.intellij.task.ProjectModelBuildTask;
import org.jetbrains.annotations.NotNull;
/**
* @deprecated to be removed, use {@link ProjectModelBuildTask}
*
* @author Vladislav.Soroka
*/
@Deprecated
public class ArtifactBuildTaskImpl extends AbstractBuildTask implements ArtifactBuildTask {
private final Artifact myArtifact;
public ArtifactBuildTaskImpl(Artifact artifact, boolean isIncrementalBuild) {
super(isIncrementalBuild);
myArtifact = artifact;
}
@Override
public Artifact getArtifact() {
return myArtifact;
}
@NotNull
@Override
public String getPresentableName() {
return "Artifact '" + myArtifact.getName() + "' build task";
}
}
@@ -67,37 +67,4 @@ public abstract class DeploymentUtil {
@Nullable
public abstract String getConfigFileErrorMessage(ConfigFile configFile);
/**
* @deprecated use {@link com.intellij.openapi.util.io.FileUtil#getRelativePath}
*/
@Deprecated
@Nullable
public static String getRelativePath(@NotNull String basePath, @NotNull final String filePath) {
if (basePath.equals(filePath)) return "";
if (!basePath.endsWith(File.separator)) basePath += File.separatorChar;
int len = 0;
int lastSeparatorIndex = 0; // need this for cases like this: base="/temp/abcde/baseDir" and file="/temp/ab"
while (len < filePath.length() && len < basePath.length() && filePath.charAt(len) == basePath.charAt(len)) {
if (basePath.charAt(len) == File.separatorChar) {
lastSeparatorIndex = len;
}
len++;
}
if (len == 0) {
return null;
}
final StringBuilder relativePath = new StringBuilder();
for (int i=len; i < basePath.length(); i++) {
if (basePath.charAt(i) == File.separatorChar) {
relativePath.append("..");
relativePath.append(File.separatorChar);
}
}
relativePath.append(filePath.substring(lastSeparatorIndex + 1));
return relativePath.toString();
}
}
@@ -1,26 +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.packaging.elements;
import org.jetbrains.annotations.ApiStatus;
/**
* @deprecated this interface was used in the old build infrastructure, it doesn't make sense anymore
*/
@ApiStatus.ScheduledForRemoval(inVersion = "192.0")
@Deprecated
public interface ArtifactIncrementalCompilerContext {
}
@@ -106,7 +106,7 @@ LIne read: #[wrote C:\temp\rmiTest\classes\mycompany\TTT.class]#
@Override
protected void doExecute(final String line, final String dta, final OutputParser.Callback callback) {
assertTrue("Expected: #" + myExpected + "#, but was: #" + dta + "#", myExpected.equals(dta));
assertEquals("Expected: #" + myExpected + "#, but was: #" + dta + "#", myExpected, dta);
}
}
}
@@ -46,7 +46,7 @@ public class ModuleCompileScopeTest extends BaseCompilerTestCase {
public void testForceCompileUpToDateFileAndDoNotCompileResources() {
VirtualFile a = createFile("src/A.java", "class A{}");
VirtualFile res = createFile("src/res.properties", "aaa=bbb");
createFile("src/res.properties", "aaa=bbb");
Module module = addModule("a", a.getParent());
make(module);
assertOutput(module, fs().file("A.class").file("res.properties"));
@@ -2,7 +2,7 @@ package com.intellij.compiler;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.testFramework.PsiTestUtil;
@@ -24,7 +24,7 @@ public class RecompileOnConfigurationChangeTest extends BaseCompilerTestCase {
File oldOutput = getOutputDir(m);
File newOutput = createTempDir("new-output");
PsiTestUtil.setCompilerOutputPath(m, VfsUtil.pathToUrl(FileUtil.toSystemIndependentName(newOutput.getAbsolutePath())), false);
PsiTestUtil.setCompilerOutputPath(m, VfsUtilCore.pathToUrl(FileUtil.toSystemIndependentName(newOutput.getAbsolutePath())), false);
make(m);
assertOutput(m, fs().file("A.class"));
File[] files = oldOutput.listFiles();
@@ -11,7 +11,6 @@ import com.intellij.debugger.DebuggerBundle;
import com.intellij.debugger.SourcePosition;
import com.intellij.debugger.engine.*;
import com.intellij.debugger.engine.evaluation.*;
import com.intellij.debugger.engine.evaluation.expression.EvaluatorBuilder;
import com.intellij.debugger.engine.evaluation.expression.ExpressionEvaluator;
import com.intellij.debugger.engine.evaluation.expression.UnBoxingEvaluator;
import com.intellij.debugger.engine.requests.RequestManagerImpl;
@@ -19,7 +18,6 @@ import com.intellij.debugger.jdi.JvmtiError;
import com.intellij.debugger.jdi.VirtualMachineProxyImpl;
import com.intellij.debugger.requests.Requestor;
import com.intellij.debugger.ui.breakpoints.Breakpoint;
import com.intellij.debugger.ui.tree.DebuggerTreeNode;
import com.intellij.execution.filters.ExceptionFilters;
import com.intellij.execution.filters.LineNumbersMapping;
import com.intellij.execution.filters.TextConsoleBuilder;
@@ -27,13 +25,11 @@ import com.intellij.execution.filters.TextConsoleBuilderFactory;
import com.intellij.execution.ui.ConsoleView;
import com.intellij.execution.ui.RunnerLayoutUi;
import com.intellij.execution.ui.layout.impl.RunnerContentUi;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.actionSystem.DefaultActionGroup;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ReadAction;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.StdFileTypes;
import com.intellij.openapi.project.Project;
@@ -175,40 +171,6 @@ public abstract class DebuggerUtilsEx extends DebuggerUtils {
return val1.equals(val2);
}
public static String getValueOrErrorAsString(final EvaluationContext evaluationContext, Value value) {
try {
return getValueAsString(evaluationContext, value);
}
catch (EvaluateException e) {
return e.getMessage();
}
}
public static boolean isCharOrInteger(Value value) {
return value instanceof CharValue || isInteger(value);
}
private static Set<String> myCharOrIntegers;
public static boolean isCharOrIntegerArray(Value value) {
if (value == null) return false;
if (myCharOrIntegers == null) {
myCharOrIntegers = new HashSet<>();
myCharOrIntegers.add("C");
myCharOrIntegers.add("B");
myCharOrIntegers.add("S");
myCharOrIntegers.add("I");
myCharOrIntegers.add("J");
}
String signature = value.type().signature();
int i;
for (i = 0; signature.charAt(i) == '['; i++) ;
if (i == 0) return false;
signature = signature.substring(i);
return myCharOrIntegers.contains(signature);
}
public static ClassFilter create(Element element) throws InvalidDataException {
ClassFilter filter = new ClassFilter();
DefaultJDOMExternalizer.readExternal(filter, element);
@@ -263,7 +225,7 @@ public abstract class DebuggerUtilsEx extends DebuggerUtils {
return filters;
}
public static void writeFilters(Element parentNode, @NonNls String tagName, ClassFilter[] filters) throws WriteExternalException {
public static void writeFilters(@NotNull Element parentNode, @NonNls String tagName, ClassFilter[] filters) throws WriteExternalException {
for (ClassFilter filter : filters) {
Element element = new Element(tagName);
parentNode.addContent(element);
@@ -370,34 +332,6 @@ public abstract class DebuggerUtilsEx extends DebuggerUtils {
return Collections.emptyList();
}
public static TextWithImports getEditorText(final Editor editor) {
if (editor == null) {
return null;
}
final Project project = editor.getProject();
if (project == null) return null;
String defaultExpression = editor.getSelectionModel().getSelectedText();
if (defaultExpression == null) {
int offset = editor.getCaretModel().getOffset();
PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
if (psiFile != null) {
PsiElement elementAtCursor = psiFile.findElementAt(offset);
if (elementAtCursor != null) {
final EditorTextProvider textProvider = EditorTextProvider.EP.forLanguage(elementAtCursor.getLanguage());
if (textProvider != null) {
final TextWithImports editorText = textProvider.getEditorText(elementAtCursor);
if (editorText != null) return editorText;
}
}
}
}
else {
return new TextWithImportsImpl(CodeFragmentKind.EXPRESSION, defaultExpression);
}
return null;
}
private static int myThreadDumpsCount = 0;
public static void addThreadDump(Project project, List<ThreadState> threads, RunnerLayoutUi ui, GlobalSearchScope searchScope) {
@@ -441,10 +375,6 @@ public abstract class DebuggerUtilsEx extends DebuggerUtils {
return context.computeAndKeep(() -> context.getDebugProcess().newInstance(arrayType, dimension));
}
public abstract DebuggerTreeNode getSelectedNode(DataContext context);
public abstract EvaluatorBuilder getEvaluatorBuilder();
@NotNull
public static CodeFragmentFactory getCodeFragmentFactory(@Nullable PsiElement context, @Nullable FileType fileType) {
DefaultCodeFragmentFactory defaultFactory = DefaultCodeFragmentFactory.getInstance();
@@ -1058,19 +988,6 @@ public abstract class DebuggerUtilsEx extends DebuggerUtils {
return Comparing.equal(getContainingMethod(elem), method);
}
public static boolean inTheSameMethod(@NotNull SourcePosition pos1, @NotNull SourcePosition pos2) {
ApplicationManager.getApplication().assertReadAccessAllowed();
PsiElement elem1 = pos1.getElementAt();
PsiElement elem2 = pos2.getElementAt();
if (elem1 == null) return elem2 == null;
if (elem2 != null) {
PsiElement expectedMethod = getContainingMethod(elem1);
PsiElement currentMethod = getContainingMethod(elem2);
return Comparing.equal(expectedMethod, currentMethod);
}
return false;
}
public static boolean methodMatches(@NotNull PsiMethod psiMethod,
String className,
String name,
@@ -10,11 +10,8 @@ import com.intellij.debugger.engine.evaluation.CodeFragmentKind;
import com.intellij.debugger.engine.evaluation.EvaluateException;
import com.intellij.debugger.engine.evaluation.TextWithImports;
import com.intellij.debugger.engine.evaluation.TextWithImportsImpl;
import com.intellij.debugger.engine.evaluation.expression.EvaluatorBuilder;
import com.intellij.debugger.engine.evaluation.expression.EvaluatorBuilderImpl;
import com.intellij.debugger.impl.attach.PidRemoteConnection;
import com.intellij.debugger.ui.impl.watch.DebuggerTreeNodeExpression;
import com.intellij.debugger.ui.tree.DebuggerTreeNode;
import com.intellij.debugger.ui.tree.render.BatchEvaluator;
import com.intellij.execution.ExecutionException;
import com.intellij.execution.configurations.RemoteConnection;
@@ -60,16 +57,6 @@ public class DebuggerUtilsImpl extends DebuggerUtilsEx{
return DebuggerTreeNodeExpression.substituteThis(expressionWithThis, howToEvaluateThis, howToEvaluateThisValue);
}
@Override
public EvaluatorBuilder getEvaluatorBuilder() {
return EvaluatorBuilderImpl.getInstance();
}
@Override
public DebuggerTreeNode getSelectedNode(DataContext context) {
return DebuggerAction.getSelectedNode(context);
}
@Override
public DebuggerContextImpl getDebuggerContext(DataContext context) {
return DebuggerAction.getDebuggerContext(context);
@@ -1,6 +1,7 @@
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.debugger.settings;
import com.intellij.configurationStore.XmlSerializer;
import com.intellij.debugger.impl.DebuggerUtilsEx;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.ApplicationManager;
@@ -14,8 +15,6 @@ import com.intellij.openapi.util.text.StringUtil;
import com.intellij.ui.classFilter.ClassFilter;
import com.intellij.util.EventDispatcher;
import com.intellij.util.containers.hash.LinkedHashMap;
import com.intellij.util.xmlb.SkipDefaultsSerializationFilter;
import com.intellij.util.xmlb.XmlSerializer;
import com.intellij.util.xmlb.annotations.OptionTag;
import com.intellij.util.xmlb.annotations.Transient;
import com.intellij.util.xmlb.annotations.XCollection;
@@ -122,7 +121,11 @@ public class DebuggerSettings implements Cloneable, PersistentStateComponent<Ele
@Nullable
@Override
public Element getState() {
Element state = XmlSerializer.serialize(this, new SkipDefaultsSerializationFilter());
Element state = XmlSerializer.serialize(this);
if (state == null) {
state = new Element("state");
}
if (!Arrays.equals(DEFAULT_STEPPING_FILTERS, mySteppingFilters)) {
DebuggerUtilsEx.writeFilters(state, "filter", mySteppingFilters);
}
@@ -138,7 +141,7 @@ public class DebuggerSettings implements Cloneable, PersistentStateComponent<Ele
@Override
public void loadState(@NotNull Element state) {
XmlSerializer.deserializeInto(this, state);
XmlSerializer.deserializeInto(state, this);
List<Element> steppingFiltersElement = state.getChildren("filter");
if (steppingFiltersElement.isEmpty()) {
@@ -1,6 +1,7 @@
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.execution.jar;
import com.intellij.configurationStore.XmlSerializer;
import com.intellij.diagnostic.logging.LogConfigurationPanel;
import com.intellij.execution.*;
import com.intellij.execution.configuration.EnvironmentVariablesComponent;
@@ -12,14 +13,10 @@ import com.intellij.openapi.module.Module;
import com.intellij.openapi.options.SettingsEditor;
import com.intellij.openapi.options.SettingsEditorGroup;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.WriteExternalException;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.GlobalSearchScopes;
import com.intellij.util.xmlb.SkipDefaultValuesSerializationFilters;
import com.intellij.util.xmlb.XmlSerializer;
import com.intellij.util.xmlb.XmlSerializerUtil;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;
@@ -34,7 +31,6 @@ import java.util.Map;
* @author nik
*/
public class JarApplicationConfiguration extends LocatableConfigurationBase implements CommonJavaRunConfigurationParameters, SearchScopeProvidingRunProfile, InputRedirectAware {
private static final SkipDefaultValuesSerializationFilters SERIALIZATION_FILTERS = new SkipDefaultValuesSerializationFilters();
private JarApplicationConfigurationBean myBean = new JarApplicationConfigurationBean();
private Map<String, String> myEnvs = new LinkedHashMap<>();
private JavaRunConfigurationModule myConfigurationModule;
@@ -62,10 +58,10 @@ public class JarApplicationConfiguration extends LocatableConfigurationBase impl
}
@Override
public void readExternal(@NotNull Element element) throws InvalidDataException {
public void readExternal(@NotNull Element element) {
super.readExternal(element);
JavaRunConfigurationExtensionManager.getInstance().readExternal(this, element);
XmlSerializer.deserializeInto(myBean, element);
XmlSerializer.deserializeInto(element, myBean);
EnvironmentVariablesComponent.readExternal(element, getEnvs());
myConfigurationModule.readExternal(element);
myInputRedirectOptions.readExternal(element);
@@ -91,10 +87,10 @@ public class JarApplicationConfiguration extends LocatableConfigurationBase impl
}
@Override
public void writeExternal(@NotNull Element element) throws WriteExternalException {
public void writeExternal(@NotNull Element element) {
super.writeExternal(element);
JavaRunConfigurationExtensionManager.getInstance().writeExternal(this, element);
XmlSerializer.serializeInto(myBean, element, SERIALIZATION_FILTERS);
XmlSerializer.serializeObjectInto(myBean, element);
EnvironmentVariablesComponent.writeExternal(element, getEnvs());
if (myConfigurationModule.getModule() != null) {
myConfigurationModule.writeExternal(element);
@@ -91,41 +91,32 @@ public class JarRepositoryManager {
return null;
}
final String coord = dialog.getCoordinateText();
final boolean attachSources = dialog.getAttachSources();
final boolean attachJavaDoc = dialog.getAttachJavaDoc();
final boolean attachAnnotations = dialog.getAttachExternalAnnotations();
boolean includeTransitiveDependencies = dialog.getIncludeTransitiveDependencies();
final String copyTo = dialog.getDirectoryPath();
JpsMavenRepositoryLibraryDescriptor libraryDescriptor = dialog.getSelectedLibraryDescriptor();
final EnumSet<ArtifactKind> artifactKinds = kindsOf(attachSources, attachJavaDoc, dialog.getPackaging());
final EnumSet<ArtifactKind> artifactKinds = ArtifactKind.kindsOf(attachSources, attachJavaDoc, libraryDescriptor.getPackaging());
if (attachAnnotations) {
artifactKinds.add(ArtifactKind.ANNOTATIONS);
}
final NewLibraryConfiguration config = resolveAndDownload(
project, coord, artifactKinds, includeTransitiveDependencies, copyTo, RemoteRepositoriesConfiguration.getInstance(project).getRepositories()
project, artifactKinds, copyTo, RemoteRepositoriesConfiguration.getInstance(project).getRepositories(), libraryDescriptor
);
if (config == null) {
Messages.showErrorDialog(parentComponent, "No files were downloaded for " + coord, CommonBundle.getErrorTitle());
Messages.showErrorDialog(parentComponent, "No files were downloaded for " + libraryDescriptor.getMavenId(), CommonBundle.getErrorTitle());
}
return config;
}
private static NewLibraryConfiguration resolveAndDownload(Project project,
String coord,
EnumSet<ArtifactKind> kinds,
boolean includeTransitiveDependencies,
String copyTo,
Collection<RemoteRepositoryDescription> repositories) {
String packaging = JpsMavenRepositoryLibraryDescriptor.DEFAULT_PACKAGING;
for (ArtifactKind kind : kinds) {
if (kind.getClassifier().isEmpty()) {
packaging = kind.getExtension(); // correct packaging according to the requested artifact kind
break;
}
}
RepositoryLibraryProperties props = new RepositoryLibraryProperties(coord, packaging, includeTransitiveDependencies);
Collection<RemoteRepositoryDescription> repositories,
JpsMavenRepositoryLibraryDescriptor libraryDescriptor) {
RepositoryLibraryProperties props = new RepositoryLibraryProperties(libraryDescriptor);
final JpsMavenRepositoryLibraryDescriptor libDescriptor = props.getRepositoryLibraryDescriptor();
final Collection<OrderRoot> roots = ContainerUtil.newArrayList();
if (libDescriptor.getMavenId() != null) {
@@ -141,26 +132,15 @@ public class JarRepositoryManager {
@Nullable
public static NewLibraryConfiguration resolveAndDownload(@NotNull Project project,
String coord,
boolean attachSources,
boolean attachJavaDoc,
boolean includeTransitiveDependencies,
String copyTo,
Collection<RemoteRepositoryDescription> repositories) {
return resolveAndDownload(project, coord, attachSources, attachJavaDoc, JpsMavenRepositoryLibraryDescriptor.DEFAULT_PACKAGING,
includeTransitiveDependencies, copyTo, repositories);
}
@Nullable
public static NewLibraryConfiguration resolveAndDownload(@NotNull Project project,
String coord,
boolean attachSources,
boolean attachJavaDoc,
String packaging,
boolean includeTransitiveDependencies,
String copyTo,
Collection<RemoteRepositoryDescription> repositories) {
return resolveAndDownload(project, coord, kindsOf(attachSources, attachJavaDoc, packaging), includeTransitiveDependencies, copyTo, repositories);
String coord,
boolean attachSources,
boolean attachJavaDoc,
boolean includeTransitiveDependencies,
String copyTo,
Collection<RemoteRepositoryDescription> repositories) {
JpsMavenRepositoryLibraryDescriptor libraryDescriptor = new JpsMavenRepositoryLibraryDescriptor(coord, includeTransitiveDependencies, Collections.emptyList());
return resolveAndDownload(project, ArtifactKind.kindsOf(attachSources, attachJavaDoc, libraryDescriptor.getPackaging()),
copyTo, repositories, libraryDescriptor);
}
@NotNull
@@ -216,7 +196,7 @@ public class JarRepositoryManager {
@Nullable Collection<RemoteRepositoryDescription> repositories) {
final JpsMavenRepositoryLibraryDescriptor libDescriptor = libraryProps.getRepositoryLibraryDescriptor();
if (libDescriptor.getMavenId() != null) {
EnumSet<ArtifactKind> kinds = kindsOf(loadSources, loadJavadoc, libraryProps.getPackaging());
EnumSet<ArtifactKind> kinds = ArtifactKind.kindsOf(loadSources, loadJavadoc, libraryProps.getPackaging());
return loadDependenciesModal(project, libDescriptor, kinds, repositories, copyTo);
}
return Collections.emptyList();
@@ -240,7 +220,7 @@ public class JarRepositoryManager {
boolean loadJavadoc,
@Nullable List<RemoteRepositoryDescription> repos,
@Nullable String copyTo) {
EnumSet<ArtifactKind> kinds = kindsOf(loadSources, loadJavadoc, libraryProps.getPackaging());
EnumSet<ArtifactKind> kinds = ArtifactKind.kindsOf(loadSources, loadJavadoc, libraryProps.getPackaging());
return loadDependenciesAsync(
project,
libraryProps.getRepositoryLibraryDescriptor(),
@@ -276,22 +256,6 @@ public class JarRepositoryManager {
return repositories;
}
public static EnumSet<ArtifactKind> kindsOf(boolean loadSources, boolean loadJavadoc, String... artifactPackaging) {
final EnumSet<ArtifactKind> kinds = ArtifactKind.kindsOf(loadSources, loadJavadoc);
if (artifactPackaging.length == 0 || artifactPackaging.length == 1 && artifactPackaging[0] == null) {
kinds.add(ArtifactKind.ARTIFACT);
}
else {
for (String packaging : artifactPackaging) {
final ArtifactKind artifact = ArtifactKind.find(ArtifactKind.ARTIFACT.getClassifier(), packaging);
if (artifact != null) {
kinds.add(artifact);
}
}
}
return kinds;
}
@NotNull
public static Promise<Collection<String>> getAvailableVersions(@NotNull Project project, @NotNull RepositoryLibraryDescription libraryDescription) {
List<RemoteRepositoryDescription> repos = RemoteRepositoriesConfiguration.getInstance(project).getRepositories();
@@ -392,22 +392,28 @@ public class RepositoryAttachDialog extends DialogWrapper {
return text.split(":").length == 3;
}
public String getCoordinateText() {
private String getCoordinateText() {
String text = getFullCoordinateText();
List<String> parts = StringUtil.split(text, ":");
return parts.size() == 4 ? parts.get(0) + ":" + parts.get(1) + ":" + parts.get(3) : text;
}
@Nullable
public String getPackaging() {
@NotNull
private String getPackaging() {
List<String> parts = StringUtil.split(getFullCoordinateText(), ":");
return parts.size() == 4 ? parts.get(2) : null;
return parts.size() == 4 ? parts.get(2) : JpsMavenRepositoryLibraryDescriptor.DEFAULT_PACKAGING;
}
private String getFullCoordinateText() {
return ((JTextField)myCombobox.getEditor().getEditorComponent()).getText();
}
@NotNull
public JpsMavenRepositoryLibraryDescriptor getSelectedLibraryDescriptor() {
return new JpsMavenRepositoryLibraryDescriptor(getCoordinateText(), getPackaging(),
getIncludeTransitiveDependencies(), Collections.emptyList());
}
private void createUIComponents() {
myProgressIcon = new AsyncProcessIcon("Progress");
}
@@ -50,9 +50,9 @@ public class RepositoryLibraryWithDescriptionEditor
//String oldVersion = properties.getVersion();
boolean wasGeneratedName =
RepositoryLibraryType.getInstance().getDescription(properties).equals(myEditorComponent.getLibraryEditor().getName());
final EnumSet<ArtifactKind> artifactKinds = JarRepositoryManager.kindsOf(libraryHasSources(myEditorComponent.getLibraryEditor()),
libraryHasJavaDocs(myEditorComponent.getLibraryEditor()),
properties.getPackaging());
final EnumSet<ArtifactKind> artifactKinds = ArtifactKind.kindsOf(libraryHasSources(myEditorComponent.getLibraryEditor()),
libraryHasJavaDocs(myEditorComponent.getLibraryEditor()),
properties.getPackaging());
if (libraryHasExternalAnnotations(myEditorComponent.getLibraryEditor())) {
artifactKinds.add(ArtifactKind.ANNOTATIONS);
}
@@ -79,7 +79,7 @@ public class IdeaProjectModelModifier extends JavaProjectModelModifier {
return Promises.rejectedPromise();
}
RepositoryLibraryProperties libraryProperties = new RepositoryLibraryProperties(dialog.getCoordinateText(), true);
RepositoryLibraryProperties libraryProperties = new RepositoryLibraryProperties(dialog.getSelectedLibraryDescriptor());
Collection<OrderRoot> roots =
JarRepositoryManager.loadDependenciesModal(myProject, libraryProperties, dialog.getAttachSources(), dialog.getAttachJavaDoc(), dialog.getDirectoryPath(), null);
if (roots.isEmpty()) {
@@ -139,8 +139,7 @@ abstract class ConvertToRepositoryLibraryActionBase(protected val context: Struc
return null
}
return JpsMavenRepositoryLibraryDescriptor(dialog.coordinateText, dialog.includeTransitiveDependencies,
emptyList<String>())
return dialog.selectedLibraryDescriptor
}
private fun replaceByLibrary(library: Library, configuration: NewLibraryConfiguration) {
@@ -16,7 +16,6 @@
package org.jetbrains.idea.maven.utils.library.propertiesEditor;
import com.google.common.base.Strings;
import com.intellij.jarRepository.JarRepositoryManager;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.idea.maven.aether.ArtifactKind;
@@ -37,7 +36,7 @@ public class RepositoryLibraryPropertiesModel {
public RepositoryLibraryPropertiesModel(String version, boolean downloadSources, boolean downloadJavaDocs,
boolean includeTransitiveDependencies, List<String> excludedDependencies) {
this(version, JarRepositoryManager.kindsOf(downloadSources, downloadJavaDocs), includeTransitiveDependencies, excludedDependencies);
this(version, ArtifactKind.kindsOf(downloadSources, downloadJavaDocs), includeTransitiveDependencies, excludedDependencies);
}
public RepositoryLibraryPropertiesModel(String version, EnumSet<ArtifactKind> artifactKinds,
@@ -7,6 +7,7 @@ import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer;
import com.intellij.codeInsight.daemon.QuickFixBundle;
import com.intellij.codeInsight.intention.IntentionAction;
import com.intellij.codeInspection.reference.*;
import com.intellij.configurationStore.XmlSerializer;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ReadAction;
import com.intellij.openapi.components.PersistentStateComponent;
@@ -24,8 +25,6 @@ import com.intellij.psi.*;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.ui.UIUtil;
import com.intellij.util.xmlb.SkipDefaultsSerializationFilter;
import com.intellij.util.xmlb.XmlSerializer;
import com.intellij.util.xmlb.annotations.Attribute;
import com.intellij.util.xmlb.annotations.Tag;
import org.jdom.Element;
@@ -133,7 +132,7 @@ public abstract class EntryPointsManagerBase extends EntryPointsManager implemen
getPatterns().clear();
for (Element pattern : element.getChildren("pattern")) {
final ClassPattern classPattern = new ClassPattern();
XmlSerializer.deserializeInto(classPattern, pattern);
XmlSerializer.deserializeInto(pattern, classPattern);
getPatterns().add(classPattern);
}
@@ -154,9 +153,8 @@ public abstract class EntryPointsManagerBase extends EntryPointsManager implemen
Element element = new Element("state");
writeExternal(element, myPersistentEntryPoints, ADDITIONAL_ANNOTATIONS);
if (!getPatterns().isEmpty()) {
SkipDefaultsSerializationFilter filter = new SkipDefaultsSerializationFilter();
for (ClassPattern pattern : getPatterns()) {
element.addContent(XmlSerializer.serialize(pattern, filter));
element.addContent(XmlSerializer.serialize(pattern));
}
}
@@ -1,4 +1,4 @@
// Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.psi.util;
import com.intellij.codeInsight.AnnotationUtil;
@@ -16,6 +16,7 @@ import com.intellij.psi.tree.IElementType;
import com.intellij.util.ArrayUtil;
import com.intellij.util.Function;
import com.intellij.util.IncorrectOperationException;
import com.siyeh.ig.psiutils.ExpectedTypeUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -767,8 +768,9 @@ public class RedundantCastUtil {
if (castType instanceof PsiPrimitiveType) {
if (opType instanceof PsiPrimitiveType) {
PsiElement parent = PsiUtil.skipParenthesizedExprUp(typeCast.getParent());
if (parent instanceof PsiReturnStatement || parent instanceof PsiExpressionList || parent instanceof PsiVariable ||
parent instanceof PsiAssignmentExpression) {
if ((parent instanceof PsiReturnStatement || parent instanceof PsiExpressionList || parent instanceof PsiVariable ||
parent instanceof PsiAssignmentExpression) &&
castType.equals(ExpectedTypeUtils.findExpectedType(typeCast, false))) {
return !TypeConversionUtil.isSafeConversion(castType, opType); // let's suppose that casts losing precision are important
} else {
return !castType.equals(opType); // cast might be necessary (e.g. ((double)1)/5)
@@ -167,9 +167,10 @@ public class ConvertSwitchToIfIntention implements IntentionAction {
parent = (PsiCodeBlock)(switchStatement.getParent());
}
}
JavaCodeStyleManager javaCodeStyleManager = JavaCodeStyleManager.getInstance(project);
if (hadSideEffects) {
final PsiStatement declarationStatement = factory.createStatementFromText(declarationString, switchStatement);
parent.addBefore(declarationStatement, switchStatement);
javaCodeStyleManager.shortenClassReferences(parent.addBefore(declarationStatement, switchStatement));
}
final PsiStatement ifStatement = factory.createStatementFromText(ifStatementText, switchStatement);
if (unwrapDefault) {
@@ -189,12 +190,11 @@ public class ConvertSwitchToIfIntention implements IntentionAction {
addedIf.delete();
}
else {
JavaCodeStyleManager.getInstance(project).shortenClassReferences(addedIf);
javaCodeStyleManager.shortenClassReferences(addedIf);
}
}
else {
JavaCodeStyleManager.getInstance(project)
.shortenClassReferences(commentTracker.replaceAndRestoreComments(switchStatement, ifStatement));
javaCodeStyleManager.shortenClassReferences(commentTracker.replaceAndRestoreComments(switchStatement, ifStatement));
}
}
@@ -24,6 +24,7 @@ import org.jetbrains.annotations.Nullable;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import static com.intellij.util.ObjectUtils.tryCast;
@@ -59,7 +60,12 @@ public class ConvertToSingleReturnAction extends PsiElementBaseIntentionAction {
PsiCodeBlock copy = (PsiCodeBlock)block.copy();
indicator.checkCanceled();
indicator.setFraction(0.3);
convertReturns(project, copy, returnType, marker, returns.size(), indicator);
PsiLocalVariable variable = convertReturns(project, copy, returnType, marker, returns.size(), indicator);
if (variable != null) {
PsiJavaToken end = Objects.requireNonNull(copy.getRBrace());
copy.addBefore(JavaPsiFacade.getElementFactory(project).createStatementFromText("return " + variable.getName() + ";", copy), end);
}
return copy;
}
@@ -122,8 +122,6 @@ class ExitContext {
// Keep final when possible to respect code style setting "generate local variables as 'final'"
requireNonNull(var.getModifierList()).setModifierProperty(PsiModifier.FINAL, false);
}
PsiJavaToken end = requireNonNull(myBlock.getRBrace());
myBlock.addBefore(myFactory.createStatementFromText("return " + myReturnVariable + ";", myBlock), end);
return var;
}
return null;
@@ -21,6 +21,7 @@ import com.intellij.codeInsight.template.PsiElementResult;
import com.intellij.codeInsight.template.PsiTypeResult;
import com.intellij.codeInsight.template.Result;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.scope.util.PsiScopesUtil;
@@ -73,7 +74,11 @@ public class MacroUtil {
String text = result.toString();
if (text == null) return null;
PsiManager manager = PsiManager.getInstance(project);
PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(context.getEditor().getDocument());
PsiDocumentManager psiDocumentManager = PsiDocumentManager.getInstance(project);
Editor editor = context.getEditor();
if(editor == null) return null;
psiDocumentManager.commitDocument(editor.getDocument());
PsiFile file = psiDocumentManager.getPsiFile(editor.getDocument());
//-1: Hack to deal with resolve algorithm
PsiElement place = file != null ? file.findElementAt(context.getStartOffset()) : null;
if (place != null) {
@@ -19,6 +19,7 @@ import com.intellij.codeInsight.CodeInsightBundle;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupElementBuilder;
import com.intellij.codeInsight.template.*;
import com.intellij.openapi.editor.Editor;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
@@ -75,11 +76,16 @@ public class SuggestVariableNameMacro extends Macro {
private static String[] getNames (final ExpressionContext context) {
String[] names = ExpressionUtil.getNames(context);
if (names == null || names.length == 0) return names;
PsiFile file = PsiDocumentManager.getInstance(context.getProject()).getPsiFile(context.getEditor().getDocument());
PsiElement e = file.findElementAt(context.getStartOffset());
PsiDocumentManager documentManager = PsiDocumentManager.getInstance(context.getProject());
Editor editor = context.getEditor();
if(editor == null) return null;
documentManager.commitDocument(editor.getDocument());
PsiFile file = documentManager.getPsiFile(editor.getDocument());
PsiElement e = file != null ? file.findElementAt(context.getStartOffset()) : null;
PsiVariable[] vars = MacroUtil.getVariablesVisibleAt(e, "");
LinkedList<String> namesList = new LinkedList<>(Arrays.asList(names));
for (PsiVariable var : vars) {
//noinspection ConstantConditions
if (e.equals(var.getNameIdentifier())) continue;
namesList.remove(var.getName());
}
@@ -90,6 +96,7 @@ public class SuggestVariableNameMacro extends Macro {
for (int j = 1; ; j++) {
String name1 = name + j;
for (PsiVariable var : vars) {
//noinspection ConstantConditions
if (name1.equals(var.getName()) && !var.getNameIdentifier().equals(e)) continue index;
}
return new String[]{name1};
@@ -1,28 +1,11 @@
/*
* Copyright 2000-2016 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.
*/
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInspection.deadCode;
import com.intellij.codeInspection.reference.EntryPoint;
import com.intellij.codeInspection.reference.RefElement;
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.WriteExternalException;
import com.intellij.configurationStore.XmlSerializer;
import com.intellij.psi.PsiDocCommentOwner;
import com.intellij.psi.PsiElement;
import com.intellij.util.xmlb.SkipDefaultValuesSerializationFilters;
import com.intellij.util.xmlb.XmlSerializer;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;
@@ -30,13 +13,13 @@ public class DeprecatedEntryPoint extends EntryPoint {
public boolean DEPRECATED_ENTRY_POINT = true;
@Override
public void readExternal(Element element) throws InvalidDataException {
XmlSerializer.deserializeInto(this, element);
public void readExternal(Element element) {
XmlSerializer.deserializeInto(element, this);
}
@Override
public void writeExternal(Element element) throws WriteExternalException {
XmlSerializer.serializeInto(this, element, new SkipDefaultValuesSerializationFilters());
public void writeExternal(Element element) {
XmlSerializer.serializeObjectInto(this, element);
}
@NotNull
@@ -83,9 +83,11 @@ abstract class SourceOperation extends Operation {
return fn == null ? null : new IterateSource(args[0], fn);
}
if (name.equals("stream") && args.length == 0 &&
InheritanceUtil.isInheritor(aClass, CommonClassNames.JAVA_UTIL_COLLECTION) &&
ExpressionUtils.getEffectiveQualifier(call.getMethodExpression()) != null) {
return new ForEachSource(call.getMethodExpression().getQualifierExpression());
InheritanceUtil.isInheritor(aClass, CommonClassNames.JAVA_UTIL_COLLECTION)) {
PsiExpression qualifier = ExpressionUtils.getEffectiveQualifier(call.getMethodExpression());
if (qualifier != null) {
return new ForEachSource(qualifier);
}
}
if (name.equals("stream") && args.length == 1 &&
CommonClassNames.JAVA_UTIL_ARRAYS.equals(className)) {
@@ -110,22 +112,20 @@ abstract class SourceOperation extends Operation {
static class ForEachSource extends SourceOperation {
private final boolean myEntrySet;
private @Nullable PsiExpression myQualifier;
private @NotNull PsiExpression myQualifier;
ForEachSource(@Nullable PsiExpression qualifier) {
ForEachSource(@NotNull PsiExpression qualifier) {
this(qualifier, false);
}
ForEachSource(@Nullable PsiExpression qualifier, boolean entrySet) {
ForEachSource(@NotNull PsiExpression qualifier, boolean entrySet) {
myQualifier = qualifier;
myEntrySet = entrySet;
}
@Override
void rename(String oldName, String newName, StreamToLoopReplacementContext context) {
if(myQualifier != null) {
myQualifier = replaceVarReference(myQualifier, oldName, newName, context);
}
myQualifier = replaceVarReference(myQualifier, oldName, newName, context);
}
@Override
@@ -148,10 +148,7 @@ abstract class SourceOperation extends Operation {
@Override
public String wrap(StreamVariable outVar, String code, StreamToLoopReplacementContext context) {
PsiExpression iterationParameter = myQualifier == null ? ExpressionUtils
.getEffectiveQualifier(((PsiMethodCallExpression)context.createExpression("stream()")).getMethodExpression()) : myQualifier;
assert iterationParameter != null; // Checked at construction site that effective qualifier is available
String iterationParameterText = iterationParameter.getText() + (myEntrySet ? ".entrySet()" : "");
String iterationParameterText = myQualifier.getText() + (myEntrySet ? ".entrySet()" : "");
return context.getLoopLabel() + "for(" + outVar.getDeclaration() + ": " + iterationParameterText + ") {" + code + "}\n";
}
}
@@ -142,7 +142,7 @@ public class StreamToLoopInspection extends AbstractBaseJavaLocalInspectionTool
@Nullable
static List<OperationRecord> extractIterableForEach(PsiMethodCallExpression terminalCall) {
if (!ITERABLE_FOREACH.test(terminalCall) || !ExpressionUtils.isVoidContext(terminalCall)) return null;
PsiExpression qualifier = terminalCall.getMethodExpression().getQualifierExpression();
PsiExpression qualifier = ExpressionUtils.getEffectiveQualifier(terminalCall.getMethodExpression());
if (qualifier == null) return null;
// Do not visit this path if some class implements both Iterable and Stream
PsiType type = qualifier.getType();
@@ -167,7 +167,7 @@ public class StreamToLoopInspection extends AbstractBaseJavaLocalInspectionTool
@Nullable
static List<OperationRecord> extractMapForEach(PsiMethodCallExpression terminalCall) {
if (!MAP_FOREACH.test(terminalCall) || !ExpressionUtils.isVoidContext(terminalCall)) return null;
PsiExpression qualifier = terminalCall.getMethodExpression().getQualifierExpression();
PsiExpression qualifier = ExpressionUtils.getEffectiveQualifier(terminalCall.getMethodExpression());
if (qualifier == null) return null;
// Do not visit this path if some class implements both Map and Stream
PsiType type = qualifier.getType();
@@ -58,7 +58,7 @@ public class SuperMethodWarningUtil {
}
@NotNull
public static PsiMethod[] getTargetMethodCandidates(@NotNull PsiMethod method, @NotNull Collection<PsiElement> ignore) {
public static PsiMethod[] getTargetMethodCandidates(@NotNull PsiMethod method, @NotNull Collection<? extends PsiElement> ignore) {
PsiClass aClass = method.getContainingClass();
if (aClass == null) return new PsiMethod[]{method};
@@ -68,7 +68,7 @@ public class SuperMethodWarningUtil {
}
@NotNull
public static PsiMethod[] checkSuperMethods(@NotNull PsiMethod method, @NotNull String actionString, @NotNull Collection<PsiElement> ignore) {
public static PsiMethod[] checkSuperMethods(@NotNull PsiMethod method, @NotNull String actionString, @NotNull Collection<? extends PsiElement> ignore) {
ApplicationManager.getApplication().assertIsDispatchThread();
PsiMethod[] methodTargetCandidates = getTargetMethodCandidates(method, ignore);
if (methodTargetCandidates.length == 1 && methodTargetCandidates[0] == method) return methodTargetCandidates;
@@ -100,7 +100,7 @@ public class SuperMethodWarningUtil {
}
@NotNull
static Collection<PsiMethod> getSuperMethods(@NotNull PsiMethod method, PsiClass aClass, @NotNull Collection<PsiElement> ignore) {
static Collection<PsiMethod> getSuperMethods(@NotNull PsiMethod method, PsiClass aClass, @NotNull Collection<? extends PsiElement> ignore) {
ApplicationManager.getApplication().assertIsDispatchThread();
assert !ApplicationManager.getApplication().isWriteAccessAllowed();
final Collection<PsiMethod> superMethods = DeepestSuperMethodsSearch.search(method).findAll();
@@ -112,11 +112,12 @@ public class SuperMethodWarningUtil {
PsiMethod[] siblingSuperMethod = new PsiMethod[1];
if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(()->{
siblingSuperMethod[0] = ReadAction.compute(()->FindSuperElementsHelper.getSiblingInheritedViaSubClass(method));
}, "Searching for sub-classes", true, aClass.getProject())) {
}, "Searching for Sub-Classes", true, aClass.getProject())) {
throw new ProcessCanceledException();
}
if (siblingSuperMethod[0] != null) {
superMethods.add(siblingSuperMethod[0]);
superMethods.add(method); // add original method too because sometimes FindUsages can't find usages of this method by sibling super method
}
}
}
@@ -191,7 +192,7 @@ public class SuperMethodWarningUtil {
.setMovable(false)
.setResizable(false)
.setRequestFocus(true)
.setItemChosenCallback((value) -> {
.setItemChosenCallback(value -> {
if (value.equals(renameBase)) {
try {
methods[0].putUserData(SIBLINGS, superMethods);
@@ -0,0 +1,177 @@
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.refactoring.inline;
import com.intellij.psi.*;
import com.intellij.psi.util.PsiUtil;
import com.intellij.util.ObjectUtils;
import com.siyeh.ig.psiutils.BoolUtils;
import com.siyeh.ig.psiutils.CommentTracker;
import com.siyeh.ig.psiutils.ControlFlowUtils;
import com.siyeh.ig.psiutils.ExpressionUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
class BooleanReturnModel {
private final boolean myEarlyReturnValue;
private final int myEarlyReturnValueCount;
private final int myTerminalNonRemovableValueCount;
private final boolean myHasReturnInLoopOrSwitch;
BooleanReturnModel(boolean value, int count, int terminalNonRemovableValueCount, boolean hasReturnInLoopOrSwitch) {
myEarlyReturnValue = value;
myEarlyReturnValueCount = count;
myTerminalNonRemovableValueCount = terminalNonRemovableValueCount;
myHasReturnInLoopOrSwitch = hasReturnInLoopOrSwitch;
}
@Nullable
InlineTransformer getTransformer(PsiReference ref) {
if (!(ref instanceof PsiReferenceExpression)) return null;
PsiMethodCallExpression call = ObjectUtils.tryCast(((PsiReferenceExpression)ref).getParent(), PsiMethodCallExpression.class);
if (call == null) return null;
boolean wantedValue = true;
PsiElement parent;
PsiExpression expression = call;
while (true) {
parent = PsiUtil.skipParenthesizedExprUp(expression.getParent());
if (parent instanceof PsiPrefixExpression && JavaTokenType.EXCL.equals(((PsiPrefixExpression)parent).getOperationTokenType())) {
wantedValue = !wantedValue;
expression = (PsiPrefixExpression)parent;
}
else {
break;
}
}
if (parent instanceof PsiIfStatement) {
PsiIfStatement ifStatement = (PsiIfStatement)parent;
PsiStatement thenStatement = ControlFlowUtils.stripBraces(ifStatement.getThenBranch());
PsiStatement elseStatement = ControlFlowUtils.stripBraces(ifStatement.getElseBranch());
if (elseStatement == null && wantedValue == myEarlyReturnValue) {
boolean allowReplacement;
if (myEarlyReturnValueCount == 1 && myTerminalNonRemovableValueCount == 0) {
allowReplacement = isJumpOut(thenStatement);
}
else {
allowReplacement = isCopyableJumpOut(thenStatement);
}
if (allowReplacement) {
return getTransformer(thenStatement, null);
}
}
if (isJumpOut(thenStatement) && isJumpOut(elseStatement) && myTerminalNonRemovableValueCount == 0 && myEarlyReturnValueCount == 1) {
PsiStatement earlyStatement = myEarlyReturnValue == wantedValue ? thenStatement : elseStatement;
PsiStatement finalStatement = myEarlyReturnValue != wantedValue ? thenStatement : elseStatement;
return getTransformer(earlyStatement, finalStatement);
}
}
return null;
}
private boolean isJumpOut(PsiStatement statement) {
return statement instanceof PsiReturnStatement || statement instanceof PsiThrowStatement ||
(!myHasReturnInLoopOrSwitch && (statement instanceof PsiBreakStatement || statement instanceof PsiContinueStatement));
}
/**
* @param statement statement to check
* @return true if given statement could be copied to several return sites. We don't copy {@code throw} or {@code return}
* with non-trivial return value as this causes code duplication.
*/
private boolean isCopyableJumpOut(PsiStatement statement) {
if (!myHasReturnInLoopOrSwitch && (statement instanceof PsiBreakStatement || statement instanceof PsiContinueStatement)) {
return true;
}
if (statement instanceof PsiReturnStatement) {
PsiReturnStatement thenReturn = (PsiReturnStatement)statement;
return thenReturn.getReturnValue() == null ||
ExpressionUtils.isSafelyRecomputableExpression(thenReturn.getReturnValue());
}
return false;
}
@NotNull
private InlineTransformer getTransformer(PsiStatement earlyStatement, PsiStatement finalStatement) {
return (methodCopy, callSite, returnType) -> {
PsiCodeBlock block = Objects.requireNonNull(methodCopy.getBody());
PsiReturnStatement[] returns = PsiUtil.findReturnStatements(methodCopy);
for (PsiReturnStatement returnStatement : returns) {
PsiExpression returnValue = Objects.requireNonNull(returnStatement.getReturnValue()); // null-checked in "from" method
PsiLiteralExpression literal = ExpressionUtils.getLiteral(returnValue);
Boolean value = literal == null ? null : ObjectUtils.tryCast(literal.getValue(), Boolean.class);
if (value == null) {
CommentTracker tracker = new CommentTracker();
String condition = myEarlyReturnValue ? tracker.text(returnValue) : BoolUtils.getNegatedExpressionText(returnValue, tracker);
tracker.replaceAndRestoreComments(returnStatement, "if(" + condition + ") {" + earlyStatement.getText() + "}");
}
else if (value == myEarlyReturnValue) {
new CommentTracker().replaceAndRestoreComments(returnStatement, earlyStatement);
}
else {
new CommentTracker().delete(returnStatement);
}
}
if (finalStatement != null) {
block.addBefore(finalStatement, block.getRBrace());
}
return null;
};
}
@Nullable
static BooleanReturnModel from(@NotNull PsiCodeBlock body, @NotNull PsiReturnStatement[] returns) {
List<PsiExpression> terminal = new ArrayList<>();
boolean earlyValue = false;
int earlyCount = 0;
boolean hasReturnInLoopOrSwitch = false;
for (PsiReturnStatement returnStatement : returns) {
if (!hasReturnInLoopOrSwitch) {
hasReturnInLoopOrSwitch = isInLoopOrSwitch(body, returnStatement);
}
PsiExpression returnValue = returnStatement.getReturnValue();
if (returnValue == null || !PsiType.BOOLEAN.equals(returnValue.getType())) return null;
if (ControlFlowUtils.blockCompletesWithStatement(body, returnStatement)) {
terminal.add(returnValue);
}
else {
PsiLiteralExpression literal = ExpressionUtils.getLiteral(returnValue);
if (literal == null) return null;
Boolean literalValue = ObjectUtils.tryCast(literal.getValue(), Boolean.class);
if (literalValue == null) return null;
if (earlyCount == 0) {
earlyValue = literalValue;
}
else if (earlyValue != literalValue) {
return null;
}
earlyCount++;
}
}
if (earlyCount == 0) return null;
int terminalCount = 0;
for (PsiExpression value : terminal) {
PsiLiteralExpression literal = ExpressionUtils.getLiteral(value);
if (literal == null || !(literal.getValue() instanceof Boolean)) {
terminalCount++;
}
else if (literal.getValue().equals(earlyValue)) {
earlyCount++;
}
}
return new BooleanReturnModel(earlyValue, earlyCount, terminalCount, hasReturnInLoopOrSwitch);
}
private static boolean isInLoopOrSwitch(@NotNull PsiCodeBlock body, @NotNull PsiReturnStatement returnStatement) {
PsiElement parent = returnStatement.getParent();
while (parent != body) {
if (parent instanceof PsiLoopStatement || parent instanceof PsiSwitchStatement) {
return true;
}
parent = parent.getParent();
}
return false;
}
}
@@ -19,7 +19,7 @@ import com.intellij.refactoring.util.RefactoringUtil;
import java.util.Collections;
import java.util.function.Supplier;
class InlineMethodHandler extends JavaInlineActionHandler {
public class InlineMethodHandler extends JavaInlineActionHandler {
private static final String REFACTORING_NAME = RefactoringBundle.message("inline.method.title");
private InlineMethodHandler() {
@@ -32,17 +32,27 @@ class InlineMethodHandler extends JavaInlineActionHandler {
@Override
public void inlineElement(final Project project, Editor editor, PsiElement element) {
PsiMethod method = (PsiMethod)element.getNavigationElement();
performInline(project, editor, (PsiMethod)element.getNavigationElement(), false);
}
/**
* Try to inline method, displaying UI or error message if necessary
* @param project project where method is declared
* @param editor active editor where cursor might point to the call site
* @param method method to be inlined
* @param allowInlineThisOnly if true, only call-site at cursor will be suggested
* (in this case caller must check that cursor points to the valid reference)
*/
public static void performInline(Project project, Editor editor, PsiMethod method, boolean allowInlineThisOnly) {
PsiReference reference = editor != null ? TargetElementUtil.findReference(editor, editor.getCaretModel().getOffset()) : null;
boolean allowInlineThisOnly = false;
PsiCodeBlock methodBody = method.getBody();
Supplier<PsiCodeBlock> specialization = InlineMethodSpecialization.forReference(reference);
if (specialization != null) {
allowInlineThisOnly = true;
methodBody = specialization.get();
}
if (methodBody == null){
String message;
if (method.hasModifierProperty(PsiModifier.ABSTRACT)) {
@@ -60,7 +70,7 @@ class InlineMethodHandler extends JavaInlineActionHandler {
if (reference != null) {
final PsiElement refElement = reference.getElement();
if (!isEnabledForLanguage(refElement.getLanguage())) {
if (!isJavaLanguage(refElement.getLanguage())) {
String message = RefactoringBundle
.message("refactoring.is.not.supported.for.language", "Inline of Java method", refElement.getLanguage().getDisplayName());
CommonRefactoringUtil.showErrorHint(project, editor, message, REFACTORING_NAME, HelpID.INLINE_METHOD);
@@ -56,6 +56,7 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Stream;
@@ -71,7 +72,7 @@ public class InlineMethodProcessor extends BaseRefactoringProcessor {
private final boolean mySearchInComments;
private final boolean mySearchForTextOccurrences;
private final boolean myDeleteTheDeclaration;
private final InlineTransformerSelector myTransformerSelector;
private final Function<PsiReference, InlineTransformer> myTransformerChooser;
private final PsiManager myManager;
private final PsiElementFactory myFactory;
@@ -112,7 +113,7 @@ public class InlineMethodProcessor extends BaseRefactoringProcessor {
boolean isDeleteTheDeclaration) {
super(project);
myMethod = InlineMethodSpecialization.specialize(method, reference);
myTransformerSelector = InlineTransformerSelector.forMethod(myMethod);
myTransformerChooser = InlineTransformer.getSuitableTransformer(myMethod);
myReference = reference;
myEditor = editor;
myInlineThisOnly = isInlineThisOnly;
@@ -232,8 +233,7 @@ public class InlineMethodProcessor extends BaseRefactoringProcessor {
}
}
}
if (element instanceof PsiReferenceExpression &&
myTransformerSelector.getTransformerFor((PsiReference)element).isFallBackTransformer()) {
if (element instanceof PsiReferenceExpression && myTransformerChooser.apply((PsiReference)element).isFallBackTransformer()) {
conflicts.putValue(element, RefactoringBundle.message("inlined.method.will.be.transformed.to.single.return.form"));
}
@@ -243,7 +243,7 @@ public class InlineMethodProcessor extends BaseRefactoringProcessor {
}
}
}
else if (myReference != null && myTransformerSelector.getTransformerFor(myReference).isFallBackTransformer()) {
else if (myReference != null && myTransformerChooser.apply(myReference).isFallBackTransformer()) {
conflicts.putValue(myReference, RefactoringBundle.message("inlined.method.will.be.transformed.to.single.return.form"));
}
@@ -611,7 +611,6 @@ public class InlineMethodProcessor extends BaseRefactoringProcessor {
}
public void inlineMethodCall(PsiReferenceExpression ref) throws IncorrectOperationException {
InlineUtil.TailCallType tailCall = InlineUtil.getTailCallType(ref);
ChangeContextUtil.encodeContextInfo(myMethod, false);
myMethodCopy = (PsiMethod)myMethod.copy();
ChangeContextUtil.clearContextInfo(myMethod);
@@ -667,11 +666,6 @@ public class InlineMethodProcessor extends BaseRefactoringProcessor {
if (firstBodyElement != null && firstBodyElement != blockData.block.getRBrace()) {
int last = statements.length - 1;
if (last > 0 && statements[last] instanceof PsiReturnStatement &&
tailCall != InlineUtil.TailCallType.Return) {
last--;
}
final PsiElement rBraceOrReturnStatement =
last >= 0 ? PsiTreeUtil.skipWhitespacesAndCommentsForward(statements[last]) : blockData.block.getLastBodyElement();
LOG.assertTrue(rBraceOrReturnStatement != null);
@@ -703,18 +697,6 @@ public class InlineMethodProcessor extends BaseRefactoringProcessor {
}
}
}
if (statements.length > 0) {
final PsiStatement lastStatement = statements[statements.length - 1];
if (lastStatement instanceof PsiReturnStatement && tailCall != InlineUtil.TailCallType.Return) {
final PsiExpression returnValue = ((PsiReturnStatement)lastStatement).getReturnValue();
if (returnValue != null && PsiUtil.isStatement(returnValue)) {
PsiExpressionStatement exprStatement = (PsiExpressionStatement)myFactory.createStatementFromText("a;", null);
exprStatement.getExpression().replace(returnValue);
anchorParent.addBefore(exprStatement, anchor);
}
}
}
}
@@ -733,25 +715,20 @@ public class InlineMethodProcessor extends BaseRefactoringProcessor {
}
ChangeContextUtil.decodeContextInfo(anchorParent, thisClass, thisAccessExpr);
PsiElement callParent = methodCall.getParent();
PsiReferenceExpression resultUsage = null;
if (callParent instanceof PsiLambdaExpression) {
methodCall.delete();
}
else if (callParent instanceof PsiExpressionStatement || tailCall == InlineUtil.TailCallType.Return) {
CommentTracker tracker = new CommentTracker();
tracker.delete(callParent);
if (firstAdded != null) {
tracker.insertCommentsBefore(firstAdded);
}
if (blockData.resultVar != null) {
PsiExpression expr = myFactory.createExpressionFromText(Objects.requireNonNull(blockData.resultVar.getName()), null);
resultUsage = (PsiReferenceExpression)new CommentTracker().replaceAndRestoreComments(methodCall, expr);
}
else {
if (blockData.resultVar != null) {
PsiExpression expr = myFactory.createExpressionFromText(Objects.requireNonNull(blockData.resultVar.getName()), null);
resultUsage = (PsiReferenceExpression)new CommentTracker().replaceAndRestoreComments(methodCall, expr);
}
else {
//??
// If return var is not specified, we trust that InlineTransformer fully processed the original anchor statement,
// and we can delete it.
CommentTracker tracker = new CommentTracker();
if (firstAdded != null) {
tracker.delete(anchor);
tracker.insertCommentsBefore(firstAdded);
} else {
tracker.deleteAndRestoreComments(anchor);
}
}
@@ -827,7 +804,7 @@ public class InlineMethodProcessor extends BaseRefactoringProcessor {
final PsiStatement[] originalStatements = block.getStatements();
PsiType returnType = callSubstitutor.substitute(myMethod.getReturnType());
InlineTransformer transformer = myTransformerSelector.getTransformerFor(ref);
InlineTransformer transformer = myTransformerChooser.apply(ref);
PsiLocalVariable[] parmVars = declareParameters(block, argumentList, callSubstitutor);
@@ -1,10 +1,24 @@
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.refactoring.inline;
import com.intellij.psi.PsiLocalVariable;
import com.intellij.psi.PsiMethod;
import com.intellij.psi.PsiReferenceExpression;
import com.intellij.psi.PsiType;
import com.intellij.codeInsight.intention.impl.singlereturn.ConvertToSingleReturnAction;
import com.intellij.codeInsight.intention.impl.singlereturn.FinishMarker;
import com.intellij.openapi.progress.EmptyProgressIndicator;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleManager;
import com.intellij.psi.codeStyle.VariableKind;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.refactoring.util.InlineUtil;
import com.siyeh.ig.psiutils.ExpressionUtils;
import com.siyeh.ig.psiutils.VariableNameGenerator;
import org.jetbrains.annotations.NotNull;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.function.Function;
@FunctionalInterface
public interface InlineTransformer {
@@ -25,4 +39,100 @@ public interface InlineTransformer {
default boolean isFallBackTransformer() {
return false;
}
class NormalTransformer implements InlineTransformer {
@Override
public PsiLocalVariable transformBody(PsiMethod methodCopy, PsiReferenceExpression callSite, PsiType returnType) {
if (returnType == null || PsiType.VOID.equals(returnType) ||
callSite.getParent() instanceof PsiMethodCallExpression && ExpressionUtils.isVoidContext((PsiExpression)callSite.getParent())) {
InlineUtil.extractReturnValues(methodCopy, false);
return null;
}
PsiCodeBlock block = Objects.requireNonNull(methodCopy.getBody());
Project project = methodCopy.getProject();
PsiElementFactory factory = JavaPsiFacade.getElementFactory(project);
String resultName = new VariableNameGenerator(block, VariableKind.LOCAL_VARIABLE).byName("result", "res").generate(true);
PsiDeclarationStatement declaration = factory.createVariableDeclarationStatement(resultName, returnType, null);
declaration = (PsiDeclarationStatement)block.addAfter(declaration, null);
PsiLocalVariable resultVar = (PsiLocalVariable)declaration.getDeclaredElements()[0];
CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project);
for (PsiReturnStatement returnStatement : PsiUtil.findReturnStatements(block)) {
final PsiExpression returnValue = returnStatement.getReturnValue();
if (returnValue == null) continue;
PsiStatement statement = factory.createStatementFromText(resultName + "=0;", null);
statement = (PsiStatement)codeStyleManager.reformat(statement);
PsiAssignmentExpression assignment = (PsiAssignmentExpression)((PsiExpressionStatement)statement).getExpression();
Objects.requireNonNull(assignment.getRExpression()).replace(returnValue);
returnStatement.replace(statement);
}
return resultVar;
}
}
class ConvertToSingleReturnTransformer implements InlineTransformer {
@Override
public boolean isFallBackTransformer() {
return true;
}
@Override
public PsiLocalVariable transformBody(PsiMethod methodCopy, PsiReferenceExpression callSite, PsiType returnType) {
if (callSite.getParent() instanceof PsiMethodCallExpression && ExpressionUtils.isVoidContext((PsiExpression)callSite.getParent())) {
InlineUtil.extractReturnValues(methodCopy, false);
returnType = PsiType.VOID;
}
PsiCodeBlock block = Objects.requireNonNull(methodCopy.getBody());
List<PsiReturnStatement> returns = Arrays.asList(PsiUtil.findReturnStatements(block));
FinishMarker marker = FinishMarker.defineFinishMarker(block, returnType, returns);
return ConvertToSingleReturnAction.convertReturns(methodCopy.getProject(), block, returnType, marker, returns.size(),
new EmptyProgressIndicator());
}
}
/**
* Returns the most suitable transformer for given method and given call site
*
* @param method method to inline (must have body)
* @return a function which produces a transformer for given reference to the inlined method.
* Should always succeed as fallback transformer which accepts any method is available.
*/
@NotNull
static Function<PsiReference, InlineTransformer> getSuitableTransformer(PsiMethod method) {
PsiReturnStatement[] returns = PsiUtil.findReturnStatements(method);
PsiCodeBlock body = Objects.requireNonNull(method.getBody());
if (!InlineMethodProcessor.checkBadReturns(returns, body)) {
return ref -> {
InlineUtil.TailCallType type = InlineUtil.getTailCallType(ref);
if (type == InlineUtil.TailCallType.Return || type == InlineUtil.TailCallType.Simple) {
return type.getTransformer();
}
return new NormalTransformer();
};
}
boolean canUseContinue = Arrays.stream(returns).allMatch(statement -> {
// We cannot use "continue" without introducing a label if any of returns is inside nested loop.
// Introducing a label is ugly, so let's move to fallback transformer
return PsiTreeUtil.getParentOfType(statement, PsiLoopStatement.class, true, PsiMethod.class) == null;
});
BooleanReturnModel model = BooleanReturnModel.from(body, returns);
return ref -> {
InlineUtil.TailCallType type = InlineUtil.getTailCallType(ref);
if (type == InlineUtil.TailCallType.Continue && !canUseContinue) {
type = InlineUtil.TailCallType.None;
}
InlineTransformer fromTailCall = type.getTransformer();
if (fromTailCall != null) {
return fromTailCall;
}
if (model != null) {
InlineTransformer fromBooleanModel = model.getTransformer(ref);
if (fromBooleanModel != null) {
return fromBooleanModel;
}
}
return new ConvertToSingleReturnTransformer();
};
}
}
@@ -1,126 +0,0 @@
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.refactoring.inline;
import com.intellij.codeInsight.intention.impl.singlereturn.ConvertToSingleReturnAction;
import com.intellij.codeInsight.intention.impl.singlereturn.FinishMarker;
import com.intellij.openapi.progress.EmptyProgressIndicator;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleManager;
import com.intellij.psi.codeStyle.VariableKind;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.refactoring.util.InlineUtil;
import com.intellij.util.Consumer;
import com.intellij.util.ObjectUtils;
import com.siyeh.ig.callMatcher.CallMapper;
import com.siyeh.ig.callMatcher.CallMatcher;
import com.siyeh.ig.psiutils.ExpressionUtils;
import com.siyeh.ig.psiutils.VariableNameGenerator;
import org.jetbrains.annotations.NotNull;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.function.Function;
public abstract class InlineTransformerSelector {
abstract InlineTransformer getTransformerFor(PsiReference reference);
private static InlineTransformerSelector common(Function<PsiReference, InlineTransformer> chooser) {
return new InlineTransformerSelector() {
@Override
InlineTransformer getTransformerFor(PsiReference reference) {
return chooser.apply(reference);
}
};
}
/**
* Returns the most suitable transformer for given method and given call site
*
* @param method method to inline (must have body)
* @return a function which produces a transformer for given reference to the inlined method.
* Should always succeed as fallback transformer which accepts any method is available.
*/
@NotNull
public static InlineTransformerSelector forMethod(PsiMethod method) {
PsiReturnStatement[] returns = PsiUtil.findReturnStatements(method);
PsiCodeBlock body = method.getBody();
if (!InlineMethodProcessor.checkBadReturns(returns, body)) {
return common(ref -> {
InlineUtil.TailCallType type = InlineUtil.getTailCallType(ref);
if (type == InlineUtil.TailCallType.Return || type == InlineUtil.TailCallType.Simple) {
return type.getTransformer();
}
return new NormalTransformer();
});
}
boolean canUseContinue = Arrays.stream(returns).allMatch(statement -> {
// We cannot use "continue" without introducing a label if any of returns is inside nested loop.
// Introducing a label is ugly, so let's move to fallback transformer
return PsiTreeUtil.getParentOfType(statement, PsiLoopStatement.class, true, PsiMethod.class) == null;
});
return common(ref -> {
InlineUtil.TailCallType type = InlineUtil.getTailCallType(ref);
if (type == InlineUtil.TailCallType.Continue && !canUseContinue) {
type = InlineUtil.TailCallType.None;
}
InlineTransformer fromTailCall = type.getTransformer();
return fromTailCall != null ? fromTailCall : new ConvertToSingleReturnTransformer();
});
}
private static class NormalTransformer implements InlineTransformer {
@Override
public PsiLocalVariable transformBody(PsiMethod methodCopy, PsiReferenceExpression callSite, PsiType returnType) {
if (returnType == null || PsiType.VOID.equals(returnType)) return null;
if (callSite.getParent() instanceof PsiMethodCallExpression && ExpressionUtils.isVoidContext((PsiExpression)callSite.getParent())) {
InlineUtil.extractReturnValues(methodCopy, false);
return null;
}
PsiCodeBlock block = Objects.requireNonNull(methodCopy.getBody());
Project project = methodCopy.getProject();
PsiElementFactory factory = JavaPsiFacade.getElementFactory(project);
String resultName = new VariableNameGenerator(block, VariableKind.LOCAL_VARIABLE).byName("result", "res").generate(true);
PsiDeclarationStatement declaration = factory.createVariableDeclarationStatement(resultName, returnType, null);
declaration = (PsiDeclarationStatement)block.addAfter(declaration, null);
PsiLocalVariable resultVar = (PsiLocalVariable)declaration.getDeclaredElements()[0];
CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project);
for (PsiReturnStatement returnStatement : PsiUtil.findReturnStatements(block)) {
final PsiExpression returnValue = returnStatement.getReturnValue();
if (returnValue == null) continue;
PsiStatement statement = factory.createStatementFromText(resultName + "=0;", null);
statement = (PsiStatement)codeStyleManager.reformat(statement);
PsiAssignmentExpression assignment = (PsiAssignmentExpression)((PsiExpressionStatement)statement).getExpression();
Objects.requireNonNull(assignment.getRExpression()).replace(returnValue);
returnStatement.replace(statement);
}
return resultVar;
}
}
private static class ConvertToSingleReturnTransformer implements InlineTransformer {
@Override
public boolean isFallBackTransformer() {
return true;
}
@Override
public PsiLocalVariable transformBody(PsiMethod methodCopy, PsiReferenceExpression callSite, PsiType returnType) {
if (callSite.getParent() instanceof PsiMethodCallExpression && ExpressionUtils.isVoidContext((PsiExpression)callSite.getParent())) {
InlineUtil.extractReturnValues(methodCopy, false);
returnType = PsiType.VOID;
}
PsiCodeBlock block = Objects.requireNonNull(methodCopy.getBody());
List<PsiReturnStatement> returns = Arrays.asList(PsiUtil.findReturnStatements(block));
FinishMarker marker = FinishMarker.defineFinishMarker(block, returnType, returns);
return ConvertToSingleReturnAction.convertReturns(methodCopy.getProject(), block, returnType, marker, returns.size(),
new EmptyProgressIndicator());
}
}
}
@@ -19,11 +19,6 @@ import com.intellij.lang.Language;
import com.intellij.lang.java.JavaLanguage;
import com.intellij.lang.refactoring.InlineActionHandler;
import com.intellij.openapi.fileTypes.StdFileTypes;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiElement;
import com.intellij.refactoring.ui.ConflictsDialog;
import com.intellij.util.containers.MultiMap;
import org.jetbrains.annotations.NotNull;
/**
* @author yole
@@ -31,6 +26,10 @@ import org.jetbrains.annotations.NotNull;
public abstract class JavaInlineActionHandler extends InlineActionHandler {
@Override
public boolean isEnabledForLanguage(Language l) {
return isJavaLanguage(l);
}
protected static boolean isJavaLanguage(Language l) {
return l instanceof JavaLanguage ||
l.equals(StdFileTypes.JSPX.getLanguage()) ||
l.equals(StdFileTypes.JSP.getLanguage());
@@ -327,10 +327,16 @@ public class InlineUtil {
if (element instanceof PsiMethodReferenceExpression) return TailCallType.Return;
PsiExpression methodCall = PsiTreeUtil.getParentOfType(element, PsiMethodCallExpression.class);
if (methodCall == null) return TailCallType.None;
PsiElement callParent = methodCall.getParent();
PsiElement callParent = PsiUtil.skipParenthesizedExprUp(methodCall.getParent());
if (callParent instanceof PsiReturnStatement || callParent instanceof PsiLambdaExpression) {
return TailCallType.Return;
}
if (callParent instanceof PsiExpression && BoolUtils.isNegation((PsiExpression)callParent)) {
PsiElement negationParent = PsiUtil.skipParenthesizedExprUp(callParent.getParent());
if (negationParent instanceof PsiReturnStatement || negationParent instanceof PsiLambdaExpression) {
return TailCallType.Invert;
}
}
if (callParent instanceof PsiExpressionStatement) {
PsiStatement curElement = (PsiStatement)callParent;
while (true) {
@@ -555,7 +561,17 @@ public class InlineUtil {
Continue((methodCopy, callSite, returnType) -> {
extractReturnValues(methodCopy, true);
return null;
}),
}),
Invert((methodCopy, callSite, returnType) -> {
for (PsiReturnStatement statement : PsiUtil.findReturnStatements(methodCopy)) {
PsiExpression value = statement.getReturnValue();
if (value != null) {
CommentTracker ct = new CommentTracker();
ct.replaceAndRestoreComments(value, BoolUtils.getNegatedExpressionText(value, ct));
}
}
return null;
}),
Return((methodCopy, callSite, returnType) -> null);
@Nullable
@@ -307,8 +307,10 @@ public class GenericsUtil {
if (refClass instanceof PsiAnonymousClass) {
type = ((PsiAnonymousClass)refClass).getBaseClassType();
}
if (type instanceof PsiCapturedWildcardType) {
type = ((PsiCapturedWildcardType)type).getUpperBound();
PsiType deepComponentType = type.getDeepComponentType();
if (deepComponentType instanceof PsiCapturedWildcardType) {
type = PsiTypesUtil.createArrayType(((PsiCapturedWildcardType)deepComponentType).getUpperBound(),
type.getArrayDimensions());
}
PsiType transformed = type.accept(new PsiTypeVisitor<PsiType>() {
@Override
@@ -600,7 +600,8 @@ public class LambdaUtil {
public static boolean isExpressionStatementExpression(PsiElement body) {
return body instanceof PsiAssignmentExpression ||
PsiUtil.isIncrementDecrementOperation(body) ||
body instanceof PsiCallExpression ||
body instanceof PsiMethodCallExpression || //method invocation
body instanceof PsiNewExpression && ((PsiNewExpression)body).getArrayInitializer() == null || //class instance creation
body instanceof PsiReferenceExpression && !body.isPhysical();
}
@@ -52,7 +52,7 @@ public class PsiResolveHelperImpl implements PsiResolveHelper {
if (aClass == null) return JavaResolveResult.EMPTY_ARRAY;
}
else {
processor = new MethodResolverProcessor(aClass, argumentList, place, place.getContainingFile());
processor = new MethodResolverProcessor(null, argumentList, place, place.getContainingFile());
}
ResolveState state = ResolveState.initial().put(PsiSubstitutor.KEY, substitutor);
@@ -0,0 +1,6 @@
package c;
import a.*;
class Test extends Base {
Test() { }
}
@@ -0,0 +1,14 @@
interface A {
void enableInspections(B... providers);
void enableInspections(Runnable r, String... inspections);
}
interface B {
Class[] get();
}
class C {
void foo(A a) {
a.enableInspections(() -> new Class[]{});
}
}
@@ -43,4 +43,14 @@ public class Main {
interface Visitor { }
}
class X implements Iterable<String> {
class Y {
void test() {
for (String s : X.this) {
System.out.println(s);
}
}
}
}
}
@@ -31,4 +31,15 @@ public class Main {
}
}
class X implements Map<String, String> {
class Y {
void test() {
for (Entry<String, String> entry : X.this.entrySet()) {
String k = entry.getKey();
String v = entry.getValue();
System.out.println(k + "-" + v);
}
}
}
}
}
@@ -33,4 +33,12 @@ public class Main {
interface Visitor { }
}
class X implements Iterable<String> {
class Y {
void test() {
forEach(System.out::println);
}
}
}
}
@@ -21,4 +21,11 @@ public class Main {
map.forEach(otherMap::putIfAbsent);
}
class X implements Map<String, String> {
class Y {
void test() {
forEach((k, v) -> System.out.println(k + "-" + v));
}
}
}
}
@@ -45,8 +45,8 @@
"blank_lines_before_imports": 1,
"blank_lines_before_method_body": 0,
"blank_lines_before_package": 0,
"block_brace_style": "end_of_line",
"block_comment_at_first_column": true,
"brace_style": "end_of_line",
"call_parameters_new_line_after_left_paren": false,
"call_parameters_right_paren_on_new_line": false,
"call_parameters_wrap": "on_every_item",
@@ -1,5 +1,3 @@
import org.jetbrains.annotations.*;
class A {
void method() {
int v = (int)(<warning descr="Casting '1L' to 'long' is redundant">long</warning>)1L;
@@ -15,4 +15,7 @@ class A {
widen((int)c);
}
Object test(int x) {
return (long) x;
}
}
@@ -0,0 +1,18 @@
interface WatchNode {
void setObsolete();
}
abstract class XValueContainerNode {
public void setObsolete() {
}
}
class WatchNodeImpl extends XValueContainerNode implements WatchNode {
}
class Use {
void fff(XValueContainerNode node) {
node.setObsolete();
}
}
@@ -0,0 +1,20 @@
class Test {
private boolean test(String s) {
if(s != null) {
s = s.trim();
if (s.isEmpty()) {
return true;
}
}
return false;
}
String use(String[] list) {
for(String str : list) {
if (<caret>test(str)) continue;
System.out.println("Ok string: "+str);
}
}
}
@@ -0,0 +1,16 @@
class Test {
String use(String[] list) {
for(String str : list) {
String s = str;
if(s != null) {
s = s.trim();
if (s.isEmpty()) {
continue;
}
}
System.out.println("Ok string: "+str);
}
}
}
@@ -0,0 +1,24 @@
class Test {
private boolean test(String s) {
if (s == null) return false;
s = s.trim();
if (s.isEmpty()) return false;
int i;
try {
i = Integer.parseInt(s);
}
catch (NumberFormatException ex) {
return false;
}
return i > 0;
}
String use(String[] list) {
for(String str : list) {
if (!<caret>test(str)) break;
System.out.println("Ok string: "+str);
}
}
}
@@ -0,0 +1,23 @@
class Test {
String use(String[] list) {
for(String str : list) {
String s = str;
if (s == null) break;
s = s.trim();
if (s.isEmpty()) break;
int i;
try {
i = Integer.parseInt(s);
}
catch (NumberFormatException ex) {
break;
}
if (i <= 0) {
break;
}
System.out.println("Ok string: "+str);
}
}
}
@@ -0,0 +1,17 @@
class Test {
private boolean test(String s) {
if(s != null) {
s = s.trim();
if (s.isEmpty()) {
return true;
}
}
return false;
}
String use(String s) {
if(<caret>test(s+s)) throw new IllegalArgumentException();
else return "nice";
}
}
@@ -0,0 +1,13 @@
class Test {
String use(String s) {
String s1 = s+s;
if(s1 != null) {
s1 = s1.trim();
if (s1.isEmpty()) {
throw new IllegalArgumentException();
}
}
return "nice";
}
}
@@ -0,0 +1,17 @@
class Test {
private boolean test() {
for(int i=0; i<10; i++) {
if (Math.random() > 0.5) return true;
}
return false;
}
String useTest() {
if(<caret>test()) {
return "foo".trim();
} else {
return "bar".trim();
}
}
}
@@ -0,0 +1,9 @@
class Test {
String useTest() {
for(int i=0; i<10; i++) {
if (Math.random() > 0.5) return "foo".trim();
}
return "bar".trim();
}
}
@@ -0,0 +1,14 @@
class Test {
private boolean test(String s) {
if (s == null) return false;
s = s.trim();
if (s.isEmpty()) return false;
return true;
}
void use(String s) {
if(!<caret>test(s+s)) return;
System.out.println("woohoo");
}
}
@@ -0,0 +1,10 @@
class Test {
void use(String s) {
String s1 = s+s;
if (s1 == null) return;
s1 = s1.trim();
if (s1.isEmpty()) return;
System.out.println("woohoo");
}
}
@@ -0,0 +1,17 @@
class Test {
private boolean test(String s) {
if(s != null) {
s = s.trim();
if (s.isEmpty()) {
return true;
}
}
return false;
}
void use(String s) {
if(<caret>test(s+s)) throw new IllegalArgumentException();
System.out.println("woohoo");
}
}
@@ -0,0 +1,13 @@
class Test {
void use(String s) {
String s1 = s+s;
if(s1 != null) {
s1 = s1.trim();
if (s1.isEmpty()) {
throw new IllegalArgumentException();
}
}
System.out.println("woohoo");
}
}
@@ -0,0 +1,13 @@
class Test {
boolean check(String s) {
if (s == null) return false;
s = s.trim();
if (s.isEmpty()) return false;
return s.length() % 2 == 0;
}
boolean use(String s) {
return !<caret>check(s + s);
}
}
@@ -0,0 +1,11 @@
class Test {
boolean use(String s) {
String s1 = s + s;
if (s1 == null) return true;
s1 = s1.trim();
if (s1.isEmpty()) return true;
return s1.length() % 2 != 0;
}
}
@@ -0,0 +1,9 @@
interface I {}
abstract class Test<T extends I> {
void foo(Test<?> t) {
I[] m = t.get();
}
abstract T[] get();
}
@@ -0,0 +1,9 @@
interface I {}
abstract class Test<T extends I> {
void foo(Test<?> t) {
<selection>t.get()</selection>
}
abstract T[] get();
}
@@ -195,6 +195,14 @@ public class LightAdvHighlightingFixtureTest extends LightCodeInsightFixtureTest
assertThat(problems).isEmpty();
}
public void testImplicitConstructorAccessibility() {
myFixture.addClass("package a; public class Base {" +
"private Base() {}\n" +
"protected Base(int... i) {}\n" +
"}");
doTest();
}
private void doTest() {
myFixture.configureByFile(getTestName(false) + ".java");
myFixture.checkHighlighting();
@@ -275,6 +275,7 @@ public class OverloadResolutionTest extends LightDaemonAnalyzerTestCase {
public void testUnqualifiedStaticInterfaceMethodCallsOnInnerClasses() { doTest(false);}
public void testStaticMethodInSuperInterfaceConflictWithCurrentStatic() { doTest(false);}
public void testPotentialCompatibilityWithArrayCreation() { doTest(false);}
public void testOverloadsWithOneNonCompatible() { doTest(false);}
public void testSecondSearchOverloadsBoxing() {
IdeaTestUtil.setTestVersion(JavaSdkVersion.JDK_1_8, getModule(), getTestRootDisposable());
@@ -106,7 +106,7 @@ public class JavaCodeStyleSettingsTest extends CodeStyleTestCase {
LanguageCodeStyleSettingsProvider.forLanguage(JavaLanguage.INSTANCE).getPropertyMapper(settings);
setSimple(mapper, "align_group_field_declarations", "true");
setSimple(mapper, "blank_lines_after_class_header", "1");
setSimple(mapper, "brace_style", "next_line");
setSimple(mapper, "block_brace_style", "next_line");
setSimple(mapper, "indent_size", "2");
setSimple(mapper, "doc_align_param_comments", "true");
setList(mapper, "imports_layout",
@@ -2,8 +2,9 @@
package com.intellij.java.psi.search;
import com.intellij.JavaTestUtil;
import com.intellij.find.findUsages.JavaFindUsagesHandler;
import com.intellij.find.findUsages.JavaFindUsagesHandlerFactory;
import com.intellij.find.FindManager;
import com.intellij.find.findUsages.*;
import com.intellij.find.impl.FindManagerImpl;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.fileTypes.StdFileTypes;
import com.intellij.openapi.module.ModifiableModuleModel;
@@ -17,6 +18,7 @@ import com.intellij.psi.search.PsiReferenceProcessorAdapter;
import com.intellij.psi.search.searches.MethodReferencesSearch;
import com.intellij.psi.search.searches.OverridingMethodsSearch;
import com.intellij.psi.search.searches.ReferencesSearch;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.testFramework.IdeaTestUtil;
import com.intellij.testFramework.PsiTestCase;
import com.intellij.testFramework.PsiTestUtil;
@@ -67,6 +69,27 @@ public class FindUsagesTest extends PsiTestCase{
assertEquals(1, overriders.size());
}
public void testSiblingFindUsages() {
PsiClass xv = myJavaFacade.findClass("XValueContainerNode", GlobalSearchScope.allScope(myProject));
PsiMethod method = xv.findMethodsByName("setObsolete", false)[0];
FindUsagesHandler handler = ((FindManagerImpl)FindManager.getInstance(getProject())).getFindUsagesManager()
.getFindUsagesHandler(method, FindUsagesHandlerFactory.OperationMode.USAGES_WITH_DEFAULT_OPTIONS);
PsiElement[] elements = handler.getPrimaryElements();
int[] count = {0};
for (PsiElement element : elements) {
handler.processElementUsages(element, info -> {
count[0]++;
PsiClass containing = PsiTreeUtil.getParentOfType(info.getElement(), PsiClass.class);
assertEquals("Use", containing.getName());
return true;
}, handler.getFindUsagesOptions());
}
assertEquals(1, count[0]);
}
public void testProtectedMethodInPackageLocalClass() {
PsiMethod method = myJavaFacade.findClass("foo.PackageLocal", GlobalSearchScope.allScope(myProject)).getMethods()[0];
assertEquals(1, OverridingMethodsSearch.search(method).findAll().size());
@@ -670,6 +670,10 @@ public class IntroduceVariableTest extends LightCodeInsightTestCase {
public void testCapturedWildcardUpperBoundSuggestedAsType() {
doTest(new MockIntroduceVariableHandler("m", false, false, false, "I"));
}
public void testArrayOfCapturedWildcardUpperBoundSuggestedAsType() {
doTest(new MockIntroduceVariableHandler("m", false, false, false, "I[]"));
}
public void testReturnNonExportedArray() {
doTest(new MockIntroduceVariableHandler("i", false, false, false, "java.io.File[]") {
@@ -490,6 +490,34 @@ public class InlineMethodTest extends LightRefactoringTestCase {
public void testSpecializeClassGetName() {
doTest();
}
public void testBooleanModelSimple() {
doTestAssertBadReturn();
}
public void testBooleanModelMultiReturns() {
doTestAssertBadReturn();
}
public void testBooleanModelIfElse() {
doTestAssertBadReturn();
}
public void testBooleanModelIfElse2() {
doTestAssertBadReturn();
}
public void testBooleanModelContinue() {
doTestAssertBadReturn();
}
public void testBooleanModelFinalCondition() {
doTestAssertBadReturn();
}
public void testInvertMethod() {
doTest();
}
@Override
protected Sdk getProjectJDK() {
@@ -24,12 +24,16 @@ public class RepositoryLibraryProperties extends LibraryProperties<RepositoryLib
public RepositoryLibraryProperties() {
}
public RepositoryLibraryProperties(JpsMavenRepositoryLibraryDescriptor descriptor) {
myDescriptor = descriptor;
}
public RepositoryLibraryProperties(String mavenId, final boolean includeTransitiveDependencies) {
myDescriptor = new JpsMavenRepositoryLibraryDescriptor(mavenId, includeTransitiveDependencies, Collections.emptyList());
this(new JpsMavenRepositoryLibraryDescriptor(mavenId, includeTransitiveDependencies, Collections.emptyList()));
}
public RepositoryLibraryProperties(String mavenId, String packaging, final boolean includeTransitiveDependencies) {
myDescriptor = new JpsMavenRepositoryLibraryDescriptor(mavenId, packaging, includeTransitiveDependencies, Collections.emptyList());
this(new JpsMavenRepositoryLibraryDescriptor(mavenId, packaging, includeTransitiveDependencies, Collections.emptyList()));
}
public RepositoryLibraryProperties(@NotNull String groupId, @NotNull String artifactId, @NotNull String version) {
@@ -40,8 +44,8 @@ public class RepositoryLibraryProperties extends LibraryProperties<RepositoryLib
@NotNull String artifactId,
@NotNull String version,
boolean includeTransitiveDependencies, @NotNull List<String> excludedDependencies) {
myDescriptor = new JpsMavenRepositoryLibraryDescriptor(groupId, artifactId, version, includeTransitiveDependencies,
excludedDependencies);
this(new JpsMavenRepositoryLibraryDescriptor(groupId, artifactId, version, includeTransitiveDependencies,
excludedDependencies));
}
@Override
@@ -90,14 +90,6 @@ public class FSOperations {
}
}
/**
* @deprecated use markDirtyIfNotDeleted(CompileContext context, final CompilationRound round, final File file)
*/
@Deprecated
public static void markDirtyIfNotDeleted(CompileContext context, final File file) throws IOException {
markDirtyIfNotDeleted(context, CompilationRound.NEXT, file);
}
public static void markDirtyIfNotDeleted(CompileContext context, final CompilationRound round, final File file) throws IOException {
final JavaSourceRootDescriptor rd = context.getProjectDescriptor().getBuildRootIndex().findJavaRootDescriptor(context, file);
if (rd != null) {
@@ -114,14 +106,6 @@ public class FSOperations {
}
}
/**
* @deprecated use markDirty(CompileContext context, final CompilationRound round, final ModuleChunk chunk, @Nullable FileFilter filter)
*/
@Deprecated
public static void markDirty(CompileContext context, final ModuleChunk chunk, @Nullable FileFilter filter) throws IOException {
markDirty(context, CompilationRound.NEXT, chunk, filter);
}
public static void markDirty(CompileContext context, final CompilationRound round, final ModuleChunk chunk, @Nullable FileFilter filter) throws IOException {
for (ModuleBuildTarget target : chunk.getTargets()) {
markDirty(context, round, target, filter);
@@ -133,14 +117,6 @@ public class FSOperations {
markDirtyFiles(context, target, round, pd.timestamps.getStorage(), true, null, filter);
}
/**
* @deprecated use markDirtyRecursively(CompileContext context, final CompilationRound round, ModuleChunk chunk, FileFilter filter)
*/
@Deprecated
public static void markDirtyRecursively(CompileContext context, ModuleChunk chunk) throws IOException {
markDirtyRecursively(context, CompilationRound.NEXT, chunk);
}
public static void markDirtyRecursively(CompileContext context, final CompilationRound round, ModuleChunk chunk) throws IOException {
markDirtyRecursively(context, round, chunk, null);
}
@@ -54,6 +54,9 @@
<item name='org.jdom.Element org.jdom.Attribute getAttribute(java.lang.String)'>
<annotation name='org.jetbrains.annotations.Nullable'/>
</item>
<item name='org.jdom.Element org.jdom.Element addContent(org.jdom.Element) 0'>
<annotation name='org.jetbrains.annotations.NotNull'/>
</item>
<item name='org.jdom.Element org.jdom.Element getChild(java.lang.String)'>
<annotation name='org.jetbrains.annotations.Nullable'/>
</item>
@@ -145,7 +145,9 @@ class CommunityLibraryLicenses {
new LibraryLicense(name: "Common Annotations for the JavaTM Platform API", libraryName: "javax.annotation-api", version: "1.3.2",
url: "https://github.com/javaee/javax.annotation",
license: "CDDL 1.1 / GPL 2.0 + Classpath", licenseUrl: "https://oss.oracle.com/licenses/CDDL+GPL-1.1"),
new LibraryLicense(name: "completion-ranking-java", attachedTo: "intellij.statsCollector.completionRanker", version: "0.0.3",
new LibraryLicense(name: "completion-ranking-java", attachedTo: "intellij.statsCollector.completionRanker", version: "0.0.6",
license: "Apache 2.0"),
new LibraryLicense(name: "completion-ranking-python", attachedTo: "intellij.statsCollector.completionRanker", version: "0.0.2",
license: "Apache 2.0"),
new LibraryLicense(name: "coverage.py", attachedTo: "intellij.python.helpers", version: "3.7.1", license: "Apache 2.0",
url: "http://coverage.readthedocs.org/"),
@@ -271,7 +273,7 @@ class CommunityLibraryLicenses {
url: "http://www.jcip.net", licenseUrl: "http://creativecommons.org/licenses/by/2.5"),
new LibraryLicense(name: "JDOM", version: "1.1 (with patches by JetBrains)", license: "modified Apache", url: "http://www.jdom.org/",
licenseUrl: "http://www.jdom.org/docs/faq.html#a0030"),
new LibraryLicense(name: "JediTerm", libraryName: "jediterm-pty", version: "2.14", license: "LGPL 3",
new LibraryLicense(name: "JediTerm", libraryName: "jediterm-pty", version: "2.15", license: "LGPL 3",
url: "https://github.com/JetBrains/jediterm",
licenseUrl: "https://github.com/JetBrains/jediterm/blob/master/LICENSE-LGPLv3.txt"),
new LibraryLicense(name: "JetBrains Annotations", libraryName: "jetbrains-annotations", version: "17.0.0", license: "Apache 2.0",
@@ -250,7 +250,6 @@ class CommunityRepositoryModules {
withModule("intellij.statsCollector.features", "features.jar")
withModule("intellij.statsCollector.logEvents")
withModule("intellij.statsCollector.completionRanker")
withResource("features/resources", "lib")
},
]
@@ -77,7 +77,7 @@ class ApplicationStorageManager(application: Application?, pathMacroManager: Pat
override fun providerDataStateChanged(storage: FileBasedStorage, writer: DataWriter?, type: DataStateChanged) {
// IDEA-144052 When "Settings repository" is enabled changes in 'Path Variables' aren't saved to default path.macros.xml file causing errors in build process
if (storage.fileSpec == "path.macros.xml") {
if (storage.fileSpec == "path.macros.xml" || storage.fileSpec == "applicationLibraries.xml") {
LOG.runAndLogException {
writer.writeTo(storage.file)
}
@@ -1,6 +1,7 @@
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.configurationStore.statistic.eventLog
import com.intellij.configurationStore.getDefaultSerializationFilter
import com.intellij.internal.statistic.eventLog.EventLogGroup
import com.intellij.internal.statistic.eventLog.fus.FeatureUsageLogger
import com.intellij.internal.statistic.utils.getProjectId
@@ -8,7 +9,6 @@ import com.intellij.openapi.components.State
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.project.Project
import com.intellij.util.xmlb.BeanBinding
import com.intellij.util.xmlb.SkipDefaultsSerializationFilter
import org.jdom.Element
import java.util.*
@@ -32,12 +32,10 @@ object FeatureUsageSettingsEvents {
}
open class FeatureUsageSettingsEventPrinter(private val recordDefault: Boolean) {
private val defaultFilter = SkipDefaultsSerializationFilter()
fun logDefaultConfigurationState(componentName: String, clazz: Class<*>, project: Project?) {
try {
if (recordDefault) {
val default = defaultFilter.getDefaultValue(clazz)
val default = getDefaultSerializationFilter().getDefaultValue(clazz)
logConfigurationState(componentName, default, project)
}
else {
@@ -68,7 +66,7 @@ open class FeatureUsageSettingsEventPrinter(private val recordDefault: Boolean)
val type = accessor.genericType
if (type === Boolean::class.javaPrimitiveType) {
val value = accessor.read(state)
val isNotDefault = defaultFilter.accepts(accessor, state)
val isNotDefault = getDefaultSerializationFilter().accepts(accessor, state)
if (recordDefault || isNotDefault) {
val content = HashMap<String, Any>()
content["name"] = accessor.name
@@ -223,7 +223,7 @@ public class PerformanceWatcher implements Disposable {
File dir = new File(myLogDir, getFreezeFolderName(myFreezeStart));
if (dir.exists()) {
//noinspection ResultOfMethodCallIgnored
dir.renameTo(new File(myLogDir, dir.getName() + "-" + unresponsiveDuration + "sec" + getFreezePlaceSuffix()));
dir.renameTo(new File(myLogDir, dir.getName() + getFreezePlaceSuffix() + "-" + unresponsiveDuration + "sec"));
}
myPublisher.uiFreezeFinished(unresponsiveDuration);
myFreezeStart = 0;
@@ -30,7 +30,6 @@ import com.intellij.icons.AllIcons;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.actionSystem.ex.ActionUtil;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.application.ReadAction;
import com.intellij.openapi.command.UndoConfirmationPolicy;
import com.intellij.openapi.diff.DiffBundle;
@@ -43,7 +42,6 @@ import com.intellij.openapi.editor.ex.EditorEx;
import com.intellij.openapi.editor.markup.MarkupEditorFilter;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.util.BackgroundTaskUtil;
import com.intellij.openapi.progress.util.ProgressWindow;
import com.intellij.openapi.project.DumbAware;
@@ -407,22 +405,18 @@ public class TextMergeViewer implements MergeTool.MergeViewer {
myLoadingPanel.startLoading();
myAcceptResolveAction.setEnabled(false);
BackgroundTaskUtil.executeOnPooledThread(this, () -> {
ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
Runnable callback;
BackgroundTaskUtil.executeAndTryWait(indicator -> BackgroundTaskUtil.runUnderDisposeAwareIndicator(this, () -> {
try {
callback = doPerformRediff(indicator);
return doPerformRediff(indicator);
}
catch (ProcessCanceledException e) {
callback = () -> myMergeContext.finishMerge(MergeResult.CANCEL);
return () -> myMergeContext.finishMerge(MergeResult.CANCEL);
}
catch (Throwable e) {
LOG.error(e);
callback = () -> myMergeContext.finishMerge(MergeResult.CANCEL);
return () -> myMergeContext.finishMerge(MergeResult.CANCEL);
}
ApplicationManager.getApplication().invokeLater(callback, ModalityState.stateForComponent(myPanel));
});
}), null, ProgressWindow.DEFAULT_PROGRESS_DIALOG_POSTPONE_TIME_MILLIS, ApplicationManager.getApplication().isUnitTestMode());
}
@NotNull
@@ -32,7 +32,7 @@ import org.jetbrains.annotations.NotNull;
import java.util.BitSet;
public abstract class IdFilter {
public static final Logger LOG = Logger.getInstance("#com.intellij.ide.util.gotoByName.DefaultFileNavigationContributor");
private static final Logger LOG = Logger.getInstance(IdFilter.class);
private static final Key<CachedValue<IdFilter>> INSIDE_PROJECT = Key.create("INSIDE_PROJECT");
private static final Key<CachedValue<IdFilter>> OUTSIDE_PROJECT = Key.create("OUTSIDE_PROJECT");
@@ -64,7 +64,8 @@ public abstract class IdFilter {
}
if (LOG.isDebugEnabled()) {
LOG.debug("Done filter " + (System.currentTimeMillis() -started) + ":" + idSet.size());
long elapsed = System.currentTimeMillis() - started;
LOG.debug("Done filter in " + elapsed + "ms. Total files in set: " + idSet.cardinality());
}
return new IdFilter() {
@Override
@@ -334,6 +334,7 @@ public class CommonCodeStyleSettings {
@Retention(RetentionPolicy.RUNTIME)
public @interface BraceStyleConstant {}
@Property(externalName = "block_brace_style")
@BraceStyleConstant public int BRACE_STYLE = END_OF_LINE;
@BraceStyleConstant public int CLASS_BRACE_STYLE = END_OF_LINE;
@BraceStyleConstant public int METHOD_BRACE_STYLE = END_OF_LINE;
@@ -63,7 +63,7 @@ public abstract class CodeStyleAbstractPanel implements Disposable, ComponentHig
private final List<TextRange> myPreviewRangesToHighlight = new ArrayList<>();
private final EditorEx myEditor;
private final Editor myEditor;
private final CodeStyleSettings mySettings;
private boolean myShouldUpdatePreview;
protected static final int[] ourWrappings =
@@ -133,7 +133,7 @@ public abstract class CodeStyleAbstractPanel implements Disposable, ComponentHig
}
@Nullable
private EditorEx createEditor() {
private Editor createEditor() {
if (StringUtil.isEmpty(getPreviewText())) return null;
EditorFactory editorFactory = EditorFactory.getInstance();
Document editorDocument = editorFactory.createDocument("");
@@ -166,6 +166,7 @@ public abstract class CodeStyleAbstractPanel implements Disposable, ComponentHig
return;
}
Project project = ProjectUtil.guessCurrentProject(getPanel());
if (myEditor.isDisposed()) return;
if (myLastDocumentModificationStamp != myEditor.getDocument().getModificationStamp()) {
@@ -175,19 +176,8 @@ public abstract class CodeStyleAbstractPanel implements Disposable, ComponentHig
myTextToReformat = StringUtil.convertLineSeparators(ObjectUtils.notNull(getPreviewText(), ""));
}
updateEditorState(true);
}
protected void setEditorText(@NotNull String text, boolean updateHighlighter) {
myTextToReformat = StringUtil.convertLineSeparators(text);
if (updateHighlighter) updatePreviewHighlighter(myEditor);
updateEditorState(false);
}
private void updateEditorState(boolean collectChanges) {
int currOffs = myEditor.getScrollingModel().getVerticalScrollOffset();
Project project = ProjectUtil.guessCurrentProject(getPanel());
CommandProcessor.getInstance().executeCommand(project, () -> replaceText(project, collectChanges), null, null);
CommandProcessor.getInstance().executeCommand(project, () -> replaceText(project), null, null);
myEditor.getSettings().setRightMargin(getAdjustedRightMargin());
myLastDocumentModificationStamp = myEditor.getDocument().getModificationStamp();
@@ -201,11 +191,11 @@ public abstract class CodeStyleAbstractPanel implements Disposable, ComponentHig
protected abstract int getRightMargin();
private void replaceText(final Project project, boolean collectChanges) {
private void replaceText(final Project project) {
ApplicationManager.getApplication().runWriteAction(() -> {
try {
Document beforeReformat = null;
if (collectChanges && myEditor.getDocument().getTextLength() > 0) {
if (myEditor.getDocument().getTextLength() > 0) {
beforeReformat = collectChangesBeforeCurrentSettingsAppliance(project);
}
@@ -603,13 +593,7 @@ public abstract class CodeStyleAbstractPanel implements Disposable, ComponentHig
protected CodeStyleSettings getCurrentSettings() {
return myCurrentSettings;
}
@Nullable
protected CodeStyleSettings getModelSettings() {
CodeStyleSchemesModel model = myModel;
return model != null ? model.getCloneSettings(model.getSelectedScheme()) : null;
}
public void setupCopyFromMenu(JPopupMenu copyMenu) {
copyMenu.removeAll();
}
@@ -1,5 +1,4 @@
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeEditor.printing;
import com.intellij.openapi.project.Project;
@@ -8,6 +7,7 @@ import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.ui.FontComboBox;
import com.intellij.ui.IdeBorderFactory;
import com.intellij.ui.TabbedPaneWrapper;
import com.intellij.util.ObjectUtils;
import com.intellij.util.ui.JBUI;
import org.jetbrains.annotations.NotNull;
@@ -15,7 +15,6 @@ import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Objects;
class PrintDialog extends DialogWrapper {
private JRadioButton myRbCurrentFile = null;
@@ -561,7 +560,7 @@ class PrintDialog extends DialogWrapper {
printSettings.PORTRAIT_LAYOUT = myRbPortrait.isSelected();
printSettings.FONT_NAME = myFontNameCombo.getFontName();
printSettings.FONT_SIZE = (Integer)Objects.requireNonNull(myFontSizeCombo.getSelectedItem());
printSettings.FONT_SIZE = ObjectUtils.notNull((Integer)myFontSizeCombo.getSelectedItem(), printSettings.FONT_SIZE);
printSettings.PRINT_LINE_NUMBERS = myCbLineNumbers.isSelected();
@@ -600,7 +599,8 @@ class PrintDialog extends DialogWrapper {
printSettings.FOOTER_HEADER_PLACEMENT2 = (PrintSettings.Placement)myLinePlacementCombo2.getSelectedItem();
printSettings.FOOTER_HEADER_FONT_NAME = myFooterFontNameCombo.getFontName();
printSettings.FOOTER_HEADER_FONT_SIZE = (Integer)Objects.requireNonNull(myFooterFontSizeCombo.getSelectedItem());
printSettings.FOOTER_HEADER_FONT_SIZE =
ObjectUtils.notNull((Integer)myFooterFontSizeCombo.getSelectedItem(), printSettings.FOOTER_HEADER_FONT_SIZE);
}
@NotNull
@@ -2,6 +2,7 @@
package com.intellij.codeInsight;
import com.intellij.codeInsight.editorActions.SmartBackspaceMode;
import com.intellij.configurationStore.XmlSerializer;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
@@ -15,9 +16,7 @@ import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.util.ArrayUtil;
import com.intellij.util.ReflectionUtil;
import com.intellij.util.xmlb.SkipDefaultValuesSerializationFilters;
import com.intellij.util.xmlb.XmlSerializationException;
import com.intellij.util.xmlb.XmlSerializer;
import com.intellij.util.xmlb.annotations.OptionTag;
import com.intellij.util.xmlb.annotations.Property;
import com.intellij.util.xmlb.annotations.Transient;
@@ -121,12 +120,12 @@ public class CodeInsightSettings implements PersistentStateComponent<Element>, C
@OptionTag("SMART_BACKSPACE") // explicit name makes it work also for obfuscated private field's name
private int SMART_BACKSPACE = SmartBackspaceMode.AUTOINDENT.ordinal();
@Transient
@NotNull
public SmartBackspaceMode getBackspaceMode() {
SmartBackspaceMode[] values = SmartBackspaceMode.values();
return SMART_BACKSPACE >= 0 && SMART_BACKSPACE < values.length ? values[SMART_BACKSPACE] : SmartBackspaceMode.OFF;
return SMART_BACKSPACE >= 0 && SMART_BACKSPACE < values.length ? values[SMART_BACKSPACE] : SmartBackspaceMode.OFF;
}
@Transient
@@ -197,7 +196,7 @@ public class CodeInsightSettings implements PersistentStateComponent<Element>, C
setDefaults();
try {
XmlSerializer.deserializeInto(this, state);
XmlSerializer.deserializeInto(state, this);
}
catch (XmlSerializationException e) {
LOG.info(e);
@@ -228,9 +227,9 @@ public class CodeInsightSettings implements PersistentStateComponent<Element>, C
return element;
}
public void writeExternal(final Element element) {
public void writeExternal(@NotNull Element element) {
try {
XmlSerializer.serializeInto(this, element, new SkipDefaultValuesSerializationFilters());
XmlSerializer.serializeObjectInto(this, element);
}
catch (XmlSerializationException e) {
LOG.info(e);
@@ -243,4 +242,4 @@ public class CodeInsightSettings implements PersistentStateComponent<Element>, C
if (o == null || getClass() != o.getClass()) return false;
return ReflectionUtil.comparePublicNonFinalFields(this, o);
}
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2017 JetBrains s.r.o.
* Copyright 2000-2019 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,8 +29,9 @@ import org.jetbrains.annotations.NotNull;
* An extension controlling aspects of Live Template insertion, like reformatting, adding imports, etc. {@link #getOptionName()} allows
* to show a checkbox to enable/disable specific such aspect in Live Template settings, {@link #processText} does the actual
* modifications during live template expansion.<p/>
*
* <p>
* During indexing, {@link #processText} is executed only for instances implementing {@link com.intellij.openapi.project.DumbAware}.
*
* @author yole
*/
public interface TemplateOptionalProcessor {
@@ -41,10 +42,14 @@ public interface TemplateOptionalProcessor {
* Note that this happens even if the corresponding option is disabled, so the implementations
* should check themselves whether they have to perform any actions.
*/
void processText(final Project project, final Template template, final Document document, final RangeMarker templateRange, final Editor editor);
void processText(final Project project,
final Template template,
final Document document,
final RangeMarker templateRange,
final Editor editor);
/**
* @return the text of a checkbox in Live Template settings controlling whether this option is enaled.
* @return the text of a checkbox in Live Template settings controlling whether this option is enabled.
*/
@Nls
String getOptionName();
@@ -832,11 +832,13 @@ public class TemplateState implements Disposable {
int start = mySegments.getSegmentStart(segmentNumber);
int end = mySegments.getSegmentEnd(segmentNumber);
PsiDocumentManager.getInstance(myProject).commitDocument(myDocument);
if(!isQuick) {
PsiDocumentManager.getInstance(myProject).commitDocument(myDocument);
}
PsiFile psiFile = getPsiFile();
PsiElement element = psiFile != null ? psiFile.findElementAt(start) : null;
if (element != null) {
PsiUtilCore.ensureValid(element);
if (element != null && !element.isValid()) {
element = null;
}
ExpressionContext context = createExpressionContext(start);
@@ -858,8 +860,8 @@ public class TemplateState implements Disposable {
if (defaultValue != null && resultIsNullOrEmpty) {
result = defaultValue.calculateResult(context);
}
if (element != null) {
PsiUtilCore.ensureValid(element);
if (element != null && !element.isValid()) {
element = null;
}
if (result == null || result.equalsToText(oldValue, element)) return;
@@ -34,6 +34,7 @@ import com.intellij.psi.PsiManager;
import com.intellij.psi.search.GlobalSearchScopesCore;
import com.intellij.psi.search.scope.packageSet.NamedScope;
import com.intellij.psi.search.scope.packageSet.NamedScopesHolder;
import com.intellij.util.PathUtil;
import com.intellij.util.containers.ContainerUtilRt;
import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;
import org.jdom.JDOMException;
@@ -117,7 +118,7 @@ public class InspectionApplication {
Disposable disposable = Disposer.newDisposable();
try {
run(FileUtilRt.toSystemIndependentName(myProjectPath), disposable);
run(FileUtilRt.toSystemIndependentName(PathUtil.getCanonicalPath(myProjectPath)), disposable);
}
finally {
Disposer.dispose(disposable);
@@ -1,21 +1,7 @@
/*
* Copyright 2000-2017 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.
*/
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.execution.ui.layout.impl;
import com.intellij.configurationStore.XmlSerializer;
import com.intellij.execution.ui.layout.LayoutAttractionPolicy;
import com.intellij.execution.ui.layout.PlaceInGrid;
import com.intellij.execution.ui.layout.Tab;
@@ -25,8 +11,6 @@ import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.ui.content.Content;
import com.intellij.util.containers.hash.LinkedHashMap;
import com.intellij.util.xmlb.SkipDefaultValuesSerializationFilters;
import com.intellij.util.xmlb.XmlSerializer;
import org.jdom.Element;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
@@ -38,7 +22,6 @@ import java.util.*;
public class RunnerLayout {
public static final Key<Integer> DEFAULT_INDEX = Key.create("RunnerLayoutDefaultIndex");
public static final Key<Integer> DROP_INDEX = Key.create("RunnerLayoutDropIndex");
private final String myID;
protected Map<String, ViewImpl> myViews = new LinkedHashMap<>();
private final Map<String, ViewImpl.Default> myDefaultViews = new HashMap<>();
@@ -50,11 +33,6 @@ public class RunnerLayout {
private final Map<String, Pair<String, LayoutAttractionPolicy>> myDefaultFocus = new HashMap<>();
private Set<String> myLightWeightIds = null;
public RunnerLayout(@NotNull String ID) {
myID = ID;
}
@Nullable
public String getDefaultDisplayName(final int defaultIndex) {
final TabImpl.Default tab = myDefaultTabs.get(defaultIndex);
@@ -132,17 +110,19 @@ public class RunnerLayout {
List<Element> tabs = parentNode.getChildren(StringUtil.getShortName(TabImpl.class.getName()));
for (Element eachTabElement : tabs) {
TabImpl eachTab = XmlSerializer.deserialize(eachTabElement, TabImpl.class);
XmlSerializer.deserializeInto(getOrCreateTab(eachTab.getIndex()), eachTabElement);
XmlSerializer.deserializeInto(eachTabElement, getOrCreateTab(eachTab.getIndex()));
}
final List views = parentNode.getChildren(StringUtil.getShortName(ViewImpl.class.getName()));
for (Object content : views) {
final ViewImpl state = new ViewImpl(this, (Element)content);
myViews.put(state.getID(), state);
final List<Element> views = parentNode.getChildren(StringUtil.getShortName(ViewImpl.class.getName()));
for (Element content : views) {
final ViewImpl view = new ViewImpl();
XmlSerializer.deserializeInto(content, view);
view.assignTab(getOrCreateTab(view.getTabIndex()));
myViews.put(view.getID(), view);
}
XmlSerializer.deserializeInto(myGeneral, parentNode.getChild(StringUtil.getShortName(myGeneral.getClass().getName(), '$')));
Element general = parentNode.getChild(StringUtil.getShortName(myGeneral.getClass().getName(), '$'));
XmlSerializer.deserializeInto(general == null ? new Element("state") : general, myGeneral);
return parentNode;
}
@@ -152,22 +132,25 @@ public class RunnerLayout {
if (myLightWeightIds != null && myLightWeightIds.contains(eachState.getID())) {
continue;
}
parentNode.addContent(XmlSerializer.serialize(eachState));
Element element = XmlSerializer.serialize(eachState);
parentNode.addContent(element == null ? new Element("ViewImpl") : element);
}
SkipDefaultValuesSerializationFilters filter = new SkipDefaultValuesSerializationFilters();
for (TabImpl eachTab : myTabs) {
if (isUsed(eachTab)) {
parentNode.addContent(XmlSerializer.serialize(eachTab, filter));
Element element = XmlSerializer.serialize(eachTab);
parentNode.addContent(element == null ? new Element("TabImpl") : element);
}
}
parentNode.addContent(XmlSerializer.serialize(myGeneral, filter));
Element generalContent = XmlSerializer.serialize(myGeneral);
if (generalContent != null) {
parentNode.addContent(generalContent);
}
return parentNode;
}
public void resetToDefault() {
myViews.clear();
myTabs.clear();

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