Merge remote-tracking branch 'origin/master'

This commit is contained in:
Ekaterina Tuzova
2012-10-02 15:06:41 +04:00
1152 changed files with 22838 additions and 22264 deletions
+4
View File
@@ -25,6 +25,10 @@
<processorPath useClasspath="true" />
</profile>
</annotationProcessing>
<bytecodeTargetLevel target="1.6">
<module name="groovy_rt" target="1.5" />
<module name="javac2" target="1.5" />
</bytecodeTargetLevel>
</component>
<component name="EclipseCompilerSettings">
<option name="GENERATE_NO_WARNINGS" value="true" />
-1
View File
@@ -1,7 +1,6 @@
<component name="libraryTable">
<library name="Mac">
<CLASSES>
<root url="jar://$PROJECT_DIR$/build/conf/mac/lib/quaqua.jar!/" />
<root url="jar://$PROJECT_DIR$/lib/eawtstub.jar!/" />
</CLASSES>
<JAVADOC />
+2 -2
View File
@@ -1,11 +1,11 @@
<component name="libraryTable">
<library name="Netty">
<CLASSES>
<root url="jar://$PROJECT_DIR$/lib/netty-3.5.5.Final.jar!/" />
<root url="jar://$PROJECT_DIR$/lib/netty-3.5.7.Final.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES>
<root url="jar://$PROJECT_DIR$/lib/src/netty-3.5.5.Final-sources.jar!/" />
<root url="jar://$PROJECT_DIR$/lib/src/netty-3.5.7.Final-sources.jar!/" />
</SOURCES>
</library>
</component>
+1 -1
View File
@@ -45,7 +45,6 @@
<module fileurl="file://$PROJECT_DIR$/java/compiler/forms-compiler/forms-compiler.iml" filepath="$PROJECT_DIR$/java/compiler/forms-compiler/forms-compiler.iml" group="java/compiler" />
<module fileurl="file://$PROJECT_DIR$/platform/forms_rt/forms_rt.iml" filepath="$PROJECT_DIR$/platform/forms_rt/forms_rt.iml" group="platform" />
<module fileurl="file://$PROJECT_DIR$/plugins/generate-tostring/generate-tostring.iml" filepath="$PROJECT_DIR$/plugins/generate-tostring/generate-tostring.iml" group="plugins" />
<module fileurl="file://$PROJECT_DIR$/plugins/gettext/gettext.iml" filepath="$PROJECT_DIR$/plugins/gettext/gettext.iml" group="plugins" />
<module fileurl="file://$PROJECT_DIR$/plugins/git4idea/git4idea.iml" filepath="$PROJECT_DIR$/plugins/git4idea/git4idea.iml" group="plugins/VCS" />
<module fileurl="file://$PROJECT_DIR$/plugins/git4idea/rt/git4idea-rt.iml" filepath="$PROJECT_DIR$/plugins/git4idea/rt/git4idea-rt.iml" group="plugins/VCS" />
<module fileurl="file://$PROJECT_DIR$/plugins/github/github.iml" filepath="$PROJECT_DIR$/plugins/github/github.iml" group="plugins" />
@@ -89,6 +88,7 @@
<module fileurl="file://$PROJECT_DIR$/platform/lvcs-api/lvcs-api.iml" filepath="$PROJECT_DIR$/platform/lvcs-api/lvcs-api.iml" group="platform" />
<module fileurl="file://$PROJECT_DIR$/platform/lvcs-impl/lvcs-impl.iml" filepath="$PROJECT_DIR$/platform/lvcs-impl/lvcs-impl.iml" group="platform" />
<module fileurl="file://$PROJECT_DIR$/plugins/maven/maven.iml" filepath="$PROJECT_DIR$/plugins/maven/maven.iml" group="plugins" />
<module fileurl="file://$PROJECT_DIR$/plugins/maven/jps-plugin/maven-jps-plugin.iml" filepath="$PROJECT_DIR$/plugins/maven/jps-plugin/maven-jps-plugin.iml" group="plugins" />
<module fileurl="file://$PROJECT_DIR$/plugins/maven/maven-server-api/maven-server-api.iml" filepath="$PROJECT_DIR$/plugins/maven/maven-server-api/maven-server-api.iml" group="plugins" />
<module fileurl="file://$PROJECT_DIR$/plugins/maven/maven2-server-impl/maven2-server-impl.iml" filepath="$PROJECT_DIR$/plugins/maven/maven2-server-impl/maven2-server-impl.iml" group="plugins" />
<module fileurl="file://$PROJECT_DIR$/plugins/maven/maven3-server-impl/maven3-server-impl.iml" filepath="$PROJECT_DIR$/plugins/maven/maven3-server-impl/maven3-server-impl.iml" group="plugins" />
@@ -1,7 +1,6 @@
<idea-plugin>
<extensionPoints>
<extensionPoint name="regExpLanguageHost" beanClass="com.intellij.openapi.util.ClassExtensionPoint"/>
<extensionPoint qualifiedName="com.intellij.regExpRangeProvider" interface="org.intellij.lang.regexp.RegExpRangeProvider"/>
</extensionPoints>
<extensions defaultExtensionNs="com.intellij">
<lang.documentationProvider language="RegExp" implementationClass="org.intellij.lang.regexp.RegExpDocumentationProvider"/>
@@ -17,6 +17,7 @@ package org.intellij.lang.regexp;
import com.intellij.openapi.editor.colors.TextAttributesKey;
import com.intellij.openapi.fileTypes.SyntaxHighlighter;
import com.intellij.openapi.fileTypes.SyntaxHighlighterFactory;
import com.intellij.openapi.options.colors.AttributesDescriptor;
import com.intellij.openapi.options.colors.ColorDescriptor;
import com.intellij.openapi.options.colors.ColorSettingsPage;
@@ -69,7 +70,7 @@ public class RegExpColorsPage implements ColorSettingsPage {
@NotNull
public SyntaxHighlighter getHighlighter() {
final SyntaxHighlighter highlighter = SyntaxHighlighter.PROVIDER.create(RegExpFileType.INSTANCE, null, null);
final SyntaxHighlighter highlighter = SyntaxHighlighterFactory.getSyntaxHighlighter(RegExpFileType.INSTANCE, null, null);
assert highlighter != null;
return highlighter;
}
@@ -28,9 +28,7 @@ import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.util.PsiUtilBase;
import org.intellij.lang.regexp.RegExpLanguage;
import org.intellij.lang.regexp.RegExpRangeProvider;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
@@ -41,21 +39,6 @@ import javax.swing.*;
*/
public class CheckRegExpIntentionAction extends QuickEditAction implements Iconable {
@Override
protected Pair<PsiElement, TextRange> getRangePair(PsiFile file, Editor editor) {
Pair<PsiElement, TextRange> pair = super.getRangePair(file, editor);
if (pair == null) {
RegExpRangeProvider[] rangeProviders = RegExpRangeProvider.EP_NAME.getExtensions();
PsiElement element = PsiUtilBase.getElementAtCaret(editor);
for (RegExpRangeProvider provider : rangeProviders) {
pair = provider.getRangePair(element);
if (pair != null) break;
}
}
return pair;
}
@Override
public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
final Pair<PsiElement, TextRange> pair = getRangePair(file, editor);
Binary file not shown.
Binary file not shown.
+22 -3
View File
@@ -1,3 +1,18 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import static org.jetbrains.jps.idea.IdeaProjectLoader.guessHome
includeTargets << new File("${guessHome(this)}/build/scripts/utils.gant")
@@ -5,22 +20,26 @@ includeTargets << new File("${guessHome(this)}/build/scripts/utils.gant")
requireProperty("out", "$home/out/classes")
target(compile: "Compile project") {
ant.delete(failonerror: false) {
fileset(dir: "$home/reports")
fileset(dir: "$home/bin", includes: "*.hprof")
}
loadProject()
projectBuilder.useInProcessJavac = true
projectBuilder.targetFolder = out
ant.delete(dir: "$home/reports")
projectBuilder.cleanOutput()
projectBuilder.buildAll()
}
def pass(String prop) {
private pass(String prop) {
if (isDefined(prop)) {
ant.jvmarg(value: "-D$prop=${p(prop)}")
}
}
target('default': 'The default target') {
depends(compile)
depends([compile])
ant.junit(fork: "yes", showoutput: "true", logfailedtests:false) {
pass("idea.test.group")
+5
View File
@@ -222,6 +222,11 @@ public def layoutCommunityPlugins(String home) {
}
layoutPlugin("maven") {
dir("jps") {
jar("maven-jps-plugin.jar") {
module("maven-jps-plugin")
}
}
jar("maven-server-api.jar") {
module("maven-server-api")
}
+2 -2
View File
@@ -211,7 +211,6 @@ libraryLicense(name: "Eclipse JDT Core", libraryName: "Eclipse", version: "4.2",
libraryLicense(name: "Jakarta ORO", libraryName: "OroMatcher", version: "2.0.8", license: "Apache", url: "http://jakarta.apache.org/oro/", licenseUrl: "http://svn.apache.org/repos/asf/jakarta/oro/trunk/LICENSE")
libraryLicense(name: "PicoContainer", libraryName: "picocontainer", version: "1.2", license: "BSD", url: "http://www.picocontainer.org/", licenseUrl: "http://docs.codehaus.org/display/PICO/License")
libraryLicense(name: "Plexus Utils", libraryName: "plexus-utils-1.5.5.jar", version: "1.5.5", license: "Apache 2.0", url: "http://plexus.codehaus.org/plexus-utils")
libraryLicense(name: "Quaqua L&F", attachedTo: "platform-impl", version: "6.2", license: "BSD", url: "http://www.randelshofer.ch/quaqua/", licenseUrl: "http://www.randelshofer.ch/quaqua/license.html")
libraryLicense(name: "Relax NG Object Model", libraryName: "rngom-20051226-patched.jar", license: "MIT", url: "http://java.net/projects/rngom/", licenseUrl: "http://www.opensource.org/licenses/mit-license.php")
libraryLicense(name: "RMI Stubs", attachedTo: "xslt-debugger-engine", license: "Apache 2.0", url: "http://confluence.jetbrains.net/display/CONTEST/XSLT-Debugger", licenseUrl: "http://www.apache.org/licenses/LICENSE-2.0")
libraryLicense(name: "Saxon-9HE", version: "9", license: "Mozilla Public License", url: "http://saxon.sourceforge.net/", licenseUrl: "http://www.mozilla.org/MPL/")
@@ -234,11 +233,12 @@ libraryLicense(name: "XML-RPC", libraryName: "XmlRPC", version: "2.0", license:
libraryLicense(name: "XStream", version: "1.2.1", license: "BSD", url: "http://xstream.codehaus.org/", licenseUrl: "http://xstream.codehaus.org/license.html")
libraryLicense(name: "YourKit Java Profiler", libraryName: "yjp-controller-api-redist.jar", version: "8.0.x", license: "link (commercial license)", url: "http://yourkit.com/", licenseUrl: "http://www.yourkit.com/purchase/license.html")
libraryLicense(name: "protobuf", version: "2.3.0", license: "New BSD", url: "http://code.google.com/p/protobuf/", licenseUrl: "http://code.google.com/p/protobuf/source/browse/trunk/COPYING.txt?r=367")
libraryLicense(name: "Netty", libraryName: "Netty", version: "3.5.5", license: "Apache 2.0", url: "http://netty.io", licenseUrl: "http://www.apache.org/licenses/LICENSE-2.0")
libraryLicense(name: "Netty", libraryName: "Netty", version: "3.5.7", license: "Apache 2.0", url: "http://netty.io", licenseUrl: "http://www.apache.org/licenses/LICENSE-2.0")
libraryLicense(name: "Kryo", libraryName: "Kryo", version: "1.04", license: "New BSD License", url: "http://code.google.com/p/kryo/", licenseUrl: "http://www.opensource.org/licenses/bsd-license.php")
libraryLicense(name: "Snappy-Java", libraryName: "Snappy-Java", version: "1.0.4.1", license: "Apache 2.0", url: "http://code.google.com/p/snappy-java/", licenseUrl: "http://www.apache.org/licenses/LICENSE-2.0")
libraryLicense(name: "Cucumber-JVM", libraryName: "cucumber-jvm", version: "1.0.11", license: "MIT License", url: "https://github.com/cucumber/cucumber-jvm/", licenseUrl: "http://www.opensource.org/licenses/mit-license.html")
libraryLicense(name: "Cucumber-Groovy", libraryName: "cucumber-groovy", version: "1.0.14", license: "MIT License", url: "https://github.com/cucumber/cucumber-jvm/", licenseUrl: "http://www.opensource.org/licenses/mit-license.html")
libraryLicense(name: "Mantis", libraryName: "mantis", license: "GNU General Public License, version 2", url: "https://github.com/rombert/mantis-axis-soap-client")
jetbrainsLibrary("JPS")
jetbrainsLibrary("Maven Embedder")
jetbrainsLibrary("tcServiceMessages")
@@ -87,7 +87,7 @@ public class ImageFileEditorState implements TransferableFileEditorState, Serial
o = options.get(ZOOM_FACTOR_OPTION);
if (o != null) {
zoomFactor = Double.valueOf(o);
zoomFactor = Double.parseDouble(o);
}
}
}
+1
View File
@@ -25,6 +25,7 @@
<orderEntry type="module" module-name="jps-builders" />
<orderEntry type="library" name="Netty" level="project" />
<orderEntry type="module" module-name="testFramework-java" scope="TEST" />
<orderEntry type="library" name="Jasper2.1" level="project" />
</component>
<component name="copyright">
<Base>
@@ -16,7 +16,7 @@
package com.intellij.compiler.ant;
import com.intellij.compiler.ant.taskdefs.*;
import com.intellij.compiler.impl.javaCompiler.javac.JavacSettings;
import com.intellij.compiler.impl.javaCompiler.javac.JavacConfiguration;
import com.intellij.openapi.compiler.CompilerBundle;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ex.ProjectEx;
@@ -31,6 +31,7 @@ import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFileManager;
import org.jetbrains.jps.model.java.compiler.JpsJavaCompilerOptions;
import java.io.File;
import java.io.IOException;
@@ -48,7 +49,7 @@ public class BuildPropertiesImpl extends BuildProperties {
//noinspection HardCodedStringLiteral
add(new Comment(CompilerBundle.message("generated.ant.build.disable.tests.property.comment"),
new Property(PROPERTY_SKIP_TESTS, "true")));
final JavacSettings javacSettings = JavacSettings.getInstance(project);
final JpsJavaCompilerOptions javacSettings = JavacConfiguration.getOptions(project, JavacConfiguration.class);
add(new Comment(CompilerBundle.message("generated.ant.build.compiler.options.comment")), 1);
//noinspection HardCodedStringLiteral
add(new Property(PROPERTY_COMPILER_GENERATE_DEBUG_INFO, javacSettings.DEBUGGING_INFO ? "on" : "off"), 1);
@@ -163,9 +163,6 @@ public class GenerationOptionsImpl extends GenerationOptions {
@Override
public String subsitutePathWithMacros(String path) {
if (myMacroReplacementMap.size() == 0) {
return path; // optimization
}
return myMacroReplacementMap.substitute(path, SystemInfo.isFileSystemCaseSensitive);
}
@@ -106,6 +106,10 @@ public class CompileContextImpl extends UserDataHolderBase implements CompileCon
myShouldUpdateProblemsView = workspaceConfig.useOutOfProcessBuild() && workspaceConfig.MAKE_PROJECT_ON_SAVE;
}
public boolean shouldUpdateProblemsView() {
return myShouldUpdateProblemsView;
}
public void recalculateOutputDirs() {
final Module[] allModules = ModuleManager.getInstance(myProject).getModules();
@@ -449,9 +449,11 @@ public class CompileDriver {
@Override
public void sessionTerminated(UUID sessionId) {
final ProblemsView view = ProblemsViewImpl.SERVICE.getInstance(myProject);
view.clearProgress();
view.clearOldMessages(compileContext.getCompileScope(), sessionId);
if (compileContext.shouldUpdateProblemsView()) {
final ProblemsView view = ProblemsViewImpl.SERVICE.getInstance(myProject);
view.clearProgress();
view.clearOldMessages(compileContext.getCompileScope(), sessionId);
}
}
@Override
@@ -635,14 +637,12 @@ public class CompileDriver {
CompilerCacheManager.getInstance(myProject).flushCaches();
if (ApplicationManager.getApplication().isUnitTestMode()) {
// need this for tests only;
final Set<File> outputs = new HashSet<File>();
for (final String path : CompilerPathsEx.getOutputPaths(ModuleManager.getInstance(myProject).getModules())) {
outputs.add(new File(path));
}
CompilerUtil.refreshIOFiles(outputs);
// refresh on output roots is required in order for the order enumerator to see all roots via VFS
final Set<File> outputs = new HashSet<File>();
for (final String path : CompilerPathsEx.getOutputPaths(ModuleManager.getInstance(myProject).getModules())) {
outputs.add(new File(path));
}
CompilerUtil.refreshIOFiles(outputs);
}
}
};
@@ -20,7 +20,6 @@ import com.intellij.compiler.impl.javaCompiler.BackendCompiler;
import com.intellij.compiler.impl.javaCompiler.ModuleChunk;
import com.intellij.compiler.impl.javaCompiler.javac.JavacCompiler;
import com.intellij.compiler.impl.javaCompiler.javac.JavacConfigurable;
import com.intellij.compiler.impl.javaCompiler.javac.JavacSettings;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.compiler.CompileContext;
import com.intellij.openapi.compiler.CompileScope;
@@ -74,7 +73,7 @@ public class CompilerAPICompiler implements BackendCompiler {
@NotNull
public Configurable createConfigurable() {
return new JavacConfigurable(CompilerAPIConfiguration.getSettings(myProject, CompilerAPIConfiguration.class));
return new JavacConfigurable(CompilerAPIConfiguration.getOptions(myProject, CompilerAPIConfiguration.class));
}
@NotNull
@@ -107,9 +106,8 @@ public class CompilerAPICompiler implements BackendCompiler {
public List<String> compute() {
try {
List<String> commandLine = new ArrayList<String>();
JavacSettings javacSettings = CompilerAPIConfiguration.getSettings(myProject, CompilerAPIConfiguration.class);
final List<String> additionalOptions =
JavacCompiler.addAdditionalSettings(commandLine, javacSettings, false, JavaSdkVersion.JDK_1_6, chunk, compileContext.isAnnotationProcessorsEnabled());
JavacCompiler.addAdditionalSettings(commandLine, CompilerAPIConfiguration.getOptions(myProject, CompilerAPIConfiguration.class), false, JavaSdkVersion.JDK_1_6, chunk, compileContext.isAnnotationProcessorsEnabled());
JavacCompiler.addCommandLineOptions(chunk, commandLine, outputDir, chunk.getJdk(), false,false, null, false, false, false);
commandLine.addAll(additionalOptions);
@@ -19,7 +19,6 @@ import com.intellij.compiler.OutputParser;
import com.intellij.compiler.impl.CompilerUtil;
import com.intellij.compiler.impl.javaCompiler.ExternalCompiler;
import com.intellij.compiler.impl.javaCompiler.ModuleChunk;
import com.intellij.compiler.impl.javaCompiler.javac.JavacSettings;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.PathManager;
import com.intellij.openapi.compiler.CompileContext;
@@ -39,6 +38,7 @@ import com.intellij.util.ArrayUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.jps.model.java.compiler.EclipseCompilerOptions;
import java.io.*;
import java.util.ArrayList;
@@ -113,7 +113,7 @@ public class EclipseCompiler extends ExternalCompiler {
@NotNull
public Configurable createConfigurable() {
return new EclipseCompilerConfigurable(EclipseCompilerConfiguration.getSettings(myProject, EclipseCompilerConfiguration.class));
return new EclipseCompilerConfigurable(EclipseCompilerConfiguration.getOptions(myProject, EclipseCompilerConfiguration.class));
}
public OutputParser createErrorParser(@NotNull final String outputDir, Process process) {
@@ -151,12 +151,12 @@ public class EclipseCompiler extends ExternalCompiler {
@NonNls final ArrayList<String> commandLine,
final String outputPath,
final boolean useTempFile) throws IOException {
JavacSettings compilerSettings = EclipseCompilerConfiguration.getSettings(myProject, EclipseCompilerConfiguration.class);
final EclipseCompilerOptions options = EclipseCompilerConfiguration.getOptions(myProject, EclipseCompilerConfiguration.class);
final Sdk projectJdk = JavaAwareProjectJdkTableImpl.getInstanceEx().getInternalJdk();
final String vmExePath = ((JavaSdkType)projectJdk.getSdkType()).getVMExecutablePath(projectJdk);
commandLine.add(vmExePath);
commandLine.add("-Xmx" + compilerSettings.MAXIMUM_HEAP_SIZE + "m");
commandLine.add("-Xmx" + options.MAXIMUM_HEAP_SIZE + "m");
CompilerUtil.addLocaleOptions(commandLine, false);
@@ -164,13 +164,13 @@ public class EclipseCompiler extends ExternalCompiler {
commandLine.add(PATH_TO_COMPILER_JAR);
commandLine.add(getCompilerClass());
addCommandLineOptions(commandLine, chunk, outputPath, compilerSettings, useTempFile, true);
addCommandLineOptions(commandLine, chunk, outputPath, options, useTempFile, true);
}
public void addCommandLineOptions(@NotNull @NonNls final List<String> commandLine,
@NotNull final ModuleChunk chunk,
@NotNull final String outputPath,
@NotNull final JavacSettings compilerSettings,
@NotNull final EclipseCompilerOptions options,
final boolean useTempFile,
boolean quoteBootClasspath) throws IOException {
final Sdk jdk = chunk.getJdk();
@@ -196,7 +196,7 @@ public class EclipseCompiler extends ExternalCompiler {
commandLine.add(outputPath.replace('/', File.separatorChar));
commandLine.add("-verbose");
StringTokenizer tokenizer = new StringTokenizer(compilerSettings.getOptionsString(chunk), " ");
StringTokenizer tokenizer = new StringTokenizer(new EclipseSettingsBuilder(options).getOptionsString(chunk), " ");
while (tokenizer.hasMoreTokens()) {
commandLine.add(tokenizer.nextToken());
}
@@ -1,9 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<form xmlns="http://www.intellij.com/uidesigner/form/" version="1" bind-to-class="com.intellij.compiler.impl.javaCompiler.eclipse.EclipseCompilerConfigurable">
<grid id="280f7" binding="myPanel" layout-manager="GridLayoutManager" row-count="5" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<grid id="280f7" binding="myPanel" layout-manager="GridLayoutManager" row-count="6" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<xy x="79" y="160" width="529" height="210"/>
<xy x="79" y="160" width="529" height="231"/>
</constraints>
<properties/>
<clientProperties>
@@ -25,7 +25,7 @@
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<selected value="true"/>
<selected value="false"/>
<text resource-bundle="messages/CompilerBundle" key="java.compiler.option.generate.debugging.info"/>
</properties>
</component>
@@ -34,14 +34,14 @@
<grid row="2" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<selected value="true"/>
<selected value="false"/>
<text resource-bundle="messages/CompilerBundle" key="java.compiler.option.generate.no.warnings"/>
</properties>
</component>
<grid id="d7ddf" layout-manager="GridLayoutManager" row-count="2" column-count="2" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="10" left="8" bottom="0" right="0"/>
<constraints>
<grid row="3" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
<grid row="4" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
<border type="none"/>
@@ -80,17 +80,22 @@
<margin top="0" left="2" bottom="0" right="0"/>
<text value="128"/>
</properties>
<clientProperties>
<caretAspectRatio class="java.lang.Float" value="0.04"/>
</clientProperties>
</component>
</children>
</grid>
<vspacer id="af30">
<constraints>
<grid row="4" column="0" row-span="1" col-span="1" vsize-policy="6" hsize-policy="1" anchor="0" fill="2" indent="0" use-parent-layout="false"/>
<grid row="5" column="0" row-span="1" col-span="1" vsize-policy="6" hsize-policy="1" anchor="0" fill="2" indent="0" use-parent-layout="false"/>
</constraints>
</vspacer>
<component id="4eacb" class="javax.swing.JCheckBox" binding="myCbProceedOnErrors">
<constraints>
<grid row="3" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Proceed on errors"/>
</properties>
</component>
</children>
</grid>
</form>
@@ -15,7 +15,6 @@
*/
package com.intellij.compiler.impl.javaCompiler.eclipse;
import com.intellij.compiler.impl.javaCompiler.javac.JavacSettings;
import com.intellij.compiler.options.ComparingUtils;
import com.intellij.openapi.compiler.CompilerBundle;
import com.intellij.openapi.options.Configurable;
@@ -23,6 +22,7 @@ import com.intellij.openapi.options.ConfigurationException;
import com.intellij.ui.RawCommandLineEditor;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.jps.model.java.compiler.EclipseCompilerOptions;
import javax.swing.*;
@@ -36,10 +36,11 @@ public class EclipseCompilerConfigurable implements Configurable {
private JCheckBox myCbGenerateNoWarnings;
private RawCommandLineEditor myAdditionalOptionsField;
private JTextField myJavacMaximumHeapField;
private final JavacSettings myCompilerSettings;
private JCheckBox myCbProceedOnErrors;
private final EclipseCompilerOptions myCompilerSettings;
public EclipseCompilerConfigurable(JavacSettings compilerSettings) {
myCompilerSettings = compilerSettings;
public EclipseCompilerConfigurable(EclipseCompilerOptions options) {
myCompilerSettings = options;
myAdditionalOptionsField.setDialogCaption(CompilerBundle.message("java.compiler.option.additional.command.line.parameters"));
}
@@ -63,6 +64,7 @@ public class EclipseCompilerConfigurable implements Configurable {
isModified |= ComparingUtils.isModified(myCbDeprecation, myCompilerSettings.DEPRECATION);
isModified |= ComparingUtils.isModified(myCbDebuggingInfo, myCompilerSettings.DEBUGGING_INFO);
isModified |= ComparingUtils.isModified(myCbGenerateNoWarnings, myCompilerSettings.GENERATE_NO_WARNINGS);
isModified |= ComparingUtils.isModified(myCbProceedOnErrors, myCompilerSettings.PROCEED_ON_ERROR);
isModified |= ComparingUtils.isModified(myAdditionalOptionsField, myCompilerSettings.ADDITIONAL_OPTIONS_STRING);
return isModified;
}
@@ -82,6 +84,7 @@ public class EclipseCompilerConfigurable implements Configurable {
myCompilerSettings.DEPRECATION = myCbDeprecation.isSelected();
myCompilerSettings.DEBUGGING_INFO = myCbDebuggingInfo.isSelected();
myCompilerSettings.GENERATE_NO_WARNINGS = myCbGenerateNoWarnings.isSelected();
myCompilerSettings.PROCEED_ON_ERROR = myCbProceedOnErrors.isSelected();
myCompilerSettings.ADDITIONAL_OPTIONS_STRING = myAdditionalOptionsField.getText();
}
@@ -90,6 +93,7 @@ public class EclipseCompilerConfigurable implements Configurable {
myCbDeprecation.setSelected(myCompilerSettings.DEPRECATION);
myCbDebuggingInfo.setSelected(myCompilerSettings.DEBUGGING_INFO);
myCbGenerateNoWarnings.setSelected(myCompilerSettings.GENERATE_NO_WARNINGS);
myCbProceedOnErrors.setSelected(myCompilerSettings.PROCEED_ON_ERROR);
myAdditionalOptionsField.setText(myCompilerSettings.ADDITIONAL_OPTIONS_STRING);
}
@@ -15,11 +15,11 @@
*/
package com.intellij.compiler.impl.javaCompiler.eclipse;
import com.intellij.compiler.impl.javaCompiler.javac.JavacConfiguration;
import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage;
import com.intellij.openapi.components.StoragePathMacros;
import com.intellij.openapi.components.StorageScheme;
import com.intellij.openapi.components.*;
import com.intellij.openapi.project.Project;
import com.intellij.util.xmlb.XmlSerializerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.jps.model.java.compiler.EclipseCompilerOptions;
@State(
name = "EclipseCompilerSettings",
@@ -28,5 +28,18 @@ import com.intellij.openapi.components.StorageScheme;
,@Storage( file = StoragePathMacros.PROJECT_CONFIG_DIR + "/compiler.xml", scheme = StorageScheme.DIRECTORY_BASED)
}
)
public class EclipseCompilerConfiguration extends JavacConfiguration {
}
public class EclipseCompilerConfiguration implements PersistentStateComponent<EclipseCompilerOptions> {
private final EclipseCompilerOptions mySettings = new EclipseCompilerOptions();
@NotNull
public EclipseCompilerOptions getState() {
return mySettings;
}
public void loadState(EclipseCompilerOptions state) {
XmlSerializerUtil.copyBean(state, mySettings);
}
public static EclipseCompilerOptions getOptions(Project project, Class<? extends EclipseCompilerConfiguration> aClass) {
return ServiceManager.getService(project, aClass).getState();
}}
@@ -18,7 +18,6 @@ package com.intellij.compiler.impl.javaCompiler.eclipse;
import com.intellij.compiler.OutputParser;
import com.intellij.compiler.impl.javaCompiler.BackendCompiler;
import com.intellij.compiler.impl.javaCompiler.ModuleChunk;
import com.intellij.compiler.impl.javaCompiler.javac.JavacSettings;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.compiler.CompileContext;
import com.intellij.openapi.compiler.CompileScope;
@@ -33,6 +32,7 @@ import com.intellij.util.ArrayUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.jps.model.java.compiler.EclipseCompilerOptions;
import java.io.IOException;
import java.io.InputStream;
@@ -75,7 +75,7 @@ public class EclipseEmbeddedCompiler implements BackendCompiler {
@NotNull
public Configurable createConfigurable() {
return new EclipseCompilerConfigurable(EclipseEmbeddedCompilerConfiguration.getSettings(myProject, EclipseEmbeddedCompilerConfiguration.class));
return new EclipseCompilerConfigurable(EclipseEmbeddedCompilerConfiguration.getOptions(myProject, EclipseEmbeddedCompilerConfiguration.class));
}
@NotNull
@@ -108,8 +108,8 @@ public class EclipseEmbeddedCompiler implements BackendCompiler {
ApplicationManager.getApplication().runReadAction(new Runnable() {
public void run() {
try {
JavacSettings settings = EclipseEmbeddedCompilerConfiguration.getSettings(myProject, EclipseEmbeddedCompilerConfiguration.class);
myEclipseExternalCompiler.addCommandLineOptions(commandLine, chunk, outputDir, settings, false, false);
final EclipseCompilerOptions options = EclipseCompilerConfiguration.getOptions(myProject, EclipseEmbeddedCompilerConfiguration.class);
myEclipseExternalCompiler.addCommandLineOptions(commandLine, chunk, outputDir, options, false, false);
}
catch (IOException e) {
ex[0] = e;
@@ -15,7 +15,6 @@
*/
package com.intellij.compiler.impl.javaCompiler.eclipse;
import com.intellij.compiler.impl.javaCompiler.javac.JavacConfiguration;
import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage;
import com.intellij.openapi.components.StoragePathMacros;
@@ -28,5 +27,5 @@ import com.intellij.openapi.components.StorageScheme;
,@Storage( file = StoragePathMacros.PROJECT_CONFIG_DIR + "/compiler.xml", scheme = StorageScheme.DIRECTORY_BASED)
}
)
public class EclipseEmbeddedCompilerConfiguration extends JavacConfiguration {
public class EclipseEmbeddedCompilerConfiguration extends EclipseCompilerConfiguration {
}
@@ -0,0 +1,47 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.compiler.impl.javaCompiler.eclipse;
import com.intellij.compiler.impl.javaCompiler.javac.JavacSettingsBuilder;
import com.intellij.openapi.module.Module;
import com.intellij.util.Chunk;
import org.jetbrains.jps.model.java.compiler.EclipseCompilerOptions;
import java.util.Collection;
/**
* @author Eugene Zhuravlev
* Date: 9/27/12
*/
public class EclipseSettingsBuilder extends JavacSettingsBuilder {
public EclipseSettingsBuilder(final EclipseCompilerOptions options) {
super(options);
}
@Override
public EclipseCompilerOptions getOptions() {
return (EclipseCompilerOptions)super.getOptions();
}
@Override
public Collection<String> getOptions(Chunk<Module> chunk) {
final Collection<String> options = super.getOptions(chunk);
if (getOptions().PROCEED_ON_ERROR) {
options.add("-proceedOnError");
}
return options;
}
}
@@ -15,7 +15,10 @@
*/
package com.intellij.compiler.impl.javaCompiler.javac;
import com.intellij.compiler.*;
import com.intellij.compiler.CompilerConfiguration;
import com.intellij.compiler.CompilerConfigurationImpl;
import com.intellij.compiler.CompilerIOUtil;
import com.intellij.compiler.OutputParser;
import com.intellij.compiler.impl.CompilerUtil;
import com.intellij.compiler.impl.javaCompiler.ExternalCompiler;
import com.intellij.compiler.impl.javaCompiler.ModuleChunk;
@@ -42,6 +45,7 @@ import com.intellij.util.ArrayUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.jps.model.java.compiler.AnnotationProcessingConfiguration;
import org.jetbrains.jps.model.java.compiler.JpsJavaCompilerOptions;
import java.io.*;
import java.util.*;
@@ -138,7 +142,7 @@ public class JavacCompiler extends ExternalCompiler {
@NotNull
public Configurable createConfigurable() {
return new JavacConfigurable(JavacSettings.getInstance(myProject));
return new JavacConfigurable(JavacConfiguration.getOptions(myProject, JavacConfiguration.class));
}
public OutputParser createErrorParser(@NotNull final String outputDir, Process process) {
@@ -164,7 +168,7 @@ public class JavacCompiler extends ExternalCompiler {
public String[] compute() {
try {
final List<String> commandLine = new ArrayList<String>();
createStartupCommand(chunk, commandLine, outputPath, JavacSettings.getInstance(myProject), context.isAnnotationProcessorsEnabled());
createStartupCommand(chunk, commandLine, outputPath, JavacConfiguration.getOptions(myProject, JavacConfiguration.class), context.isAnnotationProcessorsEnabled());
return ArrayUtil.toStringArray(commandLine);
}
catch (IOException e) {
@@ -183,7 +187,7 @@ public class JavacCompiler extends ExternalCompiler {
}
private void createStartupCommand(final ModuleChunk chunk, @NonNls final List<String> commandLine, final String outputPath,
JavacSettings javacSettings, final boolean annotationProcessorsEnabled) throws IOException {
JpsJavaCompilerOptions javacOptions, final boolean annotationProcessorsEnabled) throws IOException {
final Sdk jdk = getJdkForStartupCommand(chunk);
final String versionString = jdk.getVersionString();
JavaSdkVersion version = JavaSdk.getInstance().getVersion(jdk);
@@ -205,14 +209,14 @@ public class JavacCompiler extends ExternalCompiler {
commandLine.add(vmExePath);
if (version.isAtLeast(JavaSdkVersion.JDK_1_2)) {
commandLine.add("-Xmx" + javacSettings.MAXIMUM_HEAP_SIZE + "m");
commandLine.add("-Xmx" + javacOptions.MAXIMUM_HEAP_SIZE + "m");
}
else {
commandLine.add("-mx" + javacSettings.MAXIMUM_HEAP_SIZE + "m");
commandLine.add("-mx" + javacOptions.MAXIMUM_HEAP_SIZE + "m");
}
final List<String> additionalOptions =
addAdditionalSettings(commandLine, javacSettings, myAnnotationProcessorMode, version, chunk, annotationProcessorsEnabled);
addAdditionalSettings(commandLine, javacOptions, myAnnotationProcessorMode, version, chunk, annotationProcessorsEnabled);
CompilerUtil.addLocaleOptions(commandLine, false);
@@ -272,10 +276,10 @@ public class JavacCompiler extends ExternalCompiler {
}
}
public static List<String> addAdditionalSettings(List<String> commandLine, JavacSettings javacSettings, boolean isAnnotationProcessing,
public static List<String> addAdditionalSettings(List<String> commandLine, JpsJavaCompilerOptions javacOptions, boolean isAnnotationProcessing,
JavaSdkVersion version, ModuleChunk chunk, boolean annotationProcessorsEnabled) {
final List<String> additionalOptions = new ArrayList<String>();
StringTokenizer tokenizer = new StringTokenizer(javacSettings.getOptionsString(chunk), " ");
StringTokenizer tokenizer = new StringTokenizer(new JavacSettingsBuilder(javacOptions).getOptionsString(chunk), " ");
if (!version.isAtLeast(JavaSdkVersion.JDK_1_6)) {
isAnnotationProcessing = false; // makes no sense for these versions
annotationProcessorsEnabled = false;
@@ -425,7 +429,7 @@ public class JavacCompiler extends ExternalCompiler {
private Sdk getJdkForStartupCommand(final ModuleChunk chunk) {
final Sdk jdk = chunk.getJdk();
if (ApplicationManager.getApplication().isUnitTestMode() && JavacSettings.getInstance(myProject).isTestsUseExternalCompiler()) {
if (ApplicationManager.getApplication().isUnitTestMode() && JavacConfiguration.getOptions(myProject, JavacConfiguration.class).isTestsUseExternalCompiler()) {
final String jdkHomePath = CompilerConfigurationImpl.getTestsExternalCompilerHome();
if (jdkHomePath == null) {
throw new IllegalArgumentException("[TEST-MODE] Cannot determine home directory for JDK to use javac from");
@@ -20,6 +20,7 @@ import com.intellij.openapi.compiler.CompilerBundle;
import com.intellij.openapi.options.Configurable;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.ui.RawCommandLineEditor;
import org.jetbrains.jps.model.java.compiler.JpsJavaCompilerOptions;
import javax.swing.*;
@@ -34,9 +35,9 @@ public class JavacConfigurable implements Configurable{
private JCheckBox myCbGenerateNoWarnings;
private RawCommandLineEditor myAdditionalOptionsField;
private JTextField myJavacMaximumHeapField;
private final JavacSettings myJavacSettings;
private final JpsJavaCompilerOptions myJavacSettings;
public JavacConfigurable(final JavacSettings javacSettings) {
public JavacConfigurable(final JpsJavaCompilerOptions javacSettings) {
myJavacSettings = javacSettings;
myAdditionalOptionsField.setDialogCaption(CompilerBundle.message("java.compiler.option.additional.command.line.parameters"));
}
@@ -18,6 +18,8 @@ package com.intellij.compiler.impl.javaCompiler.javac;
import com.intellij.openapi.components.*;
import com.intellij.openapi.project.Project;
import com.intellij.util.xmlb.XmlSerializerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.jps.model.java.compiler.JpsJavaCompilerOptions;
@State(
name = "JavacSettings",
@@ -26,22 +28,19 @@ import com.intellij.util.xmlb.XmlSerializerUtil;
,@Storage( file = StoragePathMacros.PROJECT_CONFIG_DIR + "/compiler.xml", scheme = StorageScheme.DIRECTORY_BASED)
}
)
public class JavacConfiguration implements PersistentStateComponent<JavacSettings> {
private final JavacSettings mySettings = new JavacSettings();
public class JavacConfiguration implements PersistentStateComponent<JpsJavaCompilerOptions> {
private final JpsJavaCompilerOptions mySettings = new JpsJavaCompilerOptions();
public JavacSettings getState() {
@NotNull
public JpsJavaCompilerOptions getState() {
return mySettings;
}
public void loadState(JavacSettings state) {
public void loadState(JpsJavaCompilerOptions state) {
XmlSerializerUtil.copyBean(state, mySettings);
}
public JavacSettings getSettings() {
return mySettings;
}
public static JavacSettings getSettings(Project project, Class<? extends JavacConfiguration> aClass) {
return ServiceManager.getService(project, aClass).getSettings();
public static JpsJavaCompilerOptions getOptions(Project project, Class<? extends JavacConfiguration> aClass) {
return ServiceManager.getService(project, aClass).getState();
}
}
@@ -17,11 +17,8 @@ package com.intellij.compiler.impl.javaCompiler.javac;
import com.intellij.compiler.CompilerEncodingService;
import com.intellij.compiler.impl.javaCompiler.ModuleChunk;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.util.Chunk;
import org.jetbrains.annotations.TestOnly;
import org.jetbrains.jps.model.java.compiler.JpsJavaCompilerOptions;
import java.nio.charset.Charset;
@@ -30,22 +27,30 @@ import java.util.Collection;
import java.util.List;
import java.util.StringTokenizer;
public class JavacSettings extends JpsJavaCompilerOptions {
private boolean myTestsUseExternalCompiler = false;
public class JavacSettingsBuilder {
private final JpsJavaCompilerOptions myOptions;
public JavacSettingsBuilder(JpsJavaCompilerOptions options) {
myOptions = options;
}
protected JpsJavaCompilerOptions getOptions() {
return myOptions;
}
public Collection<String> getOptions(Chunk<Module> chunk) {
List<String> options = new ArrayList<String>();
if (DEBUGGING_INFO) {
if (getOptions().DEBUGGING_INFO) {
options.add("-g");
}
if (DEPRECATION) {
if (getOptions().DEPRECATION) {
options.add("-deprecation");
}
if (GENERATE_NO_WARNINGS) {
if (getOptions().GENERATE_NO_WARNINGS) {
options.add("-nowarn");
}
boolean isEncodingSet = false;
final StringTokenizer tokenizer = new StringTokenizer(ADDITIONAL_OPTIONS_STRING, " \t\r\n");
final StringTokenizer tokenizer = new StringTokenizer(getOptions().ADDITIONAL_OPTIONS_STRING, " \t\r\n");
while(tokenizer.hasMoreTokens()) {
final String token = tokenizer.nextToken();
if(!acceptUserOption(token)) {
@@ -84,19 +89,4 @@ public class JavacSettings extends JpsJavaCompilerOptions {
}
return options.toString();
}
public static JavacSettings getInstance(Project project) {
return ServiceManager.getService(project, JavacConfiguration.class).getSettings();
}
@TestOnly
public boolean isTestsUseExternalCompiler() {
return myTestsUseExternalCompiler;
}
@TestOnly
public void setTestsUseExternalCompiler(boolean testsUseExternalCompiler) {
myTestsUseExternalCompiler = testsUseExternalCompiler;
}
}
@@ -106,7 +106,7 @@ public class JikesCompiler extends ExternalCompiler {
}
private String getCompilerPath() {
return JikesConfiguration.getSettings(myProject).JIKES_PATH.replace('/', File.separatorChar);
return JikesConfiguration.getOptions(myProject).JIKES_PATH.replace('/', File.separatorChar);
}
@NotNull
@@ -123,7 +123,7 @@ public class JikesCompiler extends ExternalCompiler {
@NotNull
public Configurable createConfigurable() {
return new JikesConfigurable(JikesConfiguration.getSettings(myProject));
return new JikesConfigurable(JikesConfiguration.getOptions(myProject));
}
public OutputParser createErrorParser(@NotNull final String outputDir, Process process) {
@@ -201,7 +201,7 @@ public class JikesCompiler extends ExternalCompiler {
commandLine.add("-d");
commandLine.add(outputPath.replace('/', File.separatorChar));
JikesSettings jikesSettings = JikesConfiguration.getSettings(myProject);
JikesSettingsBuilder jikesSettings = new JikesSettingsBuilder(JikesConfiguration.getOptions(myProject));
StringTokenizer tokenizer = new StringTokenizer(jikesSettings.getOptionsString(chunk), " ");
while (tokenizer.hasMoreTokens()) {
commandLine.add(tokenizer.nextToken());
@@ -25,6 +25,7 @@ import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.ui.TextFieldWithBrowseButton;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.ui.RawCommandLineEditor;
import org.jetbrains.jps.model.java.compiler.JikesCompilerOptions;
import javax.swing.*;
import java.awt.event.ActionEvent;
@@ -42,9 +43,9 @@ public class JikesConfigurable implements Configurable {
private JCheckBox myCbGenerateNoWarnings;
private RawCommandLineEditor myAdditionalOptionsField;
private TextFieldWithBrowseButton myPathField;
private final JikesSettings myJikesSettings;
private final JikesCompilerOptions myJikesSettings;
public JikesConfigurable(JikesSettings jikesSettings) {
public JikesConfigurable(JikesCompilerOptions jikesSettings) {
myJikesSettings = jikesSettings;
myPathField.getButton().addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
@@ -18,6 +18,8 @@ package com.intellij.compiler.impl.javaCompiler.jikes;
import com.intellij.openapi.components.*;
import com.intellij.openapi.project.Project;
import com.intellij.util.xmlb.XmlSerializerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.jps.model.java.compiler.JikesCompilerOptions;
@State(
name = "JikesSettings",
@@ -26,22 +28,19 @@ import com.intellij.util.xmlb.XmlSerializerUtil;
,@Storage( file = StoragePathMacros.PROJECT_CONFIG_DIR + "/compiler.xml", scheme = StorageScheme.DIRECTORY_BASED)
}
)
public class JikesConfiguration implements PersistentStateComponent<JikesSettings> {
private final JikesSettings mySettings = new JikesSettings();
public class JikesConfiguration implements PersistentStateComponent<JikesCompilerOptions> {
private final JikesCompilerOptions mySettings = new JikesCompilerOptions();
public JikesSettings getState() {
@NotNull
public JikesCompilerOptions getState() {
return mySettings;
}
public void loadState(JikesSettings state) {
public void loadState(JikesCompilerOptions state) {
XmlSerializerUtil.copyBean(state, mySettings);
}
public JikesSettings getSettings() {
return mySettings;
}
public static JikesSettings getSettings(Project project) {
return ServiceManager.getService(project, JikesConfiguration.class).getSettings();
public static JikesCompilerOptions getOptions(Project project) {
return ServiceManager.getService(project, JikesConfiguration.class).getState();
}
}
@@ -15,19 +15,20 @@
*/
package com.intellij.compiler.impl.javaCompiler.jikes;
import com.intellij.compiler.OutputParser;
import com.intellij.openapi.compiler.CompilerMessageCategory;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFileManager;
import com.intellij.compiler.OutputParser;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.jps.model.java.compiler.JikesCompilerOptions;
import java.io.File;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class JikesOutputParser extends OutputParser {
private final JikesSettings myJikesSettings;
private final JikesCompilerOptions myJikesSettings;
@NonNls private static final String JAVA_FILE_MSG_TAIL = ".java:";
@NonNls private static final String CAUTION = "Caution";
@NonNls private static final String WARNING = "Warning";
@@ -37,7 +38,7 @@ public class JikesOutputParser extends OutputParser {
@NonNls private static final String ENTER_TO_CONTINUE_REGEXP = ".*Enter\\s+to\\s+continue.*";
public JikesOutputParser(Project project) {
myJikesSettings = JikesConfiguration.getSettings(project);
myJikesSettings = JikesConfiguration.getOptions(project);
myParserActions.add(new ParserActionJikes());
}
@@ -109,7 +110,7 @@ public class JikesOutputParser extends OutputParser {
messages.add(message);
if (colNum > 0 && messages.size() > 0) {
StringBuffer buf = new StringBuffer();
StringBuilder buf = new StringBuilder();
for (String m : messages) {
if (buf.length() > 0) {
buf.append("\n");
@@ -15,30 +15,27 @@
*/
package com.intellij.compiler.impl.javaCompiler.jikes;
import com.intellij.compiler.impl.javaCompiler.javac.JavacSettings;
import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage;
import com.intellij.openapi.components.StoragePathMacros;
import com.intellij.openapi.components.StorageScheme;
import com.intellij.compiler.impl.javaCompiler.javac.JavacSettingsBuilder;
import com.intellij.openapi.module.Module;
import com.intellij.util.Chunk;
import org.jetbrains.jps.model.java.compiler.JikesCompilerOptions;
import java.util.Collection;
@State(
name = "JikesSettings",
storages = {
@Storage( file = StoragePathMacros.PROJECT_FILE)
,@Storage( file = StoragePathMacros.PROJECT_CONFIG_DIR + "/compiler.xml", scheme = StorageScheme.DIRECTORY_BASED)
}
)
public class JikesSettings extends JavacSettings {
public String JIKES_PATH = "";
public boolean IS_EMACS_ERRORS_MODE = true;
public class JikesSettingsBuilder extends JavacSettingsBuilder {
public JikesSettingsBuilder(JikesCompilerOptions options) {
super(options);
}
@Override
public JikesCompilerOptions getOptions() {
return (JikesCompilerOptions)super.getOptions();
}
public Collection<String> getOptions(Chunk<Module> chunk) {
final Collection<String> options = super.getOptions(chunk);
if(IS_EMACS_ERRORS_MODE) {
if(getOptions().IS_EMACS_ERRORS_MODE) {
options.add("+E");
}
return options;
@@ -72,7 +72,7 @@ public class RmicCompiler implements ClassPostProcessingCompiler{
@NotNull
public ProcessingItem[] getProcessingItems(final CompileContext context) {
if (!RmicConfiguration.getSettings(context.getProject()).IS_EANABLED) {
if (!RmicConfiguration.getOptions(context.getProject()).IS_EANABLED) {
return ProcessingItem.EMPTY_ARRAY;
}
final Project project = context.getProject();
@@ -145,7 +145,7 @@ public class RmicCompiler implements ClassPostProcessingCompiler{
public ProcessingItem[] process(CompileContext context, ProcessingItem[] items) {
final Project project = context.getProject();
if (!RmicConfiguration.getSettings(project).IS_EANABLED) {
if (!RmicConfiguration.getOptions(project).IS_EANABLED) {
return ProcessingItem.EMPTY_ARRAY;
}
final ProgressIndicator progressIndicator = context.getProgressIndicator();
@@ -296,7 +296,7 @@ public class RmicCompiler implements ClassPostProcessingCompiler{
commandLine.add("-verbose");
final Project project = module.getProject();
ContainerUtil.addAll(commandLine, RmicConfiguration.getSettings(project).getOptions(new Chunk<Module>(module)));
ContainerUtil.addAll(commandLine, new RmicSettingsBuilder(RmicConfiguration.getOptions(project)).getOptions(new Chunk<Module>(module)));
commandLine.add("-classpath");
@@ -18,6 +18,8 @@ package com.intellij.compiler.impl.rmiCompiler;
import com.intellij.openapi.components.*;
import com.intellij.openapi.project.Project;
import com.intellij.util.xmlb.XmlSerializerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.jps.model.java.compiler.RmicCompilerOptions;
@State(
name = "RmicSettings",
@@ -26,22 +28,19 @@ import com.intellij.util.xmlb.XmlSerializerUtil;
,@Storage( file = StoragePathMacros.PROJECT_CONFIG_DIR + "/compiler.xml", scheme = StorageScheme.DIRECTORY_BASED)
}
)
public class RmicConfiguration implements PersistentStateComponent<RmicSettings> {
private final RmicSettings mySettings = new RmicSettings();
public class RmicConfiguration implements PersistentStateComponent<RmicCompilerOptions> {
private final RmicCompilerOptions mySettings = new RmicCompilerOptions();
public RmicSettings getState() {
@NotNull
public RmicCompilerOptions getState() {
return mySettings;
}
public void loadState(RmicSettings state) {
public void loadState(RmicCompilerOptions state) {
XmlSerializerUtil.copyBean(state, mySettings);
}
public RmicSettings getSettings() {
return mySettings;
}
public static RmicSettings getSettings(Project project) {
return ServiceManager.getService(project, RmicConfiguration.class).getSettings();
public static RmicCompilerOptions getOptions(Project project) {
return ServiceManager.getService(project, RmicConfiguration.class).getState();
}
}
@@ -15,34 +15,28 @@
*/
package com.intellij.compiler.impl.rmiCompiler;
import com.intellij.compiler.impl.javaCompiler.javac.JavacSettings;
import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage;
import com.intellij.openapi.components.StoragePathMacros;
import com.intellij.openapi.components.StorageScheme;
import com.intellij.compiler.impl.javaCompiler.javac.JavacSettingsBuilder;
import com.intellij.openapi.module.Module;
import com.intellij.util.Chunk;
import org.jetbrains.jps.model.java.compiler.RmicCompilerOptions;
import java.util.Collection;
@State(
name = "RmicSettings",
storages = {
@Storage( file = StoragePathMacros.PROJECT_FILE)
,@Storage( file = StoragePathMacros.PROJECT_CONFIG_DIR + "/compiler.xml", scheme = StorageScheme.DIRECTORY_BASED)
}
)
public class RmicSettings extends JavacSettings {
public boolean IS_EANABLED = false;
public boolean GENERATE_IIOP_STUBS = false;
public class RmicSettingsBuilder extends JavacSettingsBuilder {
public RmicSettings() {
DEPRECATION = false; // in this configuration deprecation is false by default
public RmicSettingsBuilder(final RmicCompilerOptions options) {
super(options);
getOptions().DEPRECATION = false; // in this configuration deprecation is false by default
}
@Override
public RmicCompilerOptions getOptions() {
return (RmicCompilerOptions)super.getOptions();
}
public Collection<String> getOptions(Chunk<Module> chunk) {
final Collection<String> options = super.getOptions(chunk);
if(GENERATE_IIOP_STUBS) {
if(getOptions().GENERATE_IIOP_STUBS) {
options.add("-iiop");
}
return options;
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<form xmlns="http://www.intellij.com/uidesigner/form/" version="1" bind-to-class="com.intellij.compiler.options.CompilerUIConfigurable">
<grid id="1663f" binding="myPanel" layout-manager="GridLayoutManager" row-count="7" column-count="2" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<grid id="1663f" binding="myPanel" layout-manager="GridLayoutManager" row-count="10" column-count="2" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<xy x="28" y="24" width="883" height="379"/>
@@ -10,7 +10,7 @@
<children>
<vspacer id="67edf">
<constraints>
<grid row="6" column="0" row-span="1" col-span="2" vsize-policy="6" hsize-policy="1" anchor="0" fill="2" indent="0" use-parent-layout="false"/>
<grid row="9" column="0" row-span="1" col-span="2" vsize-policy="6" hsize-policy="1" anchor="0" fill="2" indent="0" use-parent-layout="false"/>
</constraints>
</vspacer>
<grid id="b341d" layout-manager="GridLayoutManager" row-count="2" column-count="2" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
@@ -82,17 +82,57 @@
<grid row="4" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Use external build (Javac and Eclipse compilers are supported for java compilation and annotation processing)"/>
<text value="Use external build"/>
</properties>
</component>
<component id="b9b2d" class="javax.swing.JCheckBox" binding="myCbEnableAutomake">
<constraints>
<grid row="5" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="2" use-parent-layout="false"/>
<grid row="5" column="0" row-span="1" col-span="2" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="2" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Make project automatically"/>
</properties>
</component>
<component id="17126" class="javax.swing.JLabel" binding="myHeapSizeLabel">
<constraints>
<grid row="7" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="2" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Compiler process heap size (Mbytes):"/>
</properties>
</component>
<component id="a28b8" class="javax.swing.JTextField" binding="myHeapSizeField">
<constraints>
<grid row="7" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="6" anchor="8" fill="0" indent="0" use-parent-layout="false">
<preferred-size width="50" height="-1"/>
</grid>
</constraints>
<properties/>
</component>
<component id="5b86a" class="javax.swing.JLabel" binding="myVMOptionsLabel">
<constraints>
<grid row="8" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="2" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Additional compiler process VM options:"/>
</properties>
</component>
<component id="b5547" class="javax.swing.JTextField" binding="myVMOptionsField">
<constraints>
<grid row="8" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="6" anchor="8" fill="1" indent="0" use-parent-layout="false">
<preferred-size width="150" height="-1"/>
</grid>
</constraints>
<properties/>
</component>
<component id="ba694" class="javax.swing.JCheckBox" binding="myCbParallelCompilation">
<constraints>
<grid row="6" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="2" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Compile independent modules in parallel"/>
</properties>
</component>
</children>
</grid>
</form>
@@ -22,6 +22,7 @@ import com.intellij.compiler.MalformedPatternException;
import com.intellij.compiler.impl.TranslatingCompilerFilesMonitor;
import com.intellij.compiler.server.BuildManager;
import com.intellij.openapi.compiler.CompilerBundle;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.options.Configurable;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.options.SearchableConfigurable;
@@ -39,6 +40,7 @@ import java.util.Locale;
import java.util.StringTokenizer;
public class CompilerUIConfigurable implements SearchableConfigurable, Configurable.NoScroll {
private static final Logger LOG = Logger.getInstance("#com.intellij.compiler.options.CompilerUIConfigurable");
private JPanel myPanel;
private final Project myProject;
@@ -49,6 +51,11 @@ public class CompilerUIConfigurable implements SearchableConfigurable, Configura
private JCheckBox myCbAutoShowFirstError;
private JCheckBox myCbUseExternalBuild;
private JCheckBox myCbEnableAutomake;
private JCheckBox myCbParallelCompilation;
private JTextField myHeapSizeField;
private JTextField myVMOptionsField;
private JLabel myHeapSizeLabel;
private JLabel myVMOptionsLabel;
public CompilerUIConfigurable(final Project project) {
myProject = project;
@@ -62,7 +69,7 @@ public class CompilerUIConfigurable implements SearchableConfigurable, Configura
myCbUseExternalBuild.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
myCbEnableAutomake.setEnabled(myCbUseExternalBuild.isSelected());
updateExternalMakeOptionControls(myCbUseExternalBuild.isSelected());
}
});
}
@@ -76,7 +83,11 @@ public class CompilerUIConfigurable implements SearchableConfigurable, Configura
myCbAssertNotNull.setSelected(configuration.isAddNotNullAssertions());
myCbUseExternalBuild.setSelected(workspaceConfiguration.USE_COMPILE_SERVER);
myCbEnableAutomake.setSelected(workspaceConfiguration.MAKE_PROJECT_ON_SAVE);
myCbEnableAutomake.setEnabled(myCbUseExternalBuild.isSelected());
myCbParallelCompilation.setSelected(workspaceConfiguration.PARALLEL_COMPILATION);
myHeapSizeField.setText(String.valueOf(workspaceConfiguration.COMPILER_PROCESS_HEAP_SIZE));
final String options = workspaceConfiguration.COMPILER_PROCESS_ADDITIONAL_VM_OPTIONS;
myVMOptionsField.setText(options == null? "" : options.trim());
updateExternalMakeOptionControls(myCbUseExternalBuild.isSelected());
configuration.convertPatterns();
@@ -103,6 +114,14 @@ public class CompilerUIConfigurable implements SearchableConfigurable, Configura
boolean wasUsingExternalMake = workspaceConfiguration.USE_COMPILE_SERVER;
workspaceConfiguration.USE_COMPILE_SERVER = myCbUseExternalBuild.isSelected();
workspaceConfiguration.MAKE_PROJECT_ON_SAVE = myCbEnableAutomake.isSelected();
workspaceConfiguration.PARALLEL_COMPILATION = myCbParallelCompilation.isSelected();
try {
workspaceConfiguration.COMPILER_PROCESS_HEAP_SIZE = Integer.parseInt(myHeapSizeField.getText().trim());
}
catch (NumberFormatException ignored) {
LOG.info(ignored);
}
workspaceConfiguration.COMPILER_PROCESS_ADDITIONAL_VM_OPTIONS = myVMOptionsField.getText().trim();
configuration.setAddNotNullAssertions(myCbAssertNotNull.isSelected());
configuration.removeResourceFilePatterns();
@@ -178,6 +197,9 @@ public class CompilerUIConfigurable implements SearchableConfigurable, Configura
isModified |= ComparingUtils.isModified(myCbAutoShowFirstError, workspaceConfiguration.AUTO_SHOW_ERRORS_IN_EDITOR);
isModified |= ComparingUtils.isModified(myCbUseExternalBuild, workspaceConfiguration.USE_COMPILE_SERVER);
isModified |= ComparingUtils.isModified(myCbEnableAutomake, workspaceConfiguration.MAKE_PROJECT_ON_SAVE);
isModified |= ComparingUtils.isModified(myCbParallelCompilation, workspaceConfiguration.PARALLEL_COMPILATION);
isModified |= ComparingUtils.isModified(myHeapSizeField, workspaceConfiguration.COMPILER_PROCESS_HEAP_SIZE);
isModified |= ComparingUtils.isModified(myVMOptionsField, workspaceConfiguration.COMPILER_PROCESS_ADDITIONAL_VM_OPTIONS);
final CompilerConfigurationImpl compilerConfiguration = (CompilerConfigurationImpl)CompilerConfiguration.getInstance(myProject);
isModified |= ComparingUtils.isModified(myCbAssertNotNull, compilerConfiguration.isAddNotNullAssertions());
@@ -210,4 +232,14 @@ public class CompilerUIConfigurable implements SearchableConfigurable, Configura
public void disposeUIResources() {
}
private void updateExternalMakeOptionControls(boolean enabled) {
myCbEnableAutomake.setEnabled(enabled);
myCbParallelCompilation.setEnabled(enabled);
myHeapSizeField.setEnabled(enabled);
myVMOptionsField.setEnabled(enabled);
myHeapSizeLabel.setEnabled(enabled);
myVMOptionsLabel.setEnabled(enabled);
}
}
@@ -87,9 +87,10 @@ public class JavaCompilersTab implements SearchableConfigurable, Configurable.No
});
myCompiler.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
BackendCompiler compiler = (BackendCompiler)myCompiler.getSelectedItem();
if (compiler == null) return;
selectCompiler(compiler);
final BackendCompiler compiler = (BackendCompiler)myCompiler.getSelectedItem();
if (compiler != null) {
selectCompiler(compiler);
}
}
});
}
@@ -16,7 +16,6 @@
package com.intellij.compiler.options;
import com.intellij.compiler.impl.rmiCompiler.RmicConfiguration;
import com.intellij.compiler.impl.rmiCompiler.RmicSettings;
import com.intellij.openapi.compiler.CompilerBundle;
import com.intellij.openapi.options.Configurable;
import com.intellij.openapi.options.ConfigurationException;
@@ -24,6 +23,7 @@ import com.intellij.openapi.options.SearchableConfigurable;
import com.intellij.openapi.project.Project;
import com.intellij.ui.RawCommandLineEditor;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.jps.model.java.compiler.RmicCompilerOptions;
import javax.swing.*;
import java.awt.event.ItemEvent;
@@ -40,11 +40,11 @@ public class RmicConfigurable implements SearchableConfigurable, Configurable.No
private JCheckBox myCbDebuggingInfo;
private JCheckBox myCbGenerateNoWarnings;
private RawCommandLineEditor myAdditionalOptionsField;
private final RmicSettings myRmicSettings;
private final RmicCompilerOptions myRmicSettings;
private JLabel myFieldLabel;
public RmicConfigurable(final Project project) {
myRmicSettings = RmicConfiguration.getSettings(project);
myRmicSettings = RmicConfiguration.getOptions(project);
myCbEnabled.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
setOptionsEnabled(e.getStateChange() == ItemEvent.SELECTED);
@@ -498,7 +498,7 @@ public class BuildManager implements ApplicationComponent{
final CmdlineRemoteProto.Message.ControllerMessage params;
if (isRebuild) {
params = CmdlineProtoUtil.createRebuildRequest(projectPath, userData, globals);
params = CmdlineProtoUtil.createRebuildRequest(projectPath, scopes, userData, globals);
}
else {
params = isMake ?
@@ -706,12 +706,13 @@ public class BuildManager implements ApplicationComponent{
compilerPath = new File(path);
}
final CompilerWorkspaceConfiguration config = CompilerWorkspaceConfiguration.getInstance(project);
final GeneralCommandLine cmdLine = new GeneralCommandLine();
final String vmExecutablePath = ((JavaSdkType)projectJdk.getSdkType()).getVMExecutablePath(projectJdk);
cmdLine.setExePath(vmExecutablePath);
cmdLine.addParameter("-XX:MaxPermSize=150m");
cmdLine.addParameter("-XX:ReservedCodeCacheSize=64m");
final int heapSize = Registry.intValue("compiler.process.heap.size");
final int heapSize = config.COMPILER_PROCESS_HEAP_SIZE;
final int xms = heapSize / 2;
if (xms > 32) {
cmdLine.addParameter("-Xms" + xms + "m");
@@ -733,8 +734,9 @@ public class BuildManager implements ApplicationComponent{
if (shouldGenerateIndex != null) {
cmdLine.addParameter("-D"+ GlobalOptions.GENERATE_CLASSPATH_INDEX_OPTION +"=" + shouldGenerateIndex);
}
cmdLine.addParameter("-D"+ GlobalOptions.COMPILE_PARALLEL_OPTION +"=" + Boolean.toString(config.PARALLEL_COMPILATION));
final String additionalOptions = Registry.stringValue("compiler.process.vm.options");
final String additionalOptions = config.COMPILER_PROCESS_ADDITIONAL_VM_OPTIONS;
if (!StringUtil.isEmpty(additionalOptions)) {
final StringTokenizer tokenizer = new StringTokenizer(additionalOptions, " ", false);
while (tokenizer.hasMoreTokens()) {
@@ -18,7 +18,6 @@ package com.intellij.packaging.impl.compiler;
import com.intellij.openapi.fileTypes.FileTypeManager;
import com.intellij.openapi.roots.ProjectFileIndex;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
@@ -50,16 +49,14 @@ public abstract class IncrementalCompilerInstructionCreatorBase implements Incre
collectInstructionsRecursively(directory, this, filter, index, copyExcluded);
}
private static final Key<IncrementalCompilerInstructionCreatorBase> INSTRUCTION_CREATOR = Key.create("pkg.compiler.instruction.creator");
private static void collectInstructionsRecursively(VirtualFile directory,
final IncrementalCompilerInstructionCreatorBase creator,
final PackagingFileFilter filter,
@Nullable final PackagingFileFilter filter,
final ProjectFileIndex index,
final boolean copyExcluded) {
final FileTypeManager fileTypeManager = FileTypeManager.getInstance();
VfsUtilCore.visitChildrenRecursively(directory, new VirtualFileVisitor(VirtualFileVisitor.SKIP_ROOT) {
{ set(INSTRUCTION_CREATOR, creator); }
VfsUtilCore.visitChildrenRecursively(directory, new VirtualFileVisitor<IncrementalCompilerInstructionCreatorBase>(VirtualFileVisitor.SKIP_ROOT) {
{ setValueForChildren(creator); }
@Override
public boolean visitFile(@NotNull VirtualFile child) {
@@ -70,7 +67,7 @@ public abstract class IncrementalCompilerInstructionCreatorBase implements Incre
if (index.isIgnored(child)) return false;
}
final IncrementalCompilerInstructionCreatorBase creator = get(INSTRUCTION_CREATOR);
final IncrementalCompilerInstructionCreatorBase creator = getCurrentValue();
if (filter != null && !filter.accept(child, creator.myContext.getCompileContext())) {
return false;
}
@@ -79,7 +76,7 @@ public abstract class IncrementalCompilerInstructionCreatorBase implements Incre
creator.addFileCopyInstruction(child, child.getName());
}
else {
set(INSTRUCTION_CREATOR, creator.subFolder(child.getName()));
setValueForChildren(creator.subFolder(child.getName()));
}
return true;
@@ -186,8 +186,8 @@ public abstract class BaseCompilerTestCase extends ModuleTestCase {
});
}
protected void rebuild() {
compile(false, new ParameterizedRunnable<CompileStatusNotification>() {
protected CompilationLog rebuild() {
return compile(false, new ParameterizedRunnable<CompileStatusNotification>() {
@Override
public void run(CompileStatusNotification compileStatusNotification) {
getCompilerManager().rebuild(compileStatusNotification);
@@ -196,6 +196,17 @@ public abstract class BaseCompilerTestCase extends ModuleTestCase {
}
protected CompilationLog compile(final boolean errorsExpected, final ParameterizedRunnable<CompileStatusNotification> action) {
CompilationLog log = compile(action);
if (errorsExpected && log.myErrors.length == 0) {
Assert.fail("compilation finished without errors");
}
else if (!errorsExpected && log.myErrors.length > 0) {
Assert.fail("compilation finished with errors: " + Arrays.toString(log.myErrors));
}
return log;
}
private CompilationLog compile(final ParameterizedRunnable<CompileStatusNotification> action) {
final Ref<CompilationLog> result = Ref.create(null);
final Semaphore semaphore = new Semaphore();
UIUtil.invokeAndWaitIfNeeded(new Runnable() {
@@ -211,14 +222,9 @@ public abstract class BaseCompilerTestCase extends ModuleTestCase {
if (aborted) {
Assert.fail("compilation aborted");
}
if (errorsExpected && errors == 0) {
Assert.fail("compilation finished without errors");
}
else if (!errorsExpected && errors > 0) {
Assert
.fail("compilation finished with errors: " + Arrays.toString(compileContext.getMessages(CompilerMessageCategory.ERROR)));
}
result.set(new CompilationLog(CompilerManagerImpl.getPathsToRecompile(), CompilerManagerImpl.getPathsToDelete()));
result.set(new CompilationLog(CompilerManagerImpl.getPathsToRecompile(), CompilerManagerImpl.getPathsToDelete(),
compileContext.getMessages(CompilerMessageCategory.ERROR),
compileContext.getMessages(CompilerMessageCategory.WARNING)));
}
finally {
semaphore.up();
@@ -255,7 +261,7 @@ public abstract class BaseCompilerTestCase extends ModuleTestCase {
return set;
}
protected void changeFile(VirtualFile file) throws Exception {
protected void changeFile(VirtualFile file) {
changeFile(file, null);
}
@@ -349,8 +355,12 @@ public abstract class BaseCompilerTestCase extends ModuleTestCase {
protected class CompilationLog {
private final Set<String> myRecompiledPaths;
private final Set<String> myDeletedPaths;
private final CompilerMessage[] myErrors;
private final CompilerMessage[] myWarnings;
public CompilationLog(String[] recompiledPaths, String[] deletedPaths) {
public CompilationLog(String[] recompiledPaths, String[] deletedPaths, CompilerMessage[] errors, CompilerMessage[] warnings) {
myErrors = errors;
myWarnings = warnings;
myRecompiledPaths = getRelativePaths(recompiledPaths);
myDeletedPaths = getRelativePaths(deletedPaths);
}
@@ -383,6 +393,14 @@ public abstract class BaseCompilerTestCase extends ModuleTestCase {
assertSet("deleted", myDeletedPaths, expected);
}
public CompilerMessage[] getErrors() {
return myErrors;
}
public CompilerMessage[] getWarnings() {
return myWarnings;
}
private void assertSet(String name, Set<String> actual, String[] expected) {
if (useExternalCompiler()) return;
for (String path : expected) {
@@ -1,7 +1,7 @@
package com.intellij.compiler;
import com.intellij.compiler.impl.TranslatingCompilerFilesMonitor;
import com.intellij.compiler.impl.javaCompiler.javac.JavacSettings;
import com.intellij.compiler.impl.javaCompiler.javac.JavacConfiguration;
import com.intellij.compiler.server.BuildManager;
import com.intellij.openapi.application.Result;
import com.intellij.openapi.application.WriteAction;
@@ -17,6 +17,7 @@ import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.SystemProperties;
import org.jdom.Document;
import org.jdom.Element;
import org.jetbrains.jps.model.java.compiler.JpsJavaCompilerOptions;
import org.jetbrains.jps.model.serialization.JDomSerializationUtil;
import org.jetbrains.jps.model.serialization.JpsGlobalLoader;
@@ -37,7 +38,7 @@ public class CompilerTestUtil {
compilerConfiguration.projectOpened();
compilerConfiguration.setDefaultCompiler(compilerConfiguration.getJavacCompiler());
JavacSettings javacSettings = JavacSettings.getInstance(project);
JpsJavaCompilerOptions javacSettings = JavacConfiguration.getOptions(project, JavacConfiguration.class);
javacSettings.setTestsUseExternalCompiler(true);
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,19 +18,27 @@ package com.intellij.compiler.notNullVerification;
import org.jetbrains.asm4.*;
import java.util.ArrayList;
import java.util.List;
/**
* @author ven
* @noinspection HardCodedStringLiteral
*/
public class NotNullVerifyingInstrumenter extends ClassVisitor implements Opcodes {
private boolean myIsModification = false;
private String myClassName;
public static final String NOT_NULL = "org/jetbrains/annotations/NotNull";
public static final String NOT_NULL_ANNO = "L"+ NOT_NULL + ";";
public static final String IAE_CLASS_NAME = "java/lang/IllegalArgumentException";
public static final String ISE_CLASS_NAME = "java/lang/IllegalStateException";
private static final String NOT_NULL_CLASS_NAME = "org/jetbrains/annotations/NotNull";
private static final String NOT_NULL_TYPE = "L"+ NOT_NULL_CLASS_NAME + ";";
private static final String SYNTHETIC_CLASS_NAME = "java/lang/Synthetic";
private static final String SYNTHETIC_TYPE = "L" + SYNTHETIC_CLASS_NAME + ";";
private static final String IAE_CLASS_NAME = "java/lang/IllegalArgumentException";
private static final String ISE_CLASS_NAME = "java/lang/IllegalStateException";
private static final String STRING_CLASS_NAME = "java/lang/String";
private static final String CONSTRUCTOR_NAME = "<init>";
private static final String EXCEPTION_INIT_SIGNATURE = "(L" + STRING_CLASS_NAME + ";)V";
private static final String NULL_ARG_MESSAGE = "Argument %d for @NotNull parameter of %s.%s must not be null";
private static final String NULL_RESULT_MESSAGE = "@NotNull method %s.%s must not return null";
private String myClassName;
private boolean myIsModification = false;
public NotNullVerifyingInstrumenter(final ClassVisitor classVisitor) {
super(Opcodes.ASM4, classVisitor);
@@ -40,27 +48,22 @@ public class NotNullVerifyingInstrumenter extends ClassVisitor implements Opcode
return myIsModification;
}
public void visit(final int version,
final int access,
final String name,
final String signature,
final String superName,
final String[] interfaces) {
@Override
public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
super.visit(version, access, name, signature, superName, interfaces);
myClassName = name;
}
public MethodVisitor visitMethod(final int access, final String name, final String desc, final String signature, final String[] exceptions) {
@Override
public MethodVisitor visitMethod(final int access, final String name, String desc, String signature, String[] exceptions) {
final Type[] args = Type.getArgumentTypes(desc);
final Type returnType = Type.getReturnType(desc);
MethodVisitor v = cv.visitMethod(access, name, desc, signature, exceptions);
final MethodVisitor v = cv.visitMethod(access, name, desc, signature, exceptions);
return new MethodVisitor(Opcodes.ASM4, v) {
private final ArrayList myNotNullParams = new ArrayList();
private final List<Integer> myNotNullParams = new ArrayList<Integer>();
private int mySyntheticCount = 0;
private boolean myIsNotNull = false;
//private boolean myIsUnmodifiable = false;
//public Label myWrapLabel;
private Label myStartGeneratedCodeLabel;
public AnnotationVisitor visitParameterAnnotation(
@@ -69,35 +72,35 @@ public class NotNullVerifyingInstrumenter extends ClassVisitor implements Opcode
final boolean visible) {
AnnotationVisitor av;
av = mv.visitParameterAnnotation(parameter, anno, visible);
if (isReferenceType(args[parameter]) && anno.equals(NOT_NULL_ANNO)) {
if (isReferenceType(args[parameter]) && anno.equals(NOT_NULL_TYPE)) {
myNotNullParams.add(new Integer(parameter));
}
else if (anno.equals("Ljava/lang/Synthetic;")) {
// See asm r1278 for what we do this,
// http://forge.objectweb.org/tracker/index.php?func=detail&aid=307392&group_id=23&atid=100023
else if (anno.equals(SYNTHETIC_TYPE)) {
// see http://forge.ow2.org/tracker/?aid=307392&group_id=23&atid=100023&func=detail
mySyntheticCount++;
}
return av;
}
@Override
public AnnotationVisitor visitAnnotation(String anno, boolean isRuntime) {
final AnnotationVisitor av = mv.visitAnnotation(anno, isRuntime);
if (isReferenceType(returnType) &&
anno.equals(NOT_NULL_ANNO)) {
anno.equals(NOT_NULL_TYPE)) {
myIsNotNull = true;
}
return av;
}
@Override
public void visitCode() {
if (myNotNullParams.size() > 0) {
myStartGeneratedCodeLabel = new Label();
mv.visitLabel(myStartGeneratedCodeLabel);
}
for (int p = 0; p < myNotNullParams.size(); ++p) {
for (Integer param : myNotNullParams) {
int var = ((access & ACC_STATIC) == 0) ? 1 : 0;
int param = ((Integer)myNotNullParams.get(p)).intValue();
for (int i = 0; i < param; ++i) {
var += args[i].getSize();
}
@@ -106,26 +109,26 @@ public class NotNullVerifyingInstrumenter extends ClassVisitor implements Opcode
Label end = new Label();
mv.visitJumpInsn(IFNONNULL, end);
generateThrow(IAE_CLASS_NAME, "Argument " + (param - mySyntheticCount) + " for @NotNull parameter of " + myClassName + "." + name + " must not be null", end);
generateThrow(IAE_CLASS_NAME, String.format(NULL_ARG_MESSAGE, param - mySyntheticCount, myClassName, name), end);
}
}
public void visitLocalVariable(final String name, final String desc, final String signature, final Label start, final Label end,
final int index) {
@Override
public void visitLocalVariable(String name, String desc, String signature, Label start, Label end, int index) {
final boolean isStatic = (access & ACC_STATIC) != 0;
final boolean isParameter = isStatic ? index < args.length : index <= args.length;
mv.visitLocalVariable(name, desc, signature, (isParameter && myStartGeneratedCodeLabel != null) ? myStartGeneratedCodeLabel : start, end, index);
final Label label = (isParameter && myStartGeneratedCodeLabel != null) ? myStartGeneratedCodeLabel : start;
mv.visitLocalVariable(name, desc, signature, label, end, index);
}
@Override
public void visitInsn(int opcode) {
if (opcode == ARETURN) {
if (myIsNotNull) {
mv.visitInsn(DUP);
/*generateConditionalThrow("@NotNull method " + myClassName + "." + name + " must not return null",
"java/lang/IllegalStateException");*/
final Label skipLabel = new Label();
mv.visitJumpInsn(IFNONNULL, skipLabel);
generateThrow(ISE_CLASS_NAME, "@NotNull method " + myClassName + "." + name + " must not return null", skipLabel);
generateThrow(ISE_CLASS_NAME, String.format(NULL_RESULT_MESSAGE, myClassName, name), skipLabel);
}
}
@@ -133,23 +136,23 @@ public class NotNullVerifyingInstrumenter extends ClassVisitor implements Opcode
}
private void generateThrow(final String exceptionClass, final String descr, final Label end) {
String exceptionParamClass = "(Ljava/lang/String;)V";
mv.visitTypeInsn(NEW, exceptionClass);
mv.visitInsn(DUP);
mv.visitLdcInsn(descr);
mv.visitMethodInsn(INVOKESPECIAL, exceptionClass, CONSTRUCTOR_NAME, exceptionParamClass);
mv.visitMethodInsn(INVOKESPECIAL, exceptionClass, CONSTRUCTOR_NAME, EXCEPTION_INIT_SIGNATURE);
mv.visitInsn(ATHROW);
mv.visitLabel(end);
myIsModification = true;
}
@Override
public void visitMaxs(final int maxStack, final int maxLocals) {
try {
super.visitMaxs(maxStack, maxLocals);
}
catch (ArrayIndexOutOfBoundsException e) {
throw new ArrayIndexOutOfBoundsException("maxs processing failed for method " + name + ": " + e.getMessage());
throw new ArrayIndexOutOfBoundsException("Maximums processing failed for " + myClassName + "." + name + ": " + e.getMessage());
}
}
};
@@ -37,6 +37,9 @@ public class CompilerWorkspaceConfiguration implements PersistentStateComponent<
public boolean CLEAR_OUTPUT_DIRECTORY = true;
public boolean USE_COMPILE_SERVER = false;
public boolean MAKE_PROJECT_ON_SAVE = false;
public boolean PARALLEL_COMPILATION = false;
public int COMPILER_PROCESS_HEAP_SIZE = 700;
public String COMPILER_PROCESS_ADDITIONAL_VM_OPTIONS = "";
public static CompilerWorkspaceConfiguration getInstance(Project project) {
return ServiceManager.getService(project, CompilerWorkspaceConfiguration.class);
@@ -170,7 +170,7 @@ public class CompileStepBeforeRun extends BeforeRunTaskProvider<CompileStepBefor
@Nullable
public static RunConfiguration getRunConfiguration(final CompileContext context) {
return context.getCompileScope().getUserData(RUN_CONFIGURATION);
return getRunConfiguration(context.getCompileScope());
}
@Nullable
@@ -0,0 +1,60 @@
<?xml version="1.0" encoding="UTF-8"?>
<form xmlns="http://www.intellij.com/uidesigner/form/" version="1" bind-to-class="com.intellij.ide.util.newProjectWizard.SelectTemplateStep">
<grid id="27dc6" binding="myPanel" layout-manager="GridLayoutManager" row-count="2" column-count="3" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<xy x="20" y="20" width="470" height="400"/>
</constraints>
<properties/>
<border type="none"/>
<children>
<grid id="ac540" layout-manager="BorderLayout" hgap="0" vgap="0">
<constraints>
<grid row="1" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="8" fill="2" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
<border type="none"/>
<children>
<component id="3580d" class="com.intellij.ui.SearchTextField" binding="mySearchField">
<constraints border-constraint="North"/>
<properties/>
</component>
<scrollpane id="474de" class="com.intellij.ui.components.JBScrollPane">
<constraints border-constraint="Center"/>
<properties/>
<border type="none"/>
<children>
<component id="9dad" class="com.intellij.ui.components.JBList" binding="myTemplatesList">
<constraints/>
<properties>
<fixedCellWidth value="30"/>
</properties>
</component>
</children>
</scrollpane>
</children>
</grid>
<grid id="caf4" binding="mySettingsPanel" layout-manager="BorderLayout" hgap="0" vgap="0">
<constraints>
<grid row="1" column="1" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
<border type="none"/>
<children/>
</grid>
<hspacer id="fc0b6">
<constraints>
<grid row="1" column="2" row-span="1" col-span="1" vsize-policy="1" hsize-policy="6" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
</hspacer>
<component id="dafde" class="com.intellij.ui.components.JBLabel">
<constraints>
<grid row="0" column="0" row-span="1" col-span="3" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Please select desired template from the list"/>
</properties>
</component>
</children>
</grid>
</form>
@@ -0,0 +1,133 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ide.util.newProjectWizard;
import com.intellij.ide.util.projectWizard.ModuleWizardStep;
import com.intellij.ide.util.projectWizard.WizardContext;
import com.intellij.openapi.util.Condition;
import com.intellij.platform.ProjectTemplate;
import com.intellij.platform.ProjectTemplatesFactory;
import com.intellij.psi.codeStyle.MinusculeMatcher;
import com.intellij.psi.codeStyle.NameUtil;
import com.intellij.ui.CollectionListModel;
import com.intellij.ui.ColoredListCellRenderer;
import com.intellij.ui.DocumentAdapter;
import com.intellij.ui.SearchTextField;
import com.intellij.ui.components.JBList;
import com.intellij.util.containers.ContainerUtil;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* @author Dmitry Avdeev
* Date: 9/26/12
*/
public class SelectTemplateStep extends ModuleWizardStep {
private JPanel myPanel;
private JBList myTemplatesList;
private JPanel mySettingsPanel;
private SearchTextField mySearchField;
public SelectTemplateStep(WizardContext context) {
final List<ProjectTemplate> templates = new ArrayList<ProjectTemplate>();
ProjectTemplatesFactory[] factories = ProjectTemplatesFactory.EP_NAME.getExtensions();
for (ProjectTemplatesFactory factory : factories) {
templates.addAll(Arrays.asList(factory.createTemplates(context)));
}
myTemplatesList.setModel(new CollectionListModel<ProjectTemplate>(templates));
myTemplatesList.setCellRenderer(new ColoredListCellRenderer() {
@Override
protected void customizeCellRenderer(JList list, Object value, int index, boolean selected, boolean hasFocus) {
ProjectTemplate template = (ProjectTemplate)value;
append(template.getName());
}
});
myTemplatesList.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
if (mySettingsPanel.getComponentCount() > 0) {
mySettingsPanel.remove(0);
}
ProjectTemplate template = getSelectedTemplate();
if (template != null) {
JComponent settingsPanel = template.getSettingsPanel();
mySettingsPanel.add(settingsPanel, BorderLayout.NORTH);
mySettingsPanel.repaint();
}
mySettingsPanel.revalidate();
}
});
if (myTemplatesList.getModel().getSize() > 0) {
myTemplatesList.setSelectedIndex(0);
}
mySearchField.addDocumentListener(new DocumentAdapter() {
@Override
protected void textChanged(DocumentEvent e) {
final MinusculeMatcher matcher = NameUtil.buildMatcher(mySearchField.getText(), NameUtil.MatchingCaseSensitivity.NONE);
ProjectTemplate selectedTemplate = getSelectedTemplate();
List<ProjectTemplate> list = ContainerUtil.filter(templates, new Condition<ProjectTemplate>() {
@Override
public boolean value(ProjectTemplate template) {
String name = template.getName();
String[] words = NameUtil.nameToWords(name);
for (String word : words) {
if (matcher.matches(word)) return true;
}
return false;
}
});
myTemplatesList.setModel(new CollectionListModel<ProjectTemplate>(list));
if (!list.isEmpty()) {
if (list.contains(selectedTemplate)) {
myTemplatesList.setSelectedValue(selectedTemplate, true);
}
else {
myTemplatesList.setSelectedIndex(0);
}
}
}
});
}
public ProjectTemplate getSelectedTemplate() {
return (ProjectTemplate)myTemplatesList.getSelectedValue();
}
@Override
public JComponent getComponent() {
return myPanel;
}
@Override
public JComponent getPreferredFocusedComponent() {
return mySearchField;
}
@Override
public void updateDataModel() {
}
}
@@ -36,6 +36,10 @@ public class StepSequence {
@NonNls private List<String> myTypes = new ArrayList<String>();
private List<ModuleWizardStep> mySelectedSteps;
public StepSequence(ModuleWizardStep... commonSteps) {
myCommonSteps.addAll(Arrays.asList(commonSteps));
}
public void addCommonStep(@NotNull ModuleWizardStep step){
myCommonSteps.add(step);
}
@@ -0,0 +1,74 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ide.util.newProjectWizard.modes;
import com.intellij.ide.util.newProjectWizard.ProjectNameStep;
import com.intellij.ide.util.newProjectWizard.SelectTemplateStep;
import com.intellij.ide.util.newProjectWizard.StepSequence;
import com.intellij.ide.util.projectWizard.ProjectBuilder;
import com.intellij.ide.util.projectWizard.WizardContext;
import com.intellij.openapi.project.ProjectBundle;
import com.intellij.openapi.roots.ui.configuration.ModulesProvider;
import com.intellij.platform.ProjectTemplate;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* @author Dmitry Avdeev
* Date: 9/26/12
*/
public class CreateFromTemplateMode extends WizardMode {
private SelectTemplateStep mySelectTemplateStep;
@NotNull
@Override
public String getDisplayName(WizardContext context) {
return ProjectBundle.message("project.new.wizard.from.template.title", context.getPresentationName());
}
@NotNull
@Override
public String getDescription(WizardContext context) {
return ProjectBundle.message("project.new.wizard.from.template.description", context.getPresentationName());
}
@Override
public boolean isAvailable(WizardContext context) {
return true;
}
@Nullable
@Override
protected StepSequence createSteps(WizardContext context, @NotNull ModulesProvider modulesProvider) {
mySelectTemplateStep = new SelectTemplateStep(context);
return new StepSequence(mySelectTemplateStep, new ProjectNameStep(context, this));
}
@Nullable
@Override
public ProjectBuilder getModuleBuilder() {
final ProjectTemplate template = mySelectTemplateStep.getSelectedTemplate();
if (template == null) {
return null;
}
return template.createModuleBuilder();
}
@Override
public void onChosen(boolean enabled) {
}
}
@@ -73,8 +73,9 @@ public class ExistingModuleLoader extends ModuleBuilder {
public boolean validate(final Project current, final Project dest) {
if (getName() == null) return false;
if (getModuleFilePath() == null) return false;
final File file = new File(getModuleFilePath());
String moduleFilePath = getModuleFilePath();
if (moduleFilePath == null) return false;
final File file = new File(moduleFilePath);
if (file.exists()) {
try {
final ConversionResult result = ConversionService.getInstance().convertModule(dest, file);
@@ -104,7 +105,8 @@ public class ExistingModuleLoader extends ModuleBuilder {
return false;
}
} else {
Messages.showErrorDialog(current, IdeBundle.message("title.module.file.does.not.exist"), CommonBundle.message("title.error"));
Messages.showErrorDialog(current, IdeBundle.message("title.module.file.does.not.exist", moduleFilePath),
CommonBundle.message("title.error"));
return false;
}
return true;
@@ -27,9 +27,7 @@ import com.intellij.openapi.roots.libraries.LibraryKind;
import com.intellij.util.Processor;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
@@ -42,9 +40,7 @@ public class LibraryUsageCollector extends AbstractApplicationUsagesCollector {
@NotNull
@Override
public Set<UsageDescriptor> getProjectUsages(@Nullable Project project) {
if (project == null) return Collections.emptySet();
public Set<UsageDescriptor> getProjectUsages(@NotNull Project project) {
final Set<LibraryKind> usedKinds = new HashSet<LibraryKind>();
final Processor<Library> processor = new Processor<Library>() {
@Override
@@ -0,0 +1,99 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.platform.templates;
import com.intellij.ide.util.newProjectWizard.modes.ImportImlMode;
import com.intellij.ide.util.projectWizard.ExistingModuleLoader;
import com.intellij.ide.util.projectWizard.ProjectBuilder;
import com.intellij.ide.util.projectWizard.WizardContext;
import com.intellij.openapi.module.ModifiableModuleModel;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ui.configuration.ModulesProvider;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.platform.templates.github.AbstractGithubTagDownloadedProjectGenerator;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
/**
* @author Dmitry Avdeev
* Date: 10/1/12
*/
public class GithubBasedProjectTemplate extends AbstractGithubTagDownloadedProjectGenerator {
private String myDisplayName;
private String myGithubUserName;
private String myGithubRepositoryName;
private String myHomepageUrl;
private String myDescription;
private final WizardContext myContext;
public GithubBasedProjectTemplate(String displayName,
String githubRepositoryName,
String homepageUrl,
String description,
WizardContext context) {
myDisplayName = displayName;
myGithubRepositoryName = githubRepositoryName;
myHomepageUrl = homepageUrl;
myDescription = description;
myContext = context;
}
@NotNull
@Override
protected String getDisplayName() {
return myDisplayName;
}
@Override
protected String getGithubUserName() {
return myGithubUserName;
}
@NotNull
@Override
protected String getGithubRepositoryName() {
return myGithubRepositoryName;
}
@Override
public String getHomepageUrl() {
return myHomepageUrl;
}
@Override
public String getDescription() {
return myDescription;
}
@Override
public ProjectBuilder createModuleBuilder() {
final String path = myContext.getProjectFileDirectory() + "/empty-java.iml";
final ExistingModuleLoader loader = ImportImlMode.setUpLoader(path);
return new ProjectBuilder() {
@Nullable
@Override
public List<Module> commit(Project project, ModifiableModuleModel model, ModulesProvider modulesProvider) {
VirtualFile file = LocalFileSystem.getInstance().refreshAndFindFileByPath(myContext.getProjectFileDirectory());
doGenerate(project, file, myPeer.getValue().getSettings());
return loader.commit(project, model, modulesProvider);
}
};
}
}
@@ -0,0 +1,36 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.platform.templates;
import com.intellij.ide.util.projectWizard.WizardContext;
import com.intellij.platform.ProjectTemplate;
import com.intellij.platform.ProjectTemplatesFactory;
import org.jetbrains.annotations.NotNull;
/**
* @author Dmitry Avdeev
* Date: 10/1/12
*/
public class GithubBasedTemplatesFactory implements ProjectTemplatesFactory {
@NotNull
@Override
public ProjectTemplate[] createTemplates(WizardContext context) {
return new ProjectTemplate[]{
new GithubBasedProjectTemplate("Web Application", "JetBrains/idea-templates/web/empty-java", null, null, context)
};
}
}
@@ -54,16 +54,20 @@ public class JavaClassNameCompletionContributor extends CompletionContributor {
public void fillCompletionVariants(CompletionParameters parameters, final CompletionResultSet _result) {
if (parameters.getCompletionType() == CompletionType.CLASS_NAME ||
parameters.isExtendedCompletion() && mayContainClassName(parameters)) {
CompletionResultSet result = _result.withPrefixMatcher(CompletionUtil.findReferenceOrAlphanumericPrefix(parameters));
addAllClasses(parameters, parameters.getInvocationCount() <= 1, result.getPrefixMatcher(), new Consumer<LookupElement>() {
@Override
public void consume(LookupElement element) {
_result.addElement(element);
}
});
addAllClasses(parameters, _result);
}
}
static void addAllClasses(CompletionParameters parameters, final CompletionResultSet _result) {
CompletionResultSet result = _result.withPrefixMatcher(CompletionUtil.findReferenceOrAlphanumericPrefix(parameters));
addAllClasses(parameters, parameters.getInvocationCount() <= 1, result.getPrefixMatcher(), new Consumer<LookupElement>() {
@Override
public void consume(LookupElement element) {
_result.addElement(element);
}
});
}
private static boolean mayContainClassName(CompletionParameters parameters) {
PsiElement position = parameters.getPosition();
PsiFile file = position.getContainingFile();
@@ -15,6 +15,7 @@
*/
package com.intellij.codeInsight.completion;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiReference;
import com.intellij.psi.impl.source.resolve.reference.impl.PsiMultiReference;
@@ -34,10 +35,33 @@ public class JavaClassReferenceCompletionContributor extends CompletionContribut
final PsiReference last = references[references.length - 1];
context.setReplacementOffset(last.getRangeInElement().getEndOffset() + last.getElement().getTextRange().getStartOffset());
}
}
@Nullable
@Override
public void fillCompletionVariants(CompletionParameters parameters, CompletionResultSet result) {
if (parameters.getCompletionType() == CompletionType.SMART) {
return;
}
PsiElement position = parameters.getPosition();
JavaClassReference reference = findJavaClassReference(position.getContainingFile(), parameters.getOffset());
if (reference == null) {
return;
}
if (parameters.getCompletionType() == CompletionType.CLASS_NAME) {
JavaClassNameCompletionContributor.addAllClasses(parameters, result);
}
else {
CompletionData data = CompletionUtil.getCompletionDataByElement(position, parameters.getOriginalFile());
if (data != null) {
LegacyCompletionContributor.completeReference(parameters, result, data);
}
}
result.stopHere();
}
@Nullable
public static JavaClassReference findJavaClassReference(final PsiFile file, final int offset) {
PsiReference reference = file.findReferenceAt(offset);
if (reference instanceof PsiMultiReference) {
@@ -809,12 +809,15 @@ public class JavaCompletionUtil {
PsiDocumentManager.getInstance(context.getProject()).commitDocument(context.getDocument());
final CommonCodeStyleSettings styleSettings = context.getCodeStyleSettings();
ParenthesesInsertHandler.getInstance(hasParams,
styleSettings.SPACE_BEFORE_METHOD_CALL_PARENTHESES,
styleSettings.SPACE_WITHIN_METHOD_CALL_PARENTHESES && hasParams,
needRightParenth,
styleSettings.METHOD_PARAMETERS_LPAREN_ON_NEXT_LINE
).handleInsert(context, item);
final PsiElement elementAt = file.findElementAt(context.getStartOffset());
if (elementAt == null || !(elementAt.getParent() instanceof PsiMethodReferenceExpression)) {
ParenthesesInsertHandler.getInstance(hasParams,
styleSettings.SPACE_BEFORE_METHOD_CALL_PARENTHESES,
styleSettings.SPACE_WITHIN_METHOD_CALL_PARENTHESES && hasParams,
needRightParenth,
styleSettings.METHOD_PARAMETERS_LPAREN_ON_NEXT_LINE
).handleInsert(context, item);
}
if (hasParams) {
// Invoke parameters popup
@@ -66,10 +66,12 @@ public class MemberLookupHelper {
PsiFormatUtil.SHOW_PARAMETERS,
PsiFormatUtil.SHOW_NAME | PsiFormatUtil.SHOW_TYPE)
: "";
presentation.clearTail();
presentation.appendTailText(params, false);
if (myShouldImport && StringUtil.isNotEmpty(className)) {
presentation.setTailText(params + " in " + className + location);
presentation.appendTailText(" in " + className + location, true);
} else {
presentation.setTailText(params + location, !(myMember instanceof PsiMethod));
presentation.appendTailText(location, true);
}
final PsiType type = myMember instanceof PsiMethod ? ((PsiMethod)myMember).getReturnType() : ((PsiField) myMember).getType();
@@ -339,6 +339,9 @@ public class HighlightUtil {
if (operandType == null) return null;
if (operandType instanceof PsiLambdaExpressionType) {
return HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, expression, "Lambda expression is not expected here");
}
if (operandType instanceof PsiMethodReferenceType) {
return HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, expression, "Method reference expression is not expected here");
}
if (TypeConversionUtil.isPrimitiveAndNotNull(operandType)
|| TypeConversionUtil.isPrimitiveAndNotNull(checkType)
@@ -1729,7 +1732,7 @@ public class HighlightUtil {
if (element == field.getInitializer()) return field;
if (field instanceof PsiEnumConstant && element == ((PsiEnumConstant)field).getArgumentList()) return field;
}
if (element instanceof PsiClass || element instanceof PsiMethod) return null;
if (element instanceof PsiClass || element instanceof PsiMethod || parent instanceof PsiLambdaExpression) return null;
element = parent;
}
return null;
@@ -2633,11 +2636,7 @@ public class HighlightUtil {
@Nullable
public static HighlightInfo checkMethodReferencesFeature(final PsiMethodReferenceExpression expression) {
final HighlightInfo info = checkFeature(expression, Feature.METHOD_REFERENCES);
if (info != null) return info;
// todo[r.sh] stub; remove after implementing support in TypeConversionUtil
final String message = "Method references type check is not yet implemented";
return HighlightInfo.createHighlightInfo(HighlightInfoType.WEAK_WARNING, expression, message);
return checkFeature(expression, Feature.METHOD_REFERENCES);
}
@Nullable
@@ -967,6 +967,16 @@ public class HighlightVisitorImpl extends JavaElementVisitor implements Highligh
@Override
public void visitMethodReferenceExpression(PsiMethodReferenceExpression expression) {
myHolder.add(HighlightUtil.checkMethodReferencesFeature(expression));
JavaResolveResult result;
try {
result = expression.advancedResolve(true);
}
catch (IndexNotReadyException e) {
return;
}
if (myRefCountHolder != null) {
myRefCountHolder.registerReference(expression, result);
}
}
@Override
@@ -254,7 +254,9 @@ public class CreateFromUsageUtils {
names = new String[]{"p" + i};
}
if (argType == null || PsiType.NULL.equals(argType) || argType instanceof PsiLambdaExpressionType) {
if (argType == null || PsiType.NULL.equals(argType) ||
argType instanceof PsiLambdaExpressionType ||
argType instanceof PsiMethodReferenceType) {
argType = PsiType.getJavaLangObject(psiManager, resolveScope);
}
PsiParameter parameter;
@@ -19,13 +19,14 @@ import com.intellij.codeInsight.CodeInsightSettings;
import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer;
import com.intellij.codeInsight.daemon.QuickFixBundle;
import com.intellij.codeInsight.intention.IntentionAction;
import com.intellij.codeInsight.intention.LowPriorityAction;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiJavaFile;
import org.jetbrains.annotations.NotNull;
public class EnableOptimizeImportsOnTheFlyFix implements IntentionAction{
public class EnableOptimizeImportsOnTheFlyFix implements IntentionAction, LowPriorityAction{
@Override
@NotNull
public String getText() {
@@ -24,6 +24,8 @@ import com.intellij.javadoc.JavadocNavigationDelegate;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.*;
import com.intellij.psi.javadoc.PsiDocComment;
@@ -63,39 +65,32 @@ public class JavaDocCommentFixer implements DocCommentFixer {
*/
@NotNull private static final Set<String> CARET_ANCHOR_TAGS = ContainerUtilRt.newHashSet(PARAM_TAG, "@throws", "@return");
@NotNull private static final List<String> TAGS_ORDER = new ArrayList<String>();
static {
String tags = System.getProperty("java.doc.comment.fix.tags.order");
if (tags == null) {
tags = "@param:@return:@throws";
}
for (String s : tags.split(":")) {
String tagName = s.trim();
if (!tagName.isEmpty()) {
TAGS_ORDER.add("@" + tagName);
}
}
}
private static final Comparator<PsiElement> COMPARATOR = new Comparator<PsiElement>() {
@NotNull private static final Comparator<PsiElement> COMPARATOR = new Comparator<PsiElement>() {
@Override
public int compare(PsiElement e1, PsiElement e2) {
return e2.getTextRange().getEndOffset() - e1.getTextRange().getEndOffset();
}
};
@NotNull private static final String PARAM_TAG_NAME = "param";
@Override
public void fixComment(@NotNull Project project, @NotNull Editor editor, @NotNull PsiComment comment) {
if (!(comment instanceof PsiDocComment)) {
return;
}
PsiDocCommentOwner owner = ((PsiDocComment)comment).getOwner();
PsiDocComment docComment = (PsiDocComment)comment;
PsiDocCommentOwner owner = docComment.getOwner();
if (owner == null) {
return;
}
PsiFile file = comment.getContainingFile();
if (file == null) {
return;
}
JavaDocReferenceInspection referenceInspection = new JavaDocReferenceInspection();
JavaDocLocalInspection localInspection = getDocLocalInspection();
@@ -123,7 +118,8 @@ public class JavaDocCommentFixer implements DocCommentFixer {
}
PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(editor.getDocument());
locateCaret((PsiDocComment)comment, editor);
ensureContentOrdered(docComment, editor.getDocument());
locateCaret(docComment, editor, file);
}
@NotNull
@@ -137,7 +133,7 @@ public class JavaDocCommentFixer implements DocCommentFixer {
localInspection.METHOD_OPTIONS.ACCESS_JAVADOC_REQUIRED_FOR = PsiModifier.PRIVATE;
//endregion
localInspection.IGNORE_EMPTY_DESCRIPTIONS = true;
localInspection.setIgnoreEmptyDescriptions(true);
//region class type arguments
if (!localInspection.TOP_LEVEL_CLASS_OPTIONS.REQUIRED_TAGS.contains(PARAM_TAG)) {
@@ -161,7 +157,16 @@ public class JavaDocCommentFixer implements DocCommentFixer {
}
}
// TODO den add doc
/**
* This fixer is based on existing javadoc inspections - there are two of them. One detects invalid references (to unexisted
* method parameter or non-declared checked exception). Another one handles all other cases (parameter documentation is missing;
* parameter doesn't have a description etc). This method handles result of the second exception
*
* @param problems detected problems
* @param comment target comment to fix
* @param document target document which contains text of the commen being fixed
* @param project current project
*/
@SuppressWarnings("unchecked")
private static void fixCommonProblems(@NotNull ProblemDescriptor[] problems,
@NotNull PsiComment comment,
@@ -198,8 +203,9 @@ public class JavaDocCommentFixer implements DocCommentFixer {
if (toRemove.size() > 1) {
Collections.sort(toRemove, COMPARATOR);
}
PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(document);
PsiDocumentManager psiDocumentManager = PsiDocumentManager.getInstance(project);
psiDocumentManager.doPostponedOperationsAndUnblockDocument(document);
CharSequence text = document.getCharsSequence();
for (PsiElement element : toRemove) {
int startOffset = element.getTextRange().getStartOffset();
@@ -223,9 +229,90 @@ public class JavaDocCommentFixer implements DocCommentFixer {
}
document.deleteString(startOffset, endOffset);
}
psiDocumentManager.commitDocument(document);
}
private static void locateCaret(@NotNull PsiDocComment comment, @NotNull Editor editor) {
private static void ensureContentOrdered(@NotNull PsiDocComment comment, @NotNull Document document) {
//region Parse existing doc comment parameters.
List<String> current = new ArrayList<String>();
Map<String, Pair<TextRange, String>> tagInfoByName = new HashMap<String, Pair<TextRange, String>>();
for (PsiDocTag tag : comment.getTags()) {
if (!PARAM_TAG_NAME.equals(tag.getName())) {
continue;
}
PsiDocTagValue valueElement = tag.getValueElement();
if (valueElement == null) {
continue;
}
String paramName = valueElement.getText();
if (paramName != null) {
current.add(paramName);
tagInfoByName.put(paramName, parseTagValue(tag, document));
}
}
//endregion
//region Calculate desired parameters order
List<String> ordered = new ArrayList<String>();
PsiDocCommentOwner owner = comment.getOwner();
if ((owner instanceof PsiMethod)) {
PsiParameter[] parameters = ((PsiMethod)owner).getParameterList().getParameters();
for (PsiParameter parameter : parameters) {
ordered.add(parameter.getName());
}
}
if (owner instanceof PsiTypeParameterListOwner) {
PsiTypeParameter[] typeParameters = ((PsiTypeParameterListOwner)owner).getTypeParameters();
for (PsiTypeParameter parameter : typeParameters) {
ordered.add(String.format("<%s>", parameter.getName()));
}
}
//endregion
//region Fix order if necessary.
if (current.size() != ordered.size()) {
// Something is wrong, stop the processing.
return;
}
boolean changed = false;
for (int i = current.size() - 1; i >= 0; i--) {
String newTag = ordered.get(i);
String oldTag = current.get(i);
if (newTag.equals(oldTag)) {
continue;
}
TextRange range = tagInfoByName.get(oldTag).first;
document.replaceString(range.getStartOffset(), range.getEndOffset(), tagInfoByName.get(newTag).second);
changed = true;
}
if (changed) {
PsiDocumentManager manager = PsiDocumentManager.getInstance(comment.getProject());
manager.commitDocument(document);
}
//endregion
}
@NotNull
private static Pair<TextRange, String> parseTagValue(@NotNull PsiDocTag tag, @NotNull Document document) {
PsiDocTagValue valueElement = tag.getValueElement();
assert valueElement != null;
int startOffset = valueElement.getTextRange().getStartOffset();
int endOffset = tag.getTextRange().getEndOffset();
// Javadoc PSI is rather weird...
CharSequence text = document.getCharsSequence();
int i = CharArrayUtil.shiftBackward(text, endOffset - 1, " \t*");
if (i > 0 && text.charAt(i) == '\n') {
endOffset = i;
}
return Pair.create(TextRange.create(startOffset, endOffset), text.subSequence(startOffset, endOffset).toString());
}
private static void locateCaret(@NotNull PsiDocComment comment, @NotNull Editor editor, @NotNull PsiFile file) {
Document document = editor.getDocument();
int lineToNavigate = -1;
for (PsiDocTag tag : comment.getTags()) {
@@ -261,7 +348,7 @@ public class JavaDocCommentFixer implements DocCommentFixer {
if (lineToNavigate >= 0) {
editor.getCaretModel().moveToOffset(document.getLineEndOffset(lineToNavigate));
JavadocNavigationDelegate.navigateToLineEnd(editor, comment.getContainingFile());
JavadocNavigationDelegate.navigateToLineEnd(editor, file);
}
}
}
@@ -120,10 +120,10 @@ public class JavaTypedHandler extends TypedHandlerDelegate {
}
HighlighterIterator iterator = ((EditorEx) editor).getHighlighter().createIterator(offset - 1);
while (iterator.getTokenType() == TokenType.WHITE_SPACE) {
while (!iterator.atEnd() && iterator.getTokenType() == TokenType.WHITE_SPACE) {
iterator.retreat();
}
if (iterator.getTokenType() == JavaTokenType.RBRACKET || iterator.getTokenType() == JavaTokenType.EQ) {
if (iterator.atEnd() || iterator.getTokenType() == JavaTokenType.RBRACKET || iterator.getTokenType() == JavaTokenType.EQ) {
return Result.CONTINUE;
}
PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument());
@@ -32,7 +32,7 @@ import java.util.Collection;
public class HighlightExceptionsHandlerFactory implements HighlightUsagesHandlerFactory {
@Override
public HighlightUsagesHandlerBase createHighlightUsagesHandler(final Editor editor, final PsiFile file) {
int offset = TargetElementUtilBase.adjustOffset(editor.getDocument(), editor.getCaretModel().getOffset());
int offset = TargetElementUtilBase.adjustOffset(file, editor.getDocument(), editor.getCaretModel().getOffset());
PsiElement target = file.findElementAt(offset);
if (target instanceof PsiKeyword) {
PsiElement parent = target.getParent();
@@ -27,7 +27,7 @@ import com.intellij.codeInsight.TargetElementUtilBase;
public class HighlightExitPointsHandlerFactory implements HighlightUsagesHandlerFactory {
@Override
public HighlightUsagesHandlerBase createHighlightUsagesHandler(final Editor editor, final PsiFile file) {
int offset = TargetElementUtilBase.adjustOffset(editor.getDocument(), editor.getCaretModel().getOffset());
int offset = TargetElementUtilBase.adjustOffset(file, editor.getDocument(), editor.getCaretModel().getOffset());
PsiElement target = file.findElementAt(offset);
if (target instanceof PsiKeyword) {
if (PsiKeyword.RETURN.equals(target.getText()) || PsiKeyword.THROW.equals(target.getText())) {
@@ -25,7 +25,7 @@ import com.intellij.codeInsight.TargetElementUtilBase;
public class HighlightOverridingMethodsHandlerFactory implements HighlightUsagesHandlerFactory {
@Override
public HighlightUsagesHandlerBase createHighlightUsagesHandler(final Editor editor, final PsiFile file) {
int offset = TargetElementUtilBase.adjustOffset(editor.getDocument(), editor.getCaretModel().getOffset());
int offset = TargetElementUtilBase.adjustOffset(file, editor.getDocument(), editor.getCaretModel().getOffset());
final PsiElement target = file.findElementAt(offset);
if (target instanceof PsiKeyword && (PsiKeyword.EXTENDS.equals(target.getText()) || PsiKeyword.IMPLEMENTS.equals(target.getText()))) {
PsiElement parent = target.getParent();
@@ -31,7 +31,7 @@ import com.intellij.psi.util.PsiTreeUtil;
public class HighlightSuppressedWarningsFactory implements HighlightUsagesHandlerFactory {
@Override
public HighlightUsagesHandlerBase createHighlightUsagesHandler(final Editor editor, final PsiFile file) {
int offset = TargetElementUtilBase.adjustOffset(editor.getDocument(), editor.getCaretModel().getOffset());
int offset = TargetElementUtilBase.adjustOffset(file, editor.getDocument(), editor.getCaretModel().getOffset());
final PsiElement target = file.findElementAt(offset);
final PsiAnnotation annotation = PsiTreeUtil.getParentOfType(target, PsiAnnotation.class);
if (annotation != null && Comparing.strEqual(SuppressWarnings.class.getName(), annotation.getQualifiedName())) {
@@ -39,16 +39,27 @@ import java.util.Set;
* @author peter
*/
public class PsiTypeLookupItem extends LookupItem {
private static final InsertHandler<PsiTypeLookupItem> DEFAULT_IMPORT_FIXER = new InsertHandler<PsiTypeLookupItem>() {
@Override
public void handleInsert(InsertionContext context, PsiTypeLookupItem item) {
if (item.getObject() instanceof PsiClass) {
addImportForItem(context, (PsiClass)item.getObject());
}
}
};
private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.lookup.PsiTypeLookupItem");
public static final ClassConditionKey<PsiTypeLookupItem> CLASS_CONDITION_KEY = ClassConditionKey.create(PsiTypeLookupItem.class);
private final boolean myDiamond;
private final int myBracketsCount;
private boolean myIndicateAnonymous;
private final InsertHandler<PsiTypeLookupItem> myImportFixer;
private PsiTypeLookupItem(Object o, @NotNull @NonNls String lookupString, boolean diamond, int bracketsCount) {
private PsiTypeLookupItem(Object o, @NotNull @NonNls String lookupString, boolean diamond, int bracketsCount, InsertHandler<PsiTypeLookupItem> fixer) {
super(o, lookupString);
myDiamond = diamond;
myBracketsCount = bracketsCount;
myImportFixer = fixer;
}
@NotNull
@@ -77,9 +88,7 @@ public class PsiTypeLookupItem extends LookupItem {
@Override
public void handleInsert(InsertionContext context) {
if (getObject() instanceof PsiClass) {
addImportForItem(context, (PsiClass)getObject());
}
myImportFixer.handleInsert(context, this);
PsiElement position = context.getFile().findElementAt(context.getStartOffset());
assert position != null;
@@ -96,13 +105,14 @@ public class PsiTypeLookupItem extends LookupItem {
if (context.getCompletionChar() == '[') {
context.setAddCompletionChar(false);
}
} else {
}
else {
editor.getCaretModel().moveToOffset(tail);
}
editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
InsertHandler handler = getInsertHandler();
if (handler != null && !(handler instanceof DefaultInsertHandler)) {
if (handler != null && !(handler instanceof DefaultInsertHandler)) {
//noinspection unchecked
handler.handleInsert(context, this);
}
@@ -159,6 +169,11 @@ public class PsiTypeLookupItem extends LookupItem {
}
public static PsiTypeLookupItem createLookupItem(@NotNull PsiType type, @Nullable PsiElement context, boolean isDiamond) {
return createLookupItem(type, context, isDiamond, DEFAULT_IMPORT_FIXER);
}
public static PsiTypeLookupItem createLookupItem(@NotNull PsiType type, @Nullable PsiElement context, boolean isDiamond, InsertHandler<PsiTypeLookupItem> importFixer) {
final PsiType original = type;
int dim = 0;
while (type instanceof PsiArrayType) {
@@ -166,13 +181,17 @@ public class PsiTypeLookupItem extends LookupItem {
dim++;
}
PsiTypeLookupItem item = doCreateItem(type, context, dim, isDiamond);
PsiTypeLookupItem item = doCreateItem(type, context, dim, isDiamond, importFixer);
item.setAttribute(TYPE, original);
return item;
}
private static PsiTypeLookupItem doCreateItem(final PsiType type, PsiElement context, int bracketsCount, boolean diamond) {
private static PsiTypeLookupItem doCreateItem(final PsiType type,
PsiElement context,
int bracketsCount,
boolean diamond,
InsertHandler<PsiTypeLookupItem> importFixer) {
if (type instanceof PsiClassType) {
PsiClassType.ClassResolveResult classResolveResult = ((PsiClassType)type).resolveGenerics();
final PsiClass psiClass = classResolveResult.getElement();
@@ -195,17 +214,17 @@ public class PsiTypeLookupItem extends LookupItem {
}
}
PsiTypeLookupItem item = new PsiTypeLookupItem(psiClass, lookupString, diamond, bracketsCount);
PsiTypeLookupItem item = new PsiTypeLookupItem(psiClass, lookupString, diamond, bracketsCount, importFixer);
item.addLookupStrings(allStrings.toArray(new String[allStrings.size()]));
item.setAttribute(SUBSTITUTOR, substitutor);
return item;
}
}
return new PsiTypeLookupItem(type, type.getPresentableText(), false, bracketsCount);
return new PsiTypeLookupItem(type, type.getPresentableText(), false, bracketsCount, importFixer);
}
private static boolean isDiamond(PsiType type) {
public static boolean isDiamond(PsiType type) {
boolean diamond = false;
if (type instanceof PsiClassReferenceType) {
final PsiReferenceParameterList parameterList = ((PsiClassReferenceType)type).getReference().getParameterList();
@@ -247,6 +266,7 @@ public class PsiTypeLookupItem extends LookupItem {
public static void addImportForItem(InsertionContext context, PsiClass aClass) {
if (aClass.getQualifiedName() == null) return;
PsiFile file = context.getFile();
int newTail = JavaCompletionUtil.insertClassReference(aClass, file, context.getStartOffset(), context.getTailOffset());
if (newTail > context.getDocument().getTextLength() || newTail < 0) {
LOG.error(LogMessageEx.createEvent("Invalid offset after insertion ",
@@ -64,7 +64,7 @@ public class VariableLookupItem extends LookupItem<PsiVariable> implements Typed
public void renderElement(LookupElementPresentation presentation) {
super.renderElement(presentation);
if (myHelper != null) {
myHelper.renderElement(presentation, getAttribute(FORCE_QUALIFY) != null ? Boolean.TRUE : null, PsiSubstitutor.EMPTY);
myHelper.renderElement(presentation, getAttribute(FORCE_QUALIFY) != null ? Boolean.TRUE : null, getSubstitutor());
}
}
@@ -19,6 +19,7 @@ import com.intellij.codeInsight.completion.JavaCompletionUtil;
import com.intellij.codeInsight.lookup.DefaultLookupItemRenderer;
import com.intellij.codeInsight.lookup.LookupElementPresentation;
import com.intellij.codeInsight.lookup.LookupItem;
import com.intellij.codeInsight.lookup.VariableLookupItem;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.*;
import com.intellij.psi.impl.beanProperties.BeanPropertyElement;
@@ -90,7 +91,11 @@ public class JavaElementLookupRenderer implements ElementLookupRenderer {
if (element.isValid()) {
if (element instanceof PsiVariable){
PsiVariable variable = (PsiVariable)element;
text = variable.getType().getPresentableText();
PsiType type = variable.getType();
if (item instanceof VariableLookupItem) {
type = ((VariableLookupItem)item).getSubstitutor().substitute(type);
}
text = type.getPresentableText();
}
else if (element instanceof PsiExpression){
PsiExpression expression = (PsiExpression)element;
@@ -37,7 +37,6 @@ public class ArrayVariableMacro extends VariableTypeMacroBase {
Project project = context.getProject();
final int offset = context.getStartOffset();
PsiDocumentManager.getInstance(project).commitAllDocuments();
final ArrayList<PsiVariable> array = new ArrayList<PsiVariable>();
PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(context.getEditor().getDocument());
PsiElement place = file.findElementAt(offset);
@@ -43,7 +43,6 @@ public class CastToLeftSideTypeMacro extends Macro {
public Result calculateResult(@NotNull Expression[] params, ExpressionContext context) {
int offset = context.getStartOffset();
Project project = context.getProject();
PsiDocumentManager.getInstance(project).commitAllDocuments();
PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(context.getEditor().getDocument());
PsiElement element = file.findElementAt(offset);
element = PsiTreeUtil.getParentOfType(element, PsiAssignmentExpression.class, PsiVariable.class);
@@ -61,7 +61,6 @@ public class ComponentTypeOfMacro extends Macro {
final Result result = params[0].calculateResult(context);
if (result == null) return null;
PsiDocumentManager.getInstance(context.getProject()).commitAllDocuments();
if (result instanceof PsiTypeResult) {
PsiType type = ((PsiTypeResult) result).getType();
if (type instanceof PsiArrayType) {
@@ -44,7 +44,6 @@ class CurrentPackageMacro extends Macro {
Project project = context.getProject();
PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(context.getEditor().getDocument());
if (!(file instanceof PsiJavaFile)) return new TextResult ("");
PsiDocumentManager.getInstance(project).commitDocument(context.getEditor().getDocument());
return new TextResult (((PsiJavaFile)file).getPackageName());
}
@@ -69,7 +69,6 @@ public class ExpectedTypeMacro extends Macro {
if (params.length != 0) return null;
final Project project = context.getProject();
PsiDocumentManager.getInstance(project).commitAllDocuments();
PsiType[] types = null;
final int offset = context.getTemplateStartOffset();
@@ -23,7 +23,6 @@ import com.intellij.codeInsight.template.*;
import com.intellij.codeInsight.template.impl.JavaTemplateUtil;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiExpression;
import com.intellij.psi.PsiType;
import com.intellij.psi.PsiWildcardType;
@@ -70,7 +69,6 @@ public class GuessElementTypeMacro extends Macro {
if (result == null) return null;
Project project = context.getProject();
PsiDocumentManager.getInstance(project).commitAllDocuments();
PsiExpression expr = MacroUtil.resultToPsiExpression(result, context);
if (expr == null) return null;
@@ -45,7 +45,6 @@ public class IterableComponentTypeMacro extends Macro {
if (result == null) return null;
Project project = context.getProject();
PsiDocumentManager.getInstance(project).commitAllDocuments();
PsiExpression expr = MacroUtil.resultToPsiExpression(result, context);
if (expr == null) return null;
@@ -53,7 +53,6 @@ public class IterableVariableMacro extends VariableTypeMacroBase {
Project project = context.getProject();
final int offset = context.getStartOffset();
PsiDocumentManager.getInstance(project).commitAllDocuments();
PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(context.getEditor().getDocument());
assert file != null;
PsiElement place = file.findElementAt(offset);
@@ -44,7 +44,6 @@ public class MacroUtil {
String text = result.toString();
if (text == null) return null;
PsiManager manager = PsiManager.getInstance(project);
PsiDocumentManager.getInstance(project).commitAllDocuments();
PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(context.getEditor().getDocument());
//-1: Hack to deal with stupid resolve
PsiElement place = file != null ? file.findElementAt(context.getStartOffset()) : null;
@@ -72,7 +71,6 @@ public class MacroUtil {
String text = result.toString();
if (text == null) return null;
PsiManager manager = PsiManager.getInstance(project);
PsiDocumentManager.getInstance(project).commitAllDocuments();
PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(context.getEditor().getDocument());
//-1: Hack to deal with resolve algorithm
PsiElement place = file != null ? file.findElementAt(context.getStartOffset()) : null;
@@ -39,7 +39,6 @@ public class RightSideTypeMacro extends Macro {
public Result calculateResult(@NotNull Expression[] params, ExpressionContext context) {
int offset = context.getStartOffset();
Project project = context.getProject();
PsiDocumentManager.getInstance(project).commitAllDocuments();
PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(context.getEditor().getDocument());
PsiElement element = file.findElementAt(offset);
element = PsiTreeUtil.getParentOfType(element, PsiAssignmentExpression.class, PsiVariable.class);
@@ -42,8 +42,6 @@ public class SuggestIndexNameMacro extends Macro {
final Project project = context.getProject();
final int offset = context.getStartOffset();
PsiDocumentManager.getInstance(project).commitAllDocuments();
PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(context.getEditor().getDocument());
PsiElement place = file.findElementAt(offset);
PsiVariable[] vars = MacroUtil.getVariablesVisibleAt(place, "");
@@ -41,7 +41,6 @@ public class TypeOfVariableMacro extends Macro {
if (params.length == 0) return null;
final Project project = context.getProject();
PsiDocumentManager.getInstance(project).commitAllDocuments();
Result result = params[0].calculateQuickResult(context);
if (result instanceof PsiElementResult) {
final PsiElement element = ((PsiElementResult)result).getElement();
@@ -72,8 +72,6 @@ public class VariableOfTypeMacro extends Macro {
Project project = context.getProject();
final int offset = context.getStartOffset();
PsiDocumentManager.getInstance(project).commitAllDocuments();
final ArrayList<PsiElement> array = new ArrayList<PsiElement>();
PsiType type = MacroUtil.resultToPsiType(result, context);
PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(context.getEditor().getDocument());
@@ -92,16 +92,17 @@ public class JavaDocLocalInspection extends BaseLocalInspectionTool {
}
}
@NonNls public Options TOP_LEVEL_CLASS_OPTIONS = new Options("none", "");
@NonNls public Options INNER_CLASS_OPTIONS = new Options("none", "");
@NonNls public Options METHOD_OPTIONS = new Options("none", "@return@param@throws or @exception");
@NonNls public Options FIELD_OPTIONS = new Options("none", "");
public boolean IGNORE_DEPRECATED = false;
public boolean IGNORE_JAVADOC_PERIOD = true;
public boolean IGNORE_DUPLICATED_THROWS = false;
public boolean IGNORE_POINT_TO_ITSELF = false;
public boolean IGNORE_EMPTY_DESCRIPTIONS = false;
public String myAdditionalJavadocTags = "";
@NonNls public Options TOP_LEVEL_CLASS_OPTIONS = new Options("none", "");
@NonNls public Options INNER_CLASS_OPTIONS = new Options("none", "");
@NonNls public Options METHOD_OPTIONS = new Options("none", "@return@param@throws or @exception");
@NonNls public Options FIELD_OPTIONS = new Options("none", "");
public boolean IGNORE_DEPRECATED = false;
public boolean IGNORE_JAVADOC_PERIOD = true;
public boolean IGNORE_DUPLICATED_THROWS = false;
public boolean IGNORE_POINT_TO_ITSELF = false;
public String myAdditionalJavadocTags = "";
private boolean myIgnoreEmptyDescriptions = false;
private static final Logger LOG = Logger.getInstance("com.intellij.codeInspection.javaDoc.JavaDocLocalInspection");
@@ -595,7 +596,7 @@ public class JavaDocLocalInspection extends BaseLocalInspectionTool {
}
}
if (!IGNORE_EMPTY_DESCRIPTIONS) {
if (!myIgnoreEmptyDescriptions) {
for (PsiDocTag tag : tags) {
if ("param".equals(tag.getName())) {
final PsiElement[] dataElements = tag.getDataElements();
@@ -664,7 +665,7 @@ public class JavaDocLocalInspection extends BaseLocalInspectionTool {
}
}
else
if ("return".equals(tag.getName()) && !IGNORE_EMPTY_DESCRIPTIONS) {
if ("return".equals(tag.getName()) && !myIgnoreEmptyDescriptions) {
if (extractTagDescription(tag).length() == 0) {
String message = InspectionsBundle.message("inspection.javadoc.method.problem.missing.tag.description", "<code>@return</code>");
ProblemDescriptor descriptor = manager.createProblemDescriptor(tag.getNameElement(), message, (LocalQuickFix)null, ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
@@ -717,7 +718,7 @@ public class JavaDocLocalInspection extends BaseLocalInspectionTool {
PsiClassType classType = it.next();
final PsiClass psiClass = declaredExceptions.get(classType);
if (InheritanceUtil.isInheritorOrSelf(exceptionClass, psiClass, true)) {
if (!IGNORE_EMPTY_DESCRIPTIONS && extractThrowsTagDescription(tag).length() == 0) {
if (!myIgnoreEmptyDescriptions && extractThrowsTagDescription(tag).length() == 0) {
problems.add(createDescriptor(tag.getNameElement(), InspectionsBundle.message("inspection.javadoc.method.problem.missing.tag.description", "<code>" + tag.getName() + "</code>"), mananger,
isOnTheFly));
}
@@ -1150,6 +1151,10 @@ public class JavaDocLocalInspection extends BaseLocalInspectionTool {
return SHORT_NAME;
}
public void setIgnoreEmptyDescriptions(boolean ignoreEmptyDescriptions) {
myIgnoreEmptyDescriptions = ignoreEmptyDescriptions;
}
private class AddUnknownTagToCustoms implements LocalQuickFix {
private final String myTag;
@@ -152,6 +152,15 @@ public class FieldCanBeLocalInspection extends BaseLocalInspectionTool {
}
}
@Override
public void visitLambdaExpression(PsiLambdaExpression expression) {
super.visitLambdaExpression(expression);
final PsiElement body = expression.getBody();
if (body != null) {
checkCodeBlock(body, candidates, usedFields);
}
}
@Override
public void visitClassInitializer(PsiClassInitializer initializer) {
super.visitClassInitializer(initializer);
@@ -160,7 +169,7 @@ public class FieldCanBeLocalInspection extends BaseLocalInspectionTool {
});
}
private static void checkCodeBlock(final PsiCodeBlock body, final Set<PsiField> candidates, Set<PsiField> usedFields) {
private static void checkCodeBlock(final PsiElement body, final Set<PsiField> candidates, Set<PsiField> usedFields) {
try {
final ControlFlow controlFlow = ControlFlowFactory.getInstance(body.getProject()).getControlFlow(body, AllVariablesControlFlowPolicy.getInstance());
final List<PsiVariable> usedVars = ControlFlowUtil.getUsedVariables(controlFlow, 0, controlFlow.getSize());
@@ -109,7 +109,8 @@ public class JavaFindUsagesHandler extends FindUsagesHandler{
Messages.getQuestionIcon()) == 0;
}
private static PsiElement[] getParameterElementsToSearch(final PsiParameter parameter) {
@NotNull
private static PsiElement[] getParameterElementsToSearch(@NotNull PsiParameter parameter) {
final PsiMethod method = (PsiMethod)parameter.getDeclarationScope();
PsiMethod[] overrides = OverridingMethodsSearch.search(method, true).toArray(PsiMethod.EMPTY_ARRAY);
for (int i = 0; i < overrides.length; i++) {
@@ -272,15 +273,17 @@ public class JavaFindUsagesHandler extends FindUsagesHandler{
}
@Override
public void processElementUsages(@NotNull final PsiElement element, @NotNull final Processor<UsageInfo> processor, @NotNull final FindUsagesOptions options) {
public boolean processElementUsages(@NotNull final PsiElement element,
@NotNull final Processor<UsageInfo> processor,
@NotNull final FindUsagesOptions options) {
if (options instanceof JavaVariableFindUsagesOptions) {
final JavaVariableFindUsagesOptions varOptions = (JavaVariableFindUsagesOptions) options;
if (varOptions.isReadAccess || varOptions.isWriteAccess){
if (varOptions.isReadAccess && varOptions.isWriteAccess){
addElementUsages(element, processor, options);
if (!addElementUsages(element, processor, options)) return false;
}
else{
addElementUsages(element, new Processor<UsageInfo>() {
if (!addElementUsages(element, new Processor<UsageInfo>() {
@Override
public boolean process(UsageInfo info) {
final PsiElement element = info.getElement();
@@ -290,17 +293,17 @@ public class JavaFindUsagesHandler extends FindUsagesHandler{
}
return true;
}
}, varOptions);
}, varOptions)) return false;
}
}
}
else if (options.isUsages) {
addElementUsages(element, processor, options);
if (!addElementUsages(element, processor, options)) return false;
}
ApplicationManager.getApplication().runReadAction(new Runnable() {
boolean success = ApplicationManager.getApplication().runReadAction(new Computable<Boolean>() {
@Override
public void run() {
public Boolean compute() {
if (ThrowSearchUtil.isSearchable (element) && options instanceof JavaThrowFindUsagesOptions && options.isUsages) {
ThrowSearchUtil.Root root = options.getUserData(ThrowSearchUtil.THROW_SEARCH_ROOT_KEY);
if (root == null) {
@@ -310,45 +313,45 @@ public class JavaFindUsagesHandler extends FindUsagesHandler{
}
}
if (root != null) {
ThrowSearchUtil.addThrowUsages(processor, root, options);
return ThrowSearchUtil.addThrowUsages(processor, root, options);
}
}
return true;
}
});
if (!success) return false;
if (options instanceof JavaPackageFindUsagesOptions && ((JavaPackageFindUsagesOptions)options).isClassesUsages){
addClassesUsages((PsiPackage)element, processor, (JavaPackageFindUsagesOptions)options);
if (!addClassesUsages((PsiPackage)element, processor, (JavaPackageFindUsagesOptions)options)) return false;
}
if (options instanceof JavaClassFindUsagesOptions) {
final JavaClassFindUsagesOptions classOptions = (JavaClassFindUsagesOptions)options;
final PsiClass psiClass = (PsiClass)element;
if (classOptions.isMethodsUsages){
addMethodsUsages(psiClass, processor, classOptions);
if (!addMethodsUsages(psiClass, processor, classOptions)) return false;
}
if (classOptions.isFieldsUsages){
addFieldsUsages(psiClass, processor, classOptions);
if (!addFieldsUsages(psiClass, processor, classOptions)) return false;
}
if (psiClass.isInterface()) {
if (classOptions.isDerivedInterfaces){
if (classOptions.isImplementingClasses){
addInheritors(psiClass, processor, classOptions);
if (!addInheritors(psiClass, processor, classOptions)) return false;
}
else{
addDerivedInterfaces(psiClass, processor, classOptions);
if (!addDerivedInterfaces(psiClass, processor, classOptions)) return false;
}
}
else if (classOptions.isImplementingClasses){
addImplementingClasses(psiClass, processor, classOptions);
if (!addImplementingClasses(psiClass, processor, classOptions)) return false;
}
}
else if (classOptions.isDerivedClasses) {
addInheritors(psiClass, processor, classOptions);
if (!addInheritors(psiClass, processor, classOptions)) return false;
}
}
if (options instanceof JavaMethodFindUsagesOptions){
final PsiMethod psiMethod = (PsiMethod)element;
boolean isAbstract = ApplicationManager.getApplication().runReadAction(new Computable<Boolean>() {
@@ -359,12 +362,12 @@ public class JavaFindUsagesHandler extends FindUsagesHandler{
});
final JavaMethodFindUsagesOptions methodOptions = (JavaMethodFindUsagesOptions)options;
if (isAbstract && methodOptions.isImplementingMethods || methodOptions.isOverridingMethods) {
processOverridingMethods(psiMethod, processor, methodOptions);
if (!processOverridingMethods(psiMethod, processor, methodOptions)) return false;
}
}
if (element instanceof PomTarget) {
addAliasingUsages((PomTarget)element, processor, options);
if (!addAliasingUsages((PomTarget)element, processor, options)) return false;
}
final Boolean isSearchable = ApplicationManager.getApplication().runReadAction(new Computable<Boolean>() {
@Override
@@ -374,43 +377,52 @@ public class JavaFindUsagesHandler extends FindUsagesHandler{
});
if (!isSearchable && options.isSearchForTextOccurrences && options.searchScope instanceof GlobalSearchScope) {
// todo add to fastTrack
processUsagesInText(element, processor, (GlobalSearchScope)options.searchScope);
if (!processUsagesInText(element, processor, (GlobalSearchScope)options.searchScope)) return false;
}
return true;
}
private static void addAliasingUsages(PomTarget pomTarget, final Processor<UsageInfo> processor, final FindUsagesOptions options) {
private static boolean addAliasingUsages(@NotNull PomTarget pomTarget,
@NotNull final Processor<UsageInfo> processor,
@NotNull final FindUsagesOptions options) {
for (AliasingPsiTargetMapper aliasingPsiTargetMapper : Extensions.getExtensions(AliasingPsiTargetMapper.EP_NAME)) {
for (AliasingPsiTarget psiTarget : aliasingPsiTargetMapper.getTargets(pomTarget)) {
ReferencesSearch.search(new ReferencesSearch.SearchParameters(PomService.convertToPsi(psiTarget), options.searchScope, false, options.fastTrack)).forEach(new ReadActionProcessor<PsiReference>() {
boolean success = ReferencesSearch
.search(new ReferencesSearch.SearchParameters(PomService.convertToPsi(psiTarget), options.searchScope, false, options.fastTrack))
.forEach(new ReadActionProcessor<PsiReference>() {
@Override
public boolean processInReadAction(final PsiReference reference) {
addResult(processor, reference, options);
return true;
return addResult(processor, reference, options);
}
});
if (!success) return false;
}
}
return true;
}
private static void processOverridingMethods(PsiMethod psiMethod, final Processor<UsageInfo> processor, final JavaMethodFindUsagesOptions options) {
OverridingMethodsSearch.search(psiMethod, options.searchScope, options.isCheckDeepInheritance).forEach(new PsiElementProcessorAdapter<PsiMethod>(
private static boolean processOverridingMethods(@NotNull PsiMethod psiMethod,
@NotNull final Processor<UsageInfo> processor,
@NotNull final JavaMethodFindUsagesOptions options) {
return OverridingMethodsSearch.search(psiMethod, options.searchScope, options.isCheckDeepInheritance).forEach(new PsiElementProcessorAdapter<PsiMethod>(
new PsiElementProcessor<PsiMethod>() {
@Override
public boolean execute(@NotNull PsiMethod element) {
addResult(processor, element.getNavigationElement(), options);
return true;
return addResult(processor, element.getNavigationElement(), options);
}
}));
}
private static void addClassesUsages(PsiPackage aPackage, final Processor<UsageInfo> results, final JavaPackageFindUsagesOptions options) {
private static boolean addClassesUsages(@NotNull PsiPackage aPackage,
@NotNull final Processor<UsageInfo> processor,
@NotNull final JavaPackageFindUsagesOptions options) {
ProgressIndicator progress = ProgressManager.getInstance().getProgressIndicator();
if (progress != null){
progress.pushState();
}
ArrayList<PsiClass> classes = new ArrayList<PsiClass>();
List<PsiClass> classes = new ArrayList<PsiClass>();
addClassesInPackage(aPackage, options.isIncludeSubpackages, classes);
for (final PsiClass aClass : classes) {
if (progress != null) {
@@ -422,27 +434,31 @@ public class JavaFindUsagesHandler extends FindUsagesHandler{
})));
progress.checkCanceled();
}
ReferencesSearch.search(new ReferencesSearch.SearchParameters(aClass, options.searchScope, false, options.fastTrack)).forEach(new ReadActionProcessor<PsiReference>() {
boolean success = ReferencesSearch.search(new ReferencesSearch.SearchParameters(aClass, options.searchScope, false, options.fastTrack)).forEach(new ReadActionProcessor<PsiReference>() {
@Override
public boolean processInReadAction(final PsiReference psiReference) {
return addResult(results, psiReference, options);
return addResult(processor, psiReference, options);
}
});
if (!success) return false;
}
if (progress != null){
progress.popState();
}
return true;
}
private static void addClassesInPackage(PsiPackage aPackage, boolean includeSubpackages, ArrayList<PsiClass> array) {
private static void addClassesInPackage(@NotNull PsiPackage aPackage, boolean includeSubpackages, @NotNull List<PsiClass> array) {
PsiDirectory[] dirs = aPackage.getDirectories();
for (PsiDirectory dir : dirs) {
addClassesInDirectory(dir, includeSubpackages, array);
}
}
private static void addClassesInDirectory(final PsiDirectory dir, final boolean includeSubdirs, final ArrayList<PsiClass> array) {
private static void addClassesInDirectory(@NotNull final PsiDirectory dir,
final boolean includeSubdirs,
@NotNull final List<PsiClass> array) {
ApplicationManager.getApplication().runReadAction(new Runnable() {
@Override
public void run() {
@@ -458,41 +474,48 @@ public class JavaFindUsagesHandler extends FindUsagesHandler{
});
}
private static void addMethodsUsages(final PsiClass aClass, final Processor<UsageInfo> results, final JavaClassFindUsagesOptions options) {
private static boolean addMethodsUsages(@NotNull final PsiClass aClass,
@NotNull final Processor<UsageInfo> processor,
@NotNull final JavaClassFindUsagesOptions options) {
if (options.isIncludeInherited) {
final PsiManager manager = aClass.getManager();
PsiMethod[] methods = aClass.getAllMethods();
MethodsLoop:
for(int i = 0; i < methods.length; i++){
final PsiMethod method = methods[i];
// filter overriden methods
MethodSignature methodSignature = method.getSignature(PsiSubstitutor.EMPTY);
for(int j = 0; j < i; j++){
if (methodSignature.equals(methods[j].getSignature(PsiSubstitutor.EMPTY))) continue MethodsLoop;
}
final PsiClass methodClass = method.getContainingClass();
if (methodClass != null && manager.areElementsEquivalent(methodClass, aClass)){
addElementUsages(methods[i], results, options);
}
else{
MethodReferencesSearch.search(new MethodReferencesSearch.SearchParameters(method, options.searchScope, true, options.fastTrack)).forEach(new PsiReferenceProcessorAdapter(new PsiReferenceProcessor() {
@Override
public boolean execute(PsiReference reference) {
addResultFromReference(reference, methodClass, manager, aClass, results, options);
return true;
}
}));
}
for(int i = 0; i < methods.length; i++){
final PsiMethod method = methods[i];
// filter overriden methods
MethodSignature methodSignature = method.getSignature(PsiSubstitutor.EMPTY);
for(int j = 0; j < i; j++){
if (methodSignature.equals(methods[j].getSignature(PsiSubstitutor.EMPTY))) continue MethodsLoop;
}
final PsiClass methodClass = method.getContainingClass();
if (methodClass != null && manager.areElementsEquivalent(methodClass, aClass)){
if (!addElementUsages(methods[i], processor, options)) return false;
}
else {
boolean success = MethodReferencesSearch.search(new MethodReferencesSearch.SearchParameters(method, options.searchScope, true, options.fastTrack))
.forEach(new PsiReferenceProcessorAdapter(new PsiReferenceProcessor() {
@Override
public boolean execute(PsiReference reference) {
addResultFromReference(reference, methodClass, manager, aClass, processor, options);
return true;
}
}));
if (!success) return false;
}
}
}
else {
for (PsiMethod method : aClass.getMethods()) {
addElementUsages(method, results, options);
if (!addElementUsages(method, processor, options)) return false;
}
}
return true;
}
private static void addFieldsUsages(final PsiClass aClass, final Processor<UsageInfo> results, final JavaClassFindUsagesOptions options) {
private static boolean addFieldsUsages(@NotNull final PsiClass aClass,
@NotNull final Processor<UsageInfo> processor,
@NotNull final JavaClassFindUsagesOptions options) {
if (options.isIncludeInherited) {
final PsiManager manager = aClass.getManager();
PsiField[] fields = aClass.getAllFields();
@@ -505,16 +528,16 @@ public class JavaFindUsagesHandler extends FindUsagesHandler{
}
final PsiClass fieldClass = field.getContainingClass();
if (manager.areElementsEquivalent(fieldClass, aClass)) {
addElementUsages(fields[i], results, options);
if (!addElementUsages(fields[i], processor, options)) return false;
}
else {
ReferencesSearch.search(new ReferencesSearch.SearchParameters(field, options.searchScope, false, options.fastTrack)).forEach(new ReadActionProcessor<PsiReference>() {
boolean success = ReferencesSearch.search(new ReferencesSearch.SearchParameters(field, options.searchScope, false, options.fastTrack)).forEach(new ReadActionProcessor<PsiReference>() {
@Override
public boolean processInReadAction(final PsiReference reference) {
addResultFromReference(reference, fieldClass, manager, aClass, results, options);
return true;
return addResultFromReference(reference, fieldClass, manager, aClass, processor, options);
}
});
if (!success) return false;
}
}
}
@@ -526,13 +549,14 @@ public class JavaFindUsagesHandler extends FindUsagesHandler{
}
});
for (PsiField field : fields) {
addElementUsages(field, results, options);
if (!addElementUsages(field, processor, options)) return false;
}
}
return true;
}
@Nullable
private static PsiClass getFieldOrMethodAccessedClass(PsiReferenceExpression ref, PsiClass fieldOrMethodClass) {
private static PsiClass getFieldOrMethodAccessedClass(@NotNull PsiReferenceExpression ref, PsiClass fieldOrMethodClass) {
PsiElement[] children = ref.getChildren();
if (children.length > 1 && children[0] instanceof PsiExpression) {
PsiExpression expr = (PsiExpression)children[0];
@@ -559,111 +583,115 @@ public class JavaFindUsagesHandler extends FindUsagesHandler{
return null;
}
private static void addInheritors(final PsiClass aClass, final Processor<UsageInfo> results, final JavaClassFindUsagesOptions options) {
ClassInheritorsSearch.search(aClass, options.searchScope, options.isCheckDeepInheritance).forEach(new PsiElementProcessorAdapter<PsiClass>(
private static boolean addInheritors(@NotNull PsiClass aClass,
@NotNull final Processor<UsageInfo> processor,
@NotNull final JavaClassFindUsagesOptions options) {
return ClassInheritorsSearch.search(aClass, options.searchScope, options.isCheckDeepInheritance).forEach(new PsiElementProcessorAdapter<PsiClass>(
new PsiElementProcessor<PsiClass>() {
@Override
public boolean execute(@NotNull PsiClass element) {
addResult(results, element, options);
return true;
return addResult(processor, element, options);
}
}));
}
private static void addDerivedInterfaces(PsiClass anInterface, final Processor<UsageInfo> results, final JavaClassFindUsagesOptions options) {
ClassInheritorsSearch.search(anInterface, options.searchScope, options.isCheckDeepInheritance).forEach(new PsiElementProcessorAdapter<PsiClass>(
private static boolean addDerivedInterfaces(@NotNull PsiClass anInterface,
@NotNull final Processor<UsageInfo> processor,
@NotNull final JavaClassFindUsagesOptions options) {
return ClassInheritorsSearch.search(anInterface, options.searchScope, options.isCheckDeepInheritance).forEach(new PsiElementProcessorAdapter<PsiClass>(
new PsiElementProcessor<PsiClass>() {
@Override
public boolean execute(@NotNull PsiClass inheritor) {
if (inheritor.isInterface()) {
addResult(results, inheritor, options);
}
return true;
return !inheritor.isInterface() || addResult(processor, inheritor, options);
}
}));
}
private static void addImplementingClasses(PsiClass anInterface, final Processor<UsageInfo> results, final JavaClassFindUsagesOptions options) {
ClassInheritorsSearch.search(anInterface, options.searchScope, options.isCheckDeepInheritance).forEach(new PsiElementProcessorAdapter<PsiClass>(
private static boolean addImplementingClasses(@NotNull PsiClass anInterface,
@NotNull final Processor<UsageInfo> processor,
@NotNull final JavaClassFindUsagesOptions options) {
return ClassInheritorsSearch.search(anInterface, options.searchScope, options.isCheckDeepInheritance).forEach(new PsiElementProcessorAdapter<PsiClass>(
new PsiElementProcessor<PsiClass>() {
@Override
public boolean execute(@NotNull PsiClass inheritor) {
if (!inheritor.isInterface()) {
addResult(results, inheritor, options);
}
return true;
return inheritor.isInterface() || addResult(processor, inheritor, options);
}
}));
}
private static void addResultFromReference(final PsiReference reference,
final PsiClass methodClass,
final PsiManager manager,
final PsiClass aClass,
final Processor<UsageInfo> results,
final FindUsagesOptions options) {
private static boolean addResultFromReference(@NotNull PsiReference reference,
@NotNull PsiClass methodClass,
@NotNull PsiManager manager,
@NotNull PsiClass aClass,
@NotNull Processor<UsageInfo> processor,
@NotNull FindUsagesOptions options) {
PsiElement refElement = reference.getElement();
if (refElement instanceof PsiReferenceExpression) {
PsiClass usedClass = getFieldOrMethodAccessedClass((PsiReferenceExpression)refElement, methodClass);
if (usedClass != null) {
if (manager.areElementsEquivalent(usedClass, aClass) || usedClass.isInheritor(aClass, true)) {
addResult(results, refElement, options);
if (!addResult(processor, refElement, options)) return false;
}
}
}
return true;
}
public static void addElementUsages(final PsiElement element, final Processor<UsageInfo> result, final FindUsagesOptions options) {
private static boolean addElementUsages(@NotNull final PsiElement element,
@NotNull final Processor<UsageInfo> processor,
@NotNull final FindUsagesOptions options) {
final SearchScope searchScope = options.searchScope;
if (element instanceof PsiMethod && ApplicationManager.getApplication().runReadAction(new Computable<Boolean>() {
@Override
public Boolean compute() {
return ((PsiMethod)element).isConstructor();
}
})){
})) {
PsiMethod method = (PsiMethod)element;
final PsiClass parentClass = method.getContainingClass();
if (parentClass != null) {
MethodReferencesSearch.search(new MethodReferencesSearch.SearchParameters(method, searchScope, options instanceof JavaMethodFindUsagesOptions ? !((JavaMethodFindUsagesOptions)options).isIncludeOverloadUsages : true, options.fastTrack)).forEach(new ReadActionProcessor<PsiReference>() {
@Override
public boolean processInReadAction(final PsiReference ref) {
return addResult(result, ref, options);
}
});
boolean strictSignatureSearch =
!(options instanceof JavaMethodFindUsagesOptions) || !((JavaMethodFindUsagesOptions)options).isIncludeOverloadUsages;
return MethodReferencesSearch
.search(new MethodReferencesSearch.SearchParameters(method, searchScope, strictSignatureSearch, options.fastTrack))
.forEach(new ReadActionProcessor<PsiReference>() {
@Override
public boolean processInReadAction(final PsiReference ref) {
return addResult(processor, ref, options);
}
});
}
return;
return true;
}
final ReadActionProcessor<PsiReference> consumer = new ReadActionProcessor<PsiReference>() {
@Override
public boolean processInReadAction(final PsiReference ref) {
return addResult(result, ref, options);
return addResult(processor, ref, options);
}
};
if (element instanceof PsiMethod) {
final boolean strictSignatureSearch = !(options instanceof JavaMethodFindUsagesOptions) || // field with getter
!((JavaMethodFindUsagesOptions)options).isIncludeOverloadUsages;
MethodReferencesSearch.search(new MethodReferencesSearch.SearchParameters((PsiMethod)element, searchScope, strictSignatureSearch, options.fastTrack)).forEach(consumer);
} else {
ReferencesSearch.search(new ReferencesSearch.SearchParameters(element, searchScope, false, options.fastTrack)).forEach(consumer);
return MethodReferencesSearch
.search(new MethodReferencesSearch.SearchParameters((PsiMethod)element, searchScope, strictSignatureSearch, options.fastTrack))
.forEach(consumer);
}
return ReferencesSearch.search(new ReferencesSearch.SearchParameters(element, searchScope, false, options.fastTrack)).forEach(consumer);
}
public static void addResult(Processor<UsageInfo> total, PsiElement element, FindUsagesOptions options) {
if (filterUsage(element, options)){
total.process(new UsageInfo(element));
}
private static boolean addResult(@NotNull Processor<UsageInfo> processor, @NotNull PsiElement element, @NotNull FindUsagesOptions options) {
return !filterUsage(element, options) || processor.process(new UsageInfo(element));
}
public static boolean addResult(Processor<UsageInfo> results, PsiReference ref, FindUsagesOptions options) {
private static boolean addResult(Processor<UsageInfo> processor, PsiReference ref, FindUsagesOptions options) {
if (filterUsage(ref.getElement(), options)){
TextRange rangeInElement = ref.getRangeInElement();
return results.process(new UsageInfo(ref.getElement(), rangeInElement.getStartOffset(), rangeInElement.getEndOffset(), false));
return processor.process(new UsageInfo(ref.getElement(), rangeInElement.getStartOffset(), rangeInElement.getEndOffset(), false));
}
return true;
}
@@ -35,7 +35,7 @@ public class ThrowsUsageTargetProvider implements UsageTargetProvider {
public UsageTarget[] getTargets(Editor editor, final PsiFile file) {
if (editor == null || file == null) return null;
PsiElement element = file.findElementAt(TargetElementUtilBase.adjustOffset(editor.getDocument(), editor.getCaretModel().getOffset()));
PsiElement element = file.findElementAt(TargetElementUtilBase.adjustOffset(file, editor.getDocument(), editor.getCaretModel().getOffset()));
if (element == null) return null;
if (element instanceof PsiKeyword && PsiKeyword.THROWS.equals(element.getText())) {
@@ -185,6 +185,7 @@ public class JavaLanguageCodeStyleSettingsProvider extends LanguageCodeStyleSett
"\n" +
" public void foo(int x, int y) {" +
" Runnable r = () -> {};\n" +
" Runnable r1 = this :: bar;\n" +
" for (int i = 0; i < x; i++) {\n" +
" y += (y ^ 0x123) << 2;\n" +
" }\n" +
@@ -47,6 +47,7 @@ public class JavaFileTreeModel extends TextEditorBasedStructureViewModel impleme
new PublicElementsFilter()};
}
@NotNull
@Override
public Collection<NodeProvider> getNodeProviders() {
return NODE_PROVIDERS;
@@ -37,8 +37,14 @@ import java.util.ArrayList;
public class JavaModuleType extends ModuleType<JavaModuleBuilder> {
public static ModuleType getModuleType() {
return ModuleTypeManager.getInstance().findByID(JAVA_MODULE);
}
private static final String JAVA_MODULE = "JAVA_MODULE";
public JavaModuleType() {
this("JAVA_MODULE");
this(JAVA_MODULE);
}
protected JavaModuleType(@NonNls String id) {
@@ -26,20 +26,31 @@ import java.util.List;
*/
public class JavaArrangementMethodDependencyInfo {
@NotNull private final List<JavaElementArrangementEntry> getDependentMethods = new ArrayList<JavaElementArrangementEntry>();
@NotNull private final List<JavaArrangementMethodDependencyInfo> myDependentMethods
= new ArrayList<JavaArrangementMethodDependencyInfo>();
@NotNull private final JavaElementArrangementEntry myAnchorMethod;
public JavaArrangementMethodDependencyInfo(@NotNull JavaElementArrangementEntry method) {
myAnchorMethod = method;
}
public void addDependentMethodInfo(@NotNull JavaArrangementMethodDependencyInfo info) {
myDependentMethods.add(info);
}
@NotNull
public List<JavaElementArrangementEntry> getGetDependentMethods() {
return getDependentMethods;
public List<JavaArrangementMethodDependencyInfo> getDependentMethodInfos() {
return myDependentMethods;
}
@NotNull
public JavaElementArrangementEntry getAnchorMethod() {
return myAnchorMethod;
}
@Override
public String toString() {
return myAnchorMethod.toString();
}
}
@@ -0,0 +1,54 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.psi.codeStyle.arrangement;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
/**
* @author Denis Zhdanov
* @since 9/26/12 5:47 PM
*/
public class JavaArrangementOverriddenMethodsInfo {
@NotNull private final List<JavaElementArrangementEntry> myMethodEntries = new ArrayList<JavaElementArrangementEntry>();
@NotNull private final String myName;
public JavaArrangementOverriddenMethodsInfo(@NotNull String name) {
myName = name;
}
public void addMethodEntry(@NotNull JavaElementArrangementEntry entry) {
myMethodEntries.add(entry);
}
@NotNull
public String getName() {
return myName;
}
@NotNull
public List<JavaElementArrangementEntry> getMethodEntries() {
return myMethodEntries;
}
@Override
public String toString() {
return "methods from " + myName;
}
}
@@ -16,10 +16,17 @@
package com.intellij.psi.codeStyle.arrangement;
import com.intellij.openapi.util.Pair;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiMethod;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.Stack;
import gnu.trove.TObjectIntHashMap;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import java.util.HashMap;
import java.util.HashSet;
/**
* @author Denis Zhdanov
@@ -29,12 +36,27 @@ public class JavaArrangementParseInfo {
@NotNull private final List<JavaElementArrangementEntry> myEntries = new ArrayList<JavaElementArrangementEntry>();
@NotNull private final List<JavaArrangementMethodDependencyInfo> myMethodDependencyRoots
= new ArrayList<JavaArrangementMethodDependencyInfo>();
@NotNull private final Map<Pair<String/* property name */, String/* class name */>, JavaArrangementPropertyInfo> myProperties
= new HashMap<Pair<String, String>, JavaArrangementPropertyInfo>();
@NotNull private final List<JavaArrangementMethodDependencyInfo> myMethodDependencyRoots
= new ArrayList<JavaArrangementMethodDependencyInfo>();
@NotNull private final Map<PsiMethod /* anchor */, Set<PsiMethod /* dependencies */>> myMethodDependencies
= new HashMap<PsiMethod, Set<PsiMethod>>();
@NotNull private final Map<PsiMethod, JavaElementArrangementEntry> myMethodEntriesMap =
new HashMap<PsiMethod, JavaElementArrangementEntry>();
@NotNull private final Map<PsiClass, List<Pair<PsiMethod/*overridden*/, PsiMethod/*overriding*/>>> myOverriddenMethods
= new LinkedHashMap<PsiClass, List<Pair<PsiMethod, PsiMethod>>>();
@NotNull private final Set<PsiMethod> myTmpMethodDependencyRoots = new LinkedHashSet<PsiMethod>();
@NotNull private final Set<PsiMethod> myDependentMethods = new HashSet<PsiMethod>();
private boolean myRebuildMethodDependencies;
@NotNull
public List<JavaElementArrangementEntry> getEntries() {
return myEntries;
@@ -49,12 +71,66 @@ public class JavaArrangementParseInfo {
return myProperties.values();
}
// TODO den add doc
/**
* @return list of method dependency roots, i.e. there is a possible case that particular method
* {@link JavaArrangementMethodDependencyInfo#getDependentMethodInfos() calls another method}, it calls other methods
* and so forth
*/
@NotNull
public List<JavaArrangementMethodDependencyInfo> getMethodDependencyRoots() {
if (myRebuildMethodDependencies) {
myMethodDependencyRoots.clear();
Map<PsiMethod, JavaArrangementMethodDependencyInfo> cache = new HashMap<PsiMethod, JavaArrangementMethodDependencyInfo>();
for (PsiMethod method : myTmpMethodDependencyRoots) {
JavaArrangementMethodDependencyInfo info = buildMethodDependencyInfo(method, cache);
if (info != null) {
myMethodDependencyRoots.add(info);
}
}
myRebuildMethodDependencies = false;
}
return myMethodDependencyRoots;
}
@Nullable
private JavaArrangementMethodDependencyInfo buildMethodDependencyInfo(@NotNull final PsiMethod method,
@NotNull Map<PsiMethod, JavaArrangementMethodDependencyInfo> cache)
{
JavaElementArrangementEntry entry = myMethodEntriesMap.get(method);
if (entry == null) {
return null;
}
JavaArrangementMethodDependencyInfo result = new JavaArrangementMethodDependencyInfo(entry);
Stack<Pair<PsiMethod, JavaArrangementMethodDependencyInfo>> toProcess
= new Stack<Pair<PsiMethod, JavaArrangementMethodDependencyInfo>>();
toProcess.push(Pair.create(method, result));
while (!toProcess.isEmpty()) {
Pair<PsiMethod, JavaArrangementMethodDependencyInfo> pair = toProcess.pop();
Set<PsiMethod> dependentMethods = myMethodDependencies.get(pair.first);
if (dependentMethods == null) {
continue;
}
for (PsiMethod dependentMethod : dependentMethods) {
if (dependentMethod == method) {
// Prevent cyclic dependencies.
return null;
}
JavaElementArrangementEntry dependentEntry = myMethodEntriesMap.get(dependentMethod);
if (dependentEntry == null) {
continue;
}
JavaArrangementMethodDependencyInfo dependentMethodInfo = cache.get(dependentMethod);
if (dependentMethodInfo == null) {
cache.put(dependentMethod, dependentMethodInfo = new JavaArrangementMethodDependencyInfo(dependentEntry));
}
Pair<PsiMethod, JavaArrangementMethodDependencyInfo> dependentPair = Pair.create(dependentMethod, dependentMethodInfo);
pair.second.addDependentMethodInfo(dependentPair.second);
toProcess.push(dependentPair);
}
}
return result;
}
public void registerGetter(@NotNull String propertyName, @NotNull String className, @NotNull JavaElementArrangementEntry entry) {
getPropertyInfo(propertyName, className).setGetter(entry);
}
@@ -72,12 +148,75 @@ public class JavaArrangementParseInfo {
}
return propertyInfo;
}
// TODO den add doc
public void registerDependency(@NotNull PsiMethod baseMethod,
@NotNull JavaElementArrangementEntry baseMethodEntry,
@NotNull PsiMethod dependentMethod)
{
// TODO den implement
public void onMethodEntryCreated(@NotNull PsiMethod method, @NotNull JavaElementArrangementEntry entry) {
myMethodEntriesMap.put(method, entry);
}
public void onOverriddenMethod(@NotNull PsiMethod baseMethod, @NotNull PsiMethod overridingMethod) {
PsiClass clazz = baseMethod.getContainingClass();
if (clazz == null) {
return;
}
List<Pair<PsiMethod, PsiMethod>> methods = myOverriddenMethods.get(clazz);
if (methods == null) {
myOverriddenMethods.put(clazz, methods = new ArrayList<Pair<PsiMethod, PsiMethod>>());
}
methods.add(Pair.create(baseMethod, overridingMethod));
}
@NotNull
public List<JavaArrangementOverriddenMethodsInfo> getOverriddenMethods() {
List<JavaArrangementOverriddenMethodsInfo> result = new ArrayList<JavaArrangementOverriddenMethodsInfo>();
final TObjectIntHashMap<PsiMethod> weights = new TObjectIntHashMap<PsiMethod>();
Comparator<Pair<PsiMethod, PsiMethod>> comparator = new Comparator<Pair<PsiMethod, PsiMethod>>() {
@Override
public int compare(Pair<PsiMethod, PsiMethod> o1, Pair<PsiMethod, PsiMethod> o2) {
return weights.get(o1.first) - weights.get(o2.first);
}
};
for (Map.Entry<PsiClass, List<Pair<PsiMethod, PsiMethod>>> entry : myOverriddenMethods.entrySet()) {
JavaArrangementOverriddenMethodsInfo info = new JavaArrangementOverriddenMethodsInfo(entry.getKey().getName());
weights.clear();
int i = 0;
for (PsiMethod method : entry.getKey().getMethods()) {
weights.put(method, i++);
}
ContainerUtil.sort(entry.getValue(), comparator);
for (Pair<PsiMethod, PsiMethod> pair : entry.getValue()) {
JavaElementArrangementEntry overridingMethodEntry = myMethodEntriesMap.get(pair.second);
if (overridingMethodEntry != null) {
info.addMethodEntry(overridingMethodEntry);
}
}
if (!info.getMethodEntries().isEmpty()) {
result.add(info);
}
}
return result;
}
/**
* Is expected to be called when new method dependency is detected. Here given <code>'base method'</code> calls
* <code>'dependent method'</code>.
*
* @param baseMethod method which calls another method
* @param dependentMethod method being called
*/
public void registerDependency(@NotNull PsiMethod baseMethod, @NotNull PsiMethod dependentMethod) {
myTmpMethodDependencyRoots.remove(dependentMethod);
if (!myDependentMethods.contains(baseMethod)) {
myTmpMethodDependencyRoots.add(baseMethod);
}
myDependentMethods.add(dependentMethod);
Set<PsiMethod> methods = myMethodDependencies.get(baseMethod);
if (methods == null) {
myMethodDependencies.put(baseMethod, methods = new LinkedHashSet<PsiMethod>());
}
if (!methods.contains(dependentMethod)) {
methods.add(dependentMethod);
}
myRebuildMethodDependencies = true;
}
}
@@ -21,12 +21,17 @@ import com.intellij.psi.*;
import com.intellij.psi.codeStyle.arrangement.group.ArrangementGroupingType;
import com.intellij.psi.codeStyle.arrangement.match.ArrangementEntryType;
import com.intellij.psi.codeStyle.arrangement.match.ArrangementModifier;
import com.intellij.psi.search.searches.SuperMethodsSearch;
import com.intellij.psi.util.MethodSignatureBackedByPsiMethod;
import com.intellij.psi.util.PropertyUtil;
import com.intellij.util.containers.Stack;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class JavaArrangementVisitor extends JavaElementVisitor {
@@ -52,6 +57,7 @@ public class JavaArrangementVisitor extends JavaElementVisitor {
@NotNull private final JavaArrangementParseInfo myInfo;
@NotNull private final Collection<TextRange> myRanges;
@NotNull private final Set<ArrangementGroupingType> myGroupingRules;
@NotNull private final MethodBodyProcessor myMethodBodyProcessor;
@Nullable private final Document myDocument;
public JavaArrangementVisitor(@NotNull JavaArrangementParseInfo infoHolder,
@@ -63,6 +69,7 @@ public class JavaArrangementVisitor extends JavaElementVisitor {
myDocument = document;
myRanges = ranges;
myGroupingRules = groupingRules;
myMethodBodyProcessor = new MethodBodyProcessor(infoHolder);
}
@Override
@@ -150,6 +157,13 @@ public class JavaArrangementVisitor extends JavaElementVisitor {
processEntry(entry, method, method.getBody());
parseProperties(method, entry);
myInfo.onMethodEntryCreated(method, entry);
MethodSignatureBackedByPsiMethod overridden = SuperMethodsSearch.search(method, null, true, false).findFirst();
if (overridden != null) {
myInfo.onOverriddenMethod(overridden.getMethod(), method);
}
myMethodBodyProcessor.setBaseMethod(method);
method.accept(myMethodBodyProcessor);
}
private void parseProperties(PsiMethod method, JavaElementArrangementEntry entry) {
@@ -302,4 +316,32 @@ public class JavaArrangementVisitor extends JavaElementVisitor {
entry.addModifier(ArrangementModifier.PACKAGE_PRIVATE);
}
}
}
private static class MethodBodyProcessor extends JavaRecursiveElementVisitor {
@NotNull private final JavaArrangementParseInfo myInfo;
@NotNull private PsiMethod myBaseMethod;
MethodBodyProcessor(@NotNull JavaArrangementParseInfo info) {
myInfo = info;
}
public void visitMethodCallExpression(PsiMethodCallExpression psiMethodCallExpression) {
PsiReference reference = psiMethodCallExpression.getMethodExpression().getReference();
if (reference == null) {
return;
}
PsiElement e = reference.resolve();
if (e instanceof PsiMethod) {
myInfo.registerDependency(myBaseMethod, (PsiMethod)e);
}
// Now parse the expression list, it also might contain method calls.
super.visitExpressionList(psiMethodCallExpression.getArgumentList());
}
public void setBaseMethod(@NotNull PsiMethod baseMethod) {
myBaseMethod = baseMethod;
}
}
}
@@ -95,12 +95,22 @@ public class JavaRearranger implements Rearranger<JavaElementArrangementEntry>,
));
}
private static final Map<ArrangementGroupingType, Set<ArrangementEntryOrderType>> GROUPING_RULES = ContainerUtilRt.newHashMap();
static {
GROUPING_RULES.put(ArrangementGroupingType.GETTERS_AND_SETTERS, EnumSet.noneOf(ArrangementEntryOrderType.class));
GROUPING_RULES.put(ArrangementGroupingType.OVERRIDDEN_METHODS,
EnumSet.of(ArrangementEntryOrderType.BY_NAME, ArrangementEntryOrderType.KEEP));
GROUPING_RULES.put(ArrangementGroupingType.DEPENDENT_METHODS,
EnumSet.of(ArrangementEntryOrderType.BREADTH_FIRST, ArrangementEntryOrderType.DEPTH_FIRST));
}
private static final List<ArrangementGroupingRule> DEFAULT_GROUPING_RULES = new ArrayList<ArrangementGroupingRule>();
static {
DEFAULT_GROUPING_RULES.add(new ArrangementGroupingRule(ArrangementGroupingType.GETTERS_AND_SETTERS));
}
private static final List<StdArrangementMatchRule> DEFAULT_MATCH_RULES = new ArrayList<StdArrangementMatchRule>();
static {
ArrangementModifier[] visibility = {PUBLIC, PROTECTED, PACKAGE_PRIVATE, PRIVATE};
for (ArrangementModifier modifier : visibility) {
@@ -169,7 +179,7 @@ public class JavaRearranger implements Rearranger<JavaElementArrangementEntry>,
}
return Pair.create(newEntryInfo.getEntries().get(0), existingEntriesInfo.getEntries());
}
@NotNull
@Override
public List<JavaElementArrangementEntry> parse(@NotNull PsiElement root,
@@ -183,9 +193,14 @@ public class JavaRearranger implements Rearranger<JavaElementArrangementEntry>,
if (settings != null) {
for (ArrangementGroupingRule rule : settings.getGroupings()) {
switch (rule.getRule()) {
case GETTERS_AND_SETTERS: setupGettersAndSetters(parseInfo); break;
case UTILITY_METHODS: setupUtilityMethods(parseInfo, rule.getOrderType()); break;
case OVERRIDDEN_METHODS: setupOverriddenMethods(parseInfo);
case GETTERS_AND_SETTERS:
setupGettersAndSetters(parseInfo);
break;
case DEPENDENT_METHODS:
setupUtilityMethods(parseInfo, rule.getOrderType());
break;
case OVERRIDDEN_METHODS:
setupOverriddenMethods(parseInfo);
}
}
}
@@ -197,36 +212,66 @@ public class JavaRearranger implements Rearranger<JavaElementArrangementEntry>,
for (JavaArrangementPropertyInfo propertyInfo : properties) {
JavaElementArrangementEntry getter = propertyInfo.getGetter();
JavaElementArrangementEntry setter = propertyInfo.getSetter();
if (getter != null && setter != null) {
if (getter != null && setter != null && setter.getDependencies() == null) {
setter.addDependency(getter);
}
}
}
private static void setupUtilityMethods(@NotNull JavaArrangementParseInfo info, @NotNull ArrangementEntryOrderType orderType) {
if (orderType == ArrangementEntryOrderType.DEPTH_FIRST) {
JavaElementArrangementEntry base = null;
for (JavaArrangementMethodDependencyInfo rootInfo : info.getMethodDependencyRoots()) {
if (base != null) {
rootInfo.getAnchorMethod().addDependency(base);
switch (orderType) {
case DEPTH_FIRST:
for (JavaArrangementMethodDependencyInfo rootInfo : info.getMethodDependencyRoots()) {
setupDepthFirstDependency(rootInfo);
}
base = setupDepthFirstDependency(rootInfo.getAnchorMethod());
break;
case BREADTH_FIRST:
for (JavaArrangementMethodDependencyInfo rootInfo : info.getMethodDependencyRoots()) {
setupBreadthFirstDependency(rootInfo);
}
default: // Unexpected type, do nothing
}
}
private static void setupDepthFirstDependency(@NotNull JavaArrangementMethodDependencyInfo info) {
for (JavaArrangementMethodDependencyInfo dependencyInfo : info.getDependentMethodInfos()) {
setupDepthFirstDependency(dependencyInfo);
JavaElementArrangementEntry dependentEntry = dependencyInfo.getAnchorMethod();
if (dependentEntry.getDependencies() == null) {
dependentEntry.addDependency(info.getAnchorMethod());
}
}
}
@NotNull
private static JavaElementArrangementEntry setupDepthFirstDependency(@NotNull JavaElementArrangementEntry base) {
// TODO den implement
return base;
private static void setupBreadthFirstDependency(@NotNull JavaArrangementMethodDependencyInfo info) {
Deque<JavaArrangementMethodDependencyInfo> toProcess = new ArrayDeque<JavaArrangementMethodDependencyInfo>();
toProcess.add(info);
while (!toProcess.isEmpty()) {
JavaArrangementMethodDependencyInfo current = toProcess.removeFirst();
for (JavaArrangementMethodDependencyInfo dependencyInfo : current.getDependentMethodInfos()) {
JavaElementArrangementEntry dependencyMethod = dependencyInfo.getAnchorMethod();
if (dependencyMethod.getDependencies() == null) {
dependencyMethod.addDependency(current.getAnchorMethod());
}
toProcess.addLast(dependencyInfo);
}
}
}
private static void setupOverriddenMethods(JavaArrangementParseInfo info) {
// TODO den implement
for (JavaArrangementOverriddenMethodsInfo methodsInfo : info.getOverriddenMethods()) {
JavaElementArrangementEntry previous = null;
for (JavaElementArrangementEntry entry : methodsInfo.getMethodEntries()) {
if (previous != null && entry.getDependencies() == null) {
entry.addDependency(previous);
}
previous = entry;
}
}
}
@NotNull
private static Set<ArrangementGroupingType> getGroupingRules(ArrangementSettings settings) {
private static Set<ArrangementGroupingType> getGroupingRules(@Nullable ArrangementSettings settings) {
Set<ArrangementGroupingType> groupingRules = EnumSet.noneOf(ArrangementGroupingType.class);
if (settings != null) {
for (ArrangementGroupingRule rule : settings.getGroupings()) {
@@ -311,12 +356,22 @@ public class JavaRearranger implements Rearranger<JavaElementArrangementEntry>,
@NotNull
@Override
public List<Set<ArrangementMatchCondition>> getGroupingConditions() {
return UI_GROUPING_RULES;
return Collections.emptyList();
//return UI_GROUPING_RULES;
}
@Nullable
@Override
public StdArrangementSettings getDefaultSettings() {
return DEFAULT_SETTINGS;
}
@Override
public boolean isEnabled(@NotNull ArrangementGroupingType groupingType, @Nullable ArrangementEntryOrderType orderType) {
Set<ArrangementEntryOrderType> orderTypes = GROUPING_RULES.get(groupingType);
if (orderTypes == null) {
return false;
}
return orderType == null || orderTypes.contains(orderType);
}
}
@@ -1184,6 +1184,14 @@ public class JavaSpacePropertyProcessor extends JavaElementVisitor {
}
}
@Override
public void visitMethodReferenceExpression(PsiMethodReferenceExpression expression) {
if ((myRole1 == ChildRole.DOUBLE_COLON && myRole2 == ChildRole.EXPRESSION) ||
(myRole1 == ChildRole.EXPRESSION && myRole2 == ChildRole.DOUBLE_COLON)) {
createSpaceInCode(mySettings.SPACE_AROUND_METHOD_REF_DBL_COLON);
}
}
@Override public void visitForStatement(PsiForStatement statement) {
if (myRole2 == ChildRole.LPARENTH) {
createSpaceInCode(mySettings.SPACE_BEFORE_FOR_PARENTHESES);

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