Merge branch 'upsource-master'

Conflicts:
	java/java-impl/src/com/intellij/codeInsight/generation/OverrideImplementUtil.java
	plugins/groovy/src/org/jetbrains/plugins/groovy/GroovyBundle.properties
	plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/GroovyAnnotator.java
This commit is contained in:
Evgeny Pasynkov
2012-07-04 11:48:36 +02:00
537 changed files with 161970 additions and 161904 deletions
File diff suppressed because it is too large Load Diff
@@ -1,106 +1,106 @@
<?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="8" 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"/>
</constraints>
<properties/>
<border type="none"/>
<children>
<vspacer id="67edf">
<constraints>
<grid row="7" 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">
<margin top="0" left="5" bottom="0" right="0"/>
<constraints>
<grid row="0" column="0" row-span="1" col-span="2" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
<border type="none"/>
<children>
<component id="b0748" class="javax.swing.JLabel">
<constraints>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text resource-bundle="messages/CompilerBundle" key="label.option.resource.patterns.text"/>
</properties>
</component>
<component id="263f1" class="javax.swing.JTextField" binding="myResourcePatternsField">
<constraints>
<grid row="0" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="6" anchor="9" fill="1" indent="0" use-parent-layout="false">
<preferred-size width="150" height="-1"/>
</grid>
</constraints>
<properties>
<focusable value="true"/>
<margin top="0" left="2" bottom="0" right="0"/>
<text value="" noi18n="true"/>
</properties>
</component>
<component id="1337" class="javax.swing.JLabel" binding="myPatternLegendLabel">
<constraints>
<grid row="1" column="1" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="8" fill="0" indent="1" use-parent-layout="false"/>
</constraints>
<properties>
<font size="11"/>
<foreground color="-13487566"/>
<text value="label"/>
</properties>
</component>
</children>
</grid>
<component id="889a8" class="javax.swing.JCheckBox" binding="myCbClearOutputDirectory">
<constraints>
<grid row="1" column="0" row-span="1" col-span="2" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text resource-bundle="messages/CompilerBundle" key="label.option.clear.output.directory.on.rebuild"/>
</properties>
</component>
<component id="366e" class="javax.swing.JCheckBox" binding="myCbAssertNotNull">
<constraints>
<grid row="2" column="0" row-span="1" col-span="2" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text resource-bundle="messages/CompilerBundle" key="add.notnull.assertions"/>
</properties>
</component>
<component id="348ee" class="javax.swing.JCheckBox" binding="myCbAutoShowFirstError">
<constraints>
<grid row="3" column="0" row-span="1" col-span="2" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text resource-bundle="messages/CompilerBundle" key="label.option.autoshow.first.error"/>
</properties>
</component>
<component id="ce617" class="javax.swing.JCheckBox" binding="myCbUseCompileServer" default-binding="true">
<constraints>
<grid row="4" column="0" row-span="1" col-span="2" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Use external build for compilation"/>
</properties>
</component>
<component id="b9b2d" class="javax.swing.JCheckBox" binding="myCbMakeProjectOnSave">
<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"/>
</constraints>
<properties>
<text value="Make project automatically"/>
</properties>
</component>
<component id="dd48b" class="javax.swing.JCheckBox" binding="myCbAllowAutomakeWhileRunningApplication">
<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="Allow auto-make while a run configuration is active"/>
</properties>
</component>
</children>
</grid>
</form>
<?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="8" 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"/>
</constraints>
<properties/>
<border type="none"/>
<children>
<vspacer id="67edf">
<constraints>
<grid row="7" 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">
<margin top="0" left="5" bottom="0" right="0"/>
<constraints>
<grid row="0" column="0" row-span="1" col-span="2" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
<border type="none"/>
<children>
<component id="b0748" class="javax.swing.JLabel">
<constraints>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text resource-bundle="messages/CompilerBundle" key="label.option.resource.patterns.text"/>
</properties>
</component>
<component id="263f1" class="javax.swing.JTextField" binding="myResourcePatternsField">
<constraints>
<grid row="0" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="6" anchor="9" fill="1" indent="0" use-parent-layout="false">
<preferred-size width="150" height="-1"/>
</grid>
</constraints>
<properties>
<focusable value="true"/>
<margin top="0" left="2" bottom="0" right="0"/>
<text value="" noi18n="true"/>
</properties>
</component>
<component id="1337" class="javax.swing.JLabel" binding="myPatternLegendLabel">
<constraints>
<grid row="1" column="1" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="8" fill="0" indent="1" use-parent-layout="false"/>
</constraints>
<properties>
<font size="11"/>
<foreground color="-13487566"/>
<text value="label"/>
</properties>
</component>
</children>
</grid>
<component id="889a8" class="javax.swing.JCheckBox" binding="myCbClearOutputDirectory">
<constraints>
<grid row="1" column="0" row-span="1" col-span="2" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text resource-bundle="messages/CompilerBundle" key="label.option.clear.output.directory.on.rebuild"/>
</properties>
</component>
<component id="366e" class="javax.swing.JCheckBox" binding="myCbAssertNotNull">
<constraints>
<grid row="2" column="0" row-span="1" col-span="2" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text resource-bundle="messages/CompilerBundle" key="add.notnull.assertions"/>
</properties>
</component>
<component id="348ee" class="javax.swing.JCheckBox" binding="myCbAutoShowFirstError">
<constraints>
<grid row="3" column="0" row-span="1" col-span="2" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text resource-bundle="messages/CompilerBundle" key="label.option.autoshow.first.error"/>
</properties>
</component>
<component id="ce617" class="javax.swing.JCheckBox" binding="myCbUseCompileServer" default-binding="true">
<constraints>
<grid row="4" column="0" row-span="1" col-span="2" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Use external build for compilation"/>
</properties>
</component>
<component id="b9b2d" class="javax.swing.JCheckBox" binding="myCbMakeProjectOnSave">
<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"/>
</constraints>
<properties>
<text value="Make project automatically"/>
</properties>
</component>
<component id="dd48b" class="javax.swing.JCheckBox" binding="myCbAllowAutomakeWhileRunningApplication">
<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="Allow auto-make while a run configuration is active"/>
</properties>
</component>
</children>
</grid>
</form>
@@ -1,217 +1,217 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.compiler.options;
import com.intellij.compiler.*;
import com.intellij.compiler.impl.TranslatingCompilerFilesMonitor;
import com.intellij.compiler.server.BuildManager;
import com.intellij.openapi.compiler.CompilerBundle;
import com.intellij.openapi.options.Configurable;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.options.SearchableConfigurable;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.io.FileUtil;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.StringTokenizer;
public class CompilerUIConfigurable implements SearchableConfigurable, Configurable.NoScroll {
private JPanel myPanel;
private final Project myProject;
private JTextField myResourcePatternsField;
private JCheckBox myCbClearOutputDirectory;
private JCheckBox myCbAssertNotNull;
private JLabel myPatternLegendLabel;
private JCheckBox myCbAutoShowFirstError;
private JCheckBox myCbUseCompileServer;
private JCheckBox myCbMakeProjectOnSave;
private JCheckBox myCbAllowAutomakeWhileRunningApplication;
public CompilerUIConfigurable(final Project project) {
myProject = project;
myPatternLegendLabel.setText("<html>" +
"Use <b>;</b> to separate patterns and <b>!</b> to negate a pattern. " +
"Accepted wildcards: <b>?</b> &mdash; exactly one symbol; <b>*</b> &mdash; zero or more symbols; " +
"<b>/</b> &mdash; path separator; <b>/**/</b> &mdash; any number of directories; " +
"<i>&lt;dir_name&gt;</i>:<i>&lt;pattern&gt;</i> &mdash; restrict to source roots with the specified name" +
"</html>");
myCbAllowAutomakeWhileRunningApplication.setVisible(false);
myCbUseCompileServer.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
final boolean enabled = myCbUseCompileServer.isSelected();
myCbMakeProjectOnSave.setEnabled(enabled);
myCbAllowAutomakeWhileRunningApplication.setEnabled(enabled);
}
});
}
public void reset() {
final CompilerConfigurationImpl configuration = (CompilerConfigurationImpl)CompilerConfiguration.getInstance(myProject);
final CompilerWorkspaceConfiguration workspaceConfiguration = CompilerWorkspaceConfiguration.getInstance(myProject);
myCbAutoShowFirstError.setSelected(workspaceConfiguration.AUTO_SHOW_ERRORS_IN_EDITOR);
myCbClearOutputDirectory.setSelected(workspaceConfiguration.CLEAR_OUTPUT_DIRECTORY);
myCbAssertNotNull.setSelected(configuration.isAddNotNullAssertions());
myCbUseCompileServer.setSelected(workspaceConfiguration.USE_COMPILE_SERVER);
myCbMakeProjectOnSave.setSelected(workspaceConfiguration.MAKE_PROJECT_ON_SAVE);
myCbAllowAutomakeWhileRunningApplication.setEnabled(workspaceConfiguration.USE_COMPILE_SERVER);
configuration.convertPatterns();
myResourcePatternsField.setText(patternsToString(configuration.getResourceFilePatterns()));
}
private static String patternsToString(final String[] patterns) {
final StringBuffer extensionsString = new StringBuffer();
for (int idx = 0; idx < patterns.length; idx++) {
if (idx > 0) {
extensionsString.append(";");
}
extensionsString.append(patterns[idx]);
}
return extensionsString.toString();
}
public void apply() throws ConfigurationException {
CompilerConfigurationImpl configuration = (CompilerConfigurationImpl)CompilerConfiguration.getInstance(myProject);
final CompilerWorkspaceConfiguration workspaceConfiguration = CompilerWorkspaceConfiguration.getInstance(myProject);
workspaceConfiguration.AUTO_SHOW_ERRORS_IN_EDITOR = myCbAutoShowFirstError.isSelected();
workspaceConfiguration.CLEAR_OUTPUT_DIRECTORY = myCbClearOutputDirectory.isSelected();
boolean wasUsingExternalMake = workspaceConfiguration.USE_COMPILE_SERVER;
workspaceConfiguration.USE_COMPILE_SERVER = myCbUseCompileServer.isSelected();
workspaceConfiguration.MAKE_PROJECT_ON_SAVE = myCbMakeProjectOnSave.isSelected();
workspaceConfiguration.ALLOW_AUTOMAKE_WHILE_RUNNING_APPLICATION = myCbAllowAutomakeWhileRunningApplication.isSelected();
configuration.setAddNotNullAssertions(myCbAssertNotNull.isSelected());
configuration.removeResourceFilePatterns();
String extensionString = myResourcePatternsField.getText().trim();
applyResourcePatterns(extensionString, (CompilerConfigurationImpl)CompilerConfiguration.getInstance(myProject));
// this will schedule for compilation all files that might become compilable after resource patterns' changing
final TranslatingCompilerFilesMonitor monitor = TranslatingCompilerFilesMonitor.getInstance();
if (workspaceConfiguration.USE_COMPILE_SERVER) {
monitor.suspendProject(myProject);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
CompileServerManager.getInstance().sendReloadRequest(myProject);
BuildManager.getInstance().clearState(myProject);
}
});
}
else {
// use old make
if (wasUsingExternalMake) {
CompileServerManager.getInstance().shutdownServer();
monitor.watchProject(myProject);
monitor.scanSourcesForCompilableFiles(myProject);
if (!myProject.isDefault()) {
final File buildSystem = BuildManager.getInstance().getBuildSystemDirectory();
final File[] subdirs = buildSystem.listFiles();
if (subdirs != null) {
final String prefix = myProject.getName().toLowerCase(Locale.US) + "_";
for (File subdir : subdirs) {
if (subdir.getName().startsWith(prefix)) {
FileUtil.asyncDelete(subdir);
}
}
}
}
}
}
}
private static void applyResourcePatterns(String extensionString, final CompilerConfigurationImpl configuration)
throws ConfigurationException {
StringTokenizer tokenizer = new StringTokenizer(extensionString, ";", false);
List<String[]> errors = new ArrayList<String[]>();
while (tokenizer.hasMoreTokens()) {
String namePattern = tokenizer.nextToken();
try {
configuration.addResourceFilePattern(namePattern);
}
catch (MalformedPatternException e) {
errors.add(new String[]{namePattern, e.getLocalizedMessage()});
}
}
if (errors.size() > 0) {
final StringBuffer pattersnsWithErrors = new StringBuffer();
for (final Object error : errors) {
String[] pair = (String[])error;
pattersnsWithErrors.append("\n");
pattersnsWithErrors.append(pair[0]);
pattersnsWithErrors.append(": ");
pattersnsWithErrors.append(pair[1]);
}
throw new ConfigurationException(
CompilerBundle.message("error.compiler.configurable.malformed.patterns", pattersnsWithErrors.toString()), CompilerBundle.message("bad.resource.patterns.dialog.title")
);
}
}
public boolean isModified() {
boolean isModified = false;
final CompilerWorkspaceConfiguration workspaceConfiguration = CompilerWorkspaceConfiguration.getInstance(myProject);
isModified |= ComparingUtils.isModified(myCbAutoShowFirstError, workspaceConfiguration.AUTO_SHOW_ERRORS_IN_EDITOR);
isModified |= ComparingUtils.isModified(myCbUseCompileServer, workspaceConfiguration.USE_COMPILE_SERVER);
isModified |= ComparingUtils.isModified(myCbMakeProjectOnSave, workspaceConfiguration.MAKE_PROJECT_ON_SAVE);
isModified |= ComparingUtils.isModified(myCbAllowAutomakeWhileRunningApplication, workspaceConfiguration.allowAutoMakeWhileRunningApplication());
final CompilerConfigurationImpl compilerConfiguration = (CompilerConfigurationImpl)CompilerConfiguration.getInstance(myProject);
isModified |= ComparingUtils.isModified(myCbAssertNotNull, compilerConfiguration.isAddNotNullAssertions());
isModified |= ComparingUtils.isModified(myCbClearOutputDirectory, workspaceConfiguration.CLEAR_OUTPUT_DIRECTORY);
isModified |= ComparingUtils.isModified(myResourcePatternsField, patternsToString(compilerConfiguration.getResourceFilePatterns()));
return isModified;
}
public String getDisplayName() {
return "General";
}
public String getHelpTopic() {
return null;
}
@NotNull
public String getId() {
return "compiler.general";
}
public Runnable enableSearch(String option) {
return null;
}
public JComponent createComponent() {
return myPanel;
}
public void disposeUIResources() {
}
}
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.compiler.options;
import com.intellij.compiler.*;
import com.intellij.compiler.impl.TranslatingCompilerFilesMonitor;
import com.intellij.compiler.server.BuildManager;
import com.intellij.openapi.compiler.CompilerBundle;
import com.intellij.openapi.options.Configurable;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.options.SearchableConfigurable;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.io.FileUtil;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.StringTokenizer;
public class CompilerUIConfigurable implements SearchableConfigurable, Configurable.NoScroll {
private JPanel myPanel;
private final Project myProject;
private JTextField myResourcePatternsField;
private JCheckBox myCbClearOutputDirectory;
private JCheckBox myCbAssertNotNull;
private JLabel myPatternLegendLabel;
private JCheckBox myCbAutoShowFirstError;
private JCheckBox myCbUseCompileServer;
private JCheckBox myCbMakeProjectOnSave;
private JCheckBox myCbAllowAutomakeWhileRunningApplication;
public CompilerUIConfigurable(final Project project) {
myProject = project;
myPatternLegendLabel.setText("<html>" +
"Use <b>;</b> to separate patterns and <b>!</b> to negate a pattern. " +
"Accepted wildcards: <b>?</b> &mdash; exactly one symbol; <b>*</b> &mdash; zero or more symbols; " +
"<b>/</b> &mdash; path separator; <b>/**/</b> &mdash; any number of directories; " +
"<i>&lt;dir_name&gt;</i>:<i>&lt;pattern&gt;</i> &mdash; restrict to source roots with the specified name" +
"</html>");
myCbAllowAutomakeWhileRunningApplication.setVisible(false);
myCbUseCompileServer.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
final boolean enabled = myCbUseCompileServer.isSelected();
myCbMakeProjectOnSave.setEnabled(enabled);
myCbAllowAutomakeWhileRunningApplication.setEnabled(enabled);
}
});
}
public void reset() {
final CompilerConfigurationImpl configuration = (CompilerConfigurationImpl)CompilerConfiguration.getInstance(myProject);
final CompilerWorkspaceConfiguration workspaceConfiguration = CompilerWorkspaceConfiguration.getInstance(myProject);
myCbAutoShowFirstError.setSelected(workspaceConfiguration.AUTO_SHOW_ERRORS_IN_EDITOR);
myCbClearOutputDirectory.setSelected(workspaceConfiguration.CLEAR_OUTPUT_DIRECTORY);
myCbAssertNotNull.setSelected(configuration.isAddNotNullAssertions());
myCbUseCompileServer.setSelected(workspaceConfiguration.USE_COMPILE_SERVER);
myCbMakeProjectOnSave.setSelected(workspaceConfiguration.MAKE_PROJECT_ON_SAVE);
myCbAllowAutomakeWhileRunningApplication.setEnabled(workspaceConfiguration.USE_COMPILE_SERVER);
configuration.convertPatterns();
myResourcePatternsField.setText(patternsToString(configuration.getResourceFilePatterns()));
}
private static String patternsToString(final String[] patterns) {
final StringBuffer extensionsString = new StringBuffer();
for (int idx = 0; idx < patterns.length; idx++) {
if (idx > 0) {
extensionsString.append(";");
}
extensionsString.append(patterns[idx]);
}
return extensionsString.toString();
}
public void apply() throws ConfigurationException {
CompilerConfigurationImpl configuration = (CompilerConfigurationImpl)CompilerConfiguration.getInstance(myProject);
final CompilerWorkspaceConfiguration workspaceConfiguration = CompilerWorkspaceConfiguration.getInstance(myProject);
workspaceConfiguration.AUTO_SHOW_ERRORS_IN_EDITOR = myCbAutoShowFirstError.isSelected();
workspaceConfiguration.CLEAR_OUTPUT_DIRECTORY = myCbClearOutputDirectory.isSelected();
boolean wasUsingExternalMake = workspaceConfiguration.USE_COMPILE_SERVER;
workspaceConfiguration.USE_COMPILE_SERVER = myCbUseCompileServer.isSelected();
workspaceConfiguration.MAKE_PROJECT_ON_SAVE = myCbMakeProjectOnSave.isSelected();
workspaceConfiguration.ALLOW_AUTOMAKE_WHILE_RUNNING_APPLICATION = myCbAllowAutomakeWhileRunningApplication.isSelected();
configuration.setAddNotNullAssertions(myCbAssertNotNull.isSelected());
configuration.removeResourceFilePatterns();
String extensionString = myResourcePatternsField.getText().trim();
applyResourcePatterns(extensionString, (CompilerConfigurationImpl)CompilerConfiguration.getInstance(myProject));
// this will schedule for compilation all files that might become compilable after resource patterns' changing
final TranslatingCompilerFilesMonitor monitor = TranslatingCompilerFilesMonitor.getInstance();
if (workspaceConfiguration.USE_COMPILE_SERVER) {
monitor.suspendProject(myProject);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
CompileServerManager.getInstance().sendReloadRequest(myProject);
BuildManager.getInstance().clearState(myProject);
}
});
}
else {
// use old make
if (wasUsingExternalMake) {
CompileServerManager.getInstance().shutdownServer();
monitor.watchProject(myProject);
monitor.scanSourcesForCompilableFiles(myProject);
if (!myProject.isDefault()) {
final File buildSystem = BuildManager.getInstance().getBuildSystemDirectory();
final File[] subdirs = buildSystem.listFiles();
if (subdirs != null) {
final String prefix = myProject.getName().toLowerCase(Locale.US) + "_";
for (File subdir : subdirs) {
if (subdir.getName().startsWith(prefix)) {
FileUtil.asyncDelete(subdir);
}
}
}
}
}
}
}
private static void applyResourcePatterns(String extensionString, final CompilerConfigurationImpl configuration)
throws ConfigurationException {
StringTokenizer tokenizer = new StringTokenizer(extensionString, ";", false);
List<String[]> errors = new ArrayList<String[]>();
while (tokenizer.hasMoreTokens()) {
String namePattern = tokenizer.nextToken();
try {
configuration.addResourceFilePattern(namePattern);
}
catch (MalformedPatternException e) {
errors.add(new String[]{namePattern, e.getLocalizedMessage()});
}
}
if (errors.size() > 0) {
final StringBuffer pattersnsWithErrors = new StringBuffer();
for (final Object error : errors) {
String[] pair = (String[])error;
pattersnsWithErrors.append("\n");
pattersnsWithErrors.append(pair[0]);
pattersnsWithErrors.append(": ");
pattersnsWithErrors.append(pair[1]);
}
throw new ConfigurationException(
CompilerBundle.message("error.compiler.configurable.malformed.patterns", pattersnsWithErrors.toString()), CompilerBundle.message("bad.resource.patterns.dialog.title")
);
}
}
public boolean isModified() {
boolean isModified = false;
final CompilerWorkspaceConfiguration workspaceConfiguration = CompilerWorkspaceConfiguration.getInstance(myProject);
isModified |= ComparingUtils.isModified(myCbAutoShowFirstError, workspaceConfiguration.AUTO_SHOW_ERRORS_IN_EDITOR);
isModified |= ComparingUtils.isModified(myCbUseCompileServer, workspaceConfiguration.USE_COMPILE_SERVER);
isModified |= ComparingUtils.isModified(myCbMakeProjectOnSave, workspaceConfiguration.MAKE_PROJECT_ON_SAVE);
isModified |= ComparingUtils.isModified(myCbAllowAutomakeWhileRunningApplication, workspaceConfiguration.allowAutoMakeWhileRunningApplication());
final CompilerConfigurationImpl compilerConfiguration = (CompilerConfigurationImpl)CompilerConfiguration.getInstance(myProject);
isModified |= ComparingUtils.isModified(myCbAssertNotNull, compilerConfiguration.isAddNotNullAssertions());
isModified |= ComparingUtils.isModified(myCbClearOutputDirectory, workspaceConfiguration.CLEAR_OUTPUT_DIRECTORY);
isModified |= ComparingUtils.isModified(myResourcePatternsField, patternsToString(compilerConfiguration.getResourceFilePatterns()));
return isModified;
}
public String getDisplayName() {
return "General";
}
public String getHelpTopic() {
return null;
}
@NotNull
public String getId() {
return "compiler.general";
}
public Runnable enableSearch(String option) {
return null;
}
public JComponent createComponent() {
return myPanel;
}
public void disposeUIResources() {
}
}
@@ -1,249 +1,249 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.packaging.impl.run;
import com.intellij.execution.BeforeRunTask;
import com.intellij.execution.BeforeRunTaskProvider;
import com.intellij.execution.RunManagerEx;
import com.intellij.execution.configurations.RunConfiguration;
import com.intellij.execution.impl.ConfigurationSettingsEditorWrapper;
import com.intellij.execution.runners.ExecutionEnvironment;
import com.intellij.ide.DataManager;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.application.ReadAction;
import com.intellij.openapi.application.Result;
import com.intellij.openapi.compiler.*;
import com.intellij.openapi.compiler.Compiler;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogBuilder;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.Ref;
import com.intellij.packaging.artifacts.*;
import com.intellij.packaging.impl.artifacts.PlainArtifactType;
import com.intellij.packaging.impl.compiler.ArtifactAwareCompiler;
import com.intellij.packaging.impl.compiler.ArtifactCompileScope;
import com.intellij.packaging.impl.compiler.ArtifactsCompiler;
import com.intellij.util.concurrency.Semaphore;
import com.intellij.util.containers.ContainerUtil;
import gnu.trove.THashSet;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
/**
* @author nik
*/
public class BuildArtifactsBeforeRunTaskProvider extends BeforeRunTaskProvider<BuildArtifactsBeforeRunTask> {
@NonNls public static final String BUILD_ARTIFACTS_ID = "BuildArtifacts";
public static final Key<BuildArtifactsBeforeRunTask> ID = Key.create(BUILD_ARTIFACTS_ID);
private final Project myProject;
public BuildArtifactsBeforeRunTaskProvider(Project project) {
myProject = project;
project.getMessageBus().connect().subscribe(ArtifactManager.TOPIC, new ArtifactAdapter() {
@Override
public void artifactRemoved(@NotNull Artifact artifact) {
final RunManagerEx runManager = RunManagerEx.getInstanceEx(myProject);
for (RunConfiguration configuration : runManager.getAllConfigurations()) {
final List<BuildArtifactsBeforeRunTask> tasks = runManager.getBeforeRunTasks(configuration, ID);
for (BuildArtifactsBeforeRunTask task : tasks) {
final String artifactName = artifact.getName();
final List<ArtifactPointer> pointersList = task.getArtifactPointers();
final ArtifactPointer[] pointers = pointersList.toArray(new ArtifactPointer[pointersList.size()]);
for (ArtifactPointer pointer : pointers) {
if (pointer.getArtifactName().equals(artifactName) && ArtifactManager.getInstance(myProject).findArtifact(artifactName) == null) {
task.removeArtifact(pointer);
}
}
}
}
}
});
}
public Key<BuildArtifactsBeforeRunTask> getId() {
return ID;
}
@Override
public Icon getIcon() {
return PlainArtifactType.ARTIFACT_ICON;
}
@Override
public String getName() {
return CompilerBundle.message("build.artifacts.before.run.description.empty");
}
@Override
public Icon getTaskIcon(BuildArtifactsBeforeRunTask task) {
List<ArtifactPointer> pointers = task.getArtifactPointers();
if (pointers == null || pointers.isEmpty())
return getIcon();
Artifact artifact = pointers.get(0).getArtifact();
if (artifact == null)
return getIcon();
return artifact.getArtifactType().getIcon();
}
@Override
public String getDescription(BuildArtifactsBeforeRunTask task) {
final List<ArtifactPointer> pointers = task.getArtifactPointers();
if (pointers.isEmpty()) {
return CompilerBundle.message("build.artifacts.before.run.description.empty");
}
if (pointers.size() == 1) {
return CompilerBundle.message("build.artifacts.before.run.description.single", pointers.get(0).getArtifactName());
}
return CompilerBundle.message("build.artifacts.before.run.description.multiple", pointers.size());
}
public boolean isConfigurable() {
return true;
}
public BuildArtifactsBeforeRunTask createTask(RunConfiguration runConfiguration) {
if (myProject.isDefault()) return null;
return new BuildArtifactsBeforeRunTask(myProject);
}
public boolean configureTask(RunConfiguration runConfiguration, BuildArtifactsBeforeRunTask task) {
final Artifact[] artifacts = ArtifactManager.getInstance(myProject).getArtifacts();
Set<ArtifactPointer> pointers = new THashSet<ArtifactPointer>();
for (Artifact artifact : artifacts) {
pointers.add(ArtifactPointerManager.getInstance(myProject).createPointer(artifact));
}
pointers.addAll(task.getArtifactPointers());
ArtifactChooser chooser = new ArtifactChooser(new ArrayList<ArtifactPointer>(pointers));
chooser.markElements(task.getArtifactPointers());
chooser.setPreferredSize(new Dimension(400, 300));
DialogBuilder builder = new DialogBuilder(myProject);
builder.setTitle(CompilerBundle.message("build.artifacts.before.run.selector.title"));
builder.setDimensionServiceKey("#BuildArtifactsBeforeRunChooser");
builder.addOkAction();
builder.addCancelAction();
builder.setCenterPanel(chooser);
builder.setPreferedFocusComponent(chooser);
if (builder.show() == DialogWrapper.OK_EXIT_CODE) {
task.setArtifactPointers(chooser.getMarkedElements());
return true;
}
return false;
}
@Override
public boolean canExecuteTask(RunConfiguration configuration, BuildArtifactsBeforeRunTask task) {
for (ArtifactPointer pointer: task.getArtifactPointers()) {
if (pointer.getArtifact() != null)
return true;
}
return false;
}
public boolean executeTask(DataContext context,
RunConfiguration configuration,
ExecutionEnvironment env,
final BuildArtifactsBeforeRunTask task) {
final Ref<Boolean> result = Ref.create(false);
final Semaphore finished = new Semaphore();
final List<Artifact> artifacts = new ArrayList<Artifact>();
new ReadAction() {
protected void run(final Result result) {
for (ArtifactPointer pointer : task.getArtifactPointers()) {
ContainerUtil.addIfNotNull(pointer.getArtifact(), artifacts);
}
}
}.execute();
final CompileStatusNotification callback = new CompileStatusNotification() {
public void finished(boolean aborted, int errors, int warnings, CompileContext compileContext) {
result.set(!aborted && errors == 0);
finished.up();
}
};
final CompilerFilter compilerFilter = new CompilerFilter() {
public boolean acceptCompiler(Compiler compiler) {
return compiler instanceof ArtifactsCompiler
|| compiler instanceof ArtifactAwareCompiler && ((ArtifactAwareCompiler)compiler).shouldRun(artifacts);
}
};
ApplicationManager.getApplication().invokeAndWait(new Runnable() {
public void run() {
final CompilerManager manager = CompilerManager.getInstance(myProject);
finished.down();
manager.make(ArtifactCompileScope.createArtifactsScope(myProject, artifacts), compilerFilter, callback);
}
}, ModalityState.NON_MODAL);
finished.waitFor();
return result.get();
}
public static void setBuildArtifactBeforeRunOption(@NotNull JComponent runConfigurationEditorComponent, @NotNull Artifact artifact, final boolean enable) {
final DataContext dataContext = DataManager.getInstance().getDataContext(runConfigurationEditorComponent);
final ConfigurationSettingsEditorWrapper editor = ConfigurationSettingsEditorWrapper.CONFIGURATION_EDITOR_KEY.getData(dataContext);
if (editor != null) {
List<BeforeRunTask> tasks = editor.getStepsBeforeLaunch();
List<BuildArtifactsBeforeRunTask> myTasks = new ArrayList<BuildArtifactsBeforeRunTask>();
for (BeforeRunTask task : tasks) {
if (task instanceof BuildArtifactsBeforeRunTask) {
myTasks.add((BuildArtifactsBeforeRunTask)task);
}
}
for (BuildArtifactsBeforeRunTask task : myTasks) {
if (enable) {
task.addArtifact(artifact);
task.setEnabled(true);
}
else {
task.removeArtifact(artifact);
if (task.getArtifactPointers().isEmpty()) {
task.setEnabled(false);
}
}
}
}
}
public static void setBuildArtifactBeforeRun(@NotNull Project project, @NotNull RunConfiguration configuration, @NotNull Artifact artifact) {
RunManagerEx runManager = RunManagerEx.getInstanceEx(project);
final List<BuildArtifactsBeforeRunTask> buildArtifactsTasks = runManager.getBeforeRunTasks(configuration, ID);
if (buildArtifactsTasks.isEmpty()) { //Add new task if absent
BuildArtifactsBeforeRunTask task = new BuildArtifactsBeforeRunTask(project);
buildArtifactsTasks.add(task);
List<BeforeRunTask> tasks = runManager.getBeforeRunTasks(configuration);
tasks.add(task);
runManager.setBeforeRunTasks(configuration, tasks, false);
}
for (BuildArtifactsBeforeRunTask task : buildArtifactsTasks) {
task.setEnabled(true);
task.addArtifact(artifact);
}
}
}
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.packaging.impl.run;
import com.intellij.execution.BeforeRunTask;
import com.intellij.execution.BeforeRunTaskProvider;
import com.intellij.execution.RunManagerEx;
import com.intellij.execution.configurations.RunConfiguration;
import com.intellij.execution.impl.ConfigurationSettingsEditorWrapper;
import com.intellij.execution.runners.ExecutionEnvironment;
import com.intellij.ide.DataManager;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.application.ReadAction;
import com.intellij.openapi.application.Result;
import com.intellij.openapi.compiler.*;
import com.intellij.openapi.compiler.Compiler;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogBuilder;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.Ref;
import com.intellij.packaging.artifacts.*;
import com.intellij.packaging.impl.artifacts.PlainArtifactType;
import com.intellij.packaging.impl.compiler.ArtifactAwareCompiler;
import com.intellij.packaging.impl.compiler.ArtifactCompileScope;
import com.intellij.packaging.impl.compiler.ArtifactsCompiler;
import com.intellij.util.concurrency.Semaphore;
import com.intellij.util.containers.ContainerUtil;
import gnu.trove.THashSet;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
/**
* @author nik
*/
public class BuildArtifactsBeforeRunTaskProvider extends BeforeRunTaskProvider<BuildArtifactsBeforeRunTask> {
@NonNls public static final String BUILD_ARTIFACTS_ID = "BuildArtifacts";
public static final Key<BuildArtifactsBeforeRunTask> ID = Key.create(BUILD_ARTIFACTS_ID);
private final Project myProject;
public BuildArtifactsBeforeRunTaskProvider(Project project) {
myProject = project;
project.getMessageBus().connect().subscribe(ArtifactManager.TOPIC, new ArtifactAdapter() {
@Override
public void artifactRemoved(@NotNull Artifact artifact) {
final RunManagerEx runManager = RunManagerEx.getInstanceEx(myProject);
for (RunConfiguration configuration : runManager.getAllConfigurations()) {
final List<BuildArtifactsBeforeRunTask> tasks = runManager.getBeforeRunTasks(configuration, ID);
for (BuildArtifactsBeforeRunTask task : tasks) {
final String artifactName = artifact.getName();
final List<ArtifactPointer> pointersList = task.getArtifactPointers();
final ArtifactPointer[] pointers = pointersList.toArray(new ArtifactPointer[pointersList.size()]);
for (ArtifactPointer pointer : pointers) {
if (pointer.getArtifactName().equals(artifactName) && ArtifactManager.getInstance(myProject).findArtifact(artifactName) == null) {
task.removeArtifact(pointer);
}
}
}
}
}
});
}
public Key<BuildArtifactsBeforeRunTask> getId() {
return ID;
}
@Override
public Icon getIcon() {
return PlainArtifactType.ARTIFACT_ICON;
}
@Override
public String getName() {
return CompilerBundle.message("build.artifacts.before.run.description.empty");
}
@Override
public Icon getTaskIcon(BuildArtifactsBeforeRunTask task) {
List<ArtifactPointer> pointers = task.getArtifactPointers();
if (pointers == null || pointers.isEmpty())
return getIcon();
Artifact artifact = pointers.get(0).getArtifact();
if (artifact == null)
return getIcon();
return artifact.getArtifactType().getIcon();
}
@Override
public String getDescription(BuildArtifactsBeforeRunTask task) {
final List<ArtifactPointer> pointers = task.getArtifactPointers();
if (pointers.isEmpty()) {
return CompilerBundle.message("build.artifacts.before.run.description.empty");
}
if (pointers.size() == 1) {
return CompilerBundle.message("build.artifacts.before.run.description.single", pointers.get(0).getArtifactName());
}
return CompilerBundle.message("build.artifacts.before.run.description.multiple", pointers.size());
}
public boolean isConfigurable() {
return true;
}
public BuildArtifactsBeforeRunTask createTask(RunConfiguration runConfiguration) {
if (myProject.isDefault()) return null;
return new BuildArtifactsBeforeRunTask(myProject);
}
public boolean configureTask(RunConfiguration runConfiguration, BuildArtifactsBeforeRunTask task) {
final Artifact[] artifacts = ArtifactManager.getInstance(myProject).getArtifacts();
Set<ArtifactPointer> pointers = new THashSet<ArtifactPointer>();
for (Artifact artifact : artifacts) {
pointers.add(ArtifactPointerManager.getInstance(myProject).createPointer(artifact));
}
pointers.addAll(task.getArtifactPointers());
ArtifactChooser chooser = new ArtifactChooser(new ArrayList<ArtifactPointer>(pointers));
chooser.markElements(task.getArtifactPointers());
chooser.setPreferredSize(new Dimension(400, 300));
DialogBuilder builder = new DialogBuilder(myProject);
builder.setTitle(CompilerBundle.message("build.artifacts.before.run.selector.title"));
builder.setDimensionServiceKey("#BuildArtifactsBeforeRunChooser");
builder.addOkAction();
builder.addCancelAction();
builder.setCenterPanel(chooser);
builder.setPreferedFocusComponent(chooser);
if (builder.show() == DialogWrapper.OK_EXIT_CODE) {
task.setArtifactPointers(chooser.getMarkedElements());
return true;
}
return false;
}
@Override
public boolean canExecuteTask(RunConfiguration configuration, BuildArtifactsBeforeRunTask task) {
for (ArtifactPointer pointer: task.getArtifactPointers()) {
if (pointer.getArtifact() != null)
return true;
}
return false;
}
public boolean executeTask(DataContext context,
RunConfiguration configuration,
ExecutionEnvironment env,
final BuildArtifactsBeforeRunTask task) {
final Ref<Boolean> result = Ref.create(false);
final Semaphore finished = new Semaphore();
final List<Artifact> artifacts = new ArrayList<Artifact>();
new ReadAction() {
protected void run(final Result result) {
for (ArtifactPointer pointer : task.getArtifactPointers()) {
ContainerUtil.addIfNotNull(pointer.getArtifact(), artifacts);
}
}
}.execute();
final CompileStatusNotification callback = new CompileStatusNotification() {
public void finished(boolean aborted, int errors, int warnings, CompileContext compileContext) {
result.set(!aborted && errors == 0);
finished.up();
}
};
final CompilerFilter compilerFilter = new CompilerFilter() {
public boolean acceptCompiler(Compiler compiler) {
return compiler instanceof ArtifactsCompiler
|| compiler instanceof ArtifactAwareCompiler && ((ArtifactAwareCompiler)compiler).shouldRun(artifacts);
}
};
ApplicationManager.getApplication().invokeAndWait(new Runnable() {
public void run() {
final CompilerManager manager = CompilerManager.getInstance(myProject);
finished.down();
manager.make(ArtifactCompileScope.createArtifactsScope(myProject, artifacts), compilerFilter, callback);
}
}, ModalityState.NON_MODAL);
finished.waitFor();
return result.get();
}
public static void setBuildArtifactBeforeRunOption(@NotNull JComponent runConfigurationEditorComponent, @NotNull Artifact artifact, final boolean enable) {
final DataContext dataContext = DataManager.getInstance().getDataContext(runConfigurationEditorComponent);
final ConfigurationSettingsEditorWrapper editor = ConfigurationSettingsEditorWrapper.CONFIGURATION_EDITOR_KEY.getData(dataContext);
if (editor != null) {
List<BeforeRunTask> tasks = editor.getStepsBeforeLaunch();
List<BuildArtifactsBeforeRunTask> myTasks = new ArrayList<BuildArtifactsBeforeRunTask>();
for (BeforeRunTask task : tasks) {
if (task instanceof BuildArtifactsBeforeRunTask) {
myTasks.add((BuildArtifactsBeforeRunTask)task);
}
}
for (BuildArtifactsBeforeRunTask task : myTasks) {
if (enable) {
task.addArtifact(artifact);
task.setEnabled(true);
}
else {
task.removeArtifact(artifact);
if (task.getArtifactPointers().isEmpty()) {
task.setEnabled(false);
}
}
}
}
}
public static void setBuildArtifactBeforeRun(@NotNull Project project, @NotNull RunConfiguration configuration, @NotNull Artifact artifact) {
RunManagerEx runManager = RunManagerEx.getInstanceEx(project);
final List<BuildArtifactsBeforeRunTask> buildArtifactsTasks = runManager.getBeforeRunTasks(configuration, ID);
if (buildArtifactsTasks.isEmpty()) { //Add new task if absent
BuildArtifactsBeforeRunTask task = new BuildArtifactsBeforeRunTask(project);
buildArtifactsTasks.add(task);
List<BeforeRunTask> tasks = runManager.getBeforeRunTasks(configuration);
tasks.add(task);
runManager.setBeforeRunTasks(configuration, tasks, false);
}
for (BuildArtifactsBeforeRunTask task : buildArtifactsTasks) {
task.setEnabled(true);
task.addArtifact(artifact);
}
}
}
@@ -1,64 +1,64 @@
/*
* 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.
*/
/*
* @author Eugene Zhuravlev
*/
package com.intellij.compiler;
import com.intellij.openapi.components.*;
import com.intellij.openapi.project.Project;
import com.intellij.util.xmlb.XmlSerializerUtil;
@State(
name = "CompilerWorkspaceConfiguration",
storages = {
@Storage(
file = StoragePathMacros.WORKSPACE_FILE
)}
)
public class CompilerWorkspaceConfiguration implements PersistentStateComponent<CompilerWorkspaceConfiguration> {
public boolean AUTO_SHOW_ERRORS_IN_EDITOR = true;
@Deprecated public boolean CLOSE_MESSAGE_VIEW_IF_SUCCESS = true;
public boolean CLEAR_OUTPUT_DIRECTORY = true;
public boolean USE_COMPILE_SERVER = false;
public boolean MAKE_PROJECT_ON_SAVE = false;
public boolean ALLOW_AUTOMAKE_WHILE_RUNNING_APPLICATION = false;
public static CompilerWorkspaceConfiguration getInstance(Project project) {
return ServiceManager.getService(project, CompilerWorkspaceConfiguration.class);
}
public CompilerWorkspaceConfiguration getState() {
return this;
}
public void loadState(CompilerWorkspaceConfiguration state) {
XmlSerializerUtil.copyBean(state, this);
}
public boolean useOutOfProcessBuild() {
return USE_COMPILE_SERVER;
}
public static boolean useServerlessOutOfProcessBuild() {
return true/*!Registry.is("compiler.out-of-process.as-server")*/;
}
public boolean allowAutoMakeWhileRunningApplication() {
return false;/*ALLOW_AUTOMAKE_WHILE_RUNNING_APPLICATION*/
}
}
/*
* 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.
*/
/*
* @author Eugene Zhuravlev
*/
package com.intellij.compiler;
import com.intellij.openapi.components.*;
import com.intellij.openapi.project.Project;
import com.intellij.util.xmlb.XmlSerializerUtil;
@State(
name = "CompilerWorkspaceConfiguration",
storages = {
@Storage(
file = StoragePathMacros.WORKSPACE_FILE
)}
)
public class CompilerWorkspaceConfiguration implements PersistentStateComponent<CompilerWorkspaceConfiguration> {
public boolean AUTO_SHOW_ERRORS_IN_EDITOR = true;
@Deprecated public boolean CLOSE_MESSAGE_VIEW_IF_SUCCESS = true;
public boolean CLEAR_OUTPUT_DIRECTORY = true;
public boolean USE_COMPILE_SERVER = false;
public boolean MAKE_PROJECT_ON_SAVE = false;
public boolean ALLOW_AUTOMAKE_WHILE_RUNNING_APPLICATION = false;
public static CompilerWorkspaceConfiguration getInstance(Project project) {
return ServiceManager.getService(project, CompilerWorkspaceConfiguration.class);
}
public CompilerWorkspaceConfiguration getState() {
return this;
}
public void loadState(CompilerWorkspaceConfiguration state) {
XmlSerializerUtil.copyBean(state, this);
}
public boolean useOutOfProcessBuild() {
return USE_COMPILE_SERVER;
}
public static boolean useServerlessOutOfProcessBuild() {
return true/*!Registry.is("compiler.out-of-process.as-server")*/;
}
public boolean allowAutoMakeWhileRunningApplication() {
return false;/*ALLOW_AUTOMAKE_WHILE_RUNNING_APPLICATION*/
}
}
+1
View File
@@ -16,6 +16,7 @@
<orderEntry type="module" module-name="testRunner" exported="" />
<orderEntry type="module" module-name="compiler-openapi" />
<orderEntry type="module" module-name="java-impl" />
<orderEntry type="module" module-name="java-indexing-api" />
</component>
<component name="copyright">
<Base>
@@ -1,189 +1,189 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.compiler.options;
import com.intellij.execution.BeforeRunTask;
import com.intellij.execution.BeforeRunTaskProvider;
import com.intellij.execution.ExecutionBundle;
import com.intellij.execution.configurations.RunConfiguration;
import com.intellij.execution.configurations.RunConfigurationBase;
import com.intellij.execution.configurations.RunProfileWithCompileBeforeLaunchOption;
import com.intellij.execution.remote.RemoteConfiguration;
import com.intellij.execution.runners.ExecutionEnvironment;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.compiler.CompileContext;
import com.intellij.openapi.compiler.CompileScope;
import com.intellij.openapi.compiler.CompileStatusNotification;
import com.intellij.openapi.compiler.CompilerManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.Ref;
import com.intellij.util.concurrency.Semaphore;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
/**
* @author spleaner
*/
public class CompileStepBeforeRun extends BeforeRunTaskProvider<CompileStepBeforeRun.MakeBeforeRunTask> {
private static final Logger LOG = Logger.getInstance("#com.intellij.compiler.options.CompileStepBeforeRun");
public static final Key<MakeBeforeRunTask> ID = Key.create("Make");
private static final Key<RunConfiguration> RUN_CONFIGURATION = Key.create("RUN_CONFIGURATION");
private static final Key<String> RUN_CONFIGURATION_TYPE_ID = Key.create("RUN_CONFIGURATION_TYPE_ID");
@NonNls protected static final String MAKE_PROJECT_ON_RUN_KEY = "makeProjectOnRun";
private static final Icon ICON = AllIcons.Actions.Compile;
private final Project myProject;
public CompileStepBeforeRun(@NotNull final Project project) {
myProject = project;
}
public Key<MakeBeforeRunTask> getId() {
return ID;
}
@Override
public String getName() {
return ExecutionBundle.message("before.launch.compile.step");
}
@Override
public String getDescription(MakeBeforeRunTask task) {
return ExecutionBundle.message("before.launch.compile.step");
}
@Override
public Icon getIcon() {
return ICON;
}
@Override
public Icon getTaskIcon(MakeBeforeRunTask task) {
return ICON;
}
public MakeBeforeRunTask createTask(RunConfiguration runConfiguration) {
return !(runConfiguration instanceof RemoteConfiguration) && runConfiguration instanceof RunProfileWithCompileBeforeLaunchOption
? new MakeBeforeRunTask()
: null;
}
public boolean configureTask(RunConfiguration runConfiguration, MakeBeforeRunTask task) {
return false;
}
@Override
public boolean canExecuteTask(RunConfiguration configuration, MakeBeforeRunTask task) {
return true;
}
public boolean executeTask(DataContext context, final RunConfiguration configuration, ExecutionEnvironment env, MakeBeforeRunTask task) {
if (!(configuration instanceof RunProfileWithCompileBeforeLaunchOption)) {
return true;
}
if (configuration instanceof RunConfigurationBase && ((RunConfigurationBase)configuration).excludeCompileBeforeLaunchOption()) {
return true;
}
final RunProfileWithCompileBeforeLaunchOption runConfiguration = (RunProfileWithCompileBeforeLaunchOption)configuration;
final Ref<Boolean> result = new Ref<Boolean>(Boolean.FALSE);
try {
final Semaphore done = new Semaphore();
done.down();
final CompileStatusNotification callback = new CompileStatusNotification() {
public void finished(final boolean aborted, final int errors, final int warnings, CompileContext compileContext) {
if (errors == 0 && !aborted) {
result.set(Boolean.TRUE);
}
done.up();
}
};
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
CompileScope scope;
final CompilerManager compilerManager = CompilerManager.getInstance(myProject);
if (Boolean.valueOf(System.getProperty(MAKE_PROJECT_ON_RUN_KEY, Boolean.FALSE.toString())).booleanValue()) {
// user explicitly requested whole-project make
scope = compilerManager.createProjectCompileScope(myProject);
}
else {
final Module[] modules = runConfiguration.getModules();
if (modules.length > 0) {
for (Module module : modules) {
if (module == null) {
LOG.error("RunConfiguration should not return null modules. Configuration=" + runConfiguration.getName() + "; class=" +
runConfiguration.getClass().getName());
}
}
scope = compilerManager.createModulesCompileScope(modules, true);
}
else {
scope = compilerManager.createProjectCompileScope(myProject);
}
}
if (!myProject.isDisposed()) {
scope.putUserData(RUN_CONFIGURATION, configuration);
scope.putUserData(RUN_CONFIGURATION_TYPE_ID, configuration.getType().getId());
compilerManager.make(scope, callback);
}
else {
done.up();
}
}
});
done.waitFor();
}
catch (Exception e) {
return false;
}
return result.get();
}
public boolean isConfigurable() {
return false;
}
@Nullable
public static RunConfiguration getRunConfiguration(final CompileContext context) {
return context.getCompileScope().getUserData(RUN_CONFIGURATION);
}
@Nullable
public static RunConfiguration getRunConfiguration(final CompileScope compileScope) {
return compileScope.getUserData(RUN_CONFIGURATION);
}
public static class MakeBeforeRunTask extends BeforeRunTask<MakeBeforeRunTask> {
private MakeBeforeRunTask() {
super(ID);
setEnabled(true);
}
}
}
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.compiler.options;
import com.intellij.execution.BeforeRunTask;
import com.intellij.execution.BeforeRunTaskProvider;
import com.intellij.execution.ExecutionBundle;
import com.intellij.execution.configurations.RunConfiguration;
import com.intellij.execution.configurations.RunConfigurationBase;
import com.intellij.execution.configurations.RunProfileWithCompileBeforeLaunchOption;
import com.intellij.execution.remote.RemoteConfiguration;
import com.intellij.execution.runners.ExecutionEnvironment;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.compiler.CompileContext;
import com.intellij.openapi.compiler.CompileScope;
import com.intellij.openapi.compiler.CompileStatusNotification;
import com.intellij.openapi.compiler.CompilerManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.Ref;
import com.intellij.util.concurrency.Semaphore;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
/**
* @author spleaner
*/
public class CompileStepBeforeRun extends BeforeRunTaskProvider<CompileStepBeforeRun.MakeBeforeRunTask> {
private static final Logger LOG = Logger.getInstance("#com.intellij.compiler.options.CompileStepBeforeRun");
public static final Key<MakeBeforeRunTask> ID = Key.create("Make");
private static final Key<RunConfiguration> RUN_CONFIGURATION = Key.create("RUN_CONFIGURATION");
private static final Key<String> RUN_CONFIGURATION_TYPE_ID = Key.create("RUN_CONFIGURATION_TYPE_ID");
@NonNls protected static final String MAKE_PROJECT_ON_RUN_KEY = "makeProjectOnRun";
private static final Icon ICON = AllIcons.Actions.Compile;
private final Project myProject;
public CompileStepBeforeRun(@NotNull final Project project) {
myProject = project;
}
public Key<MakeBeforeRunTask> getId() {
return ID;
}
@Override
public String getName() {
return ExecutionBundle.message("before.launch.compile.step");
}
@Override
public String getDescription(MakeBeforeRunTask task) {
return ExecutionBundle.message("before.launch.compile.step");
}
@Override
public Icon getIcon() {
return ICON;
}
@Override
public Icon getTaskIcon(MakeBeforeRunTask task) {
return ICON;
}
public MakeBeforeRunTask createTask(RunConfiguration runConfiguration) {
return !(runConfiguration instanceof RemoteConfiguration) && runConfiguration instanceof RunProfileWithCompileBeforeLaunchOption
? new MakeBeforeRunTask()
: null;
}
public boolean configureTask(RunConfiguration runConfiguration, MakeBeforeRunTask task) {
return false;
}
@Override
public boolean canExecuteTask(RunConfiguration configuration, MakeBeforeRunTask task) {
return true;
}
public boolean executeTask(DataContext context, final RunConfiguration configuration, ExecutionEnvironment env, MakeBeforeRunTask task) {
if (!(configuration instanceof RunProfileWithCompileBeforeLaunchOption)) {
return true;
}
if (configuration instanceof RunConfigurationBase && ((RunConfigurationBase)configuration).excludeCompileBeforeLaunchOption()) {
return true;
}
final RunProfileWithCompileBeforeLaunchOption runConfiguration = (RunProfileWithCompileBeforeLaunchOption)configuration;
final Ref<Boolean> result = new Ref<Boolean>(Boolean.FALSE);
try {
final Semaphore done = new Semaphore();
done.down();
final CompileStatusNotification callback = new CompileStatusNotification() {
public void finished(final boolean aborted, final int errors, final int warnings, CompileContext compileContext) {
if (errors == 0 && !aborted) {
result.set(Boolean.TRUE);
}
done.up();
}
};
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
CompileScope scope;
final CompilerManager compilerManager = CompilerManager.getInstance(myProject);
if (Boolean.valueOf(System.getProperty(MAKE_PROJECT_ON_RUN_KEY, Boolean.FALSE.toString())).booleanValue()) {
// user explicitly requested whole-project make
scope = compilerManager.createProjectCompileScope(myProject);
}
else {
final Module[] modules = runConfiguration.getModules();
if (modules.length > 0) {
for (Module module : modules) {
if (module == null) {
LOG.error("RunConfiguration should not return null modules. Configuration=" + runConfiguration.getName() + "; class=" +
runConfiguration.getClass().getName());
}
}
scope = compilerManager.createModulesCompileScope(modules, true);
}
else {
scope = compilerManager.createProjectCompileScope(myProject);
}
}
if (!myProject.isDisposed()) {
scope.putUserData(RUN_CONFIGURATION, configuration);
scope.putUserData(RUN_CONFIGURATION_TYPE_ID, configuration.getType().getId());
compilerManager.make(scope, callback);
}
else {
done.up();
}
}
});
done.waitFor();
}
catch (Exception e) {
return false;
}
return result.get();
}
public boolean isConfigurable() {
return false;
}
@Nullable
public static RunConfiguration getRunConfiguration(final CompileContext context) {
return context.getCompileScope().getUserData(RUN_CONFIGURATION);
}
@Nullable
public static RunConfiguration getRunConfiguration(final CompileScope compileScope) {
return compileScope.getUserData(RUN_CONFIGURATION);
}
public static class MakeBeforeRunTask extends BeforeRunTask<MakeBeforeRunTask> {
private MakeBeforeRunTask() {
super(ID);
setEnabled(true);
}
}
}
+1
View File
@@ -32,6 +32,7 @@
<orderEntry type="module" module-name="java-psi-impl" exported="" />
<orderEntry type="module" module-name="RegExpSupport" />
<orderEntry type="module" module-name="java-indexing-impl" exported="" />
<orderEntry type="module" module-name="java-indexing-api" />
</component>
<component name="copyright">
<Base>
@@ -1,246 +1,246 @@
package com.intellij.codeInsight.completion;
import com.intellij.codeInsight.ExpectedTypeInfo;
import com.intellij.codeInsight.ExpectedTypesProvider;
import com.intellij.codeInsight.generation.GenerateMembersUtil;
import com.intellij.codeInsight.generation.OverrideImplementUtil;
import com.intellij.codeInsight.generation.PsiGenerationInfo;
import com.intellij.codeInsight.lookup.Lookup;
import com.intellij.codeInsight.lookup.LookupElementDecorator;
import com.intellij.codeInsight.lookup.LookupItem;
import com.intellij.codeInsight.lookup.PsiTypeLookupItem;
import com.intellij.featureStatistics.FeatureUsageTracker;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.command.UndoConfirmationPolicy;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.ScrollType;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleManager;
import com.intellij.psi.impl.source.PostprocessReformattingAspect;
import com.intellij.psi.infos.CandidateInfo;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collection;
import java.util.List;
/**
* @author peter
*/
public class ConstructorInsertHandler implements InsertHandler<LookupElementDecorator<LookupItem>> {
private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.completion.ConstructorInsertHandler");
public static final ConstructorInsertHandler SMART_INSTANCE = new ConstructorInsertHandler(true);
public static final ConstructorInsertHandler BASIC_INSTANCE = new ConstructorInsertHandler(false);
static final OffsetKey PARAM_LIST_START = OffsetKey.create("paramListStart");
static final OffsetKey PARAM_LIST_END = OffsetKey.create("paramListEnd");
private final boolean mySmart;
private ConstructorInsertHandler(boolean smart) {
mySmart = smart;
}
public void handleInsert(InsertionContext context, LookupElementDecorator<LookupItem> item) {
@SuppressWarnings({"unchecked"}) final LookupItem<PsiClass> delegate = item.getDelegate();
PsiClass psiClass = (PsiClass)item.getObject();
boolean isAbstract = psiClass.hasModifierProperty(PsiModifier.ABSTRACT);
if (Lookup.REPLACE_SELECT_CHAR == context.getCompletionChar()) {
final int plStart = context.getOffset(PARAM_LIST_START);
final int plEnd = context.getOffset(PARAM_LIST_END);
if (plStart >= 0 && plEnd >= 0) {
context.getDocument().deleteString(plStart, plEnd);
}
}
context.commitDocument();
OffsetKey insideRef = context.trackOffset(context.getTailOffset(), false);
final PsiElement position = SmartCompletionDecorator.getPosition(context, delegate);
final PsiExpression enclosing = PsiTreeUtil.getContextOfType(position, PsiExpression.class, true);
final PsiAnonymousClass anonymousClass = PsiTreeUtil.getParentOfType(position, PsiAnonymousClass.class);
final boolean inAnonymous = anonymousClass != null && anonymousClass.getParent() == enclosing;
boolean fillTypeArgs = false;
if (delegate instanceof PsiTypeLookupItem) {
fillTypeArgs = !isRawTypeExpected(context, (PsiTypeLookupItem)delegate) &&
psiClass.getTypeParameters().length > 0 &&
((PsiTypeLookupItem)delegate).calcGenerics(position, context).isEmpty() &&
context.getCompletionChar() != '(';
if (context.getDocument().getTextLength() > context.getTailOffset() &&
context.getDocument().getCharsSequence().charAt(context.getTailOffset()) == '<') {
PsiJavaCodeReferenceElement ref = PsiTreeUtil.findElementOfClassAtOffset(context.getFile(), context.getTailOffset(), PsiJavaCodeReferenceElement.class, false);
if (ref != null) {
PsiReferenceParameterList parameterList = ref.getParameterList();
if (parameterList != null && context.getTailOffset() == parameterList.getTextRange().getStartOffset()) {
context.getDocument().deleteString(parameterList.getTextRange().getStartOffset(), parameterList.getTextRange().getEndOffset());
context.commitDocument();
}
}
}
delegate.handleInsert(context);
PostprocessReformattingAspect.getInstance(context.getProject()).doPostponedFormatting(context.getFile().getViewProvider());
}
if (item.getDelegate() instanceof JavaPsiClassReferenceElement) {
PsiTypeLookupItem.addImportForItem(context, psiClass);
}
insertParentheses(context, delegate, psiClass, !inAnonymous && isAbstract);
if (inAnonymous) {
return;
}
if (mySmart) {
FeatureUsageTracker.getInstance().triggerFeatureUsed(JavaCompletionFeatures.AFTER_NEW);
}
if (isAbstract) {
PostprocessReformattingAspect.getInstance(context.getProject()).doPostponedFormatting(context.getFile().getViewProvider());
final Editor editor = context.getEditor();
final int offset = context.getTailOffset();
editor.getDocument().insertString(offset, " {}");
editor.getCaretModel().moveToOffset(offset + 2);
if (fillTypeArgs && JavaCompletionUtil.promptTypeArgs(context, context.getOffset(insideRef))) return;
context.setLaterRunnable(generateAnonymousBody(editor, context.getFile()));
}
else {
PsiDocumentManager.getInstance(context.getProject()).commitAllDocuments();
final PsiNewExpression newExpression =
PsiTreeUtil.findElementOfClassAtOffset(context.getFile(), context.getStartOffset(), PsiNewExpression.class, false);
if (newExpression != null) {
final PsiJavaCodeReferenceElement classReference = newExpression.getClassOrAnonymousClassReference();
if (classReference != null) {
CodeStyleManager.getInstance(context.getProject()).reformat(classReference);
}
}
if (mySmart) {
FeatureUsageTracker.getInstance().triggerFeatureUsed(JavaCompletionFeatures.AFTER_NEW);
}
if (fillTypeArgs && JavaCompletionUtil.promptTypeArgs(context, context.getOffset(insideRef))) return;
}
}
static boolean isRawTypeExpected(InsertionContext context, PsiTypeLookupItem delegate) {
PsiNewExpression newExpr =
PsiTreeUtil.findElementOfClassAtOffset(context.getFile(), context.getStartOffset(), PsiNewExpression.class, false);
if (newExpr != null) {
for (ExpectedTypeInfo info : ExpectedTypesProvider.getExpectedTypes(newExpr, true)) {
PsiType expected = info.getDefaultType();
if (expected.isAssignableFrom(delegate.getPsiType())) {
if (expected instanceof PsiClassType && ((PsiClassType)expected).isRaw()) {
return true;
}
}
}
}
return false;
}
public static boolean insertParentheses(InsertionContext context,
LookupItem delegate,
final PsiClass psiClass,
final boolean forAnonymous) {
if (context.getCompletionChar() == '[') {
return false;
}
final PsiElement place = context.getFile().findElementAt(context.getStartOffset());
assert place != null;
boolean hasParams = hasConstructorParameters(psiClass, place);
JavaCompletionUtil.insertParentheses(context, delegate, false, hasParams, forAnonymous);
return true;
}
static boolean hasConstructorParameters(PsiClass psiClass, @NotNull PsiElement place) {
final PsiResolveHelper resolveHelper = JavaPsiFacade.getInstance(place.getProject()).getResolveHelper();
boolean hasParams = false;
for (PsiMethod constructor : psiClass.getConstructors()) {
if (!resolveHelper.isAccessible(constructor, place, null)) continue;
if (constructor.getParameterList().getParametersCount() > 0) {
hasParams = true;
break;
}
}
return hasParams;
}
@Nullable
private static Runnable generateAnonymousBody(final Editor editor, final PsiFile file) {
final Project project = file.getProject();
PsiDocumentManager.getInstance(project).commitAllDocuments();
int offset = editor.getCaretModel().getOffset();
PsiElement element = file.findElementAt(offset);
if (element == null) return null;
PsiElement parent = element.getParent();
if (!(parent instanceof PsiAnonymousClass)) return null;
return genAnonymousBodyFor((PsiAnonymousClass)parent, editor, file, project);
}
public static Runnable genAnonymousBodyFor(PsiAnonymousClass parent,
final Editor editor,
final PsiFile file,
final Project project) {
try {
CodeStyleManager.getInstance(project).reformat(parent);
}
catch (IncorrectOperationException e) {
LOG.error(e);
}
int offset = parent.getTextRange().getEndOffset() - 1;
editor.getCaretModel().moveToOffset(offset);
editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
editor.getSelectionModel().removeSelection();
return new Runnable() {
public void run(){
CommandProcessor.getInstance().executeCommand(project, new Runnable() {
public void run() {
PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument());
final PsiAnonymousClass aClass = PsiTreeUtil.findElementOfClassAtOffset(file, editor.getCaretModel().getOffset(), PsiAnonymousClass.class, false);
if (aClass == null) return;
final Collection<CandidateInfo> candidatesToImplement = OverrideImplementUtil.getMethodsToOverrideImplement(aClass, true);
boolean invokeOverride = candidatesToImplement.isEmpty();
if (invokeOverride){
OverrideImplementUtil.chooseAndOverrideOrImplementMethods(project, editor, aClass, false);
}
else{
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
try{
List<PsiMethod> methods = OverrideImplementUtil.overrideOrImplementMethodCandidates(aClass, candidatesToImplement, false);
List<PsiGenerationInfo<PsiMethod>> prototypes = OverrideImplementUtil.convert2GenerationInfos(methods);
List<PsiGenerationInfo<PsiMethod>> resultMembers = GenerateMembersUtil.insertMembersBeforeAnchor(aClass, null, prototypes);
resultMembers.get(0).positionCaret(editor, true);
}
catch(IncorrectOperationException ioe){
LOG.error(ioe);
}
}
});
}
}
}, CompletionBundle.message("completion.smart.type.generate.anonymous.body"), null, UndoConfirmationPolicy.DEFAULT, editor.getDocument());
}
};
}
}
package com.intellij.codeInsight.completion;
import com.intellij.codeInsight.ExpectedTypeInfo;
import com.intellij.codeInsight.ExpectedTypesProvider;
import com.intellij.codeInsight.generation.GenerateMembersUtil;
import com.intellij.codeInsight.generation.OverrideImplementUtil;
import com.intellij.codeInsight.generation.PsiGenerationInfo;
import com.intellij.codeInsight.lookup.Lookup;
import com.intellij.codeInsight.lookup.LookupElementDecorator;
import com.intellij.codeInsight.lookup.LookupItem;
import com.intellij.codeInsight.lookup.PsiTypeLookupItem;
import com.intellij.featureStatistics.FeatureUsageTracker;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.command.UndoConfirmationPolicy;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.ScrollType;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleManager;
import com.intellij.psi.impl.source.PostprocessReformattingAspect;
import com.intellij.psi.infos.CandidateInfo;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collection;
import java.util.List;
/**
* @author peter
*/
public class ConstructorInsertHandler implements InsertHandler<LookupElementDecorator<LookupItem>> {
private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.completion.ConstructorInsertHandler");
public static final ConstructorInsertHandler SMART_INSTANCE = new ConstructorInsertHandler(true);
public static final ConstructorInsertHandler BASIC_INSTANCE = new ConstructorInsertHandler(false);
static final OffsetKey PARAM_LIST_START = OffsetKey.create("paramListStart");
static final OffsetKey PARAM_LIST_END = OffsetKey.create("paramListEnd");
private final boolean mySmart;
private ConstructorInsertHandler(boolean smart) {
mySmart = smart;
}
public void handleInsert(InsertionContext context, LookupElementDecorator<LookupItem> item) {
@SuppressWarnings({"unchecked"}) final LookupItem<PsiClass> delegate = item.getDelegate();
PsiClass psiClass = (PsiClass)item.getObject();
boolean isAbstract = psiClass.hasModifierProperty(PsiModifier.ABSTRACT);
if (Lookup.REPLACE_SELECT_CHAR == context.getCompletionChar()) {
final int plStart = context.getOffset(PARAM_LIST_START);
final int plEnd = context.getOffset(PARAM_LIST_END);
if (plStart >= 0 && plEnd >= 0) {
context.getDocument().deleteString(plStart, plEnd);
}
}
context.commitDocument();
OffsetKey insideRef = context.trackOffset(context.getTailOffset(), false);
final PsiElement position = SmartCompletionDecorator.getPosition(context, delegate);
final PsiExpression enclosing = PsiTreeUtil.getContextOfType(position, PsiExpression.class, true);
final PsiAnonymousClass anonymousClass = PsiTreeUtil.getParentOfType(position, PsiAnonymousClass.class);
final boolean inAnonymous = anonymousClass != null && anonymousClass.getParent() == enclosing;
boolean fillTypeArgs = false;
if (delegate instanceof PsiTypeLookupItem) {
fillTypeArgs = !isRawTypeExpected(context, (PsiTypeLookupItem)delegate) &&
psiClass.getTypeParameters().length > 0 &&
((PsiTypeLookupItem)delegate).calcGenerics(position, context).isEmpty() &&
context.getCompletionChar() != '(';
if (context.getDocument().getTextLength() > context.getTailOffset() &&
context.getDocument().getCharsSequence().charAt(context.getTailOffset()) == '<') {
PsiJavaCodeReferenceElement ref = PsiTreeUtil.findElementOfClassAtOffset(context.getFile(), context.getTailOffset(), PsiJavaCodeReferenceElement.class, false);
if (ref != null) {
PsiReferenceParameterList parameterList = ref.getParameterList();
if (parameterList != null && context.getTailOffset() == parameterList.getTextRange().getStartOffset()) {
context.getDocument().deleteString(parameterList.getTextRange().getStartOffset(), parameterList.getTextRange().getEndOffset());
context.commitDocument();
}
}
}
delegate.handleInsert(context);
PostprocessReformattingAspect.getInstance(context.getProject()).doPostponedFormatting(context.getFile().getViewProvider());
}
if (item.getDelegate() instanceof JavaPsiClassReferenceElement) {
PsiTypeLookupItem.addImportForItem(context, psiClass);
}
insertParentheses(context, delegate, psiClass, !inAnonymous && isAbstract);
if (inAnonymous) {
return;
}
if (mySmart) {
FeatureUsageTracker.getInstance().triggerFeatureUsed(JavaCompletionFeatures.AFTER_NEW);
}
if (isAbstract) {
PostprocessReformattingAspect.getInstance(context.getProject()).doPostponedFormatting(context.getFile().getViewProvider());
final Editor editor = context.getEditor();
final int offset = context.getTailOffset();
editor.getDocument().insertString(offset, " {}");
editor.getCaretModel().moveToOffset(offset + 2);
if (fillTypeArgs && JavaCompletionUtil.promptTypeArgs(context, context.getOffset(insideRef))) return;
context.setLaterRunnable(generateAnonymousBody(editor, context.getFile()));
}
else {
PsiDocumentManager.getInstance(context.getProject()).commitAllDocuments();
final PsiNewExpression newExpression =
PsiTreeUtil.findElementOfClassAtOffset(context.getFile(), context.getStartOffset(), PsiNewExpression.class, false);
if (newExpression != null) {
final PsiJavaCodeReferenceElement classReference = newExpression.getClassOrAnonymousClassReference();
if (classReference != null) {
CodeStyleManager.getInstance(context.getProject()).reformat(classReference);
}
}
if (mySmart) {
FeatureUsageTracker.getInstance().triggerFeatureUsed(JavaCompletionFeatures.AFTER_NEW);
}
if (fillTypeArgs && JavaCompletionUtil.promptTypeArgs(context, context.getOffset(insideRef))) return;
}
}
static boolean isRawTypeExpected(InsertionContext context, PsiTypeLookupItem delegate) {
PsiNewExpression newExpr =
PsiTreeUtil.findElementOfClassAtOffset(context.getFile(), context.getStartOffset(), PsiNewExpression.class, false);
if (newExpr != null) {
for (ExpectedTypeInfo info : ExpectedTypesProvider.getExpectedTypes(newExpr, true)) {
PsiType expected = info.getDefaultType();
if (expected.isAssignableFrom(delegate.getPsiType())) {
if (expected instanceof PsiClassType && ((PsiClassType)expected).isRaw()) {
return true;
}
}
}
}
return false;
}
public static boolean insertParentheses(InsertionContext context,
LookupItem delegate,
final PsiClass psiClass,
final boolean forAnonymous) {
if (context.getCompletionChar() == '[') {
return false;
}
final PsiElement place = context.getFile().findElementAt(context.getStartOffset());
assert place != null;
boolean hasParams = hasConstructorParameters(psiClass, place);
JavaCompletionUtil.insertParentheses(context, delegate, false, hasParams, forAnonymous);
return true;
}
static boolean hasConstructorParameters(PsiClass psiClass, @NotNull PsiElement place) {
final PsiResolveHelper resolveHelper = JavaPsiFacade.getInstance(place.getProject()).getResolveHelper();
boolean hasParams = false;
for (PsiMethod constructor : psiClass.getConstructors()) {
if (!resolveHelper.isAccessible(constructor, place, null)) continue;
if (constructor.getParameterList().getParametersCount() > 0) {
hasParams = true;
break;
}
}
return hasParams;
}
@Nullable
private static Runnable generateAnonymousBody(final Editor editor, final PsiFile file) {
final Project project = file.getProject();
PsiDocumentManager.getInstance(project).commitAllDocuments();
int offset = editor.getCaretModel().getOffset();
PsiElement element = file.findElementAt(offset);
if (element == null) return null;
PsiElement parent = element.getParent();
if (!(parent instanceof PsiAnonymousClass)) return null;
return genAnonymousBodyFor((PsiAnonymousClass)parent, editor, file, project);
}
public static Runnable genAnonymousBodyFor(PsiAnonymousClass parent,
final Editor editor,
final PsiFile file,
final Project project) {
try {
CodeStyleManager.getInstance(project).reformat(parent);
}
catch (IncorrectOperationException e) {
LOG.error(e);
}
int offset = parent.getTextRange().getEndOffset() - 1;
editor.getCaretModel().moveToOffset(offset);
editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
editor.getSelectionModel().removeSelection();
return new Runnable() {
public void run(){
CommandProcessor.getInstance().executeCommand(project, new Runnable() {
public void run() {
PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument());
final PsiAnonymousClass aClass = PsiTreeUtil.findElementOfClassAtOffset(file, editor.getCaretModel().getOffset(), PsiAnonymousClass.class, false);
if (aClass == null) return;
final Collection<CandidateInfo> candidatesToImplement = OverrideImplementUtil.getMethodsToOverrideImplement(aClass, true);
boolean invokeOverride = candidatesToImplement.isEmpty();
if (invokeOverride){
OverrideImplementUtil.chooseAndOverrideOrImplementMethods(project, editor, aClass, false);
}
else{
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
try{
List<PsiMethod> methods = OverrideImplementUtil.overrideOrImplementMethodCandidates(aClass, candidatesToImplement, false);
List<PsiGenerationInfo<PsiMethod>> prototypes = OverrideImplementUtil.convert2GenerationInfos(methods);
List<PsiGenerationInfo<PsiMethod>> resultMembers = GenerateMembersUtil.insertMembersBeforeAnchor(aClass, null, prototypes);
resultMembers.get(0).positionCaret(editor, true);
}
catch(IncorrectOperationException ioe){
LOG.error(ioe);
}
}
});
}
}
}, CompletionBundle.message("completion.smart.type.generate.anonymous.body"), null, UndoConfirmationPolicy.DEFAULT, editor.getDocument());
}
};
}
}
@@ -1,184 +1,184 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInsight.completion;
import com.intellij.codeInsight.ExpectedTypeInfo;
import com.intellij.codeInsight.ExpectedTypesProvider;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.lang.LangBundle;
import com.intellij.lang.java.JavaLanguage;
import com.intellij.openapi.actionSystem.IdeActions;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.fileTypes.impl.CustomSyntaxTableFileType;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.patterns.PsiJavaElementPattern;
import com.intellij.psi.*;
import com.intellij.psi.filters.ClassFilter;
import com.intellij.psi.filters.ElementFilter;
import com.intellij.psi.filters.TrueFilter;
import com.intellij.psi.filters.element.ExcludeDeclaredFilter;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.util.Consumer;
import com.intellij.util.SmartList;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import static com.intellij.patterns.PsiJavaPatterns.psiElement;
/**
* @author peter
*/
public class JavaClassNameCompletionContributor extends CompletionContributor {
public static final PsiJavaElementPattern.Capture<PsiElement> AFTER_NEW = psiElement().afterLeaf(PsiKeyword.NEW);
private static final PsiJavaElementPattern.Capture<PsiElement> IN_TYPE_PARAMETER =
psiElement().afterLeaf(PsiKeyword.EXTENDS, PsiKeyword.SUPER, "&").withParent(
psiElement(PsiReferenceList.class).withParent(PsiTypeParameter.class));
@Override
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);
}
});
}
}
private static boolean mayContainClassName(CompletionParameters parameters) {
PsiElement position = parameters.getPosition();
PsiFile file = position.getContainingFile();
if (file instanceof PsiPlainTextFile || file.getFileType() instanceof CustomSyntaxTableFileType) {
return true;
}
if (SkipAutopopupInStrings.isInStringLiteral(position)) {
return true;
}
if (PsiTreeUtil.getParentOfType(position, PsiComment.class, false) != null) {
return true;
}
return false;
}
public static void addAllClasses(CompletionParameters parameters,
final boolean filterByScope,
@NotNull final PrefixMatcher matcher,
@NotNull final Consumer<LookupElement> consumer) {
final PsiElement insertedElement = parameters.getPosition();
final ElementFilter filter =
IN_TYPE_PARAMETER.accepts(insertedElement) ? new ExcludeDeclaredFilter(new ClassFilter(PsiTypeParameter.class)) : TrueFilter.INSTANCE;
final boolean inJavaContext = parameters.getPosition() instanceof PsiIdentifier;
final boolean afterNew = AFTER_NEW.accepts(insertedElement);
if (afterNew) {
final PsiExpression expr = PsiTreeUtil.getContextOfType(insertedElement, PsiExpression.class, true);
for (final ExpectedTypeInfo info : ExpectedTypesProvider.getExpectedTypes(expr, true)) {
final PsiType type = info.getType();
final PsiClass psiClass = PsiUtil.resolveClassInType(type);
if (psiClass != null) {
consumer.consume(createClassLookupItem(psiClass, inJavaContext));
}
final PsiType defaultType = info.getDefaultType();
if (!defaultType.equals(type)) {
final PsiClass defClass = PsiUtil.resolveClassInType(defaultType);
if (defClass != null) {
consumer.consume(createClassLookupItem(defClass, true));
}
}
}
}
final boolean pkgContext = JavaCompletionUtil.inSomePackage(insertedElement);
AllClassesGetter.processJavaClasses(parameters, matcher, filterByScope, new Consumer<PsiClass>() {
@Override
public void consume(PsiClass psiClass) {
if (filter.isAcceptable(psiClass, insertedElement)) {
if (!inJavaContext) {
consumer.consume(AllClassesGetter.createLookupItem(psiClass, AllClassesGetter.TRY_SHORTENING));
} else {
for (JavaPsiClassReferenceElement element : createClassLookupItems(psiClass, afterNew,
JavaClassNameInsertHandler.JAVA_CLASS_INSERT_HANDLER, new Condition<PsiClass>() {
@Override
public boolean value(PsiClass psiClass) {
return filter.isAcceptable(psiClass, insertedElement) &&
AllClassesGetter.isAcceptableInContext(insertedElement, psiClass, filterByScope, pkgContext);
}
})) {
consumer.consume(element);
}
}
}
}
});
}
public static JavaPsiClassReferenceElement createClassLookupItem(final PsiClass psiClass, final boolean inJavaContext) {
return AllClassesGetter.createLookupItem(psiClass, inJavaContext ? JavaClassNameInsertHandler.JAVA_CLASS_INSERT_HANDLER
: AllClassesGetter.TRY_SHORTENING);
}
public static List<JavaPsiClassReferenceElement> createClassLookupItems(final PsiClass psiClass,
boolean withInners,
InsertHandler<JavaPsiClassReferenceElement> insertHandler,
Condition<PsiClass> condition) {
List<JavaPsiClassReferenceElement> result = new SmartList<JavaPsiClassReferenceElement>();
if (condition.value(psiClass)) {
result.add(AllClassesGetter.createLookupItem(psiClass, insertHandler));
}
String name = psiClass.getName();
if (withInners && name != null) {
for (PsiClass inner : psiClass.getInnerClasses()) {
if (inner.hasModifierProperty(PsiModifier.STATIC)) {
for (JavaPsiClassReferenceElement lookupInner : createClassLookupItems(inner, withInners, insertHandler, condition)) {
String forced = lookupInner.getForcedPresentableName();
lookupInner.setForcedPresentableName(name + "." + (forced != null ? forced : inner.getName()));
result.add(lookupInner);
}
}
}
}
return result;
}
@Override
public String handleEmptyLookup(@NotNull final CompletionParameters parameters, final Editor editor) {
if (!(parameters.getOriginalFile() instanceof PsiJavaFile)) return null;
if (shouldShowSecondSmartCompletionHint(parameters)) {
return LangBundle.message("completion.no.suggestions") +
"; " +
StringUtil.decapitalize(
CompletionBundle.message("completion.class.name.hint.2", getActionShortcut(IdeActions.ACTION_CODE_COMPLETION)));
}
return null;
}
private static boolean shouldShowSecondSmartCompletionHint(final CompletionParameters parameters) {
return parameters.getCompletionType() == CompletionType.BASIC &&
parameters.getInvocationCount() == 2 &&
parameters.getOriginalFile().getLanguage().isKindOf(JavaLanguage.INSTANCE);
}
}
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInsight.completion;
import com.intellij.codeInsight.ExpectedTypeInfo;
import com.intellij.codeInsight.ExpectedTypesProvider;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.lang.LangBundle;
import com.intellij.lang.java.JavaLanguage;
import com.intellij.openapi.actionSystem.IdeActions;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.fileTypes.impl.CustomSyntaxTableFileType;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.patterns.PsiJavaElementPattern;
import com.intellij.psi.*;
import com.intellij.psi.filters.ClassFilter;
import com.intellij.psi.filters.ElementFilter;
import com.intellij.psi.filters.TrueFilter;
import com.intellij.psi.filters.element.ExcludeDeclaredFilter;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.util.Consumer;
import com.intellij.util.SmartList;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import static com.intellij.patterns.PsiJavaPatterns.psiElement;
/**
* @author peter
*/
public class JavaClassNameCompletionContributor extends CompletionContributor {
public static final PsiJavaElementPattern.Capture<PsiElement> AFTER_NEW = psiElement().afterLeaf(PsiKeyword.NEW);
private static final PsiJavaElementPattern.Capture<PsiElement> IN_TYPE_PARAMETER =
psiElement().afterLeaf(PsiKeyword.EXTENDS, PsiKeyword.SUPER, "&").withParent(
psiElement(PsiReferenceList.class).withParent(PsiTypeParameter.class));
@Override
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);
}
});
}
}
private static boolean mayContainClassName(CompletionParameters parameters) {
PsiElement position = parameters.getPosition();
PsiFile file = position.getContainingFile();
if (file instanceof PsiPlainTextFile || file.getFileType() instanceof CustomSyntaxTableFileType) {
return true;
}
if (SkipAutopopupInStrings.isInStringLiteral(position)) {
return true;
}
if (PsiTreeUtil.getParentOfType(position, PsiComment.class, false) != null) {
return true;
}
return false;
}
public static void addAllClasses(CompletionParameters parameters,
final boolean filterByScope,
@NotNull final PrefixMatcher matcher,
@NotNull final Consumer<LookupElement> consumer) {
final PsiElement insertedElement = parameters.getPosition();
final ElementFilter filter =
IN_TYPE_PARAMETER.accepts(insertedElement) ? new ExcludeDeclaredFilter(new ClassFilter(PsiTypeParameter.class)) : TrueFilter.INSTANCE;
final boolean inJavaContext = parameters.getPosition() instanceof PsiIdentifier;
final boolean afterNew = AFTER_NEW.accepts(insertedElement);
if (afterNew) {
final PsiExpression expr = PsiTreeUtil.getContextOfType(insertedElement, PsiExpression.class, true);
for (final ExpectedTypeInfo info : ExpectedTypesProvider.getExpectedTypes(expr, true)) {
final PsiType type = info.getType();
final PsiClass psiClass = PsiUtil.resolveClassInType(type);
if (psiClass != null) {
consumer.consume(createClassLookupItem(psiClass, inJavaContext));
}
final PsiType defaultType = info.getDefaultType();
if (!defaultType.equals(type)) {
final PsiClass defClass = PsiUtil.resolveClassInType(defaultType);
if (defClass != null) {
consumer.consume(createClassLookupItem(defClass, true));
}
}
}
}
final boolean pkgContext = JavaCompletionUtil.inSomePackage(insertedElement);
AllClassesGetter.processJavaClasses(parameters, matcher, filterByScope, new Consumer<PsiClass>() {
@Override
public void consume(PsiClass psiClass) {
if (filter.isAcceptable(psiClass, insertedElement)) {
if (!inJavaContext) {
consumer.consume(AllClassesGetter.createLookupItem(psiClass, AllClassesGetter.TRY_SHORTENING));
} else {
for (JavaPsiClassReferenceElement element : createClassLookupItems(psiClass, afterNew,
JavaClassNameInsertHandler.JAVA_CLASS_INSERT_HANDLER, new Condition<PsiClass>() {
@Override
public boolean value(PsiClass psiClass) {
return filter.isAcceptable(psiClass, insertedElement) &&
AllClassesGetter.isAcceptableInContext(insertedElement, psiClass, filterByScope, pkgContext);
}
})) {
consumer.consume(element);
}
}
}
}
});
}
public static JavaPsiClassReferenceElement createClassLookupItem(final PsiClass psiClass, final boolean inJavaContext) {
return AllClassesGetter.createLookupItem(psiClass, inJavaContext ? JavaClassNameInsertHandler.JAVA_CLASS_INSERT_HANDLER
: AllClassesGetter.TRY_SHORTENING);
}
public static List<JavaPsiClassReferenceElement> createClassLookupItems(final PsiClass psiClass,
boolean withInners,
InsertHandler<JavaPsiClassReferenceElement> insertHandler,
Condition<PsiClass> condition) {
List<JavaPsiClassReferenceElement> result = new SmartList<JavaPsiClassReferenceElement>();
if (condition.value(psiClass)) {
result.add(AllClassesGetter.createLookupItem(psiClass, insertHandler));
}
String name = psiClass.getName();
if (withInners && name != null) {
for (PsiClass inner : psiClass.getInnerClasses()) {
if (inner.hasModifierProperty(PsiModifier.STATIC)) {
for (JavaPsiClassReferenceElement lookupInner : createClassLookupItems(inner, withInners, insertHandler, condition)) {
String forced = lookupInner.getForcedPresentableName();
lookupInner.setForcedPresentableName(name + "." + (forced != null ? forced : inner.getName()));
result.add(lookupInner);
}
}
}
}
return result;
}
@Override
public String handleEmptyLookup(@NotNull final CompletionParameters parameters, final Editor editor) {
if (!(parameters.getOriginalFile() instanceof PsiJavaFile)) return null;
if (shouldShowSecondSmartCompletionHint(parameters)) {
return LangBundle.message("completion.no.suggestions") +
"; " +
StringUtil.decapitalize(
CompletionBundle.message("completion.class.name.hint.2", getActionShortcut(IdeActions.ACTION_CODE_COMPLETION)));
}
return null;
}
private static boolean shouldShowSecondSmartCompletionHint(final CompletionParameters parameters) {
return parameters.getCompletionType() == CompletionType.BASIC &&
parameters.getInvocationCount() == 2 &&
parameters.getOriginalFile().getLanguage().isKindOf(JavaLanguage.INSTANCE);
}
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -1,30 +1,30 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInsight.completion;
import org.jetbrains.annotations.NonNls;
/**
* @author peter
*/
public interface JavaCompletionFeatures {
@NonNls String SECOND_SMART_COMPLETION_CHAIN = "editing.completion.second.smarttype.chain";
@NonNls String SECOND_SMART_COMPLETION_TOAR = "editing.completion.second.smarttype.toar";
@NonNls String SECOND_SMART_COMPLETION_ASLIST = "editing.completion.second.smarttype.aslist";
@NonNls String SECOND_SMART_COMPLETION_ARRAY_MEMBER = "editing.completion.second.smarttype.array.member";
@NonNls String GLOBAL_MEMBER_NAME = "editing.completion.global.member.name";
@NonNls String AFTER_NEW = "editing.completion.smarttype.afternew";
}
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInsight.completion;
import org.jetbrains.annotations.NonNls;
/**
* @author peter
*/
public interface JavaCompletionFeatures {
@NonNls String SECOND_SMART_COMPLETION_CHAIN = "editing.completion.second.smarttype.chain";
@NonNls String SECOND_SMART_COMPLETION_TOAR = "editing.completion.second.smarttype.toar";
@NonNls String SECOND_SMART_COMPLETION_ASLIST = "editing.completion.second.smarttype.aslist";
@NonNls String SECOND_SMART_COMPLETION_ARRAY_MEMBER = "editing.completion.second.smarttype.array.member";
@NonNls String GLOBAL_MEMBER_NAME = "editing.completion.global.member.name";
@NonNls String AFTER_NEW = "editing.completion.smarttype.afternew";
}
File diff suppressed because it is too large Load Diff
@@ -1,69 +1,69 @@
/*
* 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.codeInsight.completion;
import com.intellij.codeInsight.lookup.AutoCompletionPolicy;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.VariableLookupItem;
import com.intellij.psi.*;
import com.intellij.psi.util.PsiTreeUtil;
import org.jetbrains.annotations.NotNull;
import java.util.List;
/**
* @author peter
*/
public class JavaStaticMemberProcessor extends StaticMemberProcessor {
private final PsiElement myOriginalPosition;
public JavaStaticMemberProcessor(CompletionParameters parameters) {
super(parameters.getPosition());
myOriginalPosition = parameters.getOriginalPosition();
final PsiFile file = parameters.getPosition().getContainingFile();
if (file instanceof PsiJavaFile) {
final PsiImportList importList = ((PsiJavaFile)file).getImportList();
if (importList != null) {
for (PsiImportStaticStatement statement : importList.getImportStaticStatements()) {
importMembersOf(statement.resolveTargetClass());
}
}
}
}
@NotNull
@Override
protected LookupElement createLookupElement(@NotNull PsiMember member, @NotNull final PsiClass containingClass, boolean shouldImport) {
shouldImport |= myOriginalPosition != null && PsiTreeUtil.isAncestor(containingClass, myOriginalPosition, false);
if (member instanceof PsiMethod) {
return AutoCompletionPolicy.NEVER_AUTOCOMPLETE.applyPolicy(new JavaMethodCallElement((PsiMethod)member, shouldImport, false));
}
return AutoCompletionPolicy.NEVER_AUTOCOMPLETE.applyPolicy(new VariableLookupItem((PsiField)member, shouldImport));
}
@Override
protected LookupElement createLookupElement(@NotNull List<PsiMethod> overloads,
@NotNull PsiClass containingClass,
boolean shouldImport) {
shouldImport |= myOriginalPosition != null && PsiTreeUtil.isAncestor(containingClass, myOriginalPosition, false);
final JavaMethodCallElement element = new JavaMethodCallElement(overloads.get(0), shouldImport, true);
element.putUserData(JavaCompletionUtil.ALL_METHODS_ATTRIBUTE, overloads);
return element;
}
}
/*
* 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.codeInsight.completion;
import com.intellij.codeInsight.lookup.AutoCompletionPolicy;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.VariableLookupItem;
import com.intellij.psi.*;
import com.intellij.psi.util.PsiTreeUtil;
import org.jetbrains.annotations.NotNull;
import java.util.List;
/**
* @author peter
*/
public class JavaStaticMemberProcessor extends StaticMemberProcessor {
private final PsiElement myOriginalPosition;
public JavaStaticMemberProcessor(CompletionParameters parameters) {
super(parameters.getPosition());
myOriginalPosition = parameters.getOriginalPosition();
final PsiFile file = parameters.getPosition().getContainingFile();
if (file instanceof PsiJavaFile) {
final PsiImportList importList = ((PsiJavaFile)file).getImportList();
if (importList != null) {
for (PsiImportStaticStatement statement : importList.getImportStaticStatements()) {
importMembersOf(statement.resolveTargetClass());
}
}
}
}
@NotNull
@Override
protected LookupElement createLookupElement(@NotNull PsiMember member, @NotNull final PsiClass containingClass, boolean shouldImport) {
shouldImport |= myOriginalPosition != null && PsiTreeUtil.isAncestor(containingClass, myOriginalPosition, false);
if (member instanceof PsiMethod) {
return AutoCompletionPolicy.NEVER_AUTOCOMPLETE.applyPolicy(new JavaMethodCallElement((PsiMethod)member, shouldImport, false));
}
return AutoCompletionPolicy.NEVER_AUTOCOMPLETE.applyPolicy(new VariableLookupItem((PsiField)member, shouldImport));
}
@Override
protected LookupElement createLookupElement(@NotNull List<PsiMethod> overloads,
@NotNull PsiClass containingClass,
boolean shouldImport) {
shouldImport |= myOriginalPosition != null && PsiTreeUtil.isAncestor(containingClass, myOriginalPosition, false);
final JavaMethodCallElement element = new JavaMethodCallElement(overloads.get(0), shouldImport, true);
element.putUserData(JavaCompletionUtil.ALL_METHODS_ATTRIBUTE, overloads);
return element;
}
}
@@ -1,140 +1,140 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInsight.completion;
import com.intellij.codeInsight.completion.scope.JavaCompletionProcessor;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupElementWeigher;
import com.intellij.psi.*;
import com.intellij.psi.filters.getters.MembersGetter;
import com.intellij.psi.util.PropertyUtil;
import com.intellij.psi.util.PsiTreeUtil;
import org.jetbrains.annotations.NotNull;
import java.util.Set;
/**
* @author peter
*/
public class PreferLocalVariablesLiteralsAndAnnoMethodsWeigher extends LookupElementWeigher {
private final CompletionType myCompletionType;
private final PsiElement myPosition;
private final Set<PsiField> myNonInitializedFields;
public PreferLocalVariablesLiteralsAndAnnoMethodsWeigher(CompletionType completionType, PsiElement position) {
super("local");
myCompletionType = completionType;
myPosition = position;
myNonInitializedFields = JavaCompletionProcessor.getNonInitializedFields(position);
}
enum MyResult {
annoMethod,
probableKeyword,
localOrParameter,
qualifiedWithField,
qualifiedWithGetter,
superMethodParameters,
normal,
collectionFactory,
expectedTypeMember,
nonInitialized,
classLiteral,
classNameOrGlobalStatic,
}
@NotNull
@Override
public MyResult weigh(@NotNull LookupElement item) {
final Object object = item.getObject();
if (object instanceof PsiKeyword) {
String keyword = ((PsiKeyword)object).getText();
if (PsiKeyword.RETURN.equals(keyword) && isLastStatement(PsiTreeUtil.getParentOfType(myPosition, PsiStatement.class))) {
return MyResult.probableKeyword;
}
if (PsiKeyword.ELSE.equals(keyword) || PsiKeyword.FINALLY.equals(keyword)) {
return MyResult.probableKeyword;
}
}
if (object instanceof PsiLocalVariable || object instanceof PsiParameter || object instanceof PsiThisExpression) {
return MyResult.localOrParameter;
}
if (object instanceof String && item.getUserData(JavaCompletionUtil.SUPER_METHOD_PARAMETERS) == Boolean.TRUE) {
return MyResult.superMethodParameters;
}
if (myCompletionType == CompletionType.SMART) {
if (item.getUserData(CollectionsUtilityMethodsProvider.COLLECTION_FACTORY) != null) {
return MyResult.collectionFactory;
}
if (Boolean.TRUE.equals(item.getUserData(MembersGetter.EXPECTED_TYPE_INHERITOR_MEMBER))) {
return MyResult.expectedTypeMember;
}
final JavaChainLookupElement chain = item.as(JavaChainLookupElement.CLASS_CONDITION_KEY);
if (chain != null) {
Object qualifier = chain.getQualifier().getObject();
if (qualifier instanceof PsiLocalVariable || qualifier instanceof PsiParameter) {
return MyResult.localOrParameter;
}
if (qualifier instanceof PsiField) {
return MyResult.qualifiedWithField;
}
if (qualifier instanceof PsiMethod && PropertyUtil.isSimplePropertyGetter((PsiMethod)qualifier)) {
return MyResult.qualifiedWithGetter;
}
}
return MyResult.normal;
}
if (myCompletionType == CompletionType.BASIC) {
StaticallyImportable callElement = item.as(StaticallyImportable.CLASS_CONDITION_KEY);
if (callElement != null && callElement.canBeImported() && !callElement.willBeImported()) {
return MyResult.classNameOrGlobalStatic;
}
if (object instanceof PsiKeyword && PsiKeyword.CLASS.equals(item.getLookupString())) {
return MyResult.classLiteral;
}
if (object instanceof PsiAnnotationMethod && ((PsiAnnotationMethod)object).getContainingClass().isAnnotationType()) {
return MyResult.annoMethod;
}
if (object instanceof PsiClass) {
return MyResult.classNameOrGlobalStatic;
}
if (object instanceof PsiField && myNonInitializedFields.contains(object)) {
return MyResult.nonInitialized;
}
}
return MyResult.normal;
}
private static boolean isLastStatement(PsiStatement statement) {
if (statement == null || !(statement.getParent() instanceof PsiCodeBlock)) {
return true;
}
PsiStatement[] siblings = ((PsiCodeBlock)statement.getParent()).getStatements();
return statement == siblings[siblings.length - 1];
}
}
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInsight.completion;
import com.intellij.codeInsight.completion.scope.JavaCompletionProcessor;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupElementWeigher;
import com.intellij.psi.*;
import com.intellij.psi.filters.getters.MembersGetter;
import com.intellij.psi.util.PropertyUtil;
import com.intellij.psi.util.PsiTreeUtil;
import org.jetbrains.annotations.NotNull;
import java.util.Set;
/**
* @author peter
*/
public class PreferLocalVariablesLiteralsAndAnnoMethodsWeigher extends LookupElementWeigher {
private final CompletionType myCompletionType;
private final PsiElement myPosition;
private final Set<PsiField> myNonInitializedFields;
public PreferLocalVariablesLiteralsAndAnnoMethodsWeigher(CompletionType completionType, PsiElement position) {
super("local");
myCompletionType = completionType;
myPosition = position;
myNonInitializedFields = JavaCompletionProcessor.getNonInitializedFields(position);
}
enum MyResult {
annoMethod,
probableKeyword,
localOrParameter,
qualifiedWithField,
qualifiedWithGetter,
superMethodParameters,
normal,
collectionFactory,
expectedTypeMember,
nonInitialized,
classLiteral,
classNameOrGlobalStatic,
}
@NotNull
@Override
public MyResult weigh(@NotNull LookupElement item) {
final Object object = item.getObject();
if (object instanceof PsiKeyword) {
String keyword = ((PsiKeyword)object).getText();
if (PsiKeyword.RETURN.equals(keyword) && isLastStatement(PsiTreeUtil.getParentOfType(myPosition, PsiStatement.class))) {
return MyResult.probableKeyword;
}
if (PsiKeyword.ELSE.equals(keyword) || PsiKeyword.FINALLY.equals(keyword)) {
return MyResult.probableKeyword;
}
}
if (object instanceof PsiLocalVariable || object instanceof PsiParameter || object instanceof PsiThisExpression) {
return MyResult.localOrParameter;
}
if (object instanceof String && item.getUserData(JavaCompletionUtil.SUPER_METHOD_PARAMETERS) == Boolean.TRUE) {
return MyResult.superMethodParameters;
}
if (myCompletionType == CompletionType.SMART) {
if (item.getUserData(CollectionsUtilityMethodsProvider.COLLECTION_FACTORY) != null) {
return MyResult.collectionFactory;
}
if (Boolean.TRUE.equals(item.getUserData(MembersGetter.EXPECTED_TYPE_INHERITOR_MEMBER))) {
return MyResult.expectedTypeMember;
}
final JavaChainLookupElement chain = item.as(JavaChainLookupElement.CLASS_CONDITION_KEY);
if (chain != null) {
Object qualifier = chain.getQualifier().getObject();
if (qualifier instanceof PsiLocalVariable || qualifier instanceof PsiParameter) {
return MyResult.localOrParameter;
}
if (qualifier instanceof PsiField) {
return MyResult.qualifiedWithField;
}
if (qualifier instanceof PsiMethod && PropertyUtil.isSimplePropertyGetter((PsiMethod)qualifier)) {
return MyResult.qualifiedWithGetter;
}
}
return MyResult.normal;
}
if (myCompletionType == CompletionType.BASIC) {
StaticallyImportable callElement = item.as(StaticallyImportable.CLASS_CONDITION_KEY);
if (callElement != null && callElement.canBeImported() && !callElement.willBeImported()) {
return MyResult.classNameOrGlobalStatic;
}
if (object instanceof PsiKeyword && PsiKeyword.CLASS.equals(item.getLookupString())) {
return MyResult.classLiteral;
}
if (object instanceof PsiAnnotationMethod && ((PsiAnnotationMethod)object).getContainingClass().isAnnotationType()) {
return MyResult.annoMethod;
}
if (object instanceof PsiClass) {
return MyResult.classNameOrGlobalStatic;
}
if (object instanceof PsiField && myNonInitializedFields.contains(object)) {
return MyResult.nonInitialized;
}
}
return MyResult.normal;
}
private static boolean isLastStatement(PsiStatement statement) {
if (statement == null || !(statement.getParent() instanceof PsiCodeBlock)) {
return true;
}
PsiStatement[] siblings = ((PsiCodeBlock)statement.getParent()).getStatements();
return statement == siblings[siblings.length - 1];
}
}
@@ -1,151 +1,151 @@
package com.intellij.codeInsight.completion;
import com.intellij.codeInsight.daemon.impl.quickfix.StaticImportMethodFix;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.featureStatistics.FeatureUsageTracker;
import com.intellij.openapi.actionSystem.IdeActions;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Condition;
import com.intellij.psi.*;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.PsiShortNamesCache;
import com.intellij.util.Consumer;
import com.intellij.util.PairConsumer;
import com.intellij.util.containers.CollectionFactory;
import com.intellij.util.containers.ContainerUtil;
import gnu.trove.THashSet;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import static com.intellij.util.containers.CollectionFactory.hashSet;
import static com.intellij.util.containers.ContainerUtil.addIfNotNull;
/**
* @author peter
*/
public abstract class StaticMemberProcessor {
private final Set<PsiClass> myStaticImportedClasses = hashSet();
private final PsiElement myPosition;
private final Project myProject;
private final PsiResolveHelper myResolveHelper;
private boolean myHintShown = false;
private final boolean myPackagedContext;
public StaticMemberProcessor(final PsiElement position) {
myPosition = position;
myProject = myPosition.getProject();
myResolveHelper = JavaPsiFacade.getInstance(myProject).getResolveHelper();
myPackagedContext = JavaCompletionUtil.inSomePackage(position);
}
public void importMembersOf(@Nullable PsiClass psiClass) {
addIfNotNull(myStaticImportedClasses, psiClass);
}
public void processStaticMethodsGlobally(PrefixMatcher matcher, Consumer<LookupElement> consumer) {
FeatureUsageTracker.getInstance().triggerFeatureUsed(JavaCompletionFeatures.GLOBAL_MEMBER_NAME);
final GlobalSearchScope scope = myPosition.getResolveScope();
final PsiShortNamesCache namesCache = PsiShortNamesCache.getInstance(myProject);
for (final String methodName : namesCache.getAllMethodNames()) {
if (matcher.prefixMatches(methodName)) {
Set<PsiClass> classes = new THashSet<PsiClass>();
for (final PsiMethod method : namesCache.getMethodsByName(methodName, scope)) {
if (isStaticallyImportable(method)) {
final PsiClass containingClass = method.getContainingClass();
assert containingClass != null : method.getName() + "; " + method + "; " + method.getClass();
if (classes.add(containingClass) && JavaCompletionUtil.isSourceLevelAccessible(myPosition, containingClass, myPackagedContext)) {
final boolean shouldImport = myStaticImportedClasses.contains(containingClass);
showHint(shouldImport);
final PsiMethod[] allMethods = containingClass.getAllMethods();
final List<PsiMethod> overloads = ContainerUtil.findAll(allMethods, new Condition<PsiMethod>() {
@Override
public boolean value(PsiMethod psiMethod) {
return methodName.equals(psiMethod.getName()) && isStaticallyImportable(psiMethod);
}
});
assert !overloads.isEmpty();
if (overloads.size() == 1) {
assert method == overloads.get(0);
consumer.consume(createLookupElement(method, containingClass, shouldImport));
} else {
if (overloads.get(0).getParameterList().getParametersCount() == 0) {
overloads.add(0, overloads.remove(1));
}
consumer.consume(createLookupElement(overloads, containingClass, shouldImport));
}
}
}
}
}
}
for (final String fieldName : namesCache.getAllFieldNames()) {
if (matcher.prefixMatches(fieldName)) {
for (final PsiField field : namesCache.getFieldsByName(fieldName, scope)) {
if (isStaticallyImportable(field)) {
final PsiClass containingClass = field.getContainingClass();
assert containingClass != null : field.getName() + "; " + field + "; " + field.getClass();
if (JavaCompletionUtil.isSourceLevelAccessible(myPosition, containingClass, myPackagedContext)) {
final boolean shouldImport = myStaticImportedClasses.contains(containingClass);
showHint(shouldImport);
consumer.consume(createLookupElement(field, containingClass, shouldImport));
}
}
}
}
}
}
private void showHint(boolean shouldImport) {
if (!myHintShown && !shouldImport && CompletionService.getCompletionService().getAdvertisementText() == null) {
final String shortcut = CompletionContributor.getActionShortcut(IdeActions.ACTION_SHOW_INTENTION_ACTIONS);
if (shortcut != null) {
CompletionService.getCompletionService().setAdvertisementText("To import a method statically, press " + shortcut);
}
myHintShown = true;
}
}
public List<PsiMember> processMembersOfRegisteredClasses(final PrefixMatcher matcher, PairConsumer<PsiMember, PsiClass> consumer) {
final ArrayList<PsiMember> result = CollectionFactory.arrayList();
for (final PsiClass psiClass : myStaticImportedClasses) {
for (final PsiMethod method : psiClass.getAllMethods()) {
if (matcher.prefixMatches(method.getName())) {
if (isStaticallyImportable(method)) {
consumer.consume(method, psiClass);
}
}
}
for (final PsiField field : psiClass.getAllFields()) {
if (matcher.prefixMatches(field. getName())) {
if (isStaticallyImportable(field)) {
consumer.consume(field, psiClass);
}
}
}
}
return result;
}
private boolean isStaticallyImportable(final PsiMember member) {
return member.hasModifierProperty(PsiModifier.STATIC) && isAccessible(member) && !StaticImportMethodFix.isExcluded(member);
}
protected boolean isAccessible(PsiMember member) {
return myResolveHelper.isAccessible(member, myPosition, null);
}
@NotNull
protected abstract LookupElement createLookupElement(@NotNull PsiMember member, @NotNull PsiClass containingClass, boolean shouldImport);
protected abstract LookupElement createLookupElement(@NotNull List<PsiMethod> overloads, @NotNull PsiClass containingClass, boolean shouldImport);
}
package com.intellij.codeInsight.completion;
import com.intellij.codeInsight.daemon.impl.quickfix.StaticImportMethodFix;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.featureStatistics.FeatureUsageTracker;
import com.intellij.openapi.actionSystem.IdeActions;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Condition;
import com.intellij.psi.*;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.PsiShortNamesCache;
import com.intellij.util.Consumer;
import com.intellij.util.PairConsumer;
import com.intellij.util.containers.CollectionFactory;
import com.intellij.util.containers.ContainerUtil;
import gnu.trove.THashSet;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import static com.intellij.util.containers.CollectionFactory.hashSet;
import static com.intellij.util.containers.ContainerUtil.addIfNotNull;
/**
* @author peter
*/
public abstract class StaticMemberProcessor {
private final Set<PsiClass> myStaticImportedClasses = hashSet();
private final PsiElement myPosition;
private final Project myProject;
private final PsiResolveHelper myResolveHelper;
private boolean myHintShown = false;
private final boolean myPackagedContext;
public StaticMemberProcessor(final PsiElement position) {
myPosition = position;
myProject = myPosition.getProject();
myResolveHelper = JavaPsiFacade.getInstance(myProject).getResolveHelper();
myPackagedContext = JavaCompletionUtil.inSomePackage(position);
}
public void importMembersOf(@Nullable PsiClass psiClass) {
addIfNotNull(myStaticImportedClasses, psiClass);
}
public void processStaticMethodsGlobally(PrefixMatcher matcher, Consumer<LookupElement> consumer) {
FeatureUsageTracker.getInstance().triggerFeatureUsed(JavaCompletionFeatures.GLOBAL_MEMBER_NAME);
final GlobalSearchScope scope = myPosition.getResolveScope();
final PsiShortNamesCache namesCache = PsiShortNamesCache.getInstance(myProject);
for (final String methodName : namesCache.getAllMethodNames()) {
if (matcher.prefixMatches(methodName)) {
Set<PsiClass> classes = new THashSet<PsiClass>();
for (final PsiMethod method : namesCache.getMethodsByName(methodName, scope)) {
if (isStaticallyImportable(method)) {
final PsiClass containingClass = method.getContainingClass();
assert containingClass != null : method.getName() + "; " + method + "; " + method.getClass();
if (classes.add(containingClass) && JavaCompletionUtil.isSourceLevelAccessible(myPosition, containingClass, myPackagedContext)) {
final boolean shouldImport = myStaticImportedClasses.contains(containingClass);
showHint(shouldImport);
final PsiMethod[] allMethods = containingClass.getAllMethods();
final List<PsiMethod> overloads = ContainerUtil.findAll(allMethods, new Condition<PsiMethod>() {
@Override
public boolean value(PsiMethod psiMethod) {
return methodName.equals(psiMethod.getName()) && isStaticallyImportable(psiMethod);
}
});
assert !overloads.isEmpty();
if (overloads.size() == 1) {
assert method == overloads.get(0);
consumer.consume(createLookupElement(method, containingClass, shouldImport));
} else {
if (overloads.get(0).getParameterList().getParametersCount() == 0) {
overloads.add(0, overloads.remove(1));
}
consumer.consume(createLookupElement(overloads, containingClass, shouldImport));
}
}
}
}
}
}
for (final String fieldName : namesCache.getAllFieldNames()) {
if (matcher.prefixMatches(fieldName)) {
for (final PsiField field : namesCache.getFieldsByName(fieldName, scope)) {
if (isStaticallyImportable(field)) {
final PsiClass containingClass = field.getContainingClass();
assert containingClass != null : field.getName() + "; " + field + "; " + field.getClass();
if (JavaCompletionUtil.isSourceLevelAccessible(myPosition, containingClass, myPackagedContext)) {
final boolean shouldImport = myStaticImportedClasses.contains(containingClass);
showHint(shouldImport);
consumer.consume(createLookupElement(field, containingClass, shouldImport));
}
}
}
}
}
}
private void showHint(boolean shouldImport) {
if (!myHintShown && !shouldImport && CompletionService.getCompletionService().getAdvertisementText() == null) {
final String shortcut = CompletionContributor.getActionShortcut(IdeActions.ACTION_SHOW_INTENTION_ACTIONS);
if (shortcut != null) {
CompletionService.getCompletionService().setAdvertisementText("To import a method statically, press " + shortcut);
}
myHintShown = true;
}
}
public List<PsiMember> processMembersOfRegisteredClasses(final PrefixMatcher matcher, PairConsumer<PsiMember, PsiClass> consumer) {
final ArrayList<PsiMember> result = CollectionFactory.arrayList();
for (final PsiClass psiClass : myStaticImportedClasses) {
for (final PsiMethod method : psiClass.getAllMethods()) {
if (matcher.prefixMatches(method.getName())) {
if (isStaticallyImportable(method)) {
consumer.consume(method, psiClass);
}
}
}
for (final PsiField field : psiClass.getAllFields()) {
if (matcher.prefixMatches(field. getName())) {
if (isStaticallyImportable(field)) {
consumer.consume(field, psiClass);
}
}
}
}
return result;
}
private boolean isStaticallyImportable(final PsiMember member) {
return member.hasModifierProperty(PsiModifier.STATIC) && isAccessible(member) && !StaticImportMethodFix.isExcluded(member);
}
protected boolean isAccessible(PsiMember member) {
return myResolveHelper.isAccessible(member, myPosition, null);
}
@NotNull
protected abstract LookupElement createLookupElement(@NotNull PsiMember member, @NotNull PsiClass containingClass, boolean shouldImport);
protected abstract LookupElement createLookupElement(@NotNull List<PsiMethod> overloads, @NotNull PsiClass containingClass, boolean shouldImport);
}
@@ -1,59 +1,59 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInsight.completion;
import com.intellij.codeInsight.lookup.AutoCompletionPolicy;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.lang.StdLanguages;
import com.intellij.psi.PsiElement;
import com.intellij.util.Consumer;
/**
* @author peter
*/
public class XmlBasicToClassNameDelegator extends CompletionContributor {
@Override
public void fillCompletionVariants(CompletionParameters parameters, final CompletionResultSet result) {
PsiElement position = parameters.getPosition();
if (parameters.getCompletionType() != CompletionType.BASIC ||
!JavaCompletionContributor.mayStartClassName(result) ||
!position.getContainingFile().getLanguage().isKindOf(StdLanguages.XML)) {
return;
}
final boolean empty = result.runRemainingContributors(parameters, true).isEmpty();
if (!empty && parameters.getInvocationCount() == 0) {
result.restartCompletionWhenNothingMatches();
}
if (empty || parameters.isExtendedCompletion()) {
CompletionService.getCompletionService().getVariantsFromContributors(parameters.delegateToClassName(), null, new Consumer<CompletionResult>() {
public void consume(final CompletionResult completionResult) {
LookupElement lookupElement = completionResult.getLookupElement();
JavaPsiClassReferenceElement classElement = lookupElement.as(JavaPsiClassReferenceElement.CLASS_CONDITION_KEY);
if (classElement != null) {
classElement.setAutoCompletionPolicy(AutoCompletionPolicy.NEVER_AUTOCOMPLETE);
}
lookupElement.putUserData(XmlCompletionContributor.WORD_COMPLETION_COMPATIBLE, Boolean.TRUE); //todo think of a less dirty interaction
result.passResult(completionResult);
}
});
}
}
}
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInsight.completion;
import com.intellij.codeInsight.lookup.AutoCompletionPolicy;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.lang.StdLanguages;
import com.intellij.psi.PsiElement;
import com.intellij.util.Consumer;
/**
* @author peter
*/
public class XmlBasicToClassNameDelegator extends CompletionContributor {
@Override
public void fillCompletionVariants(CompletionParameters parameters, final CompletionResultSet result) {
PsiElement position = parameters.getPosition();
if (parameters.getCompletionType() != CompletionType.BASIC ||
!JavaCompletionContributor.mayStartClassName(result) ||
!position.getContainingFile().getLanguage().isKindOf(StdLanguages.XML)) {
return;
}
final boolean empty = result.runRemainingContributors(parameters, true).isEmpty();
if (!empty && parameters.getInvocationCount() == 0) {
result.restartCompletionWhenNothingMatches();
}
if (empty || parameters.isExtendedCompletion()) {
CompletionService.getCompletionService().getVariantsFromContributors(parameters.delegateToClassName(), null, new Consumer<CompletionResult>() {
public void consume(final CompletionResult completionResult) {
LookupElement lookupElement = completionResult.getLookupElement();
JavaPsiClassReferenceElement classElement = lookupElement.as(JavaPsiClassReferenceElement.CLASS_CONDITION_KEY);
if (classElement != null) {
classElement.setAutoCompletionPolicy(AutoCompletionPolicy.NEVER_AUTOCOMPLETE);
}
lookupElement.putUserData(XmlCompletionContributor.WORD_COMPLETION_COMPATIBLE, Boolean.TRUE); //todo think of a less dirty interaction
result.passResult(completionResult);
}
});
}
}
}
@@ -1,129 +1,129 @@
/*
* Copyright 2000-2011 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInsight.daemon.impl.quickfix;
import com.intellij.codeInsight.daemon.QuickFixActionRegistrar;
import com.intellij.codeInsight.daemon.impl.analysis.HighlightMethodUtil;
import com.intellij.codeInsight.intention.IntentionAction;
import com.intellij.codeInsight.intention.impl.PriorityIntentionActionWrapper;
import com.intellij.codeInsight.quickfix.UnresolvedReferenceQuickFixProvider;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.JavaCodeStyleManager;
import com.intellij.psi.codeStyle.VariableKind;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import org.jetbrains.annotations.NotNull;
import java.util.HashMap;
import java.util.Map;
public class DefaultQuickFixProvider extends UnresolvedReferenceQuickFixProvider<PsiJavaCodeReferenceElement> {
@Override
public void registerFixes(PsiJavaCodeReferenceElement ref, QuickFixActionRegistrar registrar) {
registrar.register(new ImportClassFix(ref));
registrar.register(SetupJDKFix.getInstance());
OrderEntryFix.registerFixes(registrar, ref);
MoveClassToModuleFix.registerFixes(registrar, ref);
if (ref instanceof PsiReferenceExpression) {
TextRange fixRange = HighlightMethodUtil.getFixRange(ref);
PsiReferenceExpression refExpr = (PsiReferenceExpression)ref;
registrar.register(fixRange, new CreateEnumConstantFromUsageFix(refExpr), null);
registrar.register(new RenameWrongRefFix(refExpr));
if (!ref.isQualified()) {
registrar.register(fixRange, new BringVariableIntoScopeFix(refExpr), null);
}
registerPriorityActions(registrar,fixRange,refExpr);
}
registrar.register(new CreateClassFromUsageFix(ref, CreateClassKind.INTERFACE));
if (PsiUtil.isLanguageLevel5OrHigher(ref)) {
registrar.register(new CreateClassFromUsageFix(ref, CreateClassKind.ENUM));
registrar.register(new CreateClassFromUsageFix(ref, CreateClassKind.ANNOTATION));
}
PsiElement parent = PsiTreeUtil.getParentOfType(ref, PsiNewExpression.class, PsiMethod.class);
final PsiExpressionList expressionList = PsiTreeUtil.getParentOfType(ref, PsiExpressionList.class);
if (parent instanceof PsiNewExpression && !(ref.getParent() instanceof PsiTypeElement) && (expressionList == null || !PsiTreeUtil.isAncestor(parent, expressionList, false))) {
registrar.register(new CreateClassFromNewFix((PsiNewExpression)parent));
registrar.register(new CreateInnerClassFromNewFix((PsiNewExpression)parent));
}
else {
registrar.register(new CreateClassFromUsageFix(ref, CreateClassKind.CLASS));
registrar.register(new CreateInnerClassFromUsageFix(ref, CreateClassKind.CLASS));
}
}
private static void registerPriorityActions(@NotNull final QuickFixActionRegistrar registrar,
@NotNull final TextRange fixRange,
@NotNull final PsiReferenceExpression refExpr) {
final JavaCodeStyleManager styleManager = JavaCodeStyleManager.getInstance(refExpr.getProject());
final Map<VariableKind, IntentionAction> map = new HashMap<VariableKind, IntentionAction>() {
{
put(VariableKind.FIELD, new CreateFieldFromUsageFix(refExpr));
put(VariableKind.STATIC_FINAL_FIELD, new CreateConstantFieldFromUsageFix(refExpr));
if (!refExpr.isQualified()) {
put(VariableKind.LOCAL_VARIABLE, new CreateLocalFromUsageFix(refExpr));
put(VariableKind.PARAMETER, new CreateParameterFromUsageFix(refExpr));
}
}
};
final VariableKind kind = getKind(styleManager, refExpr);
if (map.containsKey(kind)){
map.put(kind, PriorityIntentionActionWrapper.highPriority(map.get(kind)));
}
for (IntentionAction action : map.values()){
registrar.register(fixRange, action, null);
}
}
@NotNull
private static VariableKind getKind(@NotNull JavaCodeStyleManager styleManager,
@NotNull PsiReferenceExpression refExpr) {
final String reference = refExpr.getText();
if (reference.toUpperCase().equals(reference)){
return VariableKind.STATIC_FINAL_FIELD;
}
for (VariableKind kind : VariableKind.values()) {
final String prefix = styleManager.getPrefixByVariableKind(kind);
final String suffix = styleManager.getSuffixByVariableKind(kind);
if (prefix.isEmpty() && suffix.isEmpty()) {
continue;
}
if (reference.startsWith(prefix) && reference.endsWith(suffix)) {
return kind;
}
}
return VariableKind.LOCAL_VARIABLE;
}
@Override
@NotNull
public Class<PsiJavaCodeReferenceElement> getReferenceClass() {
return PsiJavaCodeReferenceElement.class;
}
/*
* Copyright 2000-2011 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInsight.daemon.impl.quickfix;
import com.intellij.codeInsight.daemon.QuickFixActionRegistrar;
import com.intellij.codeInsight.daemon.impl.analysis.HighlightMethodUtil;
import com.intellij.codeInsight.intention.IntentionAction;
import com.intellij.codeInsight.intention.impl.PriorityIntentionActionWrapper;
import com.intellij.codeInsight.quickfix.UnresolvedReferenceQuickFixProvider;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.JavaCodeStyleManager;
import com.intellij.psi.codeStyle.VariableKind;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import org.jetbrains.annotations.NotNull;
import java.util.HashMap;
import java.util.Map;
public class DefaultQuickFixProvider extends UnresolvedReferenceQuickFixProvider<PsiJavaCodeReferenceElement> {
@Override
public void registerFixes(PsiJavaCodeReferenceElement ref, QuickFixActionRegistrar registrar) {
registrar.register(new ImportClassFix(ref));
registrar.register(SetupJDKFix.getInstance());
OrderEntryFix.registerFixes(registrar, ref);
MoveClassToModuleFix.registerFixes(registrar, ref);
if (ref instanceof PsiReferenceExpression) {
TextRange fixRange = HighlightMethodUtil.getFixRange(ref);
PsiReferenceExpression refExpr = (PsiReferenceExpression)ref;
registrar.register(fixRange, new CreateEnumConstantFromUsageFix(refExpr), null);
registrar.register(new RenameWrongRefFix(refExpr));
if (!ref.isQualified()) {
registrar.register(fixRange, new BringVariableIntoScopeFix(refExpr), null);
}
registerPriorityActions(registrar,fixRange,refExpr);
}
registrar.register(new CreateClassFromUsageFix(ref, CreateClassKind.INTERFACE));
if (PsiUtil.isLanguageLevel5OrHigher(ref)) {
registrar.register(new CreateClassFromUsageFix(ref, CreateClassKind.ENUM));
registrar.register(new CreateClassFromUsageFix(ref, CreateClassKind.ANNOTATION));
}
PsiElement parent = PsiTreeUtil.getParentOfType(ref, PsiNewExpression.class, PsiMethod.class);
final PsiExpressionList expressionList = PsiTreeUtil.getParentOfType(ref, PsiExpressionList.class);
if (parent instanceof PsiNewExpression && !(ref.getParent() instanceof PsiTypeElement) && (expressionList == null || !PsiTreeUtil.isAncestor(parent, expressionList, false))) {
registrar.register(new CreateClassFromNewFix((PsiNewExpression)parent));
registrar.register(new CreateInnerClassFromNewFix((PsiNewExpression)parent));
}
else {
registrar.register(new CreateClassFromUsageFix(ref, CreateClassKind.CLASS));
registrar.register(new CreateInnerClassFromUsageFix(ref, CreateClassKind.CLASS));
}
}
private static void registerPriorityActions(@NotNull final QuickFixActionRegistrar registrar,
@NotNull final TextRange fixRange,
@NotNull final PsiReferenceExpression refExpr) {
final JavaCodeStyleManager styleManager = JavaCodeStyleManager.getInstance(refExpr.getProject());
final Map<VariableKind, IntentionAction> map = new HashMap<VariableKind, IntentionAction>() {
{
put(VariableKind.FIELD, new CreateFieldFromUsageFix(refExpr));
put(VariableKind.STATIC_FINAL_FIELD, new CreateConstantFieldFromUsageFix(refExpr));
if (!refExpr.isQualified()) {
put(VariableKind.LOCAL_VARIABLE, new CreateLocalFromUsageFix(refExpr));
put(VariableKind.PARAMETER, new CreateParameterFromUsageFix(refExpr));
}
}
};
final VariableKind kind = getKind(styleManager, refExpr);
if (map.containsKey(kind)){
map.put(kind, PriorityIntentionActionWrapper.highPriority(map.get(kind)));
}
for (IntentionAction action : map.values()){
registrar.register(fixRange, action, null);
}
}
@NotNull
private static VariableKind getKind(@NotNull JavaCodeStyleManager styleManager,
@NotNull PsiReferenceExpression refExpr) {
final String reference = refExpr.getText();
if (reference.toUpperCase().equals(reference)){
return VariableKind.STATIC_FINAL_FIELD;
}
for (VariableKind kind : VariableKind.values()) {
final String prefix = styleManager.getPrefixByVariableKind(kind);
final String suffix = styleManager.getSuffixByVariableKind(kind);
if (prefix.isEmpty() && suffix.isEmpty()) {
continue;
}
if (reference.startsWith(prefix) && reference.endsWith(suffix)) {
return kind;
}
}
return VariableKind.LOCAL_VARIABLE;
}
@Override
@NotNull
public Class<PsiJavaCodeReferenceElement> getReferenceClass() {
return PsiJavaCodeReferenceElement.class;
}
}
File diff suppressed because it is too large Load Diff
@@ -1,109 +1,109 @@
/*
* 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.codeInsight.intention.impl;
import com.intellij.codeInsight.CodeInsightBundle;
import com.intellij.codeInsight.intention.PsiElementBaseIntentionAction;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.*;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
/**
* @author Danila Ponomarenko
*/
public class BreakStringOnLineBreaksIntentionAction extends PsiElementBaseIntentionAction {
@Override
public boolean isAvailable(@NotNull Project project, Editor editor, @NotNull PsiElement element) {
if (!(element instanceof PsiJavaToken)) {
return false;
}
final PsiJavaToken token = (PsiJavaToken)element;
if (token.getTokenType() != JavaTokenType.STRING_LITERAL) {
return false;
}
final String text = token.getText();
if (text == null) {
return false;
}
final int indexOfSlashN = text.indexOf("\\n");
if (indexOfSlashN == -1 || Comparing.equal(text.substring(indexOfSlashN, text.length()), "\\n\"")){
return false;
}
final int indexOfSlashNSlashR = text.indexOf("\\n\\r");
if (indexOfSlashNSlashR != -1 && Comparing.equal(text.substring(indexOfSlashNSlashR, text.length()), "\\n\\r\"")){
return false;
}
return true;
}
@Override
public void invoke(@NotNull Project project, Editor editor, @NotNull PsiElement element) throws IncorrectOperationException {
if (!(element instanceof PsiJavaToken)) {
return;
}
final PsiJavaToken token = (PsiJavaToken)element;
if (token.getTokenType() != JavaTokenType.STRING_LITERAL) {
return;
}
final String text = token.getText();
if (text == null) {
return;
}
final PsiElementFactory factory = JavaPsiFacade.getElementFactory(project);
token.replace(factory.createExpressionFromText(breakOnLineBreaks(text), element));
}
@NotNull
private static String breakOnLineBreaks(@NotNull String string) {
final String result = StringUtil.replace(
string,
new String[]{"\\n\\r", "\\n"},
new String[]{"\\n\\r\" + \n\"", "\\n\" + \n\""}
);
final String redundantSuffix = " + \n\"\"";
return result.endsWith(redundantSuffix) ? result.substring(0, result.length() - redundantSuffix.length()) : result;
}
@NotNull
@Override
public String getText() {
return CodeInsightBundle.message("intention.break.string.on.line.breaks.text");
}
@NotNull
@Override
public String getFamilyName() {
return getText();
}
}
/*
* 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.codeInsight.intention.impl;
import com.intellij.codeInsight.CodeInsightBundle;
import com.intellij.codeInsight.intention.PsiElementBaseIntentionAction;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.*;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
/**
* @author Danila Ponomarenko
*/
public class BreakStringOnLineBreaksIntentionAction extends PsiElementBaseIntentionAction {
@Override
public boolean isAvailable(@NotNull Project project, Editor editor, @NotNull PsiElement element) {
if (!(element instanceof PsiJavaToken)) {
return false;
}
final PsiJavaToken token = (PsiJavaToken)element;
if (token.getTokenType() != JavaTokenType.STRING_LITERAL) {
return false;
}
final String text = token.getText();
if (text == null) {
return false;
}
final int indexOfSlashN = text.indexOf("\\n");
if (indexOfSlashN == -1 || Comparing.equal(text.substring(indexOfSlashN, text.length()), "\\n\"")){
return false;
}
final int indexOfSlashNSlashR = text.indexOf("\\n\\r");
if (indexOfSlashNSlashR != -1 && Comparing.equal(text.substring(indexOfSlashNSlashR, text.length()), "\\n\\r\"")){
return false;
}
return true;
}
@Override
public void invoke(@NotNull Project project, Editor editor, @NotNull PsiElement element) throws IncorrectOperationException {
if (!(element instanceof PsiJavaToken)) {
return;
}
final PsiJavaToken token = (PsiJavaToken)element;
if (token.getTokenType() != JavaTokenType.STRING_LITERAL) {
return;
}
final String text = token.getText();
if (text == null) {
return;
}
final PsiElementFactory factory = JavaPsiFacade.getElementFactory(project);
token.replace(factory.createExpressionFromText(breakOnLineBreaks(text), element));
}
@NotNull
private static String breakOnLineBreaks(@NotNull String string) {
final String result = StringUtil.replace(
string,
new String[]{"\\n\\r", "\\n"},
new String[]{"\\n\\r\" + \n\"", "\\n\" + \n\""}
);
final String redundantSuffix = " + \n\"\"";
return result.endsWith(redundantSuffix) ? result.substring(0, result.length() - redundantSuffix.length()) : result;
}
@NotNull
@Override
public String getText() {
return CodeInsightBundle.message("intention.break.string.on.line.breaks.text");
}
@NotNull
@Override
public String getFamilyName() {
return getText();
}
}
@@ -26,18 +26,14 @@ import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.fileEditor.OpenFileDescriptor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import com.intellij.psi.util.PsiSuperMethodUtil;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiMethod;
import com.intellij.psi.impl.FindSuperElementsHelper;
import com.intellij.psi.util.PsiUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
public class JavaGotoSuperHandler implements CodeInsightActionHandler {
public void invoke(@NotNull final Project project, @NotNull final Editor editor, @NotNull final PsiFile file) {
FeatureUsageTracker.getInstance().triggerFeatureUsed(GotoSuperAction.FEATURE_ID);
@@ -71,27 +67,7 @@ public class JavaGotoSuperHandler implements CodeInsightActionHandler {
PsiElement element = file.findElementAt(offset);
if (element == null) return null;
PsiMember e = PsiTreeUtil.getParentOfType(element, PsiMethod.class, PsiClass.class);
if (e instanceof PsiClass) {
PsiClass aClass = (PsiClass) e;
List<PsiClass> allSupers = new ArrayList<PsiClass>(Arrays.asList(aClass.getSupers()));
for (Iterator<PsiClass> iterator = allSupers.iterator(); iterator.hasNext();) {
PsiClass superClass = iterator.next();
if (CommonClassNames.JAVA_LANG_OBJECT.equals(superClass.getQualifiedName())) iterator.remove();
}
return allSupers.toArray(new PsiClass[allSupers.size()]);
} else if (e instanceof PsiMethod) {
PsiMethod method = (PsiMethod) e;
if (method.isConstructor()) {
PsiMethod constructorInSuper = PsiSuperMethodUtil.findConstructorInSuper(method);
if (constructorInSuper != null) {
return new PsiMethod[]{constructorInSuper};
}
} else {
return method.findSuperMethods(false);
}
}
return null;
return FindSuperElementsHelper.findSuperElements(element);
}
public boolean startInWriteAction() {
@@ -1,194 +1,194 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInspection.defaultFileTemplateUsage;
import com.intellij.codeInsight.CodeInsightUtil;
import com.intellij.codeInspection.*;
import com.intellij.ide.fileTemplates.FileTemplate;
import com.intellij.ide.fileTemplates.FileTemplateManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.JavaRecursiveElementWalkingVisitor;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.javadoc.PsiDocComment;
import com.intellij.util.IncorrectOperationException;
import gnu.trove.TIntObjectHashMap;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author Alexey
*/
public class FileHeaderChecker {
private static final Logger LOG = Logger.getInstance("#com.intellij.codeInspection.defaultFileTemplateUsage.FileHeaderChecker");
static ProblemDescriptor checkFileHeader(@NotNull final PsiFile file, final InspectionManager manager, boolean onTheFly) {
FileTemplate template = FileTemplateManager.getInstance().getDefaultTemplate(FileTemplateManager.FILE_HEADER_TEMPLATE_NAME);
TIntObjectHashMap<String> offsetToProperty = new TIntObjectHashMap<String>();
String templateText = template.getText().trim();
String regex = templateToRegex(templateText, offsetToProperty, file.getProject());
regex = StringUtil.replace(regex, "with", "(?:with|by)");
regex = ".*("+regex+").*";
String fileText = file.getText();
Pattern pattern = Pattern.compile(regex, Pattern.DOTALL);
Matcher matcher = pattern.matcher(fileText);
if (matcher.matches()) {
final int startOffset = matcher.start(1);
final int endOffset = matcher.end(1);
final Ref<PsiDocComment> docComment = new Ref<PsiDocComment>();
file.accept(new JavaRecursiveElementWalkingVisitor(){
@Override public void visitElement(PsiElement element) {
if (docComment.get() != null) return;
TextRange range = element.getTextRange();
if (!range.contains(startOffset) && !range.contains(endOffset)) return;
super.visitElement(element);
}
@Override public void visitDocComment(PsiDocComment comment) {
docComment.set(comment);
}
});
PsiDocComment element = docComment.get();
if (element == null) return null;
LocalQuickFix[] quickFix = createQuickFix(matcher, offsetToProperty);
final String description = InspectionsBundle.message("default.file.template.description");
return manager.createProblemDescriptor(element, description, onTheFly, quickFix, ProblemHighlightType.GENERIC_ERROR_OR_WARNING);
}
return null;
}
private static Properties computeProperties(final Matcher matcher, final TIntObjectHashMap<String> offsetToProperty) {
Properties properties = new Properties(FileTemplateManager.getInstance().getDefaultProperties());
int[] offsets = offsetToProperty.keys();
Arrays.sort(offsets);
for (int i = 0; i < offsets.length; i++) {
final int offset = offsets[i];
String propName = offsetToProperty.get(offset);
int groupNum = i + 2; // first group is whole doc comment
String propValue = matcher.group(groupNum);
properties.put(propName, propValue);
}
return properties;
}
private static LocalQuickFix[] createQuickFix(final Matcher matcher,
final TIntObjectHashMap<String> offsetToProperty) {
final FileTemplate template = FileTemplateManager.getInstance().getPattern(FileTemplateManager.FILE_HEADER_TEMPLATE_NAME);
final ReplaceWithFileTemplateFix replaceTemplateFix = new ReplaceWithFileTemplateFix() {
public void applyFix(@NotNull final Project project, @NotNull final ProblemDescriptor descriptor) {
PsiElement element = descriptor.getPsiElement();
if (element == null || !element.isValid()) return;
if (!CodeInsightUtil.preparePsiElementsForWrite(element)) return;
String newText;
try {
newText = template.getText(computeProperties(matcher, offsetToProperty));
}
catch (IOException e) {
LOG.error(e);
return;
}
try {
int offset = element.getTextRange().getStartOffset();
PsiFile psiFile = element.getContainingFile();
if (psiFile == null) return;
PsiDocumentManager documentManager = PsiDocumentManager.getInstance(psiFile.getProject());
Document document = documentManager.getDocument(psiFile);
if (document == null) return;
element.delete();
documentManager.doPostponedOperationsAndUnblockDocument(document);
documentManager.commitDocument(document);
document.insertString(offset, newText);
}
catch (IncorrectOperationException e) {
LOG.error(e);
}
catch (IllegalStateException e) {
LOG.error("Cannot create doc comment from text: '" + newText + "'", e);
}
}
};
final LocalQuickFix editFileTemplateFix = DefaultFileTemplateUsageInspection.createEditFileTemplateFix(template, replaceTemplateFix);
if (template.isDefault()) {
return new LocalQuickFix[]{editFileTemplateFix};
}
return new LocalQuickFix[]{replaceTemplateFix,editFileTemplateFix};
}
private static String templateToRegex(final String text, TIntObjectHashMap<String> offsetToProperty, Project project) {
String regex = text;
@NonNls Collection<String> properties = new ArrayList<String>((Collection)FileTemplateManager.getInstance().getDefaultProperties(project).keySet());
properties.add("PACKAGE_NAME");
regex = escapeRegexChars(regex);
// first group is a whole file header
int groupNumber = 1;
for (String name : properties) {
String escaped = escapeRegexChars("${"+name+"}");
boolean first = true;
for (int i = regex.indexOf(escaped); i!=-1 && i<regex.length(); i = regex.indexOf(escaped,i+1)) {
String replacement = first ? "(.*)" : "\\" + groupNumber;
final int delta = escaped.length() - replacement.length();
int[] offs = offsetToProperty.keys();
for (int off : offs) {
if (off > i) {
String prop = offsetToProperty.remove(off);
offsetToProperty.put(off - delta, prop);
}
}
offsetToProperty.put(i, name);
regex = regex.substring(0,i) + replacement + regex.substring(i+escaped.length());
if (first) {
groupNumber++;
first = false;
}
}
}
return regex;
}
private static String escapeRegexChars(String regex) {
regex = StringUtil.replace(regex,"|", "\\|");
regex = StringUtil.replace(regex,".", "\\.");
regex = StringUtil.replace(regex,"*", "\\*");
regex = StringUtil.replace(regex,"+", "\\+");
regex = StringUtil.replace(regex,"?", "\\?");
regex = StringUtil.replace(regex,"$", "\\$");
regex = StringUtil.replace(regex,"(", "\\(");
regex = StringUtil.replace(regex,")", "\\)");
regex = StringUtil.replace(regex,"[", "\\[");
regex = StringUtil.replace(regex,"]", "\\]");
regex = StringUtil.replace(regex,"{", "\\{");
regex = StringUtil.replace(regex,"}", "\\}");
return regex;
}
}
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInspection.defaultFileTemplateUsage;
import com.intellij.codeInsight.CodeInsightUtil;
import com.intellij.codeInspection.*;
import com.intellij.ide.fileTemplates.FileTemplate;
import com.intellij.ide.fileTemplates.FileTemplateManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.JavaRecursiveElementWalkingVisitor;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.javadoc.PsiDocComment;
import com.intellij.util.IncorrectOperationException;
import gnu.trove.TIntObjectHashMap;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author Alexey
*/
public class FileHeaderChecker {
private static final Logger LOG = Logger.getInstance("#com.intellij.codeInspection.defaultFileTemplateUsage.FileHeaderChecker");
static ProblemDescriptor checkFileHeader(@NotNull final PsiFile file, final InspectionManager manager, boolean onTheFly) {
FileTemplate template = FileTemplateManager.getInstance().getDefaultTemplate(FileTemplateManager.FILE_HEADER_TEMPLATE_NAME);
TIntObjectHashMap<String> offsetToProperty = new TIntObjectHashMap<String>();
String templateText = template.getText().trim();
String regex = templateToRegex(templateText, offsetToProperty, file.getProject());
regex = StringUtil.replace(regex, "with", "(?:with|by)");
regex = ".*("+regex+").*";
String fileText = file.getText();
Pattern pattern = Pattern.compile(regex, Pattern.DOTALL);
Matcher matcher = pattern.matcher(fileText);
if (matcher.matches()) {
final int startOffset = matcher.start(1);
final int endOffset = matcher.end(1);
final Ref<PsiDocComment> docComment = new Ref<PsiDocComment>();
file.accept(new JavaRecursiveElementWalkingVisitor(){
@Override public void visitElement(PsiElement element) {
if (docComment.get() != null) return;
TextRange range = element.getTextRange();
if (!range.contains(startOffset) && !range.contains(endOffset)) return;
super.visitElement(element);
}
@Override public void visitDocComment(PsiDocComment comment) {
docComment.set(comment);
}
});
PsiDocComment element = docComment.get();
if (element == null) return null;
LocalQuickFix[] quickFix = createQuickFix(matcher, offsetToProperty);
final String description = InspectionsBundle.message("default.file.template.description");
return manager.createProblemDescriptor(element, description, onTheFly, quickFix, ProblemHighlightType.GENERIC_ERROR_OR_WARNING);
}
return null;
}
private static Properties computeProperties(final Matcher matcher, final TIntObjectHashMap<String> offsetToProperty) {
Properties properties = new Properties(FileTemplateManager.getInstance().getDefaultProperties());
int[] offsets = offsetToProperty.keys();
Arrays.sort(offsets);
for (int i = 0; i < offsets.length; i++) {
final int offset = offsets[i];
String propName = offsetToProperty.get(offset);
int groupNum = i + 2; // first group is whole doc comment
String propValue = matcher.group(groupNum);
properties.put(propName, propValue);
}
return properties;
}
private static LocalQuickFix[] createQuickFix(final Matcher matcher,
final TIntObjectHashMap<String> offsetToProperty) {
final FileTemplate template = FileTemplateManager.getInstance().getPattern(FileTemplateManager.FILE_HEADER_TEMPLATE_NAME);
final ReplaceWithFileTemplateFix replaceTemplateFix = new ReplaceWithFileTemplateFix() {
public void applyFix(@NotNull final Project project, @NotNull final ProblemDescriptor descriptor) {
PsiElement element = descriptor.getPsiElement();
if (element == null || !element.isValid()) return;
if (!CodeInsightUtil.preparePsiElementsForWrite(element)) return;
String newText;
try {
newText = template.getText(computeProperties(matcher, offsetToProperty));
}
catch (IOException e) {
LOG.error(e);
return;
}
try {
int offset = element.getTextRange().getStartOffset();
PsiFile psiFile = element.getContainingFile();
if (psiFile == null) return;
PsiDocumentManager documentManager = PsiDocumentManager.getInstance(psiFile.getProject());
Document document = documentManager.getDocument(psiFile);
if (document == null) return;
element.delete();
documentManager.doPostponedOperationsAndUnblockDocument(document);
documentManager.commitDocument(document);
document.insertString(offset, newText);
}
catch (IncorrectOperationException e) {
LOG.error(e);
}
catch (IllegalStateException e) {
LOG.error("Cannot create doc comment from text: '" + newText + "'", e);
}
}
};
final LocalQuickFix editFileTemplateFix = DefaultFileTemplateUsageInspection.createEditFileTemplateFix(template, replaceTemplateFix);
if (template.isDefault()) {
return new LocalQuickFix[]{editFileTemplateFix};
}
return new LocalQuickFix[]{replaceTemplateFix,editFileTemplateFix};
}
private static String templateToRegex(final String text, TIntObjectHashMap<String> offsetToProperty, Project project) {
String regex = text;
@NonNls Collection<String> properties = new ArrayList<String>((Collection)FileTemplateManager.getInstance().getDefaultProperties(project).keySet());
properties.add("PACKAGE_NAME");
regex = escapeRegexChars(regex);
// first group is a whole file header
int groupNumber = 1;
for (String name : properties) {
String escaped = escapeRegexChars("${"+name+"}");
boolean first = true;
for (int i = regex.indexOf(escaped); i!=-1 && i<regex.length(); i = regex.indexOf(escaped,i+1)) {
String replacement = first ? "(.*)" : "\\" + groupNumber;
final int delta = escaped.length() - replacement.length();
int[] offs = offsetToProperty.keys();
for (int off : offs) {
if (off > i) {
String prop = offsetToProperty.remove(off);
offsetToProperty.put(off - delta, prop);
}
}
offsetToProperty.put(i, name);
regex = regex.substring(0,i) + replacement + regex.substring(i+escaped.length());
if (first) {
groupNumber++;
first = false;
}
}
}
return regex;
}
private static String escapeRegexChars(String regex) {
regex = StringUtil.replace(regex,"|", "\\|");
regex = StringUtil.replace(regex,".", "\\.");
regex = StringUtil.replace(regex,"*", "\\*");
regex = StringUtil.replace(regex,"+", "\\+");
regex = StringUtil.replace(regex,"?", "\\?");
regex = StringUtil.replace(regex,"$", "\\$");
regex = StringUtil.replace(regex,"(", "\\(");
regex = StringUtil.replace(regex,")", "\\)");
regex = StringUtil.replace(regex,"[", "\\[");
regex = StringUtil.replace(regex,"]", "\\]");
regex = StringUtil.replace(regex,"{", "\\{");
regex = StringUtil.replace(regex,"}", "\\}");
return regex;
}
}
@@ -1,67 +1,67 @@
/*
* 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.codeInspection.internal;
import com.intellij.codeInspection.ProblemHighlightType;
import com.intellij.codeInspection.ProblemsHolder;
import com.intellij.openapi.application.ex.ApplicationManagerEx;
import com.intellij.psi.*;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
public class FileEqualsUsageInspection extends InternalInspection {
@Nls
@NotNull
@Override
public String getDisplayName() {
return "File.equals()/hashCode()/compareTo() Usage";
}
@NotNull
@Override
public String getShortName() {
return "FileEqualsUsage";
}
@NotNull
public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, boolean isOnTheFly) {
if (!ApplicationManagerEx.getApplicationEx().isInternal()) {
return new JavaElementVisitor() {
};
}
return new JavaElementVisitor() {
@Override
public void visitMethodCallExpression(PsiMethodCallExpression expression) {
PsiReferenceExpression methodExpression = expression.getMethodExpression();
PsiElement resolved = methodExpression.resolve();
if (!(resolved instanceof PsiMethod)) return;
PsiMethod method = (PsiMethod)resolved;
PsiClass clazz = method.getContainingClass();
if (clazz == null) return;
String methodName = method.getName();
if (CommonClassNames.JAVA_IO_FILE.equals(clazz.getQualifiedName())
&& ("equals".equals(methodName) || "compareTo".equals(methodName) || "hashCode".equals(methodName))) {
holder.registerProblem(methodExpression,
"Do not use File.equals/hashCode/compareTo as they don't honor case-sensitivity on MacOS. Use FileUtil.filesEquals/fileHashCode/compareFiles instead",
ProblemHighlightType.LIKE_DEPRECATED);
}
}
};
}
}
/*
* 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.codeInspection.internal;
import com.intellij.codeInspection.ProblemHighlightType;
import com.intellij.codeInspection.ProblemsHolder;
import com.intellij.openapi.application.ex.ApplicationManagerEx;
import com.intellij.psi.*;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
public class FileEqualsUsageInspection extends InternalInspection {
@Nls
@NotNull
@Override
public String getDisplayName() {
return "File.equals()/hashCode()/compareTo() Usage";
}
@NotNull
@Override
public String getShortName() {
return "FileEqualsUsage";
}
@NotNull
public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, boolean isOnTheFly) {
if (!ApplicationManagerEx.getApplicationEx().isInternal()) {
return new JavaElementVisitor() {
};
}
return new JavaElementVisitor() {
@Override
public void visitMethodCallExpression(PsiMethodCallExpression expression) {
PsiReferenceExpression methodExpression = expression.getMethodExpression();
PsiElement resolved = methodExpression.resolve();
if (!(resolved instanceof PsiMethod)) return;
PsiMethod method = (PsiMethod)resolved;
PsiClass clazz = method.getContainingClass();
if (clazz == null) return;
String methodName = method.getName();
if (CommonClassNames.JAVA_IO_FILE.equals(clazz.getQualifiedName())
&& ("equals".equals(methodName) || "compareTo".equals(methodName) || "hashCode".equals(methodName))) {
holder.registerProblem(methodExpression,
"Do not use File.equals/hashCode/compareTo as they don't honor case-sensitivity on MacOS. Use FileUtil.filesEquals/fileHashCode/compareFiles instead",
ProblemHighlightType.LIKE_DEPRECATED);
}
}
};
}
}
@@ -1,161 +1,161 @@
/*
* Copyright 2000-2011 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.filters.getters;
import com.intellij.codeInsight.TailType;
import com.intellij.codeInsight.completion.*;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.TailTypeDecorator;
import com.intellij.codeInsight.lookup.VariableLookupItem;
import com.intellij.psi.*;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.util.Consumer;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.HashSet;
import java.util.Set;
/**
* @author peter
*/
public class JavaMembersGetter extends MembersGetter {
private final PsiType myExpectedType;
private final PsiElement myPlace;
public JavaMembersGetter(@NotNull PsiType expectedType, PsiElement place) {
myPlace = place;
myExpectedType = JavaCompletionUtil.originalize(expectedType);
}
public void addMembers(CompletionParameters parameters, boolean searchInheritors, final Consumer<LookupElement> results) {
final StaticMemberProcessor processor = new JavaStaticMemberProcessor(parameters);
final PsiElement position = parameters.getPosition();
if (myExpectedType instanceof PsiPrimitiveType && PsiType.DOUBLE.isAssignableFrom(myExpectedType)) {
addConstantsFromTargetClass(position, results, searchInheritors, processor);
addConstantsFromReferencedClassesInSwitch(position, results, processor);
}
if (position.getParent().getParent() instanceof PsiSwitchLabelStatement) {
return; //non-enum values are processed above, enum values will be suggested by reference completion
}
final PsiClass psiClass = PsiUtil.resolveClassInType(myExpectedType);
processMembers(position, results, psiClass, PsiTreeUtil.getParentOfType(position, PsiAnnotation.class) != null, searchInheritors, processor);
}
private void addConstantsFromReferencedClassesInSwitch(PsiElement position, final Consumer<LookupElement> results, final StaticMemberProcessor processor) {
final Set<PsiField> fields = ReferenceExpressionCompletionContributor.findConstantsUsedInSwitch(position);
final Set<PsiClass> classes = new HashSet<PsiClass>();
for (PsiField field : fields) {
ContainerUtil.addIfNotNull(classes, field.getContainingClass());
}
for (PsiClass aClass : classes) {
processMembers(position, new Consumer<LookupElement>() {
@Override
public void consume(LookupElement element) {
//noinspection SuspiciousMethodCalls
if (!fields.contains(element.getObject())) {
results.consume(TailTypeDecorator.withTail(element, TailType.CASE_COLON));
}
}
}, aClass, false, false, processor);
}
}
private void addConstantsFromTargetClass(PsiElement position,
Consumer<LookupElement> results,
boolean searchInheritors, final StaticMemberProcessor processor) {
PsiElement parent = position.getParent();
if (!(parent instanceof PsiReferenceExpression)) {
return;
}
PsiElement prev = parent;
parent = parent.getParent();
while (parent instanceof PsiBinaryExpression) {
final PsiBinaryExpression binaryExpression = (PsiBinaryExpression)parent;
final IElementType op = binaryExpression.getOperationTokenType();
if (JavaTokenType.EQEQ == op || JavaTokenType.NE == op) {
if (prev == binaryExpression.getROperand()) {
processMembers(position, results, getCalledClass(binaryExpression.getLOperand()), false, searchInheritors,
processor);
}
return;
}
prev = parent;
parent = parent.getParent();
}
if (parent instanceof PsiExpressionList) {
processMembers(position, results, getCalledClass(parent.getParent()), false, searchInheritors, processor);
}
}
@Nullable
private static PsiClass getCalledClass(@Nullable PsiElement call) {
if (call instanceof PsiMethodCallExpression) {
for (final JavaResolveResult result : ((PsiMethodCallExpression)call).getMethodExpression().multiResolve(true)) {
final PsiElement element = result.getElement();
if (element instanceof PsiMethod) {
final PsiClass aClass = ((PsiMethod)element).getContainingClass();
if (aClass != null) {
return aClass;
}
}
}
}
if (call instanceof PsiNewExpression) {
final PsiJavaCodeReferenceElement reference = ((PsiNewExpression)call).getClassReference();
if (reference != null) {
for (final JavaResolveResult result : reference.multiResolve(true)) {
final PsiElement element = result.getElement();
if (element instanceof PsiClass) {
return (PsiClass)element;
}
}
}
}
return null;
}
@Override
@Nullable
protected LookupElement createFieldElement(PsiField field) {
if (!myExpectedType.isAssignableFrom(field.getType())) {
return null;
}
return new VariableLookupItem(field, false);
}
@Override
@Nullable
protected LookupElement createMethodElement(PsiMethod method) {
PsiSubstitutor substitutor = SmartCompletionDecorator.calculateMethodReturnTypeSubstitutor(method, myExpectedType);
PsiType type = substitutor.substitute(method.getReturnType());
if (type == null || !myExpectedType.isAssignableFrom(type)) {
return null;
}
JavaMethodCallElement item = new JavaMethodCallElement(method, false, false);
item.setInferenceSubstitutor(substitutor, myPlace);
return item;
}
}
/*
* Copyright 2000-2011 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.filters.getters;
import com.intellij.codeInsight.TailType;
import com.intellij.codeInsight.completion.*;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.TailTypeDecorator;
import com.intellij.codeInsight.lookup.VariableLookupItem;
import com.intellij.psi.*;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.util.Consumer;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.HashSet;
import java.util.Set;
/**
* @author peter
*/
public class JavaMembersGetter extends MembersGetter {
private final PsiType myExpectedType;
private final PsiElement myPlace;
public JavaMembersGetter(@NotNull PsiType expectedType, PsiElement place) {
myPlace = place;
myExpectedType = JavaCompletionUtil.originalize(expectedType);
}
public void addMembers(CompletionParameters parameters, boolean searchInheritors, final Consumer<LookupElement> results) {
final StaticMemberProcessor processor = new JavaStaticMemberProcessor(parameters);
final PsiElement position = parameters.getPosition();
if (myExpectedType instanceof PsiPrimitiveType && PsiType.DOUBLE.isAssignableFrom(myExpectedType)) {
addConstantsFromTargetClass(position, results, searchInheritors, processor);
addConstantsFromReferencedClassesInSwitch(position, results, processor);
}
if (position.getParent().getParent() instanceof PsiSwitchLabelStatement) {
return; //non-enum values are processed above, enum values will be suggested by reference completion
}
final PsiClass psiClass = PsiUtil.resolveClassInType(myExpectedType);
processMembers(position, results, psiClass, PsiTreeUtil.getParentOfType(position, PsiAnnotation.class) != null, searchInheritors, processor);
}
private void addConstantsFromReferencedClassesInSwitch(PsiElement position, final Consumer<LookupElement> results, final StaticMemberProcessor processor) {
final Set<PsiField> fields = ReferenceExpressionCompletionContributor.findConstantsUsedInSwitch(position);
final Set<PsiClass> classes = new HashSet<PsiClass>();
for (PsiField field : fields) {
ContainerUtil.addIfNotNull(classes, field.getContainingClass());
}
for (PsiClass aClass : classes) {
processMembers(position, new Consumer<LookupElement>() {
@Override
public void consume(LookupElement element) {
//noinspection SuspiciousMethodCalls
if (!fields.contains(element.getObject())) {
results.consume(TailTypeDecorator.withTail(element, TailType.CASE_COLON));
}
}
}, aClass, false, false, processor);
}
}
private void addConstantsFromTargetClass(PsiElement position,
Consumer<LookupElement> results,
boolean searchInheritors, final StaticMemberProcessor processor) {
PsiElement parent = position.getParent();
if (!(parent instanceof PsiReferenceExpression)) {
return;
}
PsiElement prev = parent;
parent = parent.getParent();
while (parent instanceof PsiBinaryExpression) {
final PsiBinaryExpression binaryExpression = (PsiBinaryExpression)parent;
final IElementType op = binaryExpression.getOperationTokenType();
if (JavaTokenType.EQEQ == op || JavaTokenType.NE == op) {
if (prev == binaryExpression.getROperand()) {
processMembers(position, results, getCalledClass(binaryExpression.getLOperand()), false, searchInheritors,
processor);
}
return;
}
prev = parent;
parent = parent.getParent();
}
if (parent instanceof PsiExpressionList) {
processMembers(position, results, getCalledClass(parent.getParent()), false, searchInheritors, processor);
}
}
@Nullable
private static PsiClass getCalledClass(@Nullable PsiElement call) {
if (call instanceof PsiMethodCallExpression) {
for (final JavaResolveResult result : ((PsiMethodCallExpression)call).getMethodExpression().multiResolve(true)) {
final PsiElement element = result.getElement();
if (element instanceof PsiMethod) {
final PsiClass aClass = ((PsiMethod)element).getContainingClass();
if (aClass != null) {
return aClass;
}
}
}
}
if (call instanceof PsiNewExpression) {
final PsiJavaCodeReferenceElement reference = ((PsiNewExpression)call).getClassReference();
if (reference != null) {
for (final JavaResolveResult result : reference.multiResolve(true)) {
final PsiElement element = result.getElement();
if (element instanceof PsiClass) {
return (PsiClass)element;
}
}
}
}
return null;
}
@Override
@Nullable
protected LookupElement createFieldElement(PsiField field) {
if (!myExpectedType.isAssignableFrom(field.getType())) {
return null;
}
return new VariableLookupItem(field, false);
}
@Override
@Nullable
protected LookupElement createMethodElement(PsiMethod method) {
PsiSubstitutor substitutor = SmartCompletionDecorator.calculateMethodReturnTypeSubstitutor(method, myExpectedType);
PsiType type = substitutor.substitute(method.getReturnType());
if (type == null || !myExpectedType.isAssignableFrom(type)) {
return null;
}
JavaMethodCallElement item = new JavaMethodCallElement(method, false, false);
item.setInferenceSubstitutor(substitutor, myPlace);
return item;
}
}
File diff suppressed because it is too large Load Diff
@@ -1,111 +1,111 @@
/*
* 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.formatter.java;
import com.intellij.formatting.*;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.impl.source.codeStyle.ShiftIndentInsideHelper;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
public class LeafBlock implements ASTBlock{
private int myStartOffset = -1;
private final ASTNode myNode;
private final Wrap myWrap;
private final Alignment myAlignment;
private static final ArrayList<Block> EMPTY_SUB_BLOCKS = new ArrayList<Block>();
private final Indent myIndent;
public LeafBlock(final ASTNode node,
final Wrap wrap,
final Alignment alignment,
Indent indent)
{
myNode = node;
myWrap = wrap;
myAlignment = alignment;
myIndent = indent;
}
@Override
public ASTNode getNode() {
return myNode;
}
@Override
@NotNull
public TextRange getTextRange() {
if (myStartOffset != -1) {
return new TextRange(myStartOffset, myStartOffset + myNode.getTextLength());
}
return myNode.getTextRange();
}
@Override
@NotNull
public List<Block> getSubBlocks() {
return EMPTY_SUB_BLOCKS;
}
@Override
public Wrap getWrap() {
return myWrap;
}
@Override
public Indent getIndent() {
return myIndent;
}
@Override
public Alignment getAlignment() {
return myAlignment;
}
@Override
public Spacing getSpacing(Block child1, Block child2) {
return null;
}
public ASTNode getTreeNode() {
return myNode;
}
@Override
@NotNull
public ChildAttributes getChildAttributes(final int newChildIndex) {
return new ChildAttributes(getIndent(), null);
}
@Override
public boolean isIncomplete() {
return false;
}
@Override
public boolean isLeaf() {
return ShiftIndentInsideHelper.mayShiftIndentInside(myNode);
}
public void setStartOffset(final int startOffset) {
myStartOffset = startOffset;
// if (startOffset != -1) assert startOffset == myNode.getTextRange().getStartOffset();
}
}
/*
* 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.formatter.java;
import com.intellij.formatting.*;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.impl.source.codeStyle.ShiftIndentInsideHelper;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
public class LeafBlock implements ASTBlock{
private int myStartOffset = -1;
private final ASTNode myNode;
private final Wrap myWrap;
private final Alignment myAlignment;
private static final ArrayList<Block> EMPTY_SUB_BLOCKS = new ArrayList<Block>();
private final Indent myIndent;
public LeafBlock(final ASTNode node,
final Wrap wrap,
final Alignment alignment,
Indent indent)
{
myNode = node;
myWrap = wrap;
myAlignment = alignment;
myIndent = indent;
}
@Override
public ASTNode getNode() {
return myNode;
}
@Override
@NotNull
public TextRange getTextRange() {
if (myStartOffset != -1) {
return new TextRange(myStartOffset, myStartOffset + myNode.getTextLength());
}
return myNode.getTextRange();
}
@Override
@NotNull
public List<Block> getSubBlocks() {
return EMPTY_SUB_BLOCKS;
}
@Override
public Wrap getWrap() {
return myWrap;
}
@Override
public Indent getIndent() {
return myIndent;
}
@Override
public Alignment getAlignment() {
return myAlignment;
}
@Override
public Spacing getSpacing(Block child1, Block child2) {
return null;
}
public ASTNode getTreeNode() {
return myNode;
}
@Override
@NotNull
public ChildAttributes getChildAttributes(final int newChildIndex) {
return new ChildAttributes(getIndent(), null);
}
@Override
public boolean isIncomplete() {
return false;
}
@Override
public boolean isLeaf() {
return ShiftIndentInsideHelper.mayShiftIndentInside(myNode);
}
public void setStartOffset(final int startOffset) {
myStartOffset = startOffset;
// if (startOffset != -1) assert startOffset == myNode.getTextRange().getStartOffset();
}
}
@@ -1,134 +1,134 @@
/*
* 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.formatter.java;
import com.intellij.formatting.*;
import com.intellij.formatting.alignment.AlignmentStrategy;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiFile;
import com.intellij.psi.codeStyle.CommonCodeStyleSettings;
import com.intellij.psi.formatter.FormatterUtil;
import com.intellij.psi.impl.source.tree.JavaDocElementType;
import com.intellij.psi.impl.source.tree.JavaElementType;
import com.intellij.psi.impl.source.tree.StdTokenSets;
import com.intellij.psi.tree.IElementType;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class SimpleJavaBlock extends AbstractJavaBlock {
private int myStartOffset = -1;
private final Map<IElementType, Wrap> myReservedWrap = new HashMap<IElementType, Wrap>();
public SimpleJavaBlock(final ASTNode node, final Wrap wrap, final AlignmentStrategy alignment, final Indent indent, CommonCodeStyleSettings settings) {
super(node, wrap, alignment, indent,settings);
}
@Override
protected List<Block> buildChildren() {
ASTNode child = myNode.getFirstChildNode();
int offset = myStartOffset != -1 ? myStartOffset : child != null ? child.getTextRange().getStartOffset():0;
final ArrayList<Block> result = new ArrayList<Block>();
Indent indent = null;
while (child != null) {
if (StdTokenSets.COMMENT_BIT_SET.contains(child.getElementType()) || child.getElementType() == JavaDocElementType.DOC_COMMENT) {
result.add(createJavaBlock(child, mySettings, Indent.getNoneIndent(), null, AlignmentStrategy.getNullStrategy()));
indent = Indent.getNoneIndent();
}
else if (!FormatterUtil.containsWhiteSpacesOnly(child)) {
break;
}
offset += child.getTextLength();
child = child.getTreeNext();
}
myReservedAlignment = createChildAlignment();
myReservedAlignment2 = createChildAlignment2(myReservedAlignment);
Wrap childWrap = createChildWrap();
while (child != null) {
if (!FormatterUtil.containsWhiteSpacesOnly(child) && child.getTextLength() > 0){
final ASTNode astNode = child;
AlignmentStrategy alignmentStrategyToUse = ALIGN_IN_COLUMNS_ELEMENT_TYPES.contains(myNode.getElementType())
? myAlignmentStrategy
: AlignmentStrategy.wrap(chooseAlignment(myReservedAlignment, myReservedAlignment2, child));
child = processChild(result, astNode, alignmentStrategyToUse, childWrap, indent, offset);
if (astNode != child && child != null) {
offset = child.getTextRange().getStartOffset();
}
if (indent != null
&& !(myNode.getPsi() instanceof PsiFile) && child != null && child.getElementType() != JavaElementType.MODIFIER_LIST)
{
indent = Indent.getContinuationIndent(myIndentSettings.USE_RELATIVE_INDENTS);
}
}
if (child != null) {
offset += child.getTextLength();
child = child.getTreeNext();
}
}
return result;
}
@Override
@NotNull
public TextRange getTextRange() {
if (myStartOffset != -1) {
return new TextRange(myStartOffset, myStartOffset + myNode.getTextLength());
}
return super.getTextRange();
}
@Override
@NotNull
public ChildAttributes getChildAttributes(final int newChildIndex) {
if (myNode.getElementType() == JavaElementType.CONDITIONAL_EXPRESSION && mySettings.ALIGN_MULTILINE_TERNARY_OPERATION) {
final Alignment usedAlignment = getUsedAlignment(newChildIndex);
if (usedAlignment != null) {
return new ChildAttributes(null, usedAlignment);
} else {
return super.getChildAttributes(newChildIndex);
}
}
else if (myNode.getElementType() == JavaElementType.SWITCH_LABEL_STATEMENT) {
return new ChildAttributes(Indent.getNormalIndent(), null);
}
else {
return super.getChildAttributes(newChildIndex);
}
}
@Override
public Wrap getReservedWrap(final IElementType elementType) {
return myReservedWrap.get(elementType);
}
@Override
protected void setReservedWrap(final Wrap reservedWrap, final IElementType operationType) {
myReservedWrap.put(operationType, reservedWrap);
}
public void setStartOffset(final int startOffset) {
myStartOffset = startOffset;
}
}
/*
* 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.formatter.java;
import com.intellij.formatting.*;
import com.intellij.formatting.alignment.AlignmentStrategy;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiFile;
import com.intellij.psi.codeStyle.CommonCodeStyleSettings;
import com.intellij.psi.formatter.FormatterUtil;
import com.intellij.psi.impl.source.tree.JavaDocElementType;
import com.intellij.psi.impl.source.tree.JavaElementType;
import com.intellij.psi.impl.source.tree.StdTokenSets;
import com.intellij.psi.tree.IElementType;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class SimpleJavaBlock extends AbstractJavaBlock {
private int myStartOffset = -1;
private final Map<IElementType, Wrap> myReservedWrap = new HashMap<IElementType, Wrap>();
public SimpleJavaBlock(final ASTNode node, final Wrap wrap, final AlignmentStrategy alignment, final Indent indent, CommonCodeStyleSettings settings) {
super(node, wrap, alignment, indent,settings);
}
@Override
protected List<Block> buildChildren() {
ASTNode child = myNode.getFirstChildNode();
int offset = myStartOffset != -1 ? myStartOffset : child != null ? child.getTextRange().getStartOffset():0;
final ArrayList<Block> result = new ArrayList<Block>();
Indent indent = null;
while (child != null) {
if (StdTokenSets.COMMENT_BIT_SET.contains(child.getElementType()) || child.getElementType() == JavaDocElementType.DOC_COMMENT) {
result.add(createJavaBlock(child, mySettings, Indent.getNoneIndent(), null, AlignmentStrategy.getNullStrategy()));
indent = Indent.getNoneIndent();
}
else if (!FormatterUtil.containsWhiteSpacesOnly(child)) {
break;
}
offset += child.getTextLength();
child = child.getTreeNext();
}
myReservedAlignment = createChildAlignment();
myReservedAlignment2 = createChildAlignment2(myReservedAlignment);
Wrap childWrap = createChildWrap();
while (child != null) {
if (!FormatterUtil.containsWhiteSpacesOnly(child) && child.getTextLength() > 0){
final ASTNode astNode = child;
AlignmentStrategy alignmentStrategyToUse = ALIGN_IN_COLUMNS_ELEMENT_TYPES.contains(myNode.getElementType())
? myAlignmentStrategy
: AlignmentStrategy.wrap(chooseAlignment(myReservedAlignment, myReservedAlignment2, child));
child = processChild(result, astNode, alignmentStrategyToUse, childWrap, indent, offset);
if (astNode != child && child != null) {
offset = child.getTextRange().getStartOffset();
}
if (indent != null
&& !(myNode.getPsi() instanceof PsiFile) && child != null && child.getElementType() != JavaElementType.MODIFIER_LIST)
{
indent = Indent.getContinuationIndent(myIndentSettings.USE_RELATIVE_INDENTS);
}
}
if (child != null) {
offset += child.getTextLength();
child = child.getTreeNext();
}
}
return result;
}
@Override
@NotNull
public TextRange getTextRange() {
if (myStartOffset != -1) {
return new TextRange(myStartOffset, myStartOffset + myNode.getTextLength());
}
return super.getTextRange();
}
@Override
@NotNull
public ChildAttributes getChildAttributes(final int newChildIndex) {
if (myNode.getElementType() == JavaElementType.CONDITIONAL_EXPRESSION && mySettings.ALIGN_MULTILINE_TERNARY_OPERATION) {
final Alignment usedAlignment = getUsedAlignment(newChildIndex);
if (usedAlignment != null) {
return new ChildAttributes(null, usedAlignment);
} else {
return super.getChildAttributes(newChildIndex);
}
}
else if (myNode.getElementType() == JavaElementType.SWITCH_LABEL_STATEMENT) {
return new ChildAttributes(Indent.getNormalIndent(), null);
}
else {
return super.getChildAttributes(newChildIndex);
}
}
@Override
public Wrap getReservedWrap(final IElementType elementType) {
return myReservedWrap.get(elementType);
}
@Override
protected void setReservedWrap(final Wrap reservedWrap, final IElementType operationType) {
myReservedWrap.put(operationType, reservedWrap);
}
public void setStartOffset(final int startOffset) {
myStartOffset = startOffset;
}
}
@@ -1,65 +1,65 @@
/*
* 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.impl;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleUtil;
import com.intellij.openapi.projectRoots.JavaSdk;
import com.intellij.openapi.projectRoots.JavaSdkVersion;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.roots.ModuleRootManager;
import org.intellij.lang.regexp.RegExpLanguageHost;
import org.intellij.lang.regexp.psi.RegExpGroup;
/**
* @author yole
*/
public class JavaRegExpHost implements RegExpLanguageHost {
@Override
public boolean characterNeedsEscaping(char c) {
return c == ']' || c == '}';
}
@Override
public boolean supportsPerl5EmbeddedComments() {
return false;
}
@Override
public boolean supportsPossessiveQuantifiers() {
return true;
}
@Override
public boolean supportsPythonConditionalRefs() {
return false;
}
@Override
public boolean supportsNamedGroupSyntax(RegExpGroup group) {
if (group.isRubyNamedGroup()) {
final Module module = ModuleUtil.findModuleForPsiElement(group);
if (module != null) {
final Sdk sdk = ModuleRootManager.getInstance(module).getSdk();
if (sdk != null && sdk.getSdkType() instanceof JavaSdk) {
final JavaSdkVersion version = JavaSdk.getInstance().getVersion(sdk);
return version != null && version.isAtLeast(JavaSdkVersion.JDK_1_7);
}
}
}
return false;
}
}
/*
* 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.impl;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleUtil;
import com.intellij.openapi.projectRoots.JavaSdk;
import com.intellij.openapi.projectRoots.JavaSdkVersion;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.roots.ModuleRootManager;
import org.intellij.lang.regexp.RegExpLanguageHost;
import org.intellij.lang.regexp.psi.RegExpGroup;
/**
* @author yole
*/
public class JavaRegExpHost implements RegExpLanguageHost {
@Override
public boolean characterNeedsEscaping(char c) {
return c == ']' || c == '}';
}
@Override
public boolean supportsPerl5EmbeddedComments() {
return false;
}
@Override
public boolean supportsPossessiveQuantifiers() {
return true;
}
@Override
public boolean supportsPythonConditionalRefs() {
return false;
}
@Override
public boolean supportsNamedGroupSyntax(RegExpGroup group) {
if (group.isRubyNamedGroup()) {
final Module module = ModuleUtil.findModuleForPsiElement(group);
if (module != null) {
final Sdk sdk = ModuleRootManager.getInstance(module).getSdk();
if (sdk != null && sdk.getSdkType() instanceof JavaSdk) {
final JavaSdkVersion version = JavaSdk.getInstance().getVersion(sdk);
return version != null && version.isAtLeast(JavaSdkVersion.JDK_1_7);
}
}
}
return false;
}
}
@@ -1,206 +1,206 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* @author max
*/
package com.intellij.psi.impl.file;
import com.intellij.core.CoreJavaDirectoryService;
import com.intellij.ide.fileTemplates.FileTemplate;
import com.intellij.ide.fileTemplates.FileTemplateManager;
import com.intellij.ide.fileTemplates.FileTemplateUtil;
import com.intellij.ide.fileTemplates.JavaTemplateUtil;
import com.intellij.ide.fileTemplates.ui.CreateFromTemplateDialog;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.fileTypes.StdFileTypes;
import com.intellij.openapi.module.LanguageLevelUtil;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.LanguageLevelProjectExtension;
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.VirtualFile;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.psi.*;
import com.intellij.psi.util.PsiUtil;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
import java.util.Properties;
public class JavaDirectoryServiceImpl extends CoreJavaDirectoryService {
private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.file.JavaDirectoryServiceImpl");
@Override
public PsiPackage getPackage(@NotNull PsiDirectory dir) {
ProjectFileIndex projectFileIndex = ProjectRootManager.getInstance(dir.getProject()).getFileIndex();
String packageName = projectFileIndex.getPackageNameByDirectory(dir.getVirtualFile());
if (packageName == null) return null;
return JavaPsiFacade.getInstance(dir.getProject()).findPackage(packageName);
}
@Override
@NotNull
public PsiClass createClass(@NotNull PsiDirectory dir, @NotNull String name) throws IncorrectOperationException {
return createClassFromTemplate(dir, name, JavaTemplateUtil.INTERNAL_CLASS_TEMPLATE_NAME);
}
@Override
@NotNull
public PsiClass createClass(@NotNull PsiDirectory dir, @NotNull String name, @NotNull String templateName) throws IncorrectOperationException {
return createClassFromTemplate(dir, name, templateName);
}
@Override
public PsiClass createClass(@NotNull PsiDirectory dir,
@NotNull String name,
@NotNull String templateName,
boolean askForUndefinedVariables) throws IncorrectOperationException {
return createClassFromTemplate(dir, name, templateName, askForUndefinedVariables);
}
@Override
@NotNull
public PsiClass createInterface(@NotNull PsiDirectory dir, @NotNull String name) throws IncorrectOperationException {
String templateName = JavaTemplateUtil.INTERNAL_INTERFACE_TEMPLATE_NAME;
PsiClass someClass = createClassFromTemplate(dir, name, templateName);
if (!someClass.isInterface()) {
throw new IncorrectOperationException(getIncorrectTemplateMessage(templateName));
}
return someClass;
}
@Override
@NotNull
public PsiClass createEnum(@NotNull PsiDirectory dir, @NotNull String name) throws IncorrectOperationException {
String templateName = JavaTemplateUtil.INTERNAL_ENUM_TEMPLATE_NAME;
PsiClass someClass = createClassFromTemplate(dir, name, templateName);
if (!someClass.isEnum()) {
throw new IncorrectOperationException(getIncorrectTemplateMessage(templateName));
}
return someClass;
}
@Override
@NotNull
public PsiClass createAnnotationType(@NotNull PsiDirectory dir, @NotNull String name) throws IncorrectOperationException {
String templateName = JavaTemplateUtil.INTERNAL_ANNOTATION_TYPE_TEMPLATE_NAME;
PsiClass someClass = createClassFromTemplate(dir, name, templateName);
if (!someClass.isAnnotationType()) {
throw new IncorrectOperationException(getIncorrectTemplateMessage(templateName));
}
return someClass;
}
private static PsiClass createClassFromTemplate(@NotNull PsiDirectory dir, String name, String templateName) throws IncorrectOperationException {
return createClassFromTemplate(dir, name, templateName, false);
}
private static PsiClass createClassFromTemplate(@NotNull PsiDirectory dir,
String name,
String templateName,
boolean askToDefineVariables) throws IncorrectOperationException {
//checkCreateClassOrInterface(dir, name);
FileTemplate template = FileTemplateManager.getInstance().getInternalTemplate(templateName);
Properties defaultProperties = FileTemplateManager.getInstance().getDefaultProperties(dir.getProject());
Properties properties = new Properties(defaultProperties);
properties.setProperty(FileTemplate.ATTRIBUTE_NAME, name);
String ext = StdFileTypes.JAVA.getDefaultExtension();
String fileName = name + "." + ext;
PsiElement element;
try {
element = askToDefineVariables ? new CreateFromTemplateDialog(dir.getProject(), dir, template, null, properties).create()
: FileTemplateUtil.createFromTemplate(template, fileName, properties, dir);
}
catch (IncorrectOperationException e) {
throw e;
}
catch (Exception e) {
LOG.error(e);
return null;
}
if (element == null) return null;
final PsiJavaFile file = (PsiJavaFile)element.getContainingFile();
PsiClass[] classes = file.getClasses();
if (classes.length < 1) {
throw new IncorrectOperationException(getIncorrectTemplateMessage(templateName));
}
return classes[0];
}
private static String getIncorrectTemplateMessage(String templateName) {
return PsiBundle.message("psi.error.incorroect.class.template.message",
FileTemplateManager.getInstance().internalTemplateToSubject(templateName), templateName);
}
@Override
public void checkCreateClass(@NotNull PsiDirectory dir, @NotNull String name) throws IncorrectOperationException {
checkCreateClassOrInterface(dir, name);
}
public static void checkCreateClassOrInterface(@NotNull PsiDirectory directory, String name) throws IncorrectOperationException {
PsiUtil.checkIsIdentifier(directory.getManager(), name);
String fileName = name + "." + StdFileTypes.JAVA.getDefaultExtension();
directory.checkCreateFile(fileName);
PsiNameHelper helper = JavaPsiFacade.getInstance(directory.getProject()).getNameHelper();
PsiPackage aPackage = JavaDirectoryService.getInstance().getPackage(directory);
String qualifiedName = aPackage == null ? null : aPackage.getQualifiedName();
if (!StringUtil.isEmpty(qualifiedName) && !helper.isQualifiedName(qualifiedName)) {
throw new IncorrectOperationException("Cannot create class in invalid package: '"+qualifiedName+"'");
}
}
@Override
public boolean isSourceRoot(@NotNull PsiDirectory dir) {
final VirtualFile file = dir.getVirtualFile();
final VirtualFile sourceRoot = ProjectRootManager.getInstance(dir.getProject()).getFileIndex().getSourceRootForFile(file);
return file.equals(sourceRoot);
}
private static final Key<LanguageLevel> LANG_LEVEL_IN_DIRECTORY = new Key<LanguageLevel>("LANG_LEVEL_IN_DIRECTORY");
@Override
public LanguageLevel getLanguageLevel(@NotNull PsiDirectory dir) {
synchronized (PsiLock.LOCK) {
LanguageLevel level = dir.getUserData(LANG_LEVEL_IN_DIRECTORY);
if (level == null) {
level = getLanguageLevelInner(dir);
dir.putUserData(LANG_LEVEL_IN_DIRECTORY, level);
}
return level;
}
}
private static LanguageLevel getLanguageLevelInner(@NotNull PsiDirectory dir) {
final VirtualFile virtualFile = dir.getVirtualFile();
final Project project = dir.getProject();
final Module module = ProjectRootManager.getInstance(project).getFileIndex().getModuleForFile(virtualFile);
if (module != null) {
return LanguageLevelUtil.getEffectiveLanguageLevel(module);
}
return LanguageLevelProjectExtension.getInstance(project).getLanguageLevel();
}
}
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* @author max
*/
package com.intellij.psi.impl.file;
import com.intellij.core.CoreJavaDirectoryService;
import com.intellij.ide.fileTemplates.FileTemplate;
import com.intellij.ide.fileTemplates.FileTemplateManager;
import com.intellij.ide.fileTemplates.FileTemplateUtil;
import com.intellij.ide.fileTemplates.JavaTemplateUtil;
import com.intellij.ide.fileTemplates.ui.CreateFromTemplateDialog;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.fileTypes.StdFileTypes;
import com.intellij.openapi.module.LanguageLevelUtil;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.LanguageLevelProjectExtension;
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.VirtualFile;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.psi.*;
import com.intellij.psi.util.PsiUtil;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
import java.util.Properties;
public class JavaDirectoryServiceImpl extends CoreJavaDirectoryService {
private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.file.JavaDirectoryServiceImpl");
@Override
public PsiPackage getPackage(@NotNull PsiDirectory dir) {
ProjectFileIndex projectFileIndex = ProjectRootManager.getInstance(dir.getProject()).getFileIndex();
String packageName = projectFileIndex.getPackageNameByDirectory(dir.getVirtualFile());
if (packageName == null) return null;
return JavaPsiFacade.getInstance(dir.getProject()).findPackage(packageName);
}
@Override
@NotNull
public PsiClass createClass(@NotNull PsiDirectory dir, @NotNull String name) throws IncorrectOperationException {
return createClassFromTemplate(dir, name, JavaTemplateUtil.INTERNAL_CLASS_TEMPLATE_NAME);
}
@Override
@NotNull
public PsiClass createClass(@NotNull PsiDirectory dir, @NotNull String name, @NotNull String templateName) throws IncorrectOperationException {
return createClassFromTemplate(dir, name, templateName);
}
@Override
public PsiClass createClass(@NotNull PsiDirectory dir,
@NotNull String name,
@NotNull String templateName,
boolean askForUndefinedVariables) throws IncorrectOperationException {
return createClassFromTemplate(dir, name, templateName, askForUndefinedVariables);
}
@Override
@NotNull
public PsiClass createInterface(@NotNull PsiDirectory dir, @NotNull String name) throws IncorrectOperationException {
String templateName = JavaTemplateUtil.INTERNAL_INTERFACE_TEMPLATE_NAME;
PsiClass someClass = createClassFromTemplate(dir, name, templateName);
if (!someClass.isInterface()) {
throw new IncorrectOperationException(getIncorrectTemplateMessage(templateName));
}
return someClass;
}
@Override
@NotNull
public PsiClass createEnum(@NotNull PsiDirectory dir, @NotNull String name) throws IncorrectOperationException {
String templateName = JavaTemplateUtil.INTERNAL_ENUM_TEMPLATE_NAME;
PsiClass someClass = createClassFromTemplate(dir, name, templateName);
if (!someClass.isEnum()) {
throw new IncorrectOperationException(getIncorrectTemplateMessage(templateName));
}
return someClass;
}
@Override
@NotNull
public PsiClass createAnnotationType(@NotNull PsiDirectory dir, @NotNull String name) throws IncorrectOperationException {
String templateName = JavaTemplateUtil.INTERNAL_ANNOTATION_TYPE_TEMPLATE_NAME;
PsiClass someClass = createClassFromTemplate(dir, name, templateName);
if (!someClass.isAnnotationType()) {
throw new IncorrectOperationException(getIncorrectTemplateMessage(templateName));
}
return someClass;
}
private static PsiClass createClassFromTemplate(@NotNull PsiDirectory dir, String name, String templateName) throws IncorrectOperationException {
return createClassFromTemplate(dir, name, templateName, false);
}
private static PsiClass createClassFromTemplate(@NotNull PsiDirectory dir,
String name,
String templateName,
boolean askToDefineVariables) throws IncorrectOperationException {
//checkCreateClassOrInterface(dir, name);
FileTemplate template = FileTemplateManager.getInstance().getInternalTemplate(templateName);
Properties defaultProperties = FileTemplateManager.getInstance().getDefaultProperties(dir.getProject());
Properties properties = new Properties(defaultProperties);
properties.setProperty(FileTemplate.ATTRIBUTE_NAME, name);
String ext = StdFileTypes.JAVA.getDefaultExtension();
String fileName = name + "." + ext;
PsiElement element;
try {
element = askToDefineVariables ? new CreateFromTemplateDialog(dir.getProject(), dir, template, null, properties).create()
: FileTemplateUtil.createFromTemplate(template, fileName, properties, dir);
}
catch (IncorrectOperationException e) {
throw e;
}
catch (Exception e) {
LOG.error(e);
return null;
}
if (element == null) return null;
final PsiJavaFile file = (PsiJavaFile)element.getContainingFile();
PsiClass[] classes = file.getClasses();
if (classes.length < 1) {
throw new IncorrectOperationException(getIncorrectTemplateMessage(templateName));
}
return classes[0];
}
private static String getIncorrectTemplateMessage(String templateName) {
return PsiBundle.message("psi.error.incorroect.class.template.message",
FileTemplateManager.getInstance().internalTemplateToSubject(templateName), templateName);
}
@Override
public void checkCreateClass(@NotNull PsiDirectory dir, @NotNull String name) throws IncorrectOperationException {
checkCreateClassOrInterface(dir, name);
}
public static void checkCreateClassOrInterface(@NotNull PsiDirectory directory, String name) throws IncorrectOperationException {
PsiUtil.checkIsIdentifier(directory.getManager(), name);
String fileName = name + "." + StdFileTypes.JAVA.getDefaultExtension();
directory.checkCreateFile(fileName);
PsiNameHelper helper = JavaPsiFacade.getInstance(directory.getProject()).getNameHelper();
PsiPackage aPackage = JavaDirectoryService.getInstance().getPackage(directory);
String qualifiedName = aPackage == null ? null : aPackage.getQualifiedName();
if (!StringUtil.isEmpty(qualifiedName) && !helper.isQualifiedName(qualifiedName)) {
throw new IncorrectOperationException("Cannot create class in invalid package: '"+qualifiedName+"'");
}
}
@Override
public boolean isSourceRoot(@NotNull PsiDirectory dir) {
final VirtualFile file = dir.getVirtualFile();
final VirtualFile sourceRoot = ProjectRootManager.getInstance(dir.getProject()).getFileIndex().getSourceRootForFile(file);
return file.equals(sourceRoot);
}
private static final Key<LanguageLevel> LANG_LEVEL_IN_DIRECTORY = new Key<LanguageLevel>("LANG_LEVEL_IN_DIRECTORY");
@Override
public LanguageLevel getLanguageLevel(@NotNull PsiDirectory dir) {
synchronized (PsiLock.LOCK) {
LanguageLevel level = dir.getUserData(LANG_LEVEL_IN_DIRECTORY);
if (level == null) {
level = getLanguageLevelInner(dir);
dir.putUserData(LANG_LEVEL_IN_DIRECTORY, level);
}
return level;
}
}
private static LanguageLevel getLanguageLevelInner(@NotNull PsiDirectory dir) {
final VirtualFile virtualFile = dir.getVirtualFile();
final Project project = dir.getProject();
final Module module = ProjectRootManager.getInstance(project).getFileIndex().getModuleForFile(virtualFile);
if (module != null) {
return LanguageLevelUtil.getEffectiveLanguageLevel(module);
}
return LanguageLevelProjectExtension.getInstance(project).getLanguageLevel();
}
}
@@ -1,246 +1,246 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.psi.util;
import com.intellij.ide.fileTemplates.FileTemplate;
import com.intellij.ide.fileTemplates.FileTemplateManager;
import com.intellij.ide.fileTemplates.JavaCreateFromTemplateHandler;
import com.intellij.ide.util.DirectoryChooserUtil;
import com.intellij.ide.util.PackageUtil;
import com.intellij.openapi.fileTypes.StdFileTypes;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ModuleRootManager;
import com.intellij.openapi.roots.impl.DirectoryIndex;
import com.intellij.openapi.roots.impl.DirectoryInfo;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.JavaCodeStyleManager;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.text.StringTokenizer;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
/**
* author: lesya
*/
public class CreateClassUtil {
private static final Logger LOG = Logger.getInstance("#com.intellij.j2ee.CreateClassUtil");
@NonNls public static final String DEFAULT_CLASS_TEMPLATE = "#DEFAULT_CLASS_TEMPLATE";
@NonNls private static final String DO_NOT_CREATE_CLASS_TEMPLATE = "#DO_NOT_CREATE_CLASS_TEMPLATE";
@NonNls private static final String CLASS_NAME_PROPERTY = "Class_Name";
@NonNls private static final String INTERFACE_NAME_PROPERTY = "Interface_Name";
private CreateClassUtil() {}
@Nullable
private static PsiClass createClassFromTemplate(@NotNull final Properties attributes, @Nullable final String templateName,
@NotNull final PsiDirectory directoryRoot,
@NotNull final String className) throws IncorrectOperationException {
if (templateName == null) return null;
if (templateName.equals(DO_NOT_CREATE_CLASS_TEMPLATE)) return null;
final Project project = directoryRoot.getProject();
try {
final PsiDirectory directory = createParentDirectories(directoryRoot, className);
final PsiFile psiFile = directory.findFile(className + "." + StdFileTypes.JAVA.getDefaultExtension());
if (psiFile != null) {
psiFile.delete();
}
final String rawClassName = extractClassName(className);
final PsiFile existing = directory.findFile(rawClassName + ".java");
if (existing instanceof PsiJavaFile) {
final PsiClass[] classes = ((PsiJavaFile)existing).getClasses();
if (classes.length > 0) {
return classes[0];
}
return null;
}
final PsiClass aClass;
if (templateName.equals(DEFAULT_CLASS_TEMPLATE)) {
aClass = JavaDirectoryService.getInstance().createClass(directory, rawClassName);
}
else {
final FileTemplateManager fileTemplateManager = FileTemplateManager.getInstance();
FileTemplate fileTemplate = fileTemplateManager.getJ2eeTemplate(templateName);
LOG.assertTrue(fileTemplate != null, templateName + " not found");
final String text = fileTemplate.getText(attributes);
aClass = JavaCreateFromTemplateHandler.createClassOrInterface(project, directory, text, true, fileTemplate.getExtension());
}
return (PsiClass)JavaCodeStyleManager.getInstance(project).shortenClassReferences(aClass);
}
catch (IOException e) {
throw new IncorrectOperationException(e.toString(), e);
}
}
@NotNull
private static PsiDirectory createParentDirectories(@NotNull PsiDirectory directoryRoot, @NotNull String className) throws IncorrectOperationException {
final PsiPackage currentPackage = JavaDirectoryService.getInstance().getPackage(directoryRoot);
final String packagePrefix = currentPackage == null? null : currentPackage.getQualifiedName() + ".";
final String packageName = extractPackage(packagePrefix != null && className.startsWith(packagePrefix)?
className.substring(packagePrefix.length()) : className);
final StringTokenizer tokenizer = new StringTokenizer(packageName, ".");
while (tokenizer.hasMoreTokens()) {
String packagePart = tokenizer.nextToken();
PsiDirectory subdirectory = directoryRoot.findSubdirectory(packagePart);
if (subdirectory == null) {
directoryRoot.checkCreateSubdirectory(packagePart);
subdirectory = directoryRoot.createSubdirectory(packagePart);
}
directoryRoot = subdirectory;
}
return directoryRoot;
}
@Nullable
public static PsiDirectory getRootDirectory(PsiClass aClass) {
return getSourceRootDirectory(aClass.getContainingFile().getContainingDirectory());
}
@Nullable
private static PsiDirectory getSourceRootDirectory(PsiDirectory directory) {
PsiManager manager = directory.getManager();
DirectoryIndex directoryIndex = DirectoryIndex.getInstance(manager.getProject());
DirectoryInfo info = directoryIndex.getInfoForDirectory(directory.getVirtualFile());
if (info == null || info.sourceRoot == null) return null;
return manager.findDirectory(info.sourceRoot);
}
@Nullable
public static PsiDirectory obtainDirectoryRootForPackage(final Module module, final String packageName) {
final Project project = module.getProject();
GlobalSearchScope scope = GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(module);
final PsiPackage aPackage = JavaPsiFacade.getInstance(project).findPackage(packageName);
if (aPackage != null) {
PsiDirectory[] directories = aPackage.getDirectories(scope);
if (directories.length == 1) return getSourceRootDirectory(directories[0]);
}
final VirtualFile[] sourceRoots = ModuleRootManager.getInstance(module).getSourceRoots();
List<PsiDirectory> directoryList = new ArrayList<PsiDirectory>();
for (VirtualFile sourceRoot : sourceRoots) {
final PsiDirectory directory = PsiManager.getInstance(project).findDirectory(sourceRoot);
directoryList.add(directory);
}
PsiDirectory[] sourceDirectories = directoryList.toArray(new PsiDirectory[directoryList.size()]);
return DirectoryChooserUtil.selectDirectory(project, sourceDirectories, null, File.separatorChar + packageName.replace('.', File.separatorChar));
}
@Nullable
public static PsiDirectory getRoot(Module module, String className) {
String aPackage = extractPackage(className);
PsiManager psiManager = PsiManager.getInstance(module.getProject());
PsiPackage psiPackage = JavaPsiFacade.getInstance(psiManager.getProject()).findPackage(aPackage);
if (psiPackage == null) return null;
PsiDirectory[] directories = psiPackage.getDirectories(GlobalSearchScope.moduleScope(module));
if (directories.length == 0) return null;
return directories[0];
}
public static String extractClassName(String fqName) {
return StringUtil.getShortName(fqName);
}
public static String extractPackage(String fqName) {
int i = fqName.lastIndexOf('.');
return i == -1 ? "" : fqName.substring(0, i);
}
public static String makeFQName(String aPackage, String className) {
String fq = aPackage;
if (!"".equals(aPackage)) {
fq += ".";
}
fq += className;
return fq;
}
@Nullable
public static PsiClass createClassNamed(String newClassName, String templateName, @NotNull PsiDirectory directory) throws IncorrectOperationException {
return createClassNamed(newClassName, FileTemplateManager.getInstance().getDefaultProperties(directory.getProject()), templateName, directory);
}
@Nullable
public static PsiClass createClassNamed(String newClassName, Map classProperties, String templateName, @NotNull PsiDirectory directory)
throws IncorrectOperationException {
Properties defaultProperties = FileTemplateManager.getInstance().getDefaultProperties(directory.getProject());
Properties properties = new Properties(defaultProperties);
properties.putAll(classProperties);
return createClassNamed(newClassName, properties, templateName, directory);
}
@Nullable
private static PsiClass createClassNamed(@Nullable String newClassName,
@NotNull Properties properties,
String templateName,
@NotNull PsiDirectory directory) throws IncorrectOperationException {
if (newClassName == null) {
return null;
}
final String className = extractClassName(newClassName);
properties.setProperty(CLASS_NAME_PROPERTY, className);
properties.setProperty(INTERFACE_NAME_PROPERTY, className);
return createClassFromTemplate(properties, templateName, directory, newClassName);
}
@Nullable
public static PsiClass createClassFromCustomTemplate(@Nullable PsiDirectory classDirectory,
@Nullable final Module module,
final String className,
final String templateName) {
if (classDirectory == null && module != null) {
try {
classDirectory = PackageUtil.findOrCreateDirectoryForPackage(module, "", null, false);
}
catch (IncorrectOperationException e) {
return null;
}
}
if (classDirectory == null) {
return null;
}
try {
final Properties properties = ApplicationManager.getApplication().isUnitTestMode() ?
new Properties() :
FileTemplateManager.getInstance().getDefaultProperties(classDirectory.getProject());
return createClassNamed(className, new Properties(properties), templateName, classDirectory);
}
catch (IncorrectOperationException e) {
LOG.error(e);
return null;
}
}
}
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.psi.util;
import com.intellij.ide.fileTemplates.FileTemplate;
import com.intellij.ide.fileTemplates.FileTemplateManager;
import com.intellij.ide.fileTemplates.JavaCreateFromTemplateHandler;
import com.intellij.ide.util.DirectoryChooserUtil;
import com.intellij.ide.util.PackageUtil;
import com.intellij.openapi.fileTypes.StdFileTypes;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ModuleRootManager;
import com.intellij.openapi.roots.impl.DirectoryIndex;
import com.intellij.openapi.roots.impl.DirectoryInfo;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.JavaCodeStyleManager;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.text.StringTokenizer;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
/**
* author: lesya
*/
public class CreateClassUtil {
private static final Logger LOG = Logger.getInstance("#com.intellij.j2ee.CreateClassUtil");
@NonNls public static final String DEFAULT_CLASS_TEMPLATE = "#DEFAULT_CLASS_TEMPLATE";
@NonNls private static final String DO_NOT_CREATE_CLASS_TEMPLATE = "#DO_NOT_CREATE_CLASS_TEMPLATE";
@NonNls private static final String CLASS_NAME_PROPERTY = "Class_Name";
@NonNls private static final String INTERFACE_NAME_PROPERTY = "Interface_Name";
private CreateClassUtil() {}
@Nullable
private static PsiClass createClassFromTemplate(@NotNull final Properties attributes, @Nullable final String templateName,
@NotNull final PsiDirectory directoryRoot,
@NotNull final String className) throws IncorrectOperationException {
if (templateName == null) return null;
if (templateName.equals(DO_NOT_CREATE_CLASS_TEMPLATE)) return null;
final Project project = directoryRoot.getProject();
try {
final PsiDirectory directory = createParentDirectories(directoryRoot, className);
final PsiFile psiFile = directory.findFile(className + "." + StdFileTypes.JAVA.getDefaultExtension());
if (psiFile != null) {
psiFile.delete();
}
final String rawClassName = extractClassName(className);
final PsiFile existing = directory.findFile(rawClassName + ".java");
if (existing instanceof PsiJavaFile) {
final PsiClass[] classes = ((PsiJavaFile)existing).getClasses();
if (classes.length > 0) {
return classes[0];
}
return null;
}
final PsiClass aClass;
if (templateName.equals(DEFAULT_CLASS_TEMPLATE)) {
aClass = JavaDirectoryService.getInstance().createClass(directory, rawClassName);
}
else {
final FileTemplateManager fileTemplateManager = FileTemplateManager.getInstance();
FileTemplate fileTemplate = fileTemplateManager.getJ2eeTemplate(templateName);
LOG.assertTrue(fileTemplate != null, templateName + " not found");
final String text = fileTemplate.getText(attributes);
aClass = JavaCreateFromTemplateHandler.createClassOrInterface(project, directory, text, true, fileTemplate.getExtension());
}
return (PsiClass)JavaCodeStyleManager.getInstance(project).shortenClassReferences(aClass);
}
catch (IOException e) {
throw new IncorrectOperationException(e.toString(), e);
}
}
@NotNull
private static PsiDirectory createParentDirectories(@NotNull PsiDirectory directoryRoot, @NotNull String className) throws IncorrectOperationException {
final PsiPackage currentPackage = JavaDirectoryService.getInstance().getPackage(directoryRoot);
final String packagePrefix = currentPackage == null? null : currentPackage.getQualifiedName() + ".";
final String packageName = extractPackage(packagePrefix != null && className.startsWith(packagePrefix)?
className.substring(packagePrefix.length()) : className);
final StringTokenizer tokenizer = new StringTokenizer(packageName, ".");
while (tokenizer.hasMoreTokens()) {
String packagePart = tokenizer.nextToken();
PsiDirectory subdirectory = directoryRoot.findSubdirectory(packagePart);
if (subdirectory == null) {
directoryRoot.checkCreateSubdirectory(packagePart);
subdirectory = directoryRoot.createSubdirectory(packagePart);
}
directoryRoot = subdirectory;
}
return directoryRoot;
}
@Nullable
public static PsiDirectory getRootDirectory(PsiClass aClass) {
return getSourceRootDirectory(aClass.getContainingFile().getContainingDirectory());
}
@Nullable
private static PsiDirectory getSourceRootDirectory(PsiDirectory directory) {
PsiManager manager = directory.getManager();
DirectoryIndex directoryIndex = DirectoryIndex.getInstance(manager.getProject());
DirectoryInfo info = directoryIndex.getInfoForDirectory(directory.getVirtualFile());
if (info == null || info.sourceRoot == null) return null;
return manager.findDirectory(info.sourceRoot);
}
@Nullable
public static PsiDirectory obtainDirectoryRootForPackage(final Module module, final String packageName) {
final Project project = module.getProject();
GlobalSearchScope scope = GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(module);
final PsiPackage aPackage = JavaPsiFacade.getInstance(project).findPackage(packageName);
if (aPackage != null) {
PsiDirectory[] directories = aPackage.getDirectories(scope);
if (directories.length == 1) return getSourceRootDirectory(directories[0]);
}
final VirtualFile[] sourceRoots = ModuleRootManager.getInstance(module).getSourceRoots();
List<PsiDirectory> directoryList = new ArrayList<PsiDirectory>();
for (VirtualFile sourceRoot : sourceRoots) {
final PsiDirectory directory = PsiManager.getInstance(project).findDirectory(sourceRoot);
directoryList.add(directory);
}
PsiDirectory[] sourceDirectories = directoryList.toArray(new PsiDirectory[directoryList.size()]);
return DirectoryChooserUtil.selectDirectory(project, sourceDirectories, null, File.separatorChar + packageName.replace('.', File.separatorChar));
}
@Nullable
public static PsiDirectory getRoot(Module module, String className) {
String aPackage = extractPackage(className);
PsiManager psiManager = PsiManager.getInstance(module.getProject());
PsiPackage psiPackage = JavaPsiFacade.getInstance(psiManager.getProject()).findPackage(aPackage);
if (psiPackage == null) return null;
PsiDirectory[] directories = psiPackage.getDirectories(GlobalSearchScope.moduleScope(module));
if (directories.length == 0) return null;
return directories[0];
}
public static String extractClassName(String fqName) {
return StringUtil.getShortName(fqName);
}
public static String extractPackage(String fqName) {
int i = fqName.lastIndexOf('.');
return i == -1 ? "" : fqName.substring(0, i);
}
public static String makeFQName(String aPackage, String className) {
String fq = aPackage;
if (!"".equals(aPackage)) {
fq += ".";
}
fq += className;
return fq;
}
@Nullable
public static PsiClass createClassNamed(String newClassName, String templateName, @NotNull PsiDirectory directory) throws IncorrectOperationException {
return createClassNamed(newClassName, FileTemplateManager.getInstance().getDefaultProperties(directory.getProject()), templateName, directory);
}
@Nullable
public static PsiClass createClassNamed(String newClassName, Map classProperties, String templateName, @NotNull PsiDirectory directory)
throws IncorrectOperationException {
Properties defaultProperties = FileTemplateManager.getInstance().getDefaultProperties(directory.getProject());
Properties properties = new Properties(defaultProperties);
properties.putAll(classProperties);
return createClassNamed(newClassName, properties, templateName, directory);
}
@Nullable
private static PsiClass createClassNamed(@Nullable String newClassName,
@NotNull Properties properties,
String templateName,
@NotNull PsiDirectory directory) throws IncorrectOperationException {
if (newClassName == null) {
return null;
}
final String className = extractClassName(newClassName);
properties.setProperty(CLASS_NAME_PROPERTY, className);
properties.setProperty(INTERFACE_NAME_PROPERTY, className);
return createClassFromTemplate(properties, templateName, directory, newClassName);
}
@Nullable
public static PsiClass createClassFromCustomTemplate(@Nullable PsiDirectory classDirectory,
@Nullable final Module module,
final String className,
final String templateName) {
if (classDirectory == null && module != null) {
try {
classDirectory = PackageUtil.findOrCreateDirectoryForPackage(module, "", null, false);
}
catch (IncorrectOperationException e) {
return null;
}
}
if (classDirectory == null) {
return null;
}
try {
final Properties properties = ApplicationManager.getApplication().isUnitTestMode() ?
new Properties() :
FileTemplateManager.getInstance().getDefaultProperties(classDirectory.getProject());
return createClassNamed(className, new Properties(properties), templateName, classDirectory);
}
catch (IncorrectOperationException e) {
LOG.error(e);
return null;
}
}
}
@@ -1,95 +1,95 @@
/*
* Copyright 2000-2010 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.refactoring.changeSignature;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiMethod;
import com.intellij.psi.PsiParameter;
import com.intellij.psi.PsiTypeElement;
import com.intellij.util.VisibilityUtil;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
public class JavaMethodDescriptor implements MethodDescriptor<ParameterInfoImpl, String> {
private final PsiMethod myMethod;
public JavaMethodDescriptor(PsiMethod method) {
myMethod = method;
}
@Override
public String getName() {
return myMethod.getName();
}
@Override
public List<ParameterInfoImpl> getParameters() {
final ArrayList<ParameterInfoImpl> result = new ArrayList<ParameterInfoImpl>();
final PsiParameter[] parameters = myMethod.getParameterList().getParameters();
for (int i = 0; i < parameters.length; i++) {
PsiParameter parameter = parameters[i];
ParameterInfoImpl info = new ParameterInfoImpl(i, parameter.getName(), parameter.getType());
info.defaultValue = "";
result.add(info);
}
return result;
}
@Override
public String getVisibility() {
return VisibilityUtil.getVisibilityModifier(myMethod.getModifierList());
}
@Override
public PsiMethod getMethod() {
return myMethod;
}
@Override
public int getParametersCount() {
return myMethod.getParameterList().getParametersCount();
}
@Nullable
public String getReturnTypeText() {
final PsiTypeElement typeElement = myMethod.getReturnTypeElement();
return typeElement != null ? typeElement.getText() : null;
}
@Override
public boolean canChangeVisibility() {
PsiClass containingClass = myMethod.getContainingClass();
return containingClass != null && !containingClass.isInterface();
}
@Override
public boolean canChangeParameters() {
return true;
}
@Override
public ReadWriteOption canChangeReturnType() {
return myMethod.isConstructor() ? ReadWriteOption.None : ReadWriteOption.ReadWrite;
}
@Override
public boolean canChangeName() {
return !myMethod.isConstructor();
}
}
/*
* Copyright 2000-2010 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.refactoring.changeSignature;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiMethod;
import com.intellij.psi.PsiParameter;
import com.intellij.psi.PsiTypeElement;
import com.intellij.util.VisibilityUtil;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
public class JavaMethodDescriptor implements MethodDescriptor<ParameterInfoImpl, String> {
private final PsiMethod myMethod;
public JavaMethodDescriptor(PsiMethod method) {
myMethod = method;
}
@Override
public String getName() {
return myMethod.getName();
}
@Override
public List<ParameterInfoImpl> getParameters() {
final ArrayList<ParameterInfoImpl> result = new ArrayList<ParameterInfoImpl>();
final PsiParameter[] parameters = myMethod.getParameterList().getParameters();
for (int i = 0; i < parameters.length; i++) {
PsiParameter parameter = parameters[i];
ParameterInfoImpl info = new ParameterInfoImpl(i, parameter.getName(), parameter.getType());
info.defaultValue = "";
result.add(info);
}
return result;
}
@Override
public String getVisibility() {
return VisibilityUtil.getVisibilityModifier(myMethod.getModifierList());
}
@Override
public PsiMethod getMethod() {
return myMethod;
}
@Override
public int getParametersCount() {
return myMethod.getParameterList().getParametersCount();
}
@Nullable
public String getReturnTypeText() {
final PsiTypeElement typeElement = myMethod.getReturnTypeElement();
return typeElement != null ? typeElement.getText() : null;
}
@Override
public boolean canChangeVisibility() {
PsiClass containingClass = myMethod.getContainingClass();
return containingClass != null && !containingClass.isInterface();
}
@Override
public boolean canChangeParameters() {
return true;
}
@Override
public ReadWriteOption canChangeReturnType() {
return myMethod.isConstructor() ? ReadWriteOption.None : ReadWriteOption.ReadWrite;
}
@Override
public boolean canChangeName() {
return !myMethod.isConstructor();
}
}
File diff suppressed because it is too large Load Diff
@@ -33,10 +33,8 @@ import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleSettings;
@@ -64,7 +62,6 @@ import com.intellij.util.IncorrectOperationException;
import com.intellij.util.Query;
import com.intellij.util.VisibilityUtil;
import com.intellij.util.containers.HashMap;
import com.intellij.util.containers.MultiMap;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -34,7 +34,6 @@ import com.intellij.refactoring.HelpID;
import com.intellij.refactoring.JavaRefactoringSettings;
import com.intellij.refactoring.RefactoringBundle;
import com.intellij.refactoring.listeners.RefactoringElementListener;
import com.intellij.refactoring.util.ConflictsUtil;
import com.intellij.refactoring.util.MoveRenameUsageInfo;
import com.intellij.refactoring.util.RefactoringUIUtil;
import com.intellij.refactoring.util.RefactoringUtil;
@@ -1,358 +1,358 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.refactoring.rename;
import com.intellij.ide.util.SuperMethodWarningUtil;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Pass;
import com.intellij.psi.*;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.PsiElementProcessor;
import com.intellij.psi.search.SearchScope;
import com.intellij.psi.search.searches.ClassInheritorsSearch;
import com.intellij.psi.search.searches.MethodReferencesSearch;
import com.intellij.psi.search.searches.OverridingMethodsSearch;
import com.intellij.psi.util.MethodSignature;
import com.intellij.psi.util.MethodSignatureUtil;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.TypeConversionUtil;
import com.intellij.refactoring.HelpID;
import com.intellij.refactoring.JavaRefactoringSettings;
import com.intellij.refactoring.RefactoringBundle;
import com.intellij.refactoring.listeners.RefactoringElementListener;
import com.intellij.refactoring.util.ConflictsUtil;
import com.intellij.refactoring.util.MoveRenameUsageInfo;
import com.intellij.refactoring.util.RefactoringUIUtil;
import com.intellij.refactoring.util.RefactoringUtil;
import com.intellij.usageView.UsageInfo;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.Processor;
import com.intellij.util.containers.HashSet;
import com.intellij.util.containers.MultiMap;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
public class RenameJavaMethodProcessor extends RenameJavaMemberProcessor {
private static final Logger LOG = Logger.getInstance("#com.intellij.refactoring.rename.RenameJavaMethodProcessor");
public boolean canProcessElement(@NotNull final PsiElement element) {
return element instanceof PsiMethod;
}
public void renameElement(final PsiElement psiElement,
final String newName,
final UsageInfo[] usages, final RefactoringElementListener listener) throws IncorrectOperationException {
PsiMethod method = (PsiMethod) psiElement;
Set<PsiMethod> methodAndOverriders = new HashSet<PsiMethod>();
Set<PsiClass> containingClasses = new HashSet<PsiClass>();
LinkedHashSet<PsiElement> renamedReferences = new LinkedHashSet<PsiElement>();
List<MemberHidesOuterMemberUsageInfo> outerHides = new ArrayList<MemberHidesOuterMemberUsageInfo>();
List<MemberHidesStaticImportUsageInfo> staticImportHides = new ArrayList<MemberHidesStaticImportUsageInfo>();
methodAndOverriders.add(method);
containingClasses.add(method.getContainingClass());
// do actual rename of overriding/implementing methods and of references to all them
for (UsageInfo usage : usages) {
PsiElement element = usage.getElement();
if (element == null) continue;
if (usage instanceof MemberHidesStaticImportUsageInfo) {
staticImportHides.add((MemberHidesStaticImportUsageInfo)usage);
} else if (usage instanceof MemberHidesOuterMemberUsageInfo) {
PsiJavaCodeReferenceElement collidingRef = (PsiJavaCodeReferenceElement)element;
PsiMethod resolved = (PsiMethod)collidingRef.resolve();
outerHides.add(new MemberHidesOuterMemberUsageInfo(element, resolved));
}
else if (!(element instanceof PsiMethod)) {
final PsiReference ref;
if (usage instanceof MoveRenameUsageInfo) {
ref = usage.getReference();
}
else {
ref = element.getReference();
}
if (ref != null) {
PsiElement e = processRef(ref, newName);
if (e != null) {
renamedReferences.add(e);
}
}
}
else {
PsiMethod overrider = (PsiMethod)element;
methodAndOverriders.add(overrider);
containingClasses.add(overrider.getContainingClass());
}
}
// do actual rename of method
method.setName(newName);
for (UsageInfo usage : usages) {
PsiElement element = usage.getElement();
if (element instanceof PsiMethod) {
((PsiMethod)element).setName(newName);
}
}
listener.elementRenamed(method);
for (PsiElement element: renamedReferences) {
fixNameCollisionsWithInnerClassMethod(element, newName, methodAndOverriders, containingClasses,
method.hasModifierProperty(PsiModifier.STATIC));
}
qualifyOuterMemberReferences(outerHides);
qualifyStaticImportReferences(staticImportHides);
}
/**
* handles rename of refs
* @param ref
* @param newName
* @return
*/
@Nullable
protected PsiElement processRef(PsiReference ref, String newName) {
return ref.handleElementRename(newName);
}
private static void fixNameCollisionsWithInnerClassMethod(final PsiElement element, final String newName,
final Set<PsiMethod> methodAndOverriders, final Set<PsiClass> containingClasses,
final boolean isStatic) throws IncorrectOperationException {
if (!(element instanceof PsiReferenceExpression)) return;
PsiElement elem = ((PsiReferenceExpression)element).resolve();
if (elem instanceof PsiMethod) {
PsiMethod actualMethod = (PsiMethod) elem;
if (!methodAndOverriders.contains(actualMethod)) {
PsiClass outerClass = PsiTreeUtil.getParentOfType(element, PsiClass.class);
while (outerClass != null) {
if (containingClasses.contains(outerClass)) {
qualifyMember(element, newName, outerClass, isStatic);
break;
}
outerClass = PsiTreeUtil.getParentOfType(outerClass, PsiClass.class);
}
}
}
}
@NotNull
public Collection<PsiReference> findReferences(final PsiElement element) {
GlobalSearchScope projectScope = GlobalSearchScope.projectScope(element.getProject());
return MethodReferencesSearch.search((PsiMethod)element, projectScope, true).findAll();
}
public void findCollisions(final PsiElement element, final String newName, final Map<? extends PsiElement, String> allRenames,
final List<UsageInfo> result) {
final PsiMethod methodToRename = (PsiMethod)element;
findSubmemberHidesMemberCollisions(methodToRename, newName, result);
findMemberHidesOuterMemberCollisions((PsiMethod) element, newName, result);
findCollisionsAgainstNewName(methodToRename, newName, result);
findHidingMethodWithOtherSignature(methodToRename, newName, result);
final PsiClass containingClass = methodToRename.getContainingClass();
if (containingClass != null) {
final PsiMethod patternMethod = (PsiMethod)methodToRename.copy();
try {
patternMethod.setName(newName);
final PsiMethod methodInBaseClass = containingClass.findMethodBySignature(patternMethod, true);
if (methodInBaseClass != null && methodInBaseClass.getContainingClass() != containingClass) {
if (methodInBaseClass.hasModifierProperty(PsiModifier.FINAL)) {
result.add(new UnresolvableCollisionUsageInfo(methodInBaseClass, methodToRename) {
@Override
public String getDescription() {
return "Renaming method will override final \"" + RefactoringUIUtil.getDescription(methodInBaseClass, true) + "\"";
}
});
}
}
}
catch (IncorrectOperationException e) {
LOG.error(e);
}
}
}
private void findHidingMethodWithOtherSignature(final PsiMethod methodToRename, final String newName, final List<UsageInfo> result) {
final PsiClass containingClass = methodToRename.getContainingClass();
if (containingClass != null) {
final PsiMethod prototype = getPrototypeWithNewName(methodToRename, newName);
if (prototype == null || containingClass.findMethodBySignature(prototype, true) != null) return;
final PsiMethod[] methodsByName = containingClass.findMethodsByName(newName, true);
if (methodsByName.length > 0) {
for (UsageInfo info : result) {
final PsiElement element = info.getElement();
if (element instanceof PsiReferenceExpression) {
if (((PsiReferenceExpression)element).resolve() == methodToRename) {
final PsiMethodCallExpression copy = (PsiMethodCallExpression)JavaPsiFacade.getElementFactory(element.getProject())
.createExpressionFromText(element.getParent().getText(), element);
final PsiReferenceExpression expression = (PsiReferenceExpression)processRef(copy.getMethodExpression(), newName);
if (expression == null) continue;
final JavaResolveResult resolveResult = expression.advancedResolve(true);
final PsiMember resolveResultElement = (PsiMember)resolveResult.getElement();
if (resolveResult.isValidResult() && resolveResultElement != null) {
result.add(new UnresolvableCollisionUsageInfo(element, methodToRename) {
@Override
public String getDescription() {
return "Method call would be linked to \"" + RefactoringUIUtil.getDescription(resolveResultElement, true) +
"\" after rename";
}
});
break;
}
}
}
}
}
}
}
private static PsiMethod getPrototypeWithNewName(PsiMethod methodToRename, String newName) {
final PsiMethod prototype = (PsiMethod)methodToRename.copy();
try {
prototype.setName(newName);
}
catch (IncorrectOperationException e) {
LOG.error(e);
return null;
}
return prototype;
}
public void findExistingNameConflicts(final PsiElement element, final String newName, final MultiMap<PsiElement, String> conflicts) {
if (element instanceof PsiCompiledElement) return;
final PsiMethod refactoredMethod = (PsiMethod)element;
if (newName.equals(refactoredMethod.getName())) return;
final PsiMethod prototype = getPrototypeWithNewName(refactoredMethod, newName);
if (prototype == null) return;
ConflictsUtil.checkMethodConflicts(
refactoredMethod.getContainingClass(),
refactoredMethod,
prototype,
conflicts);
}
@Override
public void prepareRenaming(PsiElement element, final String newName, final Map<PsiElement, String> allRenames, SearchScope scope) {
final PsiMethod method = (PsiMethod) element;
OverridingMethodsSearch.search(method, scope, true).forEach(new Processor<PsiMethod>() {
public boolean process(PsiMethod overrider) {
final String overriderName = overrider.getName();
final String baseName = method.getName();
final String newOverriderName = RefactoringUtil.suggestNewOverriderName(overriderName, baseName, newName);
if (newOverriderName != null) {
RenameProcessor.assertNonCompileElement(overrider);
allRenames.put(overrider, newOverriderName);
}
return true;
}
});
}
@NonNls
public String getHelpID(final PsiElement element) {
return HelpID.RENAME_METHOD;
}
public boolean isToSearchInComments(final PsiElement psiElement) {
return JavaRefactoringSettings.getInstance().RENAME_SEARCH_IN_COMMENTS_FOR_METHOD;
}
public void setToSearchInComments(final PsiElement element, final boolean enabled) {
JavaRefactoringSettings.getInstance().RENAME_SEARCH_IN_COMMENTS_FOR_METHOD = enabled;
}
@Nullable
public PsiElement substituteElementToRename(PsiElement element, Editor editor) {
PsiMethod psiMethod = (PsiMethod)element;
if (psiMethod.isConstructor()) {
PsiClass containingClass = psiMethod.getContainingClass();
if (containingClass == null) return null;
if (Comparing.strEqual(psiMethod.getName(), containingClass.getName())) {
element = containingClass;
if (!PsiElementRenameHandler.canRename(element.getProject(), editor, element)) {
return null;
}
return element;
}
}
return SuperMethodWarningUtil.checkSuperMethod(psiMethod, RefactoringBundle.message("to.rename"));
}
@Override
public void substituteElementToRename(@NotNull PsiElement element,
@NotNull final Editor editor,
@NotNull final Pass<PsiElement> renameCallback) {
final PsiMethod psiMethod = (PsiMethod)element;
if (psiMethod.isConstructor()) {
final PsiClass containingClass = psiMethod.getContainingClass();
if (containingClass == null) return;
if (!Comparing.strEqual(psiMethod.getName(), containingClass.getName())) {
renameCallback.pass(psiMethod);
return;
}
super.substituteElementToRename(element, editor, renameCallback);
}
else {
SuperMethodWarningUtil.checkSuperMethod(psiMethod, "Rename", new PsiElementProcessor<PsiMethod>() {
@Override
public boolean execute(@NotNull PsiMethod method) {
if (!PsiElementRenameHandler.canRename(method.getProject(), editor, method)) return false;
renameCallback.pass(method);
return false;
}
}, editor);
}
}
private static void findSubmemberHidesMemberCollisions(final PsiMethod method, final String newName, final List<UsageInfo> result) {
final PsiClass containingClass = method.getContainingClass();
if (containingClass == null) return;
if (method.hasModifierProperty(PsiModifier.PRIVATE)) return;
Collection<PsiClass> inheritors = ClassInheritorsSearch.search(containingClass, true).findAll();
MethodSignature oldSignature = method.getSignature(PsiSubstitutor.EMPTY);
MethodSignature newSignature = MethodSignatureUtil.createMethodSignature(newName, oldSignature.getParameterTypes(),
oldSignature.getTypeParameters(),
oldSignature.getSubstitutor(),
method.isConstructor());
for (PsiClass inheritor : inheritors) {
PsiSubstitutor superSubstitutor = TypeConversionUtil.getSuperClassSubstitutor(containingClass, inheritor, PsiSubstitutor.EMPTY);
final PsiMethod[] methodsByName = inheritor.findMethodsByName(newName, false);
for (PsiMethod conflictingMethod : methodsByName) {
if (newSignature.equals(conflictingMethod.getSignature(superSubstitutor))) {
result.add(new SubmemberHidesMemberUsageInfo(conflictingMethod, method));
break;
}
}
}
}
public boolean isToSearchForTextOccurrences(final PsiElement element) {
return JavaRefactoringSettings.getInstance().RENAME_SEARCH_FOR_TEXT_FOR_METHOD;
}
public void setToSearchForTextOccurrences(final PsiElement element, final boolean enabled) {
JavaRefactoringSettings.getInstance().RENAME_SEARCH_FOR_TEXT_FOR_METHOD = enabled;
}
}
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.refactoring.rename;
import com.intellij.ide.util.SuperMethodWarningUtil;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Pass;
import com.intellij.psi.*;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.PsiElementProcessor;
import com.intellij.psi.search.SearchScope;
import com.intellij.psi.search.searches.ClassInheritorsSearch;
import com.intellij.psi.search.searches.MethodReferencesSearch;
import com.intellij.psi.search.searches.OverridingMethodsSearch;
import com.intellij.psi.util.MethodSignature;
import com.intellij.psi.util.MethodSignatureUtil;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.TypeConversionUtil;
import com.intellij.refactoring.HelpID;
import com.intellij.refactoring.JavaRefactoringSettings;
import com.intellij.refactoring.RefactoringBundle;
import com.intellij.refactoring.listeners.RefactoringElementListener;
import com.intellij.refactoring.util.ConflictsUtil;
import com.intellij.refactoring.util.MoveRenameUsageInfo;
import com.intellij.refactoring.util.RefactoringUIUtil;
import com.intellij.refactoring.util.RefactoringUtil;
import com.intellij.usageView.UsageInfo;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.Processor;
import com.intellij.util.containers.HashSet;
import com.intellij.util.containers.MultiMap;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
public class RenameJavaMethodProcessor extends RenameJavaMemberProcessor {
private static final Logger LOG = Logger.getInstance("#com.intellij.refactoring.rename.RenameJavaMethodProcessor");
public boolean canProcessElement(@NotNull final PsiElement element) {
return element instanceof PsiMethod;
}
public void renameElement(final PsiElement psiElement,
final String newName,
final UsageInfo[] usages, final RefactoringElementListener listener) throws IncorrectOperationException {
PsiMethod method = (PsiMethod) psiElement;
Set<PsiMethod> methodAndOverriders = new HashSet<PsiMethod>();
Set<PsiClass> containingClasses = new HashSet<PsiClass>();
LinkedHashSet<PsiElement> renamedReferences = new LinkedHashSet<PsiElement>();
List<MemberHidesOuterMemberUsageInfo> outerHides = new ArrayList<MemberHidesOuterMemberUsageInfo>();
List<MemberHidesStaticImportUsageInfo> staticImportHides = new ArrayList<MemberHidesStaticImportUsageInfo>();
methodAndOverriders.add(method);
containingClasses.add(method.getContainingClass());
// do actual rename of overriding/implementing methods and of references to all them
for (UsageInfo usage : usages) {
PsiElement element = usage.getElement();
if (element == null) continue;
if (usage instanceof MemberHidesStaticImportUsageInfo) {
staticImportHides.add((MemberHidesStaticImportUsageInfo)usage);
} else if (usage instanceof MemberHidesOuterMemberUsageInfo) {
PsiJavaCodeReferenceElement collidingRef = (PsiJavaCodeReferenceElement)element;
PsiMethod resolved = (PsiMethod)collidingRef.resolve();
outerHides.add(new MemberHidesOuterMemberUsageInfo(element, resolved));
}
else if (!(element instanceof PsiMethod)) {
final PsiReference ref;
if (usage instanceof MoveRenameUsageInfo) {
ref = usage.getReference();
}
else {
ref = element.getReference();
}
if (ref != null) {
PsiElement e = processRef(ref, newName);
if (e != null) {
renamedReferences.add(e);
}
}
}
else {
PsiMethod overrider = (PsiMethod)element;
methodAndOverriders.add(overrider);
containingClasses.add(overrider.getContainingClass());
}
}
// do actual rename of method
method.setName(newName);
for (UsageInfo usage : usages) {
PsiElement element = usage.getElement();
if (element instanceof PsiMethod) {
((PsiMethod)element).setName(newName);
}
}
listener.elementRenamed(method);
for (PsiElement element: renamedReferences) {
fixNameCollisionsWithInnerClassMethod(element, newName, methodAndOverriders, containingClasses,
method.hasModifierProperty(PsiModifier.STATIC));
}
qualifyOuterMemberReferences(outerHides);
qualifyStaticImportReferences(staticImportHides);
}
/**
* handles rename of refs
* @param ref
* @param newName
* @return
*/
@Nullable
protected PsiElement processRef(PsiReference ref, String newName) {
return ref.handleElementRename(newName);
}
private static void fixNameCollisionsWithInnerClassMethod(final PsiElement element, final String newName,
final Set<PsiMethod> methodAndOverriders, final Set<PsiClass> containingClasses,
final boolean isStatic) throws IncorrectOperationException {
if (!(element instanceof PsiReferenceExpression)) return;
PsiElement elem = ((PsiReferenceExpression)element).resolve();
if (elem instanceof PsiMethod) {
PsiMethod actualMethod = (PsiMethod) elem;
if (!methodAndOverriders.contains(actualMethod)) {
PsiClass outerClass = PsiTreeUtil.getParentOfType(element, PsiClass.class);
while (outerClass != null) {
if (containingClasses.contains(outerClass)) {
qualifyMember(element, newName, outerClass, isStatic);
break;
}
outerClass = PsiTreeUtil.getParentOfType(outerClass, PsiClass.class);
}
}
}
}
@NotNull
public Collection<PsiReference> findReferences(final PsiElement element) {
GlobalSearchScope projectScope = GlobalSearchScope.projectScope(element.getProject());
return MethodReferencesSearch.search((PsiMethod)element, projectScope, true).findAll();
}
public void findCollisions(final PsiElement element, final String newName, final Map<? extends PsiElement, String> allRenames,
final List<UsageInfo> result) {
final PsiMethod methodToRename = (PsiMethod)element;
findSubmemberHidesMemberCollisions(methodToRename, newName, result);
findMemberHidesOuterMemberCollisions((PsiMethod) element, newName, result);
findCollisionsAgainstNewName(methodToRename, newName, result);
findHidingMethodWithOtherSignature(methodToRename, newName, result);
final PsiClass containingClass = methodToRename.getContainingClass();
if (containingClass != null) {
final PsiMethod patternMethod = (PsiMethod)methodToRename.copy();
try {
patternMethod.setName(newName);
final PsiMethod methodInBaseClass = containingClass.findMethodBySignature(patternMethod, true);
if (methodInBaseClass != null && methodInBaseClass.getContainingClass() != containingClass) {
if (methodInBaseClass.hasModifierProperty(PsiModifier.FINAL)) {
result.add(new UnresolvableCollisionUsageInfo(methodInBaseClass, methodToRename) {
@Override
public String getDescription() {
return "Renaming method will override final \"" + RefactoringUIUtil.getDescription(methodInBaseClass, true) + "\"";
}
});
}
}
}
catch (IncorrectOperationException e) {
LOG.error(e);
}
}
}
private void findHidingMethodWithOtherSignature(final PsiMethod methodToRename, final String newName, final List<UsageInfo> result) {
final PsiClass containingClass = methodToRename.getContainingClass();
if (containingClass != null) {
final PsiMethod prototype = getPrototypeWithNewName(methodToRename, newName);
if (prototype == null || containingClass.findMethodBySignature(prototype, true) != null) return;
final PsiMethod[] methodsByName = containingClass.findMethodsByName(newName, true);
if (methodsByName.length > 0) {
for (UsageInfo info : result) {
final PsiElement element = info.getElement();
if (element instanceof PsiReferenceExpression) {
if (((PsiReferenceExpression)element).resolve() == methodToRename) {
final PsiMethodCallExpression copy = (PsiMethodCallExpression)JavaPsiFacade.getElementFactory(element.getProject())
.createExpressionFromText(element.getParent().getText(), element);
final PsiReferenceExpression expression = (PsiReferenceExpression)processRef(copy.getMethodExpression(), newName);
if (expression == null) continue;
final JavaResolveResult resolveResult = expression.advancedResolve(true);
final PsiMember resolveResultElement = (PsiMember)resolveResult.getElement();
if (resolveResult.isValidResult() && resolveResultElement != null) {
result.add(new UnresolvableCollisionUsageInfo(element, methodToRename) {
@Override
public String getDescription() {
return "Method call would be linked to \"" + RefactoringUIUtil.getDescription(resolveResultElement, true) +
"\" after rename";
}
});
break;
}
}
}
}
}
}
}
private static PsiMethod getPrototypeWithNewName(PsiMethod methodToRename, String newName) {
final PsiMethod prototype = (PsiMethod)methodToRename.copy();
try {
prototype.setName(newName);
}
catch (IncorrectOperationException e) {
LOG.error(e);
return null;
}
return prototype;
}
public void findExistingNameConflicts(final PsiElement element, final String newName, final MultiMap<PsiElement, String> conflicts) {
if (element instanceof PsiCompiledElement) return;
final PsiMethod refactoredMethod = (PsiMethod)element;
if (newName.equals(refactoredMethod.getName())) return;
final PsiMethod prototype = getPrototypeWithNewName(refactoredMethod, newName);
if (prototype == null) return;
ConflictsUtil.checkMethodConflicts(
refactoredMethod.getContainingClass(),
refactoredMethod,
prototype,
conflicts);
}
@Override
public void prepareRenaming(PsiElement element, final String newName, final Map<PsiElement, String> allRenames, SearchScope scope) {
final PsiMethod method = (PsiMethod) element;
OverridingMethodsSearch.search(method, scope, true).forEach(new Processor<PsiMethod>() {
public boolean process(PsiMethod overrider) {
final String overriderName = overrider.getName();
final String baseName = method.getName();
final String newOverriderName = RefactoringUtil.suggestNewOverriderName(overriderName, baseName, newName);
if (newOverriderName != null) {
RenameProcessor.assertNonCompileElement(overrider);
allRenames.put(overrider, newOverriderName);
}
return true;
}
});
}
@NonNls
public String getHelpID(final PsiElement element) {
return HelpID.RENAME_METHOD;
}
public boolean isToSearchInComments(final PsiElement psiElement) {
return JavaRefactoringSettings.getInstance().RENAME_SEARCH_IN_COMMENTS_FOR_METHOD;
}
public void setToSearchInComments(final PsiElement element, final boolean enabled) {
JavaRefactoringSettings.getInstance().RENAME_SEARCH_IN_COMMENTS_FOR_METHOD = enabled;
}
@Nullable
public PsiElement substituteElementToRename(PsiElement element, Editor editor) {
PsiMethod psiMethod = (PsiMethod)element;
if (psiMethod.isConstructor()) {
PsiClass containingClass = psiMethod.getContainingClass();
if (containingClass == null) return null;
if (Comparing.strEqual(psiMethod.getName(), containingClass.getName())) {
element = containingClass;
if (!PsiElementRenameHandler.canRename(element.getProject(), editor, element)) {
return null;
}
return element;
}
}
return SuperMethodWarningUtil.checkSuperMethod(psiMethod, RefactoringBundle.message("to.rename"));
}
@Override
public void substituteElementToRename(@NotNull PsiElement element,
@NotNull final Editor editor,
@NotNull final Pass<PsiElement> renameCallback) {
final PsiMethod psiMethod = (PsiMethod)element;
if (psiMethod.isConstructor()) {
final PsiClass containingClass = psiMethod.getContainingClass();
if (containingClass == null) return;
if (!Comparing.strEqual(psiMethod.getName(), containingClass.getName())) {
renameCallback.pass(psiMethod);
return;
}
super.substituteElementToRename(element, editor, renameCallback);
}
else {
SuperMethodWarningUtil.checkSuperMethod(psiMethod, "Rename", new PsiElementProcessor<PsiMethod>() {
@Override
public boolean execute(@NotNull PsiMethod method) {
if (!PsiElementRenameHandler.canRename(method.getProject(), editor, method)) return false;
renameCallback.pass(method);
return false;
}
}, editor);
}
}
private static void findSubmemberHidesMemberCollisions(final PsiMethod method, final String newName, final List<UsageInfo> result) {
final PsiClass containingClass = method.getContainingClass();
if (containingClass == null) return;
if (method.hasModifierProperty(PsiModifier.PRIVATE)) return;
Collection<PsiClass> inheritors = ClassInheritorsSearch.search(containingClass, true).findAll();
MethodSignature oldSignature = method.getSignature(PsiSubstitutor.EMPTY);
MethodSignature newSignature = MethodSignatureUtil.createMethodSignature(newName, oldSignature.getParameterTypes(),
oldSignature.getTypeParameters(),
oldSignature.getSubstitutor(),
method.isConstructor());
for (PsiClass inheritor : inheritors) {
PsiSubstitutor superSubstitutor = TypeConversionUtil.getSuperClassSubstitutor(containingClass, inheritor, PsiSubstitutor.EMPTY);
final PsiMethod[] methodsByName = inheritor.findMethodsByName(newName, false);
for (PsiMethod conflictingMethod : methodsByName) {
if (newSignature.equals(conflictingMethod.getSignature(superSubstitutor))) {
result.add(new SubmemberHidesMemberUsageInfo(conflictingMethod, method));
break;
}
}
}
}
public boolean isToSearchForTextOccurrences(final PsiElement element) {
return JavaRefactoringSettings.getInstance().RENAME_SEARCH_FOR_TEXT_FOR_METHOD;
}
public void setToSearchForTextOccurrences(final PsiElement element, final boolean enabled) {
JavaRefactoringSettings.getInstance().RENAME_SEARCH_FOR_TEXT_FOR_METHOD = enabled;
}
}
@@ -1,38 +1,38 @@
/*
* Copyright 2000-2011 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.refactoring.ui;
import com.intellij.psi.PsiModifier;
import static com.intellij.util.VisibilityUtil.toPresentableText;
/**
* @author Konstantin Bulenkov
*/
public class JavaComboBoxVisibilityPanel extends ComboBoxVisibilityPanel<String> implements PsiModifier {
private static final String[] MODIFIERS = {PRIVATE, PACKAGE_LOCAL, PROTECTED, PUBLIC};
private static final String[] PRESENTABLE_NAMES = {
toPresentableText(PRIVATE),
toPresentableText(PACKAGE_LOCAL),
toPresentableText(PROTECTED),
toPresentableText(PUBLIC)
};
public JavaComboBoxVisibilityPanel() {
super(MODIFIERS, PRESENTABLE_NAMES);
}
}
/*
* Copyright 2000-2011 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.refactoring.ui;
import com.intellij.psi.PsiModifier;
import static com.intellij.util.VisibilityUtil.toPresentableText;
/**
* @author Konstantin Bulenkov
*/
public class JavaComboBoxVisibilityPanel extends ComboBoxVisibilityPanel<String> implements PsiModifier {
private static final String[] MODIFIERS = {PRIVATE, PACKAGE_LOCAL, PROTECTED, PUBLIC};
private static final String[] PRESENTABLE_NAMES = {
toPresentableText(PRIVATE),
toPresentableText(PACKAGE_LOCAL),
toPresentableText(PROTECTED),
toPresentableText(PUBLIC)
};
public JavaComboBoxVisibilityPanel() {
super(MODIFIERS, PRESENTABLE_NAMES);
}
}
@@ -1,165 +1,165 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Created by IntelliJ IDEA.
* User: dsl
* Date: 07.06.2002
* Time: 18:16:19
* To change template for new class use
* Code Style | Class Templates options (Tools | IDE Options).
*/
package com.intellij.refactoring.ui;
import com.intellij.psi.PsiModifier;
import com.intellij.refactoring.RefactoringBundle;
import com.intellij.util.VisibilityUtil;
import com.intellij.ui.IdeBorderFactory;
import com.intellij.util.ui.UIUtil;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
public class JavaVisibilityPanel extends VisibilityPanelBase<String> {
private JRadioButton myRbAsIs;
private JRadioButton myRbEscalate;
private final JRadioButton myRbPrivate;
private final JRadioButton myRbProtected;
private final JRadioButton myRbPackageLocal;
private final JRadioButton myRbPublic;
public JavaVisibilityPanel(boolean hasAsIs, final boolean hasEscalate) {
setBorder(IdeBorderFactory.createTitledBorder(RefactoringBundle.message("visibility.border.title"), true,
new Insets(IdeBorderFactory.TITLED_BORDER_TOP_INSET,
UIUtil.DEFAULT_HGAP,
IdeBorderFactory.TITLED_BORDER_BOTTOM_INSET,
IdeBorderFactory.TITLED_BORDER_RIGHT_INSET)));
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
ButtonGroup bg = new ButtonGroup();
ItemListener listener = new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
myEventDispatcher.getMulticaster().stateChanged(new ChangeEvent(this));
}
}
};
if (hasEscalate) {
myRbEscalate = new JRadioButton();
myRbEscalate.setText(RefactoringBundle.getEscalateVisibility());
myRbEscalate.addItemListener(listener);
add(myRbEscalate);
bg.add(myRbEscalate);
}
if (hasAsIs) {
myRbAsIs = new JRadioButton();
myRbAsIs.setText(RefactoringBundle.getVisibilityAsIs());
myRbAsIs.addItemListener(listener);
add(myRbAsIs);
bg.add(myRbAsIs);
}
myRbPrivate = new JRadioButton();
myRbPrivate.setText(RefactoringBundle.getVisibilityPrivate());
myRbPrivate.addItemListener(listener);
myRbPrivate.setFocusable(false);
add(myRbPrivate);
bg.add(myRbPrivate);
myRbPackageLocal = new JRadioButton();
myRbPackageLocal.setText(RefactoringBundle.getVisibilityPackageLocal());
myRbPackageLocal.addItemListener(listener);
myRbPackageLocal.setFocusable(false);
add(myRbPackageLocal);
bg.add(myRbPackageLocal);
myRbProtected = new JRadioButton();
myRbProtected.setText(RefactoringBundle.getVisibilityProtected());
myRbProtected.addItemListener(listener);
myRbProtected.setFocusable(false);
add(myRbProtected);
bg.add(myRbProtected);
myRbPublic = new JRadioButton();
myRbPublic.setText(RefactoringBundle.getVisibilityPublic());
myRbPublic.addItemListener(listener);
myRbPublic.setFocusable(false);
add(myRbPublic);
bg.add(myRbPublic);
}
public String getVisibility() {
if (myRbPublic.isSelected()) {
return PsiModifier.PUBLIC;
}
if (myRbPackageLocal.isSelected()) {
return PsiModifier.PACKAGE_LOCAL;
}
if (myRbProtected.isSelected()) {
return PsiModifier.PROTECTED;
}
if (myRbPrivate.isSelected()) {
return PsiModifier.PRIVATE;
}
if (myRbEscalate != null && myRbEscalate.isSelected()) {
return VisibilityUtil.ESCALATE_VISIBILITY;
}
return null;
}
public void setVisibility(String visibility) {
if (PsiModifier.PUBLIC.equals(visibility)) {
myRbPublic.setSelected(true);
}
else if (PsiModifier.PROTECTED.equals(visibility)) {
myRbProtected.setSelected(true);
}
else if (PsiModifier.PACKAGE_LOCAL.equals(visibility)) {
myRbPackageLocal.setSelected(true);
}
else if (PsiModifier.PRIVATE.equals(visibility)) {
myRbPrivate.setSelected(true);
}
else if (myRbEscalate != null) {
myRbEscalate.setSelected(true);
}
else if (myRbAsIs != null) {
myRbAsIs.setSelected(true);
}
}
public void disableAllButPublic() {
myRbPrivate.setEnabled(false);
myRbProtected.setEnabled(false);
myRbPackageLocal.setEnabled(false);
if (myRbEscalate != null) {
myRbEscalate.setEnabled(false);
}
if (myRbAsIs != null) {
myRbAsIs.setEnabled(false);
}
myRbPublic.setEnabled(true);
myRbPublic.setSelected(true);
}
}
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Created by IntelliJ IDEA.
* User: dsl
* Date: 07.06.2002
* Time: 18:16:19
* To change template for new class use
* Code Style | Class Templates options (Tools | IDE Options).
*/
package com.intellij.refactoring.ui;
import com.intellij.psi.PsiModifier;
import com.intellij.refactoring.RefactoringBundle;
import com.intellij.util.VisibilityUtil;
import com.intellij.ui.IdeBorderFactory;
import com.intellij.util.ui.UIUtil;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
public class JavaVisibilityPanel extends VisibilityPanelBase<String> {
private JRadioButton myRbAsIs;
private JRadioButton myRbEscalate;
private final JRadioButton myRbPrivate;
private final JRadioButton myRbProtected;
private final JRadioButton myRbPackageLocal;
private final JRadioButton myRbPublic;
public JavaVisibilityPanel(boolean hasAsIs, final boolean hasEscalate) {
setBorder(IdeBorderFactory.createTitledBorder(RefactoringBundle.message("visibility.border.title"), true,
new Insets(IdeBorderFactory.TITLED_BORDER_TOP_INSET,
UIUtil.DEFAULT_HGAP,
IdeBorderFactory.TITLED_BORDER_BOTTOM_INSET,
IdeBorderFactory.TITLED_BORDER_RIGHT_INSET)));
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
ButtonGroup bg = new ButtonGroup();
ItemListener listener = new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
myEventDispatcher.getMulticaster().stateChanged(new ChangeEvent(this));
}
}
};
if (hasEscalate) {
myRbEscalate = new JRadioButton();
myRbEscalate.setText(RefactoringBundle.getEscalateVisibility());
myRbEscalate.addItemListener(listener);
add(myRbEscalate);
bg.add(myRbEscalate);
}
if (hasAsIs) {
myRbAsIs = new JRadioButton();
myRbAsIs.setText(RefactoringBundle.getVisibilityAsIs());
myRbAsIs.addItemListener(listener);
add(myRbAsIs);
bg.add(myRbAsIs);
}
myRbPrivate = new JRadioButton();
myRbPrivate.setText(RefactoringBundle.getVisibilityPrivate());
myRbPrivate.addItemListener(listener);
myRbPrivate.setFocusable(false);
add(myRbPrivate);
bg.add(myRbPrivate);
myRbPackageLocal = new JRadioButton();
myRbPackageLocal.setText(RefactoringBundle.getVisibilityPackageLocal());
myRbPackageLocal.addItemListener(listener);
myRbPackageLocal.setFocusable(false);
add(myRbPackageLocal);
bg.add(myRbPackageLocal);
myRbProtected = new JRadioButton();
myRbProtected.setText(RefactoringBundle.getVisibilityProtected());
myRbProtected.addItemListener(listener);
myRbProtected.setFocusable(false);
add(myRbProtected);
bg.add(myRbProtected);
myRbPublic = new JRadioButton();
myRbPublic.setText(RefactoringBundle.getVisibilityPublic());
myRbPublic.addItemListener(listener);
myRbPublic.setFocusable(false);
add(myRbPublic);
bg.add(myRbPublic);
}
public String getVisibility() {
if (myRbPublic.isSelected()) {
return PsiModifier.PUBLIC;
}
if (myRbPackageLocal.isSelected()) {
return PsiModifier.PACKAGE_LOCAL;
}
if (myRbProtected.isSelected()) {
return PsiModifier.PROTECTED;
}
if (myRbPrivate.isSelected()) {
return PsiModifier.PRIVATE;
}
if (myRbEscalate != null && myRbEscalate.isSelected()) {
return VisibilityUtil.ESCALATE_VISIBILITY;
}
return null;
}
public void setVisibility(String visibility) {
if (PsiModifier.PUBLIC.equals(visibility)) {
myRbPublic.setSelected(true);
}
else if (PsiModifier.PROTECTED.equals(visibility)) {
myRbProtected.setSelected(true);
}
else if (PsiModifier.PACKAGE_LOCAL.equals(visibility)) {
myRbPackageLocal.setSelected(true);
}
else if (PsiModifier.PRIVATE.equals(visibility)) {
myRbPrivate.setSelected(true);
}
else if (myRbEscalate != null) {
myRbEscalate.setSelected(true);
}
else if (myRbAsIs != null) {
myRbAsIs.setSelected(true);
}
}
public void disableAllButPublic() {
myRbPrivate.setEnabled(false);
myRbProtected.setEnabled(false);
myRbPackageLocal.setEnabled(false);
if (myRbEscalate != null) {
myRbEscalate.setEnabled(false);
}
if (myRbAsIs != null) {
myRbAsIs.setEnabled(false);
}
myRbPublic.setEnabled(true);
myRbPublic.setSelected(true);
}
}
@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="module" module-name="core-api" />
<orderEntry type="module" module-name="java-psi-api" />
</component>
</module>
@@ -17,8 +17,9 @@ package com.intellij.psi.search.searches;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.ProgressIndicatorProvider;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.Pair;
@@ -43,6 +44,7 @@ import java.util.Set;
* @author max
*/
public class ClassInheritorsSearch extends ExtensibleQueryFactory<PsiClass, ClassInheritorsSearch.SearchParameters> {
public static ExtensionPointName<QueryExecutor> EP_NAME = ExtensionPointName.create("com.intellij.classInheritorsSearch");
private static final Logger LOG = Logger.getInstance("#com.intellij.psi.search.searches.ClassInheritorsSearch");
public static final ClassInheritorsSearch INSTANCE = new ClassInheritorsSearch();
@@ -56,7 +58,7 @@ public class ClassInheritorsSearch extends ExtensibleQueryFactory<PsiClass, Clas
LOG.assertTrue(searchScope != null);
ProgressIndicator progress = ProgressManager.getInstance().getProgressIndicator();
ProgressIndicator progress = ProgressIndicatorProvider.getInstance().getProgressIndicator();
if (progress != null) {
progress.pushState();
String className = ApplicationManager.getApplication().runReadAction(new Computable<String>() {
@@ -171,7 +173,7 @@ public class ClassInheritorsSearch extends ExtensibleQueryFactory<PsiClass, Clas
return AllClassesSearch.search(searchScope, baseClass.getProject(), parameters.getNameCondition()).forEach(new Processor<PsiClass>() {
@Override
public boolean process(final PsiClass aClass) {
ProgressManager.checkCanceled();
ProgressIndicatorProvider.checkCanceled();
final String qname1 = ApplicationManager.getApplication().runReadAction(new Computable<String>() {
@Override
@Nullable
@@ -193,7 +195,7 @@ public class ClassInheritorsSearch extends ExtensibleQueryFactory<PsiClass, Clas
final Processor<PsiClass> processor = new Processor<PsiClass>() {
@Override
public boolean process(final PsiClass candidate) {
ProgressManager.checkCanceled();
ProgressIndicatorProvider.checkCanceled();
final Ref<Boolean> result = new Ref<Boolean>();
final String[] fqn = new String[1];
@@ -233,7 +235,7 @@ public class ClassInheritorsSearch extends ExtensibleQueryFactory<PsiClass, Clas
final GlobalSearchScope projectScope = GlobalSearchScope.allScope(baseClass.getProject());
final JavaPsiFacade facade = JavaPsiFacade.getInstance(projectScope.getProject());
while (!stack.isEmpty()) {
ProgressManager.checkCanceled();
ProgressIndicatorProvider.checkCanceled();
Pair<Reference<PsiClass>, String> pair = stack.pop();
PsiClass psiClass = pair.getFirst().get();
@@ -15,6 +15,7 @@
*/
package com.intellij.psi.search.searches;
import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.openapi.util.Condition;
import com.intellij.psi.PsiAnonymousClass;
import com.intellij.psi.PsiClass;
@@ -22,11 +23,13 @@ import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.SearchScope;
import com.intellij.util.FilteredQuery;
import com.intellij.util.Query;
import com.intellij.util.QueryExecutor;
/**
* @author max
*/
public class DirectClassInheritorsSearch extends ExtensibleQueryFactory<PsiClass, DirectClassInheritorsSearch.SearchParameters> {
public static ExtensionPointName<QueryExecutor> EP_NAME = ExtensionPointName.create("com.intellij.directClassInheritorsSearch");
public static DirectClassInheritorsSearch INSTANCE = new DirectClassInheritorsSearch();
public static class SearchParameters {
@@ -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.
@@ -13,6 +13,7 @@
<orderEntry type="module" module-name="indexing-impl" exported="" />
<orderEntry type="module" module-name="projectModel-api" />
<orderEntry type="module" module-name="projectModel-impl" />
<orderEntry type="module" module-name="java-indexing-api" />
</component>
</module>
@@ -12,7 +12,7 @@ import org.jetbrains.annotations.NotNull;
* @author max
*/
public class ConstructorReferencesSearcher extends QueryExecutorBase<PsiReference, ReferencesSearch.SearchParameters> {
protected ConstructorReferencesSearcher() {
public ConstructorReferencesSearcher() {
super(true);
}
@@ -3,8 +3,7 @@ package com.intellij.psi.impl.search;
import com.intellij.openapi.application.AccessToken;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ReadAction;
import com.intellij.openapi.fileTypes.StdFileTypes;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.ProgressIndicatorProvider;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
@@ -53,8 +52,10 @@ public class JavaDirectInheritorsSearcher implements QueryExecutor<PsiClass, Dir
});
if (CommonClassNames.JAVA_LANG_OBJECT.equals(qualifiedName)) {
final SearchScope scope = useScope.intersectWith(GlobalSearchScope.notScope(GlobalSearchScope.getScopeRestrictedByFileTypes(
GlobalSearchScope.allScope(psiManager.getProject()), StdFileTypes.JSP, StdFileTypes.JSPX)));
//[pasynkov]: WTF?
//final SearchScope scope = useScope.intersectWith(GlobalSearchScope.notScope(GlobalSearchScope.getScopeRestrictedByFileTypes(
// GlobalSearchScope.allScope(psiManager.getProject()), StdFileTypes.JSP, StdFileTypes.JSPX)));
final SearchScope scope = useScope;
return AllClassesSearch.search(scope, aClass.getProject()).forEach(new Processor<PsiClass>() {
@Override
@@ -96,7 +97,7 @@ public class JavaDirectInheritorsSearcher implements QueryExecutor<PsiClass, Dir
Map<String, List<PsiClass>> classes = new HashMap<String, List<PsiClass>>();
for (PsiReferenceList referenceList : candidates) {
ProgressManager.checkCanceled();
ProgressIndicatorProvider.checkCanceled();
final PsiClass candidate = (PsiClass)referenceList.getParent();
if (!checkInheritance(p, aClass, candidate)) continue;
@@ -127,7 +128,7 @@ public class JavaDirectInheritorsSearcher implements QueryExecutor<PsiClass, Dir
});
for (PsiAnonymousClass candidate : anonymousCandidates) {
ProgressManager.checkCanceled();
ProgressIndicatorProvider.checkCanceled();
if (!checkInheritance(p, aClass, candidate)) continue;
if (!consumer.process(candidate)) return false;
@@ -1,91 +1,91 @@
/*
* Copyright 2000-2011 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.psi;
import org.jetbrains.annotations.NonNls;
/**
* @author peter
*/
public interface CommonClassNames {
@NonNls String DEFAULT_PACKAGE = "java.lang";
@NonNls String JAVA_LANG_OBJECT = "java.lang.Object";
@NonNls String JAVA_LANG_CLASS = "java.lang.Class";
@NonNls String JAVA_LANG_ENUM = "java.lang.Enum";
@NonNls String JAVA_LANG_THROWABLE = "java.lang.Throwable";
@NonNls String JAVA_LANG_EXCEPTION = "java.lang.Exception";
@NonNls String JAVA_LANG_ERROR = "java.lang.Error";
@NonNls String JAVA_LANG_RUNTIME_EXCEPTION = "java.lang.RuntimeException";
@NonNls String JAVA_LANG_AUTO_CLOSEABLE = "java.lang.AutoCloseable";
@NonNls String JAVA_LANG_ITERABLE = "java.lang.Iterable";
@NonNls String JAVA_UTIL_ITERATOR = "java.util.Iterator";
@NonNls String JAVA_LANG_DEPRECATED = "java.lang.Deprecated";
@NonNls String JAVA_LANG_ANNOTATION_INHERITED = "java.lang.annotation.Inherited";
@NonNls String JAVA_LANG_ANNOTATION_ANNOTATION = "java.lang.annotation.Annotation";
@NonNls String JAVA_LANG_REFLECT_ARRAY = "java.lang.reflect.Array";
@NonNls String JAVA_UTIL_ARRAYS = "java.util.Arrays";
@NonNls String JAVA_UTIL_COLLECTIONS = "java.util.Collections";
@NonNls String JAVA_UTIL_COLLECTION = "java.util.Collection";
@NonNls String JAVA_UTIL_MAP = "java.util.Map";
@NonNls String JAVA_UTIL_LIST = "java.util.List";
@NonNls String JAVA_UTIL_SET = "java.util.Set";
@NonNls String JAVA_UTIL_PROPERTIES = "java.util.Properties";
@NonNls String JAVA_UTIL_PROPERTY_RESOURCE_BUNDLE = "java.util.PropertyResourceBundle";
@NonNls String JAVA_UTIL_DATE = "java.util.Date";
@NonNls String JAVA_UTIL_CALENDAR = "java.util.Calendar";
@NonNls String JAVA_UTIL_DICTIONARY = "java.util.Dictionary";
@NonNls String JAVA_UTIL_COMPARATOR = "java.util.Comparator";
@NonNls String JAVA_SQL_DATE = "java.sql.Date";
@NonNls String JAVA_IO_SERIALIZABLE = "java.io.Serializable";
@NonNls String JAVA_IO_EXTERNALIZABLE = "java.io.Externalizable";
@NonNls String JAVA_LANG_STRING = "java.lang.String";
@NonNls String JAVA_LANG_STRING_SHORT = "String";
@NonNls String JAVA_LANG_NUMBER = "java.lang.Number";
@NonNls String JAVA_LANG_BOOLEAN = "java.lang.Boolean";
@NonNls String JAVA_LANG_BYTE = "java.lang.Byte";
@NonNls String JAVA_LANG_SHORT = "java.lang.Short";
@NonNls String JAVA_LANG_INTEGER = "java.lang.Integer";
@NonNls String JAVA_LANG_LONG = "java.lang.Long";
@NonNls String JAVA_LANG_FLOAT = "java.lang.Float";
@NonNls String JAVA_LANG_DOUBLE = "java.lang.Double";
@NonNls String JAVA_LANG_CHARACTER = "java.lang.Character";
@NonNls String JAVA_LANG_STRING_BUFFER = "java.lang.StringBuffer";
@NonNls String JAVA_LANG_STRING_BUILDER = "java.lang.StringBuilder";
@NonNls String JAVA_LANG_ABSTRACT_STRING_BUILDER = "java.lang.AbstractStringBuilder";
@NonNls String JAVA_LANG_CLONEABLE = "java.lang.Cloneable";
@NonNls String JAVA_LANG_COMPARABLE = "java.lang.Comparable";
@NonNls String CLASS_FILE_EXTENSION = ".class";
@NonNls String JAVA_UTIL_CONCURRENT_FUTURE = "java.util.concurrent.Future";
@NonNls String JAVA_UTIL_ARRAY_LIST = "java.util.ArrayList";
@NonNls String JAVA_LANG_INVOKE_MH_POLYMORPHIC = "java.lang.invoke.MethodHandle.PolymorphicSignature";
String TARGET_ANNOTATION_FQ_NAME = "java.lang.annotation.Target";
@NonNls String JAVA_LANG_RUNNABLE = "java.lang.Runnable";
@NonNls String JAVA_IO_FILE = "java.io.File";
}
/*
* Copyright 2000-2011 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.psi;
import org.jetbrains.annotations.NonNls;
/**
* @author peter
*/
public interface CommonClassNames {
@NonNls String DEFAULT_PACKAGE = "java.lang";
@NonNls String JAVA_LANG_OBJECT = "java.lang.Object";
@NonNls String JAVA_LANG_CLASS = "java.lang.Class";
@NonNls String JAVA_LANG_ENUM = "java.lang.Enum";
@NonNls String JAVA_LANG_THROWABLE = "java.lang.Throwable";
@NonNls String JAVA_LANG_EXCEPTION = "java.lang.Exception";
@NonNls String JAVA_LANG_ERROR = "java.lang.Error";
@NonNls String JAVA_LANG_RUNTIME_EXCEPTION = "java.lang.RuntimeException";
@NonNls String JAVA_LANG_AUTO_CLOSEABLE = "java.lang.AutoCloseable";
@NonNls String JAVA_LANG_ITERABLE = "java.lang.Iterable";
@NonNls String JAVA_UTIL_ITERATOR = "java.util.Iterator";
@NonNls String JAVA_LANG_DEPRECATED = "java.lang.Deprecated";
@NonNls String JAVA_LANG_ANNOTATION_INHERITED = "java.lang.annotation.Inherited";
@NonNls String JAVA_LANG_ANNOTATION_ANNOTATION = "java.lang.annotation.Annotation";
@NonNls String JAVA_LANG_REFLECT_ARRAY = "java.lang.reflect.Array";
@NonNls String JAVA_UTIL_ARRAYS = "java.util.Arrays";
@NonNls String JAVA_UTIL_COLLECTIONS = "java.util.Collections";
@NonNls String JAVA_UTIL_COLLECTION = "java.util.Collection";
@NonNls String JAVA_UTIL_MAP = "java.util.Map";
@NonNls String JAVA_UTIL_LIST = "java.util.List";
@NonNls String JAVA_UTIL_SET = "java.util.Set";
@NonNls String JAVA_UTIL_PROPERTIES = "java.util.Properties";
@NonNls String JAVA_UTIL_PROPERTY_RESOURCE_BUNDLE = "java.util.PropertyResourceBundle";
@NonNls String JAVA_UTIL_DATE = "java.util.Date";
@NonNls String JAVA_UTIL_CALENDAR = "java.util.Calendar";
@NonNls String JAVA_UTIL_DICTIONARY = "java.util.Dictionary";
@NonNls String JAVA_UTIL_COMPARATOR = "java.util.Comparator";
@NonNls String JAVA_SQL_DATE = "java.sql.Date";
@NonNls String JAVA_IO_SERIALIZABLE = "java.io.Serializable";
@NonNls String JAVA_IO_EXTERNALIZABLE = "java.io.Externalizable";
@NonNls String JAVA_LANG_STRING = "java.lang.String";
@NonNls String JAVA_LANG_STRING_SHORT = "String";
@NonNls String JAVA_LANG_NUMBER = "java.lang.Number";
@NonNls String JAVA_LANG_BOOLEAN = "java.lang.Boolean";
@NonNls String JAVA_LANG_BYTE = "java.lang.Byte";
@NonNls String JAVA_LANG_SHORT = "java.lang.Short";
@NonNls String JAVA_LANG_INTEGER = "java.lang.Integer";
@NonNls String JAVA_LANG_LONG = "java.lang.Long";
@NonNls String JAVA_LANG_FLOAT = "java.lang.Float";
@NonNls String JAVA_LANG_DOUBLE = "java.lang.Double";
@NonNls String JAVA_LANG_CHARACTER = "java.lang.Character";
@NonNls String JAVA_LANG_STRING_BUFFER = "java.lang.StringBuffer";
@NonNls String JAVA_LANG_STRING_BUILDER = "java.lang.StringBuilder";
@NonNls String JAVA_LANG_ABSTRACT_STRING_BUILDER = "java.lang.AbstractStringBuilder";
@NonNls String JAVA_LANG_CLONEABLE = "java.lang.Cloneable";
@NonNls String JAVA_LANG_COMPARABLE = "java.lang.Comparable";
@NonNls String CLASS_FILE_EXTENSION = ".class";
@NonNls String JAVA_UTIL_CONCURRENT_FUTURE = "java.util.concurrent.Future";
@NonNls String JAVA_UTIL_ARRAY_LIST = "java.util.ArrayList";
@NonNls String JAVA_LANG_INVOKE_MH_POLYMORPHIC = "java.lang.invoke.MethodHandle.PolymorphicSignature";
String TARGET_ANNOTATION_FQ_NAME = "java.lang.annotation.Target";
@NonNls String JAVA_LANG_RUNNABLE = "java.lang.Runnable";
@NonNls String JAVA_IO_FILE = "java.io.File";
}
@@ -1,127 +1,127 @@
/*
* Copyright 2000-2011 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.util;
import com.intellij.psi.*;
import com.intellij.util.Processor;
import gnu.trove.THashSet;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Set;
public class InheritanceUtil {
private InheritanceUtil() { }
/**
* @deprecated Use {@link PsiClass#isInheritor(com.intellij.psi.PsiClass, boolean)} instead.
*/
public static boolean isInheritor(@NotNull PsiClass candidateClass, @NotNull PsiClass baseClass, boolean checkDeep) {
return candidateClass.isInheritor(baseClass, checkDeep);
}
/**
* @param aClass a class to check.
* @param baseClass supposed base class.
* @param checkDeep true to check deeper than aClass.super (see {@linkplain PsiClass#isInheritor(com.intellij.psi.PsiClass, boolean)}).
* @return true if aClass is the baseClass or baseClass inheritor
*/
public static boolean isInheritorOrSelf(@Nullable PsiClass aClass, @Nullable PsiClass baseClass, boolean checkDeep) {
if (aClass == null || baseClass == null) return false;
PsiManager manager = aClass.getManager();
return manager.areElementsEquivalent(baseClass, aClass) || aClass.isInheritor(baseClass, checkDeep);
}
/**
* @deprecated use {@linkplain #isInheritorOrSelf(com.intellij.psi.PsiClass, com.intellij.psi.PsiClass, boolean)}.
*/
public static boolean isCorrectDescendant(@Nullable PsiClass aClass, @Nullable PsiClass baseClass, boolean checkDeep) {
return isInheritorOrSelf(aClass, baseClass, checkDeep);
}
public static boolean processSupers(@Nullable PsiClass aClass, boolean includeSelf, @NotNull Processor<PsiClass> superProcessor) {
if (aClass == null) return true;
if (includeSelf && !superProcessor.process(aClass)) return false;
return processSupers(aClass, superProcessor, new THashSet<PsiClass>());
}
private static boolean processSupers(@NotNull PsiClass aClass, @NotNull Processor<PsiClass> superProcessor, @NotNull Set<PsiClass> visited) {
if (!visited.add(aClass)) return true;
for (final PsiClass intf : aClass.getInterfaces()) {
if (!superProcessor.process(intf) || !processSupers(intf, superProcessor, visited)) return false;
}
final PsiClass superClass = aClass.getSuperClass();
if (superClass != null) {
if (!superProcessor.process(superClass) || !processSupers(superClass, superProcessor, visited)) return false;
}
return true;
}
public static boolean isInheritor(@Nullable PsiType type, @NotNull @NonNls final String baseClassName) {
if (type instanceof PsiClassType) {
return isInheritor(((PsiClassType)type).resolve(), baseClassName);
}
return false;
}
public static boolean isInheritor(@Nullable PsiClass psiClass, @NotNull final String baseClassName) {
return isInheritor(psiClass, false, baseClassName);
}
public static boolean isInheritor(@Nullable PsiClass psiClass, final boolean strict, @NotNull final String baseClassName) {
if (psiClass == null) {
return false;
}
final PsiClass base = JavaPsiFacade.getInstance(psiClass.getProject()).findClass(baseClassName, psiClass.getResolveScope());
if (base == null) {
return false;
}
return strict ? psiClass.isInheritor(base, true) : isInheritorOrSelf(psiClass, base, true);
}
/**
* Gets all superclasses. Classes are added to result in DFS order
* @param aClass
* @param results
* @param includeNonProject
*/
public static void getSuperClasses(@NotNull PsiClass aClass, @NotNull Set<PsiClass> results, boolean includeNonProject) {
getSuperClassesOfList(aClass.getSuperTypes(), results, includeNonProject, new THashSet<PsiClass>(), aClass.getManager());
}
private static void getSuperClassesOfList(@NotNull PsiClassType[] types,
@NotNull Set<PsiClass> results,
boolean includeNonProject,
@NotNull Set<PsiClass> visited,
@NotNull PsiManager manager) {
for (PsiClassType type : types) {
PsiClass resolved = type.resolve();
if (resolved != null && visited.add(resolved)) {
if (includeNonProject || manager.isInProject(resolved)) {
results.add(resolved);
}
getSuperClassesOfList(resolved.getSuperTypes(), results, includeNonProject, visited, manager);
}
}
}
}
/*
* Copyright 2000-2011 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.util;
import com.intellij.psi.*;
import com.intellij.util.Processor;
import gnu.trove.THashSet;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Set;
public class InheritanceUtil {
private InheritanceUtil() { }
/**
* @deprecated Use {@link PsiClass#isInheritor(com.intellij.psi.PsiClass, boolean)} instead.
*/
public static boolean isInheritor(@NotNull PsiClass candidateClass, @NotNull PsiClass baseClass, boolean checkDeep) {
return candidateClass.isInheritor(baseClass, checkDeep);
}
/**
* @param aClass a class to check.
* @param baseClass supposed base class.
* @param checkDeep true to check deeper than aClass.super (see {@linkplain PsiClass#isInheritor(com.intellij.psi.PsiClass, boolean)}).
* @return true if aClass is the baseClass or baseClass inheritor
*/
public static boolean isInheritorOrSelf(@Nullable PsiClass aClass, @Nullable PsiClass baseClass, boolean checkDeep) {
if (aClass == null || baseClass == null) return false;
PsiManager manager = aClass.getManager();
return manager.areElementsEquivalent(baseClass, aClass) || aClass.isInheritor(baseClass, checkDeep);
}
/**
* @deprecated use {@linkplain #isInheritorOrSelf(com.intellij.psi.PsiClass, com.intellij.psi.PsiClass, boolean)}.
*/
public static boolean isCorrectDescendant(@Nullable PsiClass aClass, @Nullable PsiClass baseClass, boolean checkDeep) {
return isInheritorOrSelf(aClass, baseClass, checkDeep);
}
public static boolean processSupers(@Nullable PsiClass aClass, boolean includeSelf, @NotNull Processor<PsiClass> superProcessor) {
if (aClass == null) return true;
if (includeSelf && !superProcessor.process(aClass)) return false;
return processSupers(aClass, superProcessor, new THashSet<PsiClass>());
}
private static boolean processSupers(@NotNull PsiClass aClass, @NotNull Processor<PsiClass> superProcessor, @NotNull Set<PsiClass> visited) {
if (!visited.add(aClass)) return true;
for (final PsiClass intf : aClass.getInterfaces()) {
if (!superProcessor.process(intf) || !processSupers(intf, superProcessor, visited)) return false;
}
final PsiClass superClass = aClass.getSuperClass();
if (superClass != null) {
if (!superProcessor.process(superClass) || !processSupers(superClass, superProcessor, visited)) return false;
}
return true;
}
public static boolean isInheritor(@Nullable PsiType type, @NotNull @NonNls final String baseClassName) {
if (type instanceof PsiClassType) {
return isInheritor(((PsiClassType)type).resolve(), baseClassName);
}
return false;
}
public static boolean isInheritor(@Nullable PsiClass psiClass, @NotNull final String baseClassName) {
return isInheritor(psiClass, false, baseClassName);
}
public static boolean isInheritor(@Nullable PsiClass psiClass, final boolean strict, @NotNull final String baseClassName) {
if (psiClass == null) {
return false;
}
final PsiClass base = JavaPsiFacade.getInstance(psiClass.getProject()).findClass(baseClassName, psiClass.getResolveScope());
if (base == null) {
return false;
}
return strict ? psiClass.isInheritor(base, true) : isInheritorOrSelf(psiClass, base, true);
}
/**
* Gets all superclasses. Classes are added to result in DFS order
* @param aClass
* @param results
* @param includeNonProject
*/
public static void getSuperClasses(@NotNull PsiClass aClass, @NotNull Set<PsiClass> results, boolean includeNonProject) {
getSuperClassesOfList(aClass.getSuperTypes(), results, includeNonProject, new THashSet<PsiClass>(), aClass.getManager());
}
private static void getSuperClassesOfList(@NotNull PsiClassType[] types,
@NotNull Set<PsiClass> results,
boolean includeNonProject,
@NotNull Set<PsiClass> visited,
@NotNull PsiManager manager) {
for (PsiClassType type : types) {
PsiClass resolved = type.resolve();
if (resolved != null && visited.add(resolved)) {
if (includeNonProject || manager.isInProject(resolved)) {
results.add(resolved);
}
getSuperClassesOfList(resolved.getSuperTypes(), results, includeNonProject, visited, manager);
}
}
}
}
@@ -0,0 +1,55 @@
/*
* 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.impl;
import com.intellij.psi.*;
import com.intellij.psi.util.PsiSuperMethodUtil;
import com.intellij.psi.util.PsiTreeUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
public class FindSuperElementsHelper {
@Nullable
public static PsiElement[] findSuperElements(@NotNull PsiElement element) {
PsiMember e = PsiTreeUtil.getParentOfType(element, PsiMethod.class, PsiClass.class);
if (e instanceof PsiClass) {
PsiClass aClass = (PsiClass) e;
List<PsiClass> allSupers = new ArrayList<PsiClass>(Arrays.asList(aClass.getSupers()));
for (Iterator<PsiClass> iterator = allSupers.iterator(); iterator.hasNext();) {
PsiClass superClass = iterator.next();
if (CommonClassNames.JAVA_LANG_OBJECT.equals(superClass.getQualifiedName())) iterator.remove();
}
return allSupers.toArray(new PsiClass[allSupers.size()]);
} else if (e instanceof PsiMethod) {
PsiMethod method = (PsiMethod) e;
if (method.isConstructor()) {
PsiMethod constructorInSuper = PsiSuperMethodUtil.findConstructorInSuper(method);
if (constructorInSuper != null) {
return new PsiMethod[]{constructorInSuper};
}
} else {
return method.findSuperMethods(false);
}
}
return null;
}
}
@@ -1,401 +1,401 @@
/*
* 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.impl.source.tree.java;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.*;
import com.intellij.psi.impl.PsiManagerEx;
import com.intellij.psi.impl.ResolveScopeManager;
import com.intellij.psi.impl.source.tree.JavaElementType;
import com.intellij.psi.impl.source.tree.LeafElement;
import com.intellij.psi.impl.source.tree.TreeElement;
import com.intellij.psi.impl.source.tree.injected.StringLiteralEscaper;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.tree.TokenSet;
import com.intellij.util.text.LiteralFormatUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class PsiLiteralExpressionImpl
extends ExpressionPsiElement
implements PsiLiteralExpression, PsiLanguageInjectionHost, ContributedReferenceHost {
@NonNls private static final String QUOT = "&quot;";
@NonNls public static final String HEX_PREFIX = "0x";
@NonNls public static final String BIN_PREFIX = "0b";
@NonNls public static final String _2_IN_31 = Long.toString(-1L << 31).substring(1);
@NonNls public static final String _2_IN_63 = Long.toString(-1L << 63).substring(1);
public static final TokenSet INTEGER_LITERALS = TokenSet.create(JavaTokenType.INTEGER_LITERAL, JavaTokenType.LONG_LITERAL);
public static final TokenSet REAL_LITERALS = TokenSet.create(JavaTokenType.FLOAT_LITERAL, JavaTokenType.DOUBLE_LITERAL);
public static final TokenSet NUMERIC_LITERALS = TokenSet.orSet(INTEGER_LITERALS, REAL_LITERALS);
public PsiLiteralExpressionImpl() {
super(JavaElementType.LITERAL_EXPRESSION);
}
@Override
public PsiType getType() {
final IElementType type = getLiteralElementType();
if (type == JavaTokenType.INTEGER_LITERAL) {
return PsiType.INT;
}
if (type == JavaTokenType.LONG_LITERAL) {
return PsiType.LONG;
}
if (type == JavaTokenType.FLOAT_LITERAL) {
return PsiType.FLOAT;
}
if (type == JavaTokenType.DOUBLE_LITERAL) {
return PsiType.DOUBLE;
}
if (type == JavaTokenType.CHARACTER_LITERAL) {
return PsiType.CHAR;
}
if (type == JavaTokenType.STRING_LITERAL) {
PsiManagerEx manager = getManager();
GlobalSearchScope resolveScope = ResolveScopeManager.getElementResolveScope(this);
return PsiType.getJavaLangString(manager, resolveScope);
}
if (type == JavaTokenType.TRUE_KEYWORD || type == JavaTokenType.FALSE_KEYWORD) {
return PsiType.BOOLEAN;
}
if (type == JavaTokenType.NULL_KEYWORD) {
return PsiType.NULL;
}
return null;
}
public IElementType getLiteralElementType() {
return getFirstChildNode().getElementType();
}
public String getCanonicalText() {
final TreeElement literal = getFirstChildNode();
final IElementType type = literal.getElementType();
return NUMERIC_LITERALS.contains(type) ? LiteralFormatUtil.removeUnderscores(literal.getText()) : literal.getText();
}
@Override
public Object getValue() {
final IElementType type = getLiteralElementType();
String text = NUMERIC_LITERALS.contains(type) ? getCanonicalText().toLowerCase() : getCanonicalText();
final int textLength = text.length();
if (type == JavaTokenType.INTEGER_LITERAL) {
try {
if (text.startsWith(HEX_PREFIX)) {
// should fit in 32 bits
final long value = parseDigits(text.substring(2), 4, 32);
return Integer.valueOf((int)value);
}
if (text.startsWith(BIN_PREFIX)) {
// should fit in 32 bits
final long value = parseDigits(text.substring(2), 1, 32);
return Integer.valueOf((int)value);
}
if (StringUtil.startsWithChar(text, '0')) {
// should fit in 32 bits
final long value = parseDigits(text, 3, 32);
return Integer.valueOf((int)value);
}
final long l = Long.parseLong(text, 10);
if (text.equals(_2_IN_31)) return Integer.valueOf((int)l);
long converted = (int)l;
return l == converted ? Integer.valueOf((int)l) : null;
}
catch (NumberFormatException e) {
return null;
}
}
if (type == JavaTokenType.LONG_LITERAL) {
if (StringUtil.endsWithChar(text, 'L') || StringUtil.endsWithChar(text, 'l')) {
text = text.substring(0, textLength - 1);
}
try {
if (text.startsWith(HEX_PREFIX)) {
return parseDigits(text.substring(2), 4, 64);
}
if (text.startsWith(BIN_PREFIX)) {
return parseDigits(text.substring(2), 1, 64);
}
if (StringUtil.startsWithChar(text, '0')) {
// should fit in 64 bits
return parseDigits(text, 3, 64);
}
if (_2_IN_63.equals(text)) return Long.valueOf(-1L << 63);
return Long.valueOf(text, 10);
}
catch (NumberFormatException e) {
return null;
}
}
if (type == JavaTokenType.FLOAT_LITERAL) {
try {
return Float.valueOf(text);
}
catch (NumberFormatException e) {
return null;
}
}
if (type == JavaTokenType.DOUBLE_LITERAL) {
try {
return Double.valueOf(text);
}
catch (NumberFormatException e) {
return null;
}
}
if (type == JavaTokenType.CHARACTER_LITERAL) {
if (StringUtil.endsWithChar(text, '\'')) {
if (textLength == 1) return null;
text = text.substring(1, textLength - 1);
}
else {
text = text.substring(1, textLength);
}
StringBuilder chars = new StringBuilder();
boolean success = parseStringCharacters(text, chars, null);
if (!success) return null;
if (chars.length() != 1) return null;
return Character.valueOf(chars.charAt(0));
}
if (type == JavaTokenType.STRING_LITERAL) {
String innerText = getInnerText();
return innerText == null ? null : internedParseStringCharacters(innerText);
}
if (type == JavaTokenType.TRUE_KEYWORD) {
return Boolean.TRUE;
}
if (type == JavaTokenType.FALSE_KEYWORD) {
return Boolean.FALSE;
}
return null;
}
@Nullable
public String getInnerText() {
String text = getCanonicalText();
int textLength = text.length();
if (StringUtil.endsWithChar(text, '\"')) {
if (textLength == 1) return null;
text = text.substring(1, textLength - 1);
}
else {
if (text.startsWith(QUOT) && text.endsWith(QUOT) && textLength > QUOT.length()) {
text = text.substring(QUOT.length(), textLength - QUOT.length());
}
else {
return null;
}
}
return text;
}
// convert text to number according to radix specified
// if number is more than maxBits bits long, throws NumberFormatException
private static long parseDigits(final String text, final int bitsInRadix, final int maxBits) throws NumberFormatException {
final int radix = 1 << bitsInRadix;
final int textLength = text.length();
if (textLength == 0) {
throw new NumberFormatException(text);
}
long integer = textLength == 1 ? 0 : Long.parseLong(text.substring(0, textLength - 1), radix);
if ((integer & (-1L << (maxBits - bitsInRadix))) != 0) {
throw new NumberFormatException(text);
}
final int lastDigit = Character.digit(text.charAt(textLength - 1), radix);
if (lastDigit == -1) {
throw new NumberFormatException(text);
}
integer <<= bitsInRadix;
integer |= lastDigit;
return integer;
}
@Nullable
private static String internedParseStringCharacters(final String chars) {
final StringBuilder outChars = new StringBuilder(chars.length());
final boolean success = parseStringCharacters(chars, outChars, null);
return success ? outChars.toString() : null;
}
public static boolean parseStringCharacters(@NotNull String chars, @NotNull StringBuilder outChars, @Nullable int[] sourceOffsets) {
assert sourceOffsets == null || sourceOffsets.length == chars.length()+1;
if (chars.indexOf('\\') < 0) {
outChars.append(chars);
if (sourceOffsets != null) {
for (int i = 0; i < sourceOffsets.length; i++) {
sourceOffsets[i] = i;
}
}
return true;
}
int index = 0;
final int outOffset = outChars.length();
while (index < chars.length()) {
char c = chars.charAt(index++);
if (sourceOffsets != null) {
sourceOffsets[outChars.length()-outOffset] = index - 1;
sourceOffsets[outChars.length() + 1 -outOffset] = index;
}
if (c != '\\') {
outChars.append(c);
continue;
}
if (index == chars.length()) return false;
c = chars.charAt(index++);
switch (c) {
case'b':
outChars.append('\b');
break;
case't':
outChars.append('\t');
break;
case'n':
outChars.append('\n');
break;
case'f':
outChars.append('\f');
break;
case'r':
outChars.append('\r');
break;
case'"':
outChars.append('"');
break;
case'\'':
outChars.append('\'');
break;
case'\\':
outChars.append('\\');
break;
case'0':
case'1':
case'2':
case'3':
case'4':
case'5':
case'6':
case'7':
char startC = c;
int v = (int)c - '0';
if (index < chars.length()) {
c = chars.charAt(index++);
if ('0' <= c && c <= '7') {
v <<= 3;
v += c - '0';
if (startC <= '3' && index < chars.length()) {
c = chars.charAt(index++);
if ('0' <= c && c <= '7') {
v <<= 3;
v += c - '0';
}
else {
index--;
}
}
}
else {
index--;
}
}
outChars.append((char)v);
break;
case'u':
// uuuuu1234 is valid too
while (index != chars.length() && chars.charAt(index) == 'u') {
index++;
}
if (index + 4 <= chars.length()) {
try {
int code = Integer.parseInt(chars.substring(index, index + 4), 16);
//line separators are invalid here
if (code == 0x000a || code == 0x000d) return false;
c = chars.charAt(index);
if (c == '+' || c == '-') return false;
outChars.append((char)code);
index += 4;
}
catch (Exception e) {
return false;
}
}
else {
return false;
}
break;
default:
return false;
}
if (sourceOffsets != null) {
sourceOffsets[outChars.length()-outOffset] = index;
}
}
return true;
}
@Override
public void accept(@NotNull PsiElementVisitor visitor) {
if (visitor instanceof JavaElementVisitor) {
((JavaElementVisitor)visitor).visitLiteralExpression(this);
}
else {
visitor.visitElement(this);
}
}
public String toString() {
return "PsiLiteralExpression:" + getText();
}
@Override
public boolean isValidHost() {
return getValue() instanceof String;
}
@Override
@NotNull
public PsiReference[] getReferences() {
return PsiReferenceService.getService().getContributedReferences(this);
}
@Override
public PsiLanguageInjectionHost updateText(@NotNull final String text) {
TreeElement valueNode = getFirstChildNode();
assert valueNode instanceof LeafElement;
((LeafElement)valueNode).replaceWithText(text);
return this;
}
@Override
@NotNull
public LiteralTextEscaper<PsiLiteralExpressionImpl> createLiteralTextEscaper() {
return new StringLiteralEscaper<PsiLiteralExpressionImpl>(this);
}
}
/*
* 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.impl.source.tree.java;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.*;
import com.intellij.psi.impl.PsiManagerEx;
import com.intellij.psi.impl.ResolveScopeManager;
import com.intellij.psi.impl.source.tree.JavaElementType;
import com.intellij.psi.impl.source.tree.LeafElement;
import com.intellij.psi.impl.source.tree.TreeElement;
import com.intellij.psi.impl.source.tree.injected.StringLiteralEscaper;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.tree.TokenSet;
import com.intellij.util.text.LiteralFormatUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class PsiLiteralExpressionImpl
extends ExpressionPsiElement
implements PsiLiteralExpression, PsiLanguageInjectionHost, ContributedReferenceHost {
@NonNls private static final String QUOT = "&quot;";
@NonNls public static final String HEX_PREFIX = "0x";
@NonNls public static final String BIN_PREFIX = "0b";
@NonNls public static final String _2_IN_31 = Long.toString(-1L << 31).substring(1);
@NonNls public static final String _2_IN_63 = Long.toString(-1L << 63).substring(1);
public static final TokenSet INTEGER_LITERALS = TokenSet.create(JavaTokenType.INTEGER_LITERAL, JavaTokenType.LONG_LITERAL);
public static final TokenSet REAL_LITERALS = TokenSet.create(JavaTokenType.FLOAT_LITERAL, JavaTokenType.DOUBLE_LITERAL);
public static final TokenSet NUMERIC_LITERALS = TokenSet.orSet(INTEGER_LITERALS, REAL_LITERALS);
public PsiLiteralExpressionImpl() {
super(JavaElementType.LITERAL_EXPRESSION);
}
@Override
public PsiType getType() {
final IElementType type = getLiteralElementType();
if (type == JavaTokenType.INTEGER_LITERAL) {
return PsiType.INT;
}
if (type == JavaTokenType.LONG_LITERAL) {
return PsiType.LONG;
}
if (type == JavaTokenType.FLOAT_LITERAL) {
return PsiType.FLOAT;
}
if (type == JavaTokenType.DOUBLE_LITERAL) {
return PsiType.DOUBLE;
}
if (type == JavaTokenType.CHARACTER_LITERAL) {
return PsiType.CHAR;
}
if (type == JavaTokenType.STRING_LITERAL) {
PsiManagerEx manager = getManager();
GlobalSearchScope resolveScope = ResolveScopeManager.getElementResolveScope(this);
return PsiType.getJavaLangString(manager, resolveScope);
}
if (type == JavaTokenType.TRUE_KEYWORD || type == JavaTokenType.FALSE_KEYWORD) {
return PsiType.BOOLEAN;
}
if (type == JavaTokenType.NULL_KEYWORD) {
return PsiType.NULL;
}
return null;
}
public IElementType getLiteralElementType() {
return getFirstChildNode().getElementType();
}
public String getCanonicalText() {
final TreeElement literal = getFirstChildNode();
final IElementType type = literal.getElementType();
return NUMERIC_LITERALS.contains(type) ? LiteralFormatUtil.removeUnderscores(literal.getText()) : literal.getText();
}
@Override
public Object getValue() {
final IElementType type = getLiteralElementType();
String text = NUMERIC_LITERALS.contains(type) ? getCanonicalText().toLowerCase() : getCanonicalText();
final int textLength = text.length();
if (type == JavaTokenType.INTEGER_LITERAL) {
try {
if (text.startsWith(HEX_PREFIX)) {
// should fit in 32 bits
final long value = parseDigits(text.substring(2), 4, 32);
return Integer.valueOf((int)value);
}
if (text.startsWith(BIN_PREFIX)) {
// should fit in 32 bits
final long value = parseDigits(text.substring(2), 1, 32);
return Integer.valueOf((int)value);
}
if (StringUtil.startsWithChar(text, '0')) {
// should fit in 32 bits
final long value = parseDigits(text, 3, 32);
return Integer.valueOf((int)value);
}
final long l = Long.parseLong(text, 10);
if (text.equals(_2_IN_31)) return Integer.valueOf((int)l);
long converted = (int)l;
return l == converted ? Integer.valueOf((int)l) : null;
}
catch (NumberFormatException e) {
return null;
}
}
if (type == JavaTokenType.LONG_LITERAL) {
if (StringUtil.endsWithChar(text, 'L') || StringUtil.endsWithChar(text, 'l')) {
text = text.substring(0, textLength - 1);
}
try {
if (text.startsWith(HEX_PREFIX)) {
return parseDigits(text.substring(2), 4, 64);
}
if (text.startsWith(BIN_PREFIX)) {
return parseDigits(text.substring(2), 1, 64);
}
if (StringUtil.startsWithChar(text, '0')) {
// should fit in 64 bits
return parseDigits(text, 3, 64);
}
if (_2_IN_63.equals(text)) return Long.valueOf(-1L << 63);
return Long.valueOf(text, 10);
}
catch (NumberFormatException e) {
return null;
}
}
if (type == JavaTokenType.FLOAT_LITERAL) {
try {
return Float.valueOf(text);
}
catch (NumberFormatException e) {
return null;
}
}
if (type == JavaTokenType.DOUBLE_LITERAL) {
try {
return Double.valueOf(text);
}
catch (NumberFormatException e) {
return null;
}
}
if (type == JavaTokenType.CHARACTER_LITERAL) {
if (StringUtil.endsWithChar(text, '\'')) {
if (textLength == 1) return null;
text = text.substring(1, textLength - 1);
}
else {
text = text.substring(1, textLength);
}
StringBuilder chars = new StringBuilder();
boolean success = parseStringCharacters(text, chars, null);
if (!success) return null;
if (chars.length() != 1) return null;
return Character.valueOf(chars.charAt(0));
}
if (type == JavaTokenType.STRING_LITERAL) {
String innerText = getInnerText();
return innerText == null ? null : internedParseStringCharacters(innerText);
}
if (type == JavaTokenType.TRUE_KEYWORD) {
return Boolean.TRUE;
}
if (type == JavaTokenType.FALSE_KEYWORD) {
return Boolean.FALSE;
}
return null;
}
@Nullable
public String getInnerText() {
String text = getCanonicalText();
int textLength = text.length();
if (StringUtil.endsWithChar(text, '\"')) {
if (textLength == 1) return null;
text = text.substring(1, textLength - 1);
}
else {
if (text.startsWith(QUOT) && text.endsWith(QUOT) && textLength > QUOT.length()) {
text = text.substring(QUOT.length(), textLength - QUOT.length());
}
else {
return null;
}
}
return text;
}
// convert text to number according to radix specified
// if number is more than maxBits bits long, throws NumberFormatException
private static long parseDigits(final String text, final int bitsInRadix, final int maxBits) throws NumberFormatException {
final int radix = 1 << bitsInRadix;
final int textLength = text.length();
if (textLength == 0) {
throw new NumberFormatException(text);
}
long integer = textLength == 1 ? 0 : Long.parseLong(text.substring(0, textLength - 1), radix);
if ((integer & (-1L << (maxBits - bitsInRadix))) != 0) {
throw new NumberFormatException(text);
}
final int lastDigit = Character.digit(text.charAt(textLength - 1), radix);
if (lastDigit == -1) {
throw new NumberFormatException(text);
}
integer <<= bitsInRadix;
integer |= lastDigit;
return integer;
}
@Nullable
private static String internedParseStringCharacters(final String chars) {
final StringBuilder outChars = new StringBuilder(chars.length());
final boolean success = parseStringCharacters(chars, outChars, null);
return success ? outChars.toString() : null;
}
public static boolean parseStringCharacters(@NotNull String chars, @NotNull StringBuilder outChars, @Nullable int[] sourceOffsets) {
assert sourceOffsets == null || sourceOffsets.length == chars.length()+1;
if (chars.indexOf('\\') < 0) {
outChars.append(chars);
if (sourceOffsets != null) {
for (int i = 0; i < sourceOffsets.length; i++) {
sourceOffsets[i] = i;
}
}
return true;
}
int index = 0;
final int outOffset = outChars.length();
while (index < chars.length()) {
char c = chars.charAt(index++);
if (sourceOffsets != null) {
sourceOffsets[outChars.length()-outOffset] = index - 1;
sourceOffsets[outChars.length() + 1 -outOffset] = index;
}
if (c != '\\') {
outChars.append(c);
continue;
}
if (index == chars.length()) return false;
c = chars.charAt(index++);
switch (c) {
case'b':
outChars.append('\b');
break;
case't':
outChars.append('\t');
break;
case'n':
outChars.append('\n');
break;
case'f':
outChars.append('\f');
break;
case'r':
outChars.append('\r');
break;
case'"':
outChars.append('"');
break;
case'\'':
outChars.append('\'');
break;
case'\\':
outChars.append('\\');
break;
case'0':
case'1':
case'2':
case'3':
case'4':
case'5':
case'6':
case'7':
char startC = c;
int v = (int)c - '0';
if (index < chars.length()) {
c = chars.charAt(index++);
if ('0' <= c && c <= '7') {
v <<= 3;
v += c - '0';
if (startC <= '3' && index < chars.length()) {
c = chars.charAt(index++);
if ('0' <= c && c <= '7') {
v <<= 3;
v += c - '0';
}
else {
index--;
}
}
}
else {
index--;
}
}
outChars.append((char)v);
break;
case'u':
// uuuuu1234 is valid too
while (index != chars.length() && chars.charAt(index) == 'u') {
index++;
}
if (index + 4 <= chars.length()) {
try {
int code = Integer.parseInt(chars.substring(index, index + 4), 16);
//line separators are invalid here
if (code == 0x000a || code == 0x000d) return false;
c = chars.charAt(index);
if (c == '+' || c == '-') return false;
outChars.append((char)code);
index += 4;
}
catch (Exception e) {
return false;
}
}
else {
return false;
}
break;
default:
return false;
}
if (sourceOffsets != null) {
sourceOffsets[outChars.length()-outOffset] = index;
}
}
return true;
}
@Override
public void accept(@NotNull PsiElementVisitor visitor) {
if (visitor instanceof JavaElementVisitor) {
((JavaElementVisitor)visitor).visitLiteralExpression(this);
}
else {
visitor.visitElement(this);
}
}
public String toString() {
return "PsiLiteralExpression:" + getText();
}
@Override
public boolean isValidHost() {
return getValue() instanceof String;
}
@Override
@NotNull
public PsiReference[] getReferences() {
return PsiReferenceService.getService().getContributedReferences(this);
}
@Override
public PsiLanguageInjectionHost updateText(@NotNull final String text) {
TreeElement valueNode = getFirstChildNode();
assert valueNode instanceof LeafElement;
((LeafElement)valueNode).replaceWithText(text);
return this;
}
@Override
@NotNull
public LiteralTextEscaper<PsiLiteralExpressionImpl> createLiteralTextEscaper() {
return new StringLiteralEscaper<PsiLiteralExpressionImpl>(this);
}
}
+1
View File
@@ -29,6 +29,7 @@
<orderEntry type="module" module-name="platform-tests" scope="TEST" />
<orderEntry type="module" module-name="IntentionPowerPackPlugin" scope="TEST" />
<orderEntry type="module" module-name="InspectionGadgetsPlugin" scope="TEST" />
<orderEntry type="module" module-name="java-indexing-api" scope="TEST" />
</component>
</module>
@@ -1,5 +1,5 @@
public class Util {
int goo() {
ret<caret>cond ? 1: 0;
}
}
public class Util {
int goo() {
ret<caret>cond ? 1: 0;
}
}
@@ -1,7 +1,7 @@
class Util {
void foox() {
int fooy;
foo<caret>
}
class Util {
void foox() {
int fooy;
foo<caret>
}
}
@@ -1,17 +1,17 @@
class Foo {
int ELXEMENT_A = 1;
int ELXEMENT_B = 1;
int ELXEMENT_C = 1;
int ELXEMENT_D = 1;
int ELXEMENT_E = 1;
int ELXEMENT_F = 1;
int ELXEMENT_G = 1;
int ELXEMENT_H = 1;
int ELXEMENT_I = 1;
{
Elx<caret>
}
class Foo {
int ELXEMENT_A = 1;
int ELXEMENT_B = 1;
int ELXEMENT_C = 1;
int ELXEMENT_D = 1;
int ELXEMENT_E = 1;
int ELXEMENT_F = 1;
int ELXEMENT_G = 1;
int ELXEMENT_H = 1;
int ELXEMENT_I = 1;
{
Elx<caret>
}
}
@@ -1,5 +1,5 @@
class FooBar {
void foo(FooBar _fooBar) {
fb<caret>
}
class FooBar {
void foo(FooBar _fooBar) {
fb<caret>
}
}
@@ -1,33 +1,33 @@
class MyClass {
public void foo() {
MyDD<String> d = new MyDD<String>() {
@Override
public int hashCode() {
<selection>return super.hashCode(); //To change body of overridden methods use File | Settings | File Templates.</selection>
}
@Override
public boolean equals(Object obj) {
return super.equals(obj); //To change body of overridden methods use File | Settings | File Templates.
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone(); //To change body of overridden methods use File | Settings | File Templates.
}
@Override
public String toString() {
return super.toString(); //To change body of overridden methods use File | Settings | File Templates.
}
@Override
protected void finalize() throws Throwable {
super.finalize(); //To change body of overridden methods use File | Settings | File Templates.
}
};
}
}
abstract class MyDD<T> {
class MyClass {
public void foo() {
MyDD<String> d = new MyDD<String>() {
@Override
public int hashCode() {
<selection>return super.hashCode(); //To change body of overridden methods use File | Settings | File Templates.</selection>
}
@Override
public boolean equals(Object obj) {
return super.equals(obj); //To change body of overridden methods use File | Settings | File Templates.
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone(); //To change body of overridden methods use File | Settings | File Templates.
}
@Override
public String toString() {
return super.toString(); //To change body of overridden methods use File | Settings | File Templates.
}
@Override
protected void finalize() throws Throwable {
super.finalize(); //To change body of overridden methods use File | Settings | File Templates.
}
};
}
}
abstract class MyDD<T> {
}
@@ -1,29 +1,29 @@
interface Function<X, Y> { }
class A {
private static final Function<String, String> a = new Function<String, String>() {
@Override
public int hashCode() {
<selection>return super.hashCode(); //To change body of overridden methods use File | Settings | File Templates.</selection>
}
@Override
public boolean equals(Object obj) {
return super.equals(obj); //To change body of overridden methods use File | Settings | File Templates.
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone(); //To change body of overridden methods use File | Settings | File Templates.
}
@Override
public String toString() {
return super.toString(); //To change body of overridden methods use File | Settings | File Templates.
}
@Override
protected void finalize() throws Throwable {
super.finalize(); //To change body of overridden methods use File | Settings | File Templates.
}
};
interface Function<X, Y> { }
class A {
private static final Function<String, String> a = new Function<String, String>() {
@Override
public int hashCode() {
<selection>return super.hashCode(); //To change body of overridden methods use File | Settings | File Templates.</selection>
}
@Override
public boolean equals(Object obj) {
return super.equals(obj); //To change body of overridden methods use File | Settings | File Templates.
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone(); //To change body of overridden methods use File | Settings | File Templates.
}
@Override
public String toString() {
return super.toString(); //To change body of overridden methods use File | Settings | File Templates.
}
@Override
protected void finalize() throws Throwable {
super.finalize(); //To change body of overridden methods use File | Settings | File Templates.
}
};
}
@@ -1,7 +1,7 @@
// "Break string on '\n'" "true"
class A {
String s = "Hello,\n\r" +
"world\n" +
"!\n";
}
// "Break string on '\n'" "true"
class A {
String s = "Hello,\n\r" +
"world\n" +
"!\n";
}
@@ -1,5 +1,5 @@
// "Break string on '\n'" "true"
class A {
String s = "Hello,\n\rwor<caret>ld\n!\n";
}
// "Break string on '\n'" "true"
class A {
String s = "Hello,\n\rwor<caret>ld\n!\n";
}
@@ -1,5 +1,5 @@
// "Break string on '\n'" "false"
class A {
String s = "Hello!\n";
}
// "Break string on '\n'" "false"
class A {
String s = "Hello!\n";
}
@@ -1,5 +1,5 @@
// "Break string on '\n'" "false"
class A {
String s = "Hello!\n\r";
}
// "Break string on '\n'" "false"
class A {
String s = "Hello!\n\r";
}
@@ -1,21 +1,21 @@
// "Convert to 'new Color(0x10101)'" "true"
package java.awt;
class A {
private Color color = new Color(0x10101);
}
class Color {
Color(int r, int g, int b) {
}
Color(int r, int g, int b, int a) {
}
Color(int rgb) {
}
Color(int rgba, boolean hasAlpha) {
}
}
// "Convert to 'new Color(0x10101)'" "true"
package java.awt;
class A {
private Color color = new Color(0x10101);
}
class Color {
Color(int r, int g, int b) {
}
Color(int r, int g, int b, int a) {
}
Color(int rgb) {
}
Color(int rgba, boolean hasAlpha) {
}
}
@@ -1,21 +1,21 @@
// "Convert to 'new Color(0x10101)'" "true"
package java.awt;
class A {
private Color color = new Color(257, 257,<caret> 257);
}
class Color {
Color(int r, int g, int b) {
}
Color(int r, int g, int b, int a) {
}
Color(int rgb) {
}
Color(int rgba, boolean hasAlpha) {
}
}
// "Convert to 'new Color(0x10101)'" "true"
package java.awt;
class A {
private Color color = new Color(257, 257,<caret> 257);
}
class Color {
Color(int r, int g, int b) {
}
Color(int r, int g, int b, int a) {
}
Color(int rgb) {
}
Color(int rgba, boolean hasAlpha) {
}
}
@@ -1,270 +1,270 @@
/*
* 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.codeInsight.completion;
import com.intellij.JavaTestUtil;
import com.intellij.codeInsight.lookup.LookupManager;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.roots.LanguageLevelProjectExtension;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.testFramework.TestDataPath;
import java.io.IOException;
@TestDataPath("$CONTENT_ROOT/testData")
public class ClassNameCompletionTest extends LightFixtureCompletionTestCase {
@Override
protected void setUp() throws Exception {
super.setUp();
LanguageLevelProjectExtension.getInstance(getProject()).setLanguageLevel(LanguageLevel.JDK_1_7);
}
@Override
protected String getBasePath() {
return JavaTestUtil.getRelativeJavaTestDataPath() + "/codeInsight/completion/className/";
}
public void testImportAfterNew() throws Exception {
createClass("package pack; public class AAClass {}");
createClass("package pack; public class WithInnerAClass{\n" +
" public static class Inner{}\n" +
"}");
String path = "/importAfterNew";
configureByFile(path + "/before1.java");
checkResultByFile(path + "/after1.java");
configureByFile(path + "/before2.java");
selectItem(myItems[0]);
checkResultByFile(path + "/after2.java");
}
private void createClass(String text) {
myFixture.addClass(text);
}
public void testAfterNewThrowable1() throws Exception {
addClassesForAfterNewThrowable();
String path = "/afterNewThrowable";
configureByFile(path + "/before1.java");
myFixture.type('\n');
checkResultByFile(path + "/after1.java");
}
private void addClassesForAfterNewThrowable() throws IOException {
createClass("public class OurException extends Throwable{}");
createClass("public class OurNotException {\n" +
" public static class InnerException extends Throwable{}\n" +
" public static class InnerNonException{}\n" +
"}");
}
public void testAfterNewThrowable2() throws Exception {
addClassesForAfterNewThrowable();
String path = "/afterNewThrowable";
configureByFile(path + "/before2.java");
myFixture.type('\n');
checkResultByFile(path + "/after2.java");
}
public void testExcessParensAfterNew() throws Exception { doTest(); }
public void testReuseParensAfterNew() throws Exception { doTest(); }
public void testBracesAfterNew() throws Exception { doTest(); }
public void testInPlainTextFile() throws Exception {
configureByFile(getTestName(false) + ".txt");
checkResultByFile(getTestName(false) + "_after.txt");
}
public void testInPropertiesFile() throws Exception {
myFixture.configureByText("a.properties", "abc = StrinBui<caret>");
complete();
myFixture.checkResult("abc = java.lang.StringBuilder<caret>");
}
public void testDoubleStringBuffer() throws Exception {
createClass("package java.lang; public class StringBuffer {}");
doTest();
assertNull(myItems);
}
public void testReplaceReferenceExpressionWithTypeElement() throws Exception {
createClass("package foo.bar; public class ABCDEF {}");
doTest();
}
public void testCamelHumpPrefix() throws Exception {
String path = "/java/";
configureByFile(path + getTestName(false) + ".java");
complete();
checkResultByFile(path + getTestName(false) + "_after.java");
assertEquals(2, myItems.length);
}
private void doTest() throws Exception {
String path = "/java/";
configureByFile(path + getTestName(false) + ".java");
checkResultByFile(path + getTestName(false) + "_after.java");
}
public void testNameCompletionJava() throws Exception {
String path = "/nameCompletion/java";
configureByFile(path + "/test1-source.java");
performAction();
checkResultByFile(path + "/test1-result.java");
configureByFile(path + "/test2-source.java");
performAction();
checkResultByFile(path + "/test2-result.java");
}
public void testImplementsFiltering1() throws Exception {
final String path = "/nameCompletion/java";
configureByFile(path + "/test4-source.java");
performAction();
checkResultByFile(path + "/test4-result.java");
}
public void testImplementsFiltering2() throws Exception {
final String path = "/nameCompletion/java";
configureByFile(path + "/test3-source.java");
performAction();
checkResultByFile(path + "/test3-result.java");
configureByFile(path + "/implements2-source.java");
performAction();
checkResultByFile(path + "/implements2-result.java");
configureByFile(path + "/implements3-source.java");
performAction();
checkResultByFile(path + "/implements3-result.java");
}
public void testAnnotationFiltering() throws Exception {
createClass("@interface MyObjectType {}");
final String path = "/nameCompletion/java";
configureByFile(path + "/test8-source.java");
performAction();
checkResultByFile(path + "/test8-result.java");
cleanupVfs();
configureByFile(path + "/test9-source.java");
performAction();
checkResultByFile(path + "/test9-result.java");
cleanupVfs();
configureByFile(path + "/test9_2-source.java");
performAction();
checkResultByFile(path + "/test9_2-result.java");
cleanupVfs();
configureByFile(path + "/test9_3-source.java");
performAction();
checkResultByFile(path + "/test9_3-result.java");
cleanupVfs();
configureByFile(path + "/test11-source.java");
performAction();
checkResultByFile(path + "/test11-result.java");
cleanupVfs();
configureByFile(path + "/test10-source.java");
performAction();
checkResultByFile(path + "/test10-result.java");
cleanupVfs();
configureByFile(path + "/test12-source.java");
performAction();
checkResultByFile(path + "/test12-result.java");
cleanupVfs();
configureByFile(path + "/test13-source.java");
performAction();
checkResultByFile(path + "/test13-result.java");
}
private void cleanupVfs() {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
FileDocumentManager.getInstance().saveAllDocuments();
for (VirtualFile file : myFixture.getTempDirFixture().getFile("").getChildren()) {
try {
file.delete(this);
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
}
});
}
public void testInMethodCall() throws Exception {
final String path = "/nameCompletion/java";
configureByFile(path + "/methodCall-source.java");
performAction();
checkResultByFile(path + "/methodCall-result.java");
}
public void testInMethodCallQualifier() throws Exception {
final String path = "/nameCompletion/java";
configureByFile(path + "/methodCall1-source.java");
performAction();
checkResultByFile(path + "/methodCall1-result.java");
}
public void testInVariableDeclarationType() throws Exception {
final String path = "/nameCompletion/java";
configureByFile(path + "/varType-source.java");
performAction();
checkResultByFile(path + "/varType-result.java");
}
public void testExtraSpace() throws Exception { doJavaTest(); }
public void testAnnotation() throws Exception { doJavaTest(); }
public void testInStaticImport() throws Exception { doJavaTest(); }
public void testInCommentWithPackagePrefix() throws Exception { doJavaTest(); }
private void doJavaTest() throws Exception {
final String path = "/nameCompletion/java";
myFixture.configureByFile(path + "/" + getTestName(false) + "-source.java");
performAction();
checkResultByFile(path + "/" + getTestName(false) + "-result.java");
}
@Override
protected void complete() {
myItems = myFixture.complete(CompletionType.BASIC, 2);
}
private void performAction() {
complete();
if (LookupManager.getActiveLookup(myFixture.getEditor()) != null) {
myFixture.type('\n');
}
}
}
/*
* 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.codeInsight.completion;
import com.intellij.JavaTestUtil;
import com.intellij.codeInsight.lookup.LookupManager;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.roots.LanguageLevelProjectExtension;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.testFramework.TestDataPath;
import java.io.IOException;
@TestDataPath("$CONTENT_ROOT/testData")
public class ClassNameCompletionTest extends LightFixtureCompletionTestCase {
@Override
protected void setUp() throws Exception {
super.setUp();
LanguageLevelProjectExtension.getInstance(getProject()).setLanguageLevel(LanguageLevel.JDK_1_7);
}
@Override
protected String getBasePath() {
return JavaTestUtil.getRelativeJavaTestDataPath() + "/codeInsight/completion/className/";
}
public void testImportAfterNew() throws Exception {
createClass("package pack; public class AAClass {}");
createClass("package pack; public class WithInnerAClass{\n" +
" public static class Inner{}\n" +
"}");
String path = "/importAfterNew";
configureByFile(path + "/before1.java");
checkResultByFile(path + "/after1.java");
configureByFile(path + "/before2.java");
selectItem(myItems[0]);
checkResultByFile(path + "/after2.java");
}
private void createClass(String text) {
myFixture.addClass(text);
}
public void testAfterNewThrowable1() throws Exception {
addClassesForAfterNewThrowable();
String path = "/afterNewThrowable";
configureByFile(path + "/before1.java");
myFixture.type('\n');
checkResultByFile(path + "/after1.java");
}
private void addClassesForAfterNewThrowable() throws IOException {
createClass("public class OurException extends Throwable{}");
createClass("public class OurNotException {\n" +
" public static class InnerException extends Throwable{}\n" +
" public static class InnerNonException{}\n" +
"}");
}
public void testAfterNewThrowable2() throws Exception {
addClassesForAfterNewThrowable();
String path = "/afterNewThrowable";
configureByFile(path + "/before2.java");
myFixture.type('\n');
checkResultByFile(path + "/after2.java");
}
public void testExcessParensAfterNew() throws Exception { doTest(); }
public void testReuseParensAfterNew() throws Exception { doTest(); }
public void testBracesAfterNew() throws Exception { doTest(); }
public void testInPlainTextFile() throws Exception {
configureByFile(getTestName(false) + ".txt");
checkResultByFile(getTestName(false) + "_after.txt");
}
public void testInPropertiesFile() throws Exception {
myFixture.configureByText("a.properties", "abc = StrinBui<caret>");
complete();
myFixture.checkResult("abc = java.lang.StringBuilder<caret>");
}
public void testDoubleStringBuffer() throws Exception {
createClass("package java.lang; public class StringBuffer {}");
doTest();
assertNull(myItems);
}
public void testReplaceReferenceExpressionWithTypeElement() throws Exception {
createClass("package foo.bar; public class ABCDEF {}");
doTest();
}
public void testCamelHumpPrefix() throws Exception {
String path = "/java/";
configureByFile(path + getTestName(false) + ".java");
complete();
checkResultByFile(path + getTestName(false) + "_after.java");
assertEquals(2, myItems.length);
}
private void doTest() throws Exception {
String path = "/java/";
configureByFile(path + getTestName(false) + ".java");
checkResultByFile(path + getTestName(false) + "_after.java");
}
public void testNameCompletionJava() throws Exception {
String path = "/nameCompletion/java";
configureByFile(path + "/test1-source.java");
performAction();
checkResultByFile(path + "/test1-result.java");
configureByFile(path + "/test2-source.java");
performAction();
checkResultByFile(path + "/test2-result.java");
}
public void testImplementsFiltering1() throws Exception {
final String path = "/nameCompletion/java";
configureByFile(path + "/test4-source.java");
performAction();
checkResultByFile(path + "/test4-result.java");
}
public void testImplementsFiltering2() throws Exception {
final String path = "/nameCompletion/java";
configureByFile(path + "/test3-source.java");
performAction();
checkResultByFile(path + "/test3-result.java");
configureByFile(path + "/implements2-source.java");
performAction();
checkResultByFile(path + "/implements2-result.java");
configureByFile(path + "/implements3-source.java");
performAction();
checkResultByFile(path + "/implements3-result.java");
}
public void testAnnotationFiltering() throws Exception {
createClass("@interface MyObjectType {}");
final String path = "/nameCompletion/java";
configureByFile(path + "/test8-source.java");
performAction();
checkResultByFile(path + "/test8-result.java");
cleanupVfs();
configureByFile(path + "/test9-source.java");
performAction();
checkResultByFile(path + "/test9-result.java");
cleanupVfs();
configureByFile(path + "/test9_2-source.java");
performAction();
checkResultByFile(path + "/test9_2-result.java");
cleanupVfs();
configureByFile(path + "/test9_3-source.java");
performAction();
checkResultByFile(path + "/test9_3-result.java");
cleanupVfs();
configureByFile(path + "/test11-source.java");
performAction();
checkResultByFile(path + "/test11-result.java");
cleanupVfs();
configureByFile(path + "/test10-source.java");
performAction();
checkResultByFile(path + "/test10-result.java");
cleanupVfs();
configureByFile(path + "/test12-source.java");
performAction();
checkResultByFile(path + "/test12-result.java");
cleanupVfs();
configureByFile(path + "/test13-source.java");
performAction();
checkResultByFile(path + "/test13-result.java");
}
private void cleanupVfs() {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
FileDocumentManager.getInstance().saveAllDocuments();
for (VirtualFile file : myFixture.getTempDirFixture().getFile("").getChildren()) {
try {
file.delete(this);
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
}
});
}
public void testInMethodCall() throws Exception {
final String path = "/nameCompletion/java";
configureByFile(path + "/methodCall-source.java");
performAction();
checkResultByFile(path + "/methodCall-result.java");
}
public void testInMethodCallQualifier() throws Exception {
final String path = "/nameCompletion/java";
configureByFile(path + "/methodCall1-source.java");
performAction();
checkResultByFile(path + "/methodCall1-result.java");
}
public void testInVariableDeclarationType() throws Exception {
final String path = "/nameCompletion/java";
configureByFile(path + "/varType-source.java");
performAction();
checkResultByFile(path + "/varType-result.java");
}
public void testExtraSpace() throws Exception { doJavaTest(); }
public void testAnnotation() throws Exception { doJavaTest(); }
public void testInStaticImport() throws Exception { doJavaTest(); }
public void testInCommentWithPackagePrefix() throws Exception { doJavaTest(); }
private void doJavaTest() throws Exception {
final String path = "/nameCompletion/java";
myFixture.configureByFile(path + "/" + getTestName(false) + "-source.java");
performAction();
checkResultByFile(path + "/" + getTestName(false) + "-result.java");
}
@Override
protected void complete() {
myItems = myFixture.complete(CompletionType.BASIC, 2);
}
private void performAction() {
complete();
if (LookupManager.getActiveLookup(myFixture.getEditor()) != null) {
myFixture.type('\n');
}
}
}
@@ -1,83 +1,83 @@
/*
* Copyright (c) 2000-2005 by JetBrains s.r.o. All Rights Reserved.
* Use is subject to license terms.
*/
package com.intellij.codeInsight.completion;
import com.intellij.codeInsight.CodeInsightSettings;
import com.intellij.codeInsight.completion.impl.CompletionServiceImpl;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupManager;
import com.intellij.codeInsight.lookup.impl.LookupImpl;
import com.intellij.ide.ui.UISettings;
import com.intellij.psi.statistics.StatisticsManager;
import com.intellij.psi.statistics.impl.StatisticsManagerImpl;
import com.intellij.testFramework.TestDataPath;
import org.jetbrains.annotations.NonNls;
/**
* @author peter
*/
@TestDataPath("$CONTENT_ROOT/testData")
public abstract class CompletionSortingTestCase extends LightFixtureCompletionTestCase {
private final CompletionType myType;
@SuppressWarnings({"JUnitTestCaseWithNonTrivialConstructors"})
protected CompletionSortingTestCase(CompletionType type) {
myType = type;
}
@Override
protected void setUp() throws Exception {
super.setUp();
((StatisticsManagerImpl)StatisticsManager.getInstance()).enableStatistics(getTestRootDisposable());
}
@Override
protected void tearDown() throws Exception {
LookupManager.getInstance(getProject()).hideActiveLookup();
UISettings.getInstance().SORT_LOOKUP_ELEMENTS_LEXICOGRAPHICALLY = false;
CodeInsightSettings.getInstance().COMPLETION_CASE_SENSITIVE = CodeInsightSettings.FIRST_LETTER;
super.tearDown();
}
@Override
protected abstract String getBasePath();
protected void checkPreferredItems(final int selected, @NonNls final String... expected) {
invokeCompletion(getTestName(false) + ".java");
assertPreferredItems(selected, expected);
}
protected void assertPreferredItems(final int selected, @NonNls final String... expected) {
myFixture.assertPreferredCompletionItems(selected, expected);
}
protected LookupImpl invokeCompletion(final String path) {
configureNoCompletion(path);
myFixture.complete(myType);
return getLookup();
}
protected void configureNoCompletion(String path) {
myFixture.configureFromExistingVirtualFile(
myFixture.copyFileToProject(path, com.intellij.openapi.util.text.StringUtil.getShortName(path, '/')));
}
protected static void incUseCount(final LookupImpl lookup, final int index) {
imitateItemSelection(lookup, index);
refreshSorting(lookup);
}
protected static void refreshSorting(final LookupImpl lookup) {
lookup.setSelectionTouched(false);
lookup.resort(true);
}
protected static void imitateItemSelection(final LookupImpl lookup, final int index) {
final LookupElement item = lookup.getItems().get(index);
lookup.setCurrentItem(item);
CompletionLookupArranger.collectStatisticChanges(CompletionServiceImpl.getCompletionService().getCurrentCompletion(), item);
CompletionLookupArranger.applyLastCompletionStatisticsUpdate();
}
}
/*
* Copyright (c) 2000-2005 by JetBrains s.r.o. All Rights Reserved.
* Use is subject to license terms.
*/
package com.intellij.codeInsight.completion;
import com.intellij.codeInsight.CodeInsightSettings;
import com.intellij.codeInsight.completion.impl.CompletionServiceImpl;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupManager;
import com.intellij.codeInsight.lookup.impl.LookupImpl;
import com.intellij.ide.ui.UISettings;
import com.intellij.psi.statistics.StatisticsManager;
import com.intellij.psi.statistics.impl.StatisticsManagerImpl;
import com.intellij.testFramework.TestDataPath;
import org.jetbrains.annotations.NonNls;
/**
* @author peter
*/
@TestDataPath("$CONTENT_ROOT/testData")
public abstract class CompletionSortingTestCase extends LightFixtureCompletionTestCase {
private final CompletionType myType;
@SuppressWarnings({"JUnitTestCaseWithNonTrivialConstructors"})
protected CompletionSortingTestCase(CompletionType type) {
myType = type;
}
@Override
protected void setUp() throws Exception {
super.setUp();
((StatisticsManagerImpl)StatisticsManager.getInstance()).enableStatistics(getTestRootDisposable());
}
@Override
protected void tearDown() throws Exception {
LookupManager.getInstance(getProject()).hideActiveLookup();
UISettings.getInstance().SORT_LOOKUP_ELEMENTS_LEXICOGRAPHICALLY = false;
CodeInsightSettings.getInstance().COMPLETION_CASE_SENSITIVE = CodeInsightSettings.FIRST_LETTER;
super.tearDown();
}
@Override
protected abstract String getBasePath();
protected void checkPreferredItems(final int selected, @NonNls final String... expected) {
invokeCompletion(getTestName(false) + ".java");
assertPreferredItems(selected, expected);
}
protected void assertPreferredItems(final int selected, @NonNls final String... expected) {
myFixture.assertPreferredCompletionItems(selected, expected);
}
protected LookupImpl invokeCompletion(final String path) {
configureNoCompletion(path);
myFixture.complete(myType);
return getLookup();
}
protected void configureNoCompletion(String path) {
myFixture.configureFromExistingVirtualFile(
myFixture.copyFileToProject(path, com.intellij.openapi.util.text.StringUtil.getShortName(path, '/')));
}
protected static void incUseCount(final LookupImpl lookup, final int index) {
imitateItemSelection(lookup, index);
refreshSorting(lookup);
}
protected static void refreshSorting(final LookupImpl lookup) {
lookup.setSelectionTouched(false);
lookup.resort(true);
}
protected static void imitateItemSelection(final LookupImpl lookup, final int index) {
final LookupElement item = lookup.getItems().get(index);
lookup.setCurrentItem(item);
CompletionLookupArranger.collectStatisticChanges(CompletionServiceImpl.getCompletionService().getCurrentCompletion(), item);
CompletionLookupArranger.applyLastCompletionStatisticsUpdate();
}
}
@@ -1,206 +1,206 @@
package com.intellij.codeInsight.completion;
import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase
import com.intellij.codeInsight.CodeInsightSettings
import com.intellij.util.ArrayUtil
import com.intellij.codeInsight.lookup.LookupElementPresentation
import com.intellij.codeInsight.lookup.LookupElement;
/**
* @author peter
*/
public class GlobalMemberNameCompletionTest extends LightCodeInsightFixtureTestCase {
public void testMethodName() throws Exception {
myFixture.addClass("""
package foo;
public class Foo {
public static int abcmethod() {}
static void methodThatsNotVisible() {}
}
""")
doTest "class Bar {{ abcm<caret> }}", true, """import static foo.Foo.abcmethod;
class Bar {{ abcmethod()<caret> }}"""
}
public void testFieldName() throws Exception {
myFixture.addClass("""
package foo;
public class Foo {
public static int abcfield = 2
static final int fieldThatsNotVisible = 3
}
""")
doTest "class Bar {{ abcf<caret> }}", true, """import static foo.Foo.abcfield;
class Bar {{ abcfield<caret> }}"""
}
public void testFieldNameQualified() throws Exception {
myFixture.addClass("""
package foo;
public class Foo {
public static int abcfield = 2
static final int fieldThatsNotVisible = 3
}
""")
doTest "class Bar {{ abcf<caret> }}", false, """import foo.Foo;
class Bar {{ Foo.abcfield<caret> }}"""
}
public void testFieldNamePresentation() {
myFixture.addClass("""
package foo;
public class Foo {
public static int abcfield = 2
static final int fieldThatsNotVisible = 3
}
""")
myFixture.configureByText "a.java", "class Bar {{ abcf<caret> }}"
def element = complete()[0]
def presentation = new LookupElementPresentation()
element.renderElement(presentation)
assert 'Foo.abcfield' == presentation.itemText
assert ' (foo)' == presentation.tailText
assert 'int' == presentation.typeText
}
private LookupElement[] complete() {
myFixture.complete(CompletionType.BASIC, 2)
}
public void testQualifiedMethodName() throws Exception {
myFixture.addClass("""
package foo;
public class Foo {
public static int abcmethod() {}
}
""")
doTest "class Bar {{ abcm<caret> }}", false, """import foo.Foo;
class Bar {{ Foo.abcmethod()<caret> }}"""
}
public void testIfThereAreAlreadyStaticImportsWithThatClass() throws Exception {
myFixture.addClass("""
package foo;
public class Foo {
public static int anotherMethod(int a) {}
public static int abcmethod() {}
void methodThatsNotVisible() {}
}
""")
doTest """import static foo.Foo.abcmethod;
class Bar {{ abcmethod(); anoMe<caret> }}""", false,
"""import static foo.Foo.abcmethod;
import static foo.Foo.anotherMethod;
class Bar {{ abcmethod(); anotherMethod(<caret>) }}"""
}
@Override protected void tearDown() {
CodeInsightSettings.instance.EXCLUDED_PACKAGES = ArrayUtil.EMPTY_STRING_ARRAY
super.tearDown()
}
public void testExcludeClassFromCompletion() throws Exception {
myFixture.addClass("""package foo;
public class Foo {
public static int abcmethod() {}
}
""")
myFixture.addClass("""package foo;
public class Excl {
public static int abcmethod2() {}
}
""")
CodeInsightSettings.instance.EXCLUDED_PACKAGES = ["foo.Excl"] as String[]
doTest "class Bar {{ abcm<caret> }}", true, """import static foo.Foo.abcmethod;
class Bar {{ abcmethod()<caret> }}"""
}
public void testExcludeMethodFromCompletion() throws Exception {
myFixture.addClass("""package foo;
public class Foo {
public static int abcmethod1() {}
public static int abcmethodExcluded() {}
}
""")
CodeInsightSettings.instance.EXCLUDED_PACKAGES = ["foo.Foo.abcmethodExcluded"] as String[]
doTest "class Bar {{ abcm<caret> }}", true, """import static foo.Foo.abcmethod1;
class Bar {{ abcmethod1()<caret> }}"""
}
public void testMergeOverloads() throws Exception {
myFixture.addClass("""package foo;
public class Foo {
public static int abcmethod(int a) {}
public static int abcmethod(boolean a) {}
public static int abcmethod1(boolean a) {}
}
""")
myFixture.configureByText("a.java", "class Bar {{ abcm<caret> }}")
complete()
assertOrderedEquals myFixture.lookupElementStrings, "abcmethod", "abcmethod1"
}
public void testMethodFromTheSameClass() {
myFixture.configureByText("a.java", """
class A {
static void foo() {}
static void goo() {
f<caret>
}
}
""")
def element = complete()[0]
def presentation = new LookupElementPresentation()
element.renderElement(presentation)
assert 'foo' == presentation.itemText
myFixture.type '\n'
myFixture.checkResult '''
class A {
static void foo() {}
static void goo() {
foo();<caret>
}
}
'''
}
private void doTest(String input, boolean importStatic, String output) {
myFixture.configureByText("a.java", input)
def item = assertOneElement(complete())
if (importStatic) {
item.'as'(StaticallyImportable).shouldBeImported = true
}
myFixture.type('\n')
myFixture.checkResult output
}
}
package com.intellij.codeInsight.completion;
import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase
import com.intellij.codeInsight.CodeInsightSettings
import com.intellij.util.ArrayUtil
import com.intellij.codeInsight.lookup.LookupElementPresentation
import com.intellij.codeInsight.lookup.LookupElement;
/**
* @author peter
*/
public class GlobalMemberNameCompletionTest extends LightCodeInsightFixtureTestCase {
public void testMethodName() throws Exception {
myFixture.addClass("""
package foo;
public class Foo {
public static int abcmethod() {}
static void methodThatsNotVisible() {}
}
""")
doTest "class Bar {{ abcm<caret> }}", true, """import static foo.Foo.abcmethod;
class Bar {{ abcmethod()<caret> }}"""
}
public void testFieldName() throws Exception {
myFixture.addClass("""
package foo;
public class Foo {
public static int abcfield = 2
static final int fieldThatsNotVisible = 3
}
""")
doTest "class Bar {{ abcf<caret> }}", true, """import static foo.Foo.abcfield;
class Bar {{ abcfield<caret> }}"""
}
public void testFieldNameQualified() throws Exception {
myFixture.addClass("""
package foo;
public class Foo {
public static int abcfield = 2
static final int fieldThatsNotVisible = 3
}
""")
doTest "class Bar {{ abcf<caret> }}", false, """import foo.Foo;
class Bar {{ Foo.abcfield<caret> }}"""
}
public void testFieldNamePresentation() {
myFixture.addClass("""
package foo;
public class Foo {
public static int abcfield = 2
static final int fieldThatsNotVisible = 3
}
""")
myFixture.configureByText "a.java", "class Bar {{ abcf<caret> }}"
def element = complete()[0]
def presentation = new LookupElementPresentation()
element.renderElement(presentation)
assert 'Foo.abcfield' == presentation.itemText
assert ' (foo)' == presentation.tailText
assert 'int' == presentation.typeText
}
private LookupElement[] complete() {
myFixture.complete(CompletionType.BASIC, 2)
}
public void testQualifiedMethodName() throws Exception {
myFixture.addClass("""
package foo;
public class Foo {
public static int abcmethod() {}
}
""")
doTest "class Bar {{ abcm<caret> }}", false, """import foo.Foo;
class Bar {{ Foo.abcmethod()<caret> }}"""
}
public void testIfThereAreAlreadyStaticImportsWithThatClass() throws Exception {
myFixture.addClass("""
package foo;
public class Foo {
public static int anotherMethod(int a) {}
public static int abcmethod() {}
void methodThatsNotVisible() {}
}
""")
doTest """import static foo.Foo.abcmethod;
class Bar {{ abcmethod(); anoMe<caret> }}""", false,
"""import static foo.Foo.abcmethod;
import static foo.Foo.anotherMethod;
class Bar {{ abcmethod(); anotherMethod(<caret>) }}"""
}
@Override protected void tearDown() {
CodeInsightSettings.instance.EXCLUDED_PACKAGES = ArrayUtil.EMPTY_STRING_ARRAY
super.tearDown()
}
public void testExcludeClassFromCompletion() throws Exception {
myFixture.addClass("""package foo;
public class Foo {
public static int abcmethod() {}
}
""")
myFixture.addClass("""package foo;
public class Excl {
public static int abcmethod2() {}
}
""")
CodeInsightSettings.instance.EXCLUDED_PACKAGES = ["foo.Excl"] as String[]
doTest "class Bar {{ abcm<caret> }}", true, """import static foo.Foo.abcmethod;
class Bar {{ abcmethod()<caret> }}"""
}
public void testExcludeMethodFromCompletion() throws Exception {
myFixture.addClass("""package foo;
public class Foo {
public static int abcmethod1() {}
public static int abcmethodExcluded() {}
}
""")
CodeInsightSettings.instance.EXCLUDED_PACKAGES = ["foo.Foo.abcmethodExcluded"] as String[]
doTest "class Bar {{ abcm<caret> }}", true, """import static foo.Foo.abcmethod1;
class Bar {{ abcmethod1()<caret> }}"""
}
public void testMergeOverloads() throws Exception {
myFixture.addClass("""package foo;
public class Foo {
public static int abcmethod(int a) {}
public static int abcmethod(boolean a) {}
public static int abcmethod1(boolean a) {}
}
""")
myFixture.configureByText("a.java", "class Bar {{ abcm<caret> }}")
complete()
assertOrderedEquals myFixture.lookupElementStrings, "abcmethod", "abcmethod1"
}
public void testMethodFromTheSameClass() {
myFixture.configureByText("a.java", """
class A {
static void foo() {}
static void goo() {
f<caret>
}
}
""")
def element = complete()[0]
def presentation = new LookupElementPresentation()
element.renderElement(presentation)
assert 'foo' == presentation.itemText
myFixture.type '\n'
myFixture.checkResult '''
class A {
static void foo() {}
static void goo() {
foo();<caret>
}
}
'''
}
private void doTest(String input, boolean importStatic, String output) {
myFixture.configureByText("a.java", input)
def item = assertOneElement(complete())
if (importStatic) {
item.'as'(StaticallyImportable).shouldBeImported = true
}
myFixture.type('\n')
myFixture.checkResult output
}
}
@@ -1,113 +1,113 @@
/*
* Copyright (c) 2000-2005 by JetBrains s.r.o. All Rights Reserved.
* Use is subject to license terms.
*/
package com.intellij.codeInsight.completion;
import com.intellij.JavaTestUtil;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupManager;
import com.intellij.codeInsight.lookup.impl.LookupImpl;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.module.StdModuleTypes;
import com.intellij.openapi.roots.ContentEntry;
import com.intellij.openapi.roots.ModifiableRootModel;
import com.intellij.openapi.roots.ModuleRootManager;
import com.intellij.openapi.roots.SourceFolder;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.JavaPsiFacade;
import com.intellij.testFramework.PsiTestUtil;
import com.intellij.testFramework.fixtures.JavaCodeInsightFixtureTestCase;
/**
* @author peter
*/
public class HeavyNormalCompletionTest extends JavaCodeInsightFixtureTestCase {
@Override
protected String getTestDataPath() {
return JavaTestUtil.getJavaTestDataPath();
}
public void testPackagePrefix() throws Throwable {
myFixture.configureByFile("/codeInsight/completion/normal/" + getTestName(false) + ".java");
new WriteCommandAction.Simple(getProject()) {
@Override
protected void run() throws Throwable {
final ModifiableRootModel model = ModuleRootManager.getInstance(myFixture.getModule()).getModifiableModel();
model.getContentEntries()[0].getSourceFolders()[0].setPackagePrefix("foo.bar.goo");
model.commit();
}
}.execute().throwException();
myFixture.completeBasic();
myFixture.checkResultByFile("/codeInsight/completion/normal/" + getTestName(false) + "_after.java");
assertTrue(JavaPsiFacade.getInstance(getProject()).findPackage("foo").isValid());
assertTrue(JavaPsiFacade.getInstance(getProject()).findPackage("foo.bar").isValid());
assertTrue(JavaPsiFacade.getInstance(getProject()).findPackage("foo.bar.goo").isValid());
}
public void testPreferTestCases() throws Throwable {
myFixture.configureByFile("/codeInsight/completion/normal/" + getTestName(false) + ".java");
new WriteCommandAction.Simple(getProject()) {
@Override
protected void run() throws Throwable {
final ModifiableRootModel model = ModuleRootManager.getInstance(myFixture.getModule()).getModifiableModel();
ContentEntry contentEntry = model.getContentEntries()[0];
SourceFolder sourceFolder = contentEntry.getSourceFolders()[0];
VirtualFile file = sourceFolder.getFile();
contentEntry.removeSourceFolder(sourceFolder);
contentEntry.addSourceFolder(file, true);
model.commit();
}
}.execute().throwException();
myFixture.addClass("package foo; public class SomeTestCase {}");
myFixture.addClass("package bar; public class SomeTestec {}");
myFixture.addClass("package goo; public class SomeAnchor {}");
myFixture.completeBasic();
myFixture.assertPreferredCompletionItems(0, "SomeTestCase", "SomeAnchor", "SomeTestec");
}
public void testAllClassesWhenNothingIsFound() throws Throwable {
myFixture.addClass("package foo.bar; public class AxBxCxDxEx {}");
myFixture.configureByFile("/codeInsight/completion/normal/" + getTestName(false) + ".java");
myFixture.completeBasic();
myFixture.type('\n');
myFixture.checkResultByFile("/codeInsight/completion/normal/" + getTestName(false) + "_after.java");
}
public void testAllClassesOnSecondBasicCompletion() throws Throwable {
myFixture.addClass("package foo.bar; public class AxBxCxDxEx {}");
myFixture.configureByFile("/codeInsight/completion/normal/" + getTestName(false) + ".java");
myFixture.complete(CompletionType.BASIC, 2);
LookupImpl lookup = (LookupImpl)LookupManager.getActiveLookup(myFixture.getEditor());
LookupElement[] myItems = lookup.getItems().toArray(LookupElement.EMPTY_ARRAY);
assertEquals(2, myItems.length);
assertEquals("AxBxCxDxEx", myItems[1].getLookupString());
assertEquals("AyByCyDyEy", myItems[0].getLookupString());
}
public void testMapsInvalidation() throws Exception {
myFixture.configureByFile("/codeInsight/completion/normal/" + getTestName(false) + ".java");
assertInstanceOf(myFixture.getFile().getVirtualFile().getFileSystem(), LocalFileSystem.class); // otherwise the completion copy won't be preserved which is critical here
myFixture.completeBasic();
assertOrderedEquals(myFixture.getLookupElementStrings(), "getAaa", "getBbb");
myFixture.getEditor().getCaretModel().moveToOffset(myFixture.getEditor().getCaretModel().getOffset() + 2);
assertNull(myFixture.completeBasic());
}
public void testQualifyInaccessibleClassName() throws Exception {
PsiTestUtil.addModule(getProject(), StdModuleTypes.JAVA, "second", myFixture.getTempDirFixture().findOrCreateDir("second"));
myFixture.addFileToProject("second/foo/bar/AxBxCxDxEx.java", "package foo.bar; class AxBxCxDxEx {}");
myFixture.configureByText("a.java", "class Main { ABCDE<caret> }");
myFixture.complete(CompletionType.BASIC, 3);
myFixture.checkResult("class Main { foo.bar.AxBxCxDxEx<caret> }");
}
}
/*
* Copyright (c) 2000-2005 by JetBrains s.r.o. All Rights Reserved.
* Use is subject to license terms.
*/
package com.intellij.codeInsight.completion;
import com.intellij.JavaTestUtil;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupManager;
import com.intellij.codeInsight.lookup.impl.LookupImpl;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.module.StdModuleTypes;
import com.intellij.openapi.roots.ContentEntry;
import com.intellij.openapi.roots.ModifiableRootModel;
import com.intellij.openapi.roots.ModuleRootManager;
import com.intellij.openapi.roots.SourceFolder;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.JavaPsiFacade;
import com.intellij.testFramework.PsiTestUtil;
import com.intellij.testFramework.fixtures.JavaCodeInsightFixtureTestCase;
/**
* @author peter
*/
public class HeavyNormalCompletionTest extends JavaCodeInsightFixtureTestCase {
@Override
protected String getTestDataPath() {
return JavaTestUtil.getJavaTestDataPath();
}
public void testPackagePrefix() throws Throwable {
myFixture.configureByFile("/codeInsight/completion/normal/" + getTestName(false) + ".java");
new WriteCommandAction.Simple(getProject()) {
@Override
protected void run() throws Throwable {
final ModifiableRootModel model = ModuleRootManager.getInstance(myFixture.getModule()).getModifiableModel();
model.getContentEntries()[0].getSourceFolders()[0].setPackagePrefix("foo.bar.goo");
model.commit();
}
}.execute().throwException();
myFixture.completeBasic();
myFixture.checkResultByFile("/codeInsight/completion/normal/" + getTestName(false) + "_after.java");
assertTrue(JavaPsiFacade.getInstance(getProject()).findPackage("foo").isValid());
assertTrue(JavaPsiFacade.getInstance(getProject()).findPackage("foo.bar").isValid());
assertTrue(JavaPsiFacade.getInstance(getProject()).findPackage("foo.bar.goo").isValid());
}
public void testPreferTestCases() throws Throwable {
myFixture.configureByFile("/codeInsight/completion/normal/" + getTestName(false) + ".java");
new WriteCommandAction.Simple(getProject()) {
@Override
protected void run() throws Throwable {
final ModifiableRootModel model = ModuleRootManager.getInstance(myFixture.getModule()).getModifiableModel();
ContentEntry contentEntry = model.getContentEntries()[0];
SourceFolder sourceFolder = contentEntry.getSourceFolders()[0];
VirtualFile file = sourceFolder.getFile();
contentEntry.removeSourceFolder(sourceFolder);
contentEntry.addSourceFolder(file, true);
model.commit();
}
}.execute().throwException();
myFixture.addClass("package foo; public class SomeTestCase {}");
myFixture.addClass("package bar; public class SomeTestec {}");
myFixture.addClass("package goo; public class SomeAnchor {}");
myFixture.completeBasic();
myFixture.assertPreferredCompletionItems(0, "SomeTestCase", "SomeAnchor", "SomeTestec");
}
public void testAllClassesWhenNothingIsFound() throws Throwable {
myFixture.addClass("package foo.bar; public class AxBxCxDxEx {}");
myFixture.configureByFile("/codeInsight/completion/normal/" + getTestName(false) + ".java");
myFixture.completeBasic();
myFixture.type('\n');
myFixture.checkResultByFile("/codeInsight/completion/normal/" + getTestName(false) + "_after.java");
}
public void testAllClassesOnSecondBasicCompletion() throws Throwable {
myFixture.addClass("package foo.bar; public class AxBxCxDxEx {}");
myFixture.configureByFile("/codeInsight/completion/normal/" + getTestName(false) + ".java");
myFixture.complete(CompletionType.BASIC, 2);
LookupImpl lookup = (LookupImpl)LookupManager.getActiveLookup(myFixture.getEditor());
LookupElement[] myItems = lookup.getItems().toArray(LookupElement.EMPTY_ARRAY);
assertEquals(2, myItems.length);
assertEquals("AxBxCxDxEx", myItems[1].getLookupString());
assertEquals("AyByCyDyEy", myItems[0].getLookupString());
}
public void testMapsInvalidation() throws Exception {
myFixture.configureByFile("/codeInsight/completion/normal/" + getTestName(false) + ".java");
assertInstanceOf(myFixture.getFile().getVirtualFile().getFileSystem(), LocalFileSystem.class); // otherwise the completion copy won't be preserved which is critical here
myFixture.completeBasic();
assertOrderedEquals(myFixture.getLookupElementStrings(), "getAaa", "getBbb");
myFixture.getEditor().getCaretModel().moveToOffset(myFixture.getEditor().getCaretModel().getOffset() + 2);
assertNull(myFixture.completeBasic());
}
public void testQualifyInaccessibleClassName() throws Exception {
PsiTestUtil.addModule(getProject(), StdModuleTypes.JAVA, "second", myFixture.getTempDirFixture().findOrCreateDir("second"));
myFixture.addFileToProject("second/foo/bar/AxBxCxDxEx.java", "package foo.bar; class AxBxCxDxEx {}");
myFixture.configureByText("a.java", "class Main { ABCDE<caret> }");
myFixture.complete(CompletionType.BASIC, 3);
myFixture.checkResult("class Main { foo.bar.AxBxCxDxEx<caret> }");
}
}
File diff suppressed because it is too large Load Diff
@@ -1,232 +1,232 @@
package com.intellij.codeInsight.completion;
import com.intellij.JavaTestUtil;
import com.intellij.codeInsight.CodeInsightSettings;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInspection.javaDoc.JavaDocLocalInspection;
import com.intellij.lang.StdLanguages;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiReference;
import com.intellij.psi.PsiReferenceBase;
import com.intellij.psi.PsiReferenceProvider;
import com.intellij.psi.codeStyle.CodeStyleSettingsManager;
import com.intellij.psi.impl.source.resolve.reference.PsiReferenceRegistrarImpl;
import com.intellij.psi.impl.source.resolve.reference.ReferenceProvidersRegistry;
import com.intellij.psi.javadoc.PsiDocTag;
import com.intellij.util.ObjectUtils;
import com.intellij.util.ProcessingContext;
import org.jetbrains.annotations.NotNull;
import java.util.Arrays;
import java.util.List;
/**
* @author mike
*/
public class JavadocCompletionTest extends LightFixtureCompletionTestCase {
@Override
protected String getBasePath() {
return JavaTestUtil.getRelativeJavaTestDataPath() + "/codeInsight/completion/javadoc/";
}
@Override
protected void setUp() throws Exception {
super.setUp();
myFixture.enableInspections(new JavaDocLocalInspection());
}
public void testNamesInClass() throws Exception {
configureByFile("ClassTagName.java");
assertStringItems("author", "deprecated", "param", "see", "serial", "since", "version");
}
public void testNamesInField() throws Exception {
configureByFile("FieldTagName.java");
assertStringItems("deprecated", "see", "serial", "serialField", "since");
}
public void testNamesInMethod0() throws Exception {
configureByFile("MethodTagName0.java");
assertStringItems("deprecated", "exception", "param", "return", "see", "serialData", "since", "throws");
}
public void testNamesInMethod1() throws Exception {
configureByFile("MethodTagName1.java");
assertStringItems("see", "serialData", "since");
}
public void testParamValueCompletion() throws Exception {
configureByFile("ParamValue0.java");
assertStringItems("a", "b", "c");
}
public void testParamValueWithPrefixCompletion() throws Exception {
configureByFile("ParamValue1.java");
assertStringItems("a1", "a2", "a3");
}
public void testDescribedParameters() throws Exception {
configureByFile("ParamValue2.java");
assertStringItems("a2", "a3");
}
public void testSee0() throws Exception {
configureByFile("See0.java");
assertStringItems("foo", "clone", "equals", "getClass", "hashCode", "notify", "notifyAll", "Object", "toString", "wait", "wait", "wait", "finalize", "registerNatives");
}
public void testSee1() throws Exception {
configureByFile("See1.java");
assertStringItems("notify", "notifyAll");
}
public void testSee2() throws Exception {
configureByFile("See2.java");
assertStringItems("notify", "notifyAll");
}
public void testSee3() throws Exception {
configureByFile("See3.java");
assertTrue(getLookupElementStrings().containsAll(Arrays.asList("foo", "myField")));
}
@NotNull
private List<String> getLookupElementStrings() {
return ObjectUtils.assertNotNull(myFixture.getLookupElementStrings());
}
public void testSee4() throws Exception {
configureByFile("See4.java");
assertTrue(getLookupElementStrings().containsAll(Arrays.asList("A", "B", "C")));
}
public void testSee5() throws Exception {
configureByFile("See5.java");
assertTrue(getLookupElementStrings().containsAll(Arrays.asList("foo", "myName")));
}
public void testIDEADEV10620() throws Exception {
configureByFile("IDEADEV10620.java");
checkResultByFile("IDEADEV10620-after.java");
}
public void testException0() throws Exception {
configureByFile("Exception0.java");
assertStringItems("deprecated", "exception", "param", "see", "serialData", "since", "throws");
}
public void testException1() throws Exception {
configureByFile("Exception1.java");
assertTrue(myItems.length > 18);
}
public void testException2() throws Exception {
myFixture.configureByFile("Exception2.java");
myFixture.complete(CompletionType.SMART);
assertStringItems("IllegalStateException", "IOException");
}
public void testInlineLookup() throws Exception {
configureByFile("InlineTagName.java");
assertStringItems("code", "docRoot", "inheritDoc", "link", "linkplain", "literal", "value");
}
public void testFinishWithSharp() throws Throwable {
boolean old = CodeInsightSettings.getInstance().AUTOCOMPLETE_ON_CODE_COMPLETION;
CodeInsightSettings.getInstance().AUTOCOMPLETE_ON_CODE_COMPLETION = false;
try {
checkFinishWithSharp();
}
finally {
CodeInsightSettings.getInstance().AUTOCOMPLETE_ON_CODE_COMPLETION = old;
}
}
private void checkFinishWithSharp() throws Exception {
myFixture.configureByFile("FinishWithSharp.java");
myFixture.completeBasic();
type('#');
checkResultByFile("FinishWithSharp_after.java");
final List<LookupElement> items = getLookup().getItems();
assertEquals("bar", items.get(0).getLookupString());
assertEquals("foo", items.get(1).getLookupString());
}
public void testShortenClassName() throws Throwable {
CodeStyleSettingsManager.getSettings(getProject()).USE_FQ_CLASS_NAMES_IN_JAVADOC = false;
try {
doTest();
}
finally {
CodeStyleSettingsManager.getSettings(getProject()).USE_FQ_CLASS_NAMES_IN_JAVADOC = true;
}
}
public void testMethodBeforeSharp() throws Throwable {
doTest();
}
public void testFieldReferenceInInnerClassJavadoc() throws Throwable {
doTest();
}
public void testShortenClassReference() throws Throwable { doTest(); }
public void testQualifiedClassReference() throws Throwable {
configureByFile(getTestName(false) + ".java");
myFixture.complete(CompletionType.BASIC, 2);
checkResultByFile(getTestName(false) + "_after.java");
}
public void testThrowsNonImported() throws Throwable {
configureByFile(getTestName(false) + ".java");
myFixture.complete(CompletionType.BASIC, 2);
checkResultByFile(getTestName(false) + "_after.java");
}
private void doTest() throws Exception {
configureByFile(getTestName(false) + ".java");
checkResultByFile(getTestName(false) + "_after.java");
}
public void testInlinePackageReferenceCompletion() throws Exception {
configureByFile("InlineReference.java");
assertTrue(getLookupElementStrings().containsAll(Arrays.asList("io", "lang", "util")));
}
public void testCustomReferenceProvider() throws Exception {
PsiReferenceRegistrarImpl registrar =
(PsiReferenceRegistrarImpl) ReferenceProvidersRegistry.getInstance().getRegistrar(StdLanguages.JAVA);
PsiReferenceProvider provider = new PsiReferenceProvider() {
@Override
@NotNull
public PsiReference[] getReferencesByElement(@NotNull final PsiElement element, @NotNull final ProcessingContext context) {
return new PsiReference[]{new PsiReferenceBase<PsiElement>(element) {
@Override
public PsiElement resolve() {
return element;
}
@Override
@NotNull
public Object[] getVariants() {
return new Object[]{"1", "2", "3"};
}
}};
}
};
try {
registrar.registerReferenceProvider(PsiDocTag.class, provider);
configureByFile("ReferenceProvider.java");
assertStringItems("1", "2", "3");
}
finally {
registrar.unregisterReferenceProvider(PsiDocTag.class, provider);
}
}
}
package com.intellij.codeInsight.completion;
import com.intellij.JavaTestUtil;
import com.intellij.codeInsight.CodeInsightSettings;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInspection.javaDoc.JavaDocLocalInspection;
import com.intellij.lang.StdLanguages;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiReference;
import com.intellij.psi.PsiReferenceBase;
import com.intellij.psi.PsiReferenceProvider;
import com.intellij.psi.codeStyle.CodeStyleSettingsManager;
import com.intellij.psi.impl.source.resolve.reference.PsiReferenceRegistrarImpl;
import com.intellij.psi.impl.source.resolve.reference.ReferenceProvidersRegistry;
import com.intellij.psi.javadoc.PsiDocTag;
import com.intellij.util.ObjectUtils;
import com.intellij.util.ProcessingContext;
import org.jetbrains.annotations.NotNull;
import java.util.Arrays;
import java.util.List;
/**
* @author mike
*/
public class JavadocCompletionTest extends LightFixtureCompletionTestCase {
@Override
protected String getBasePath() {
return JavaTestUtil.getRelativeJavaTestDataPath() + "/codeInsight/completion/javadoc/";
}
@Override
protected void setUp() throws Exception {
super.setUp();
myFixture.enableInspections(new JavaDocLocalInspection());
}
public void testNamesInClass() throws Exception {
configureByFile("ClassTagName.java");
assertStringItems("author", "deprecated", "param", "see", "serial", "since", "version");
}
public void testNamesInField() throws Exception {
configureByFile("FieldTagName.java");
assertStringItems("deprecated", "see", "serial", "serialField", "since");
}
public void testNamesInMethod0() throws Exception {
configureByFile("MethodTagName0.java");
assertStringItems("deprecated", "exception", "param", "return", "see", "serialData", "since", "throws");
}
public void testNamesInMethod1() throws Exception {
configureByFile("MethodTagName1.java");
assertStringItems("see", "serialData", "since");
}
public void testParamValueCompletion() throws Exception {
configureByFile("ParamValue0.java");
assertStringItems("a", "b", "c");
}
public void testParamValueWithPrefixCompletion() throws Exception {
configureByFile("ParamValue1.java");
assertStringItems("a1", "a2", "a3");
}
public void testDescribedParameters() throws Exception {
configureByFile("ParamValue2.java");
assertStringItems("a2", "a3");
}
public void testSee0() throws Exception {
configureByFile("See0.java");
assertStringItems("foo", "clone", "equals", "getClass", "hashCode", "notify", "notifyAll", "Object", "toString", "wait", "wait", "wait", "finalize", "registerNatives");
}
public void testSee1() throws Exception {
configureByFile("See1.java");
assertStringItems("notify", "notifyAll");
}
public void testSee2() throws Exception {
configureByFile("See2.java");
assertStringItems("notify", "notifyAll");
}
public void testSee3() throws Exception {
configureByFile("See3.java");
assertTrue(getLookupElementStrings().containsAll(Arrays.asList("foo", "myField")));
}
@NotNull
private List<String> getLookupElementStrings() {
return ObjectUtils.assertNotNull(myFixture.getLookupElementStrings());
}
public void testSee4() throws Exception {
configureByFile("See4.java");
assertTrue(getLookupElementStrings().containsAll(Arrays.asList("A", "B", "C")));
}
public void testSee5() throws Exception {
configureByFile("See5.java");
assertTrue(getLookupElementStrings().containsAll(Arrays.asList("foo", "myName")));
}
public void testIDEADEV10620() throws Exception {
configureByFile("IDEADEV10620.java");
checkResultByFile("IDEADEV10620-after.java");
}
public void testException0() throws Exception {
configureByFile("Exception0.java");
assertStringItems("deprecated", "exception", "param", "see", "serialData", "since", "throws");
}
public void testException1() throws Exception {
configureByFile("Exception1.java");
assertTrue(myItems.length > 18);
}
public void testException2() throws Exception {
myFixture.configureByFile("Exception2.java");
myFixture.complete(CompletionType.SMART);
assertStringItems("IllegalStateException", "IOException");
}
public void testInlineLookup() throws Exception {
configureByFile("InlineTagName.java");
assertStringItems("code", "docRoot", "inheritDoc", "link", "linkplain", "literal", "value");
}
public void testFinishWithSharp() throws Throwable {
boolean old = CodeInsightSettings.getInstance().AUTOCOMPLETE_ON_CODE_COMPLETION;
CodeInsightSettings.getInstance().AUTOCOMPLETE_ON_CODE_COMPLETION = false;
try {
checkFinishWithSharp();
}
finally {
CodeInsightSettings.getInstance().AUTOCOMPLETE_ON_CODE_COMPLETION = old;
}
}
private void checkFinishWithSharp() throws Exception {
myFixture.configureByFile("FinishWithSharp.java");
myFixture.completeBasic();
type('#');
checkResultByFile("FinishWithSharp_after.java");
final List<LookupElement> items = getLookup().getItems();
assertEquals("bar", items.get(0).getLookupString());
assertEquals("foo", items.get(1).getLookupString());
}
public void testShortenClassName() throws Throwable {
CodeStyleSettingsManager.getSettings(getProject()).USE_FQ_CLASS_NAMES_IN_JAVADOC = false;
try {
doTest();
}
finally {
CodeStyleSettingsManager.getSettings(getProject()).USE_FQ_CLASS_NAMES_IN_JAVADOC = true;
}
}
public void testMethodBeforeSharp() throws Throwable {
doTest();
}
public void testFieldReferenceInInnerClassJavadoc() throws Throwable {
doTest();
}
public void testShortenClassReference() throws Throwable { doTest(); }
public void testQualifiedClassReference() throws Throwable {
configureByFile(getTestName(false) + ".java");
myFixture.complete(CompletionType.BASIC, 2);
checkResultByFile(getTestName(false) + "_after.java");
}
public void testThrowsNonImported() throws Throwable {
configureByFile(getTestName(false) + ".java");
myFixture.complete(CompletionType.BASIC, 2);
checkResultByFile(getTestName(false) + "_after.java");
}
private void doTest() throws Exception {
configureByFile(getTestName(false) + ".java");
checkResultByFile(getTestName(false) + "_after.java");
}
public void testInlinePackageReferenceCompletion() throws Exception {
configureByFile("InlineReference.java");
assertTrue(getLookupElementStrings().containsAll(Arrays.asList("io", "lang", "util")));
}
public void testCustomReferenceProvider() throws Exception {
PsiReferenceRegistrarImpl registrar =
(PsiReferenceRegistrarImpl) ReferenceProvidersRegistry.getInstance().getRegistrar(StdLanguages.JAVA);
PsiReferenceProvider provider = new PsiReferenceProvider() {
@Override
@NotNull
public PsiReference[] getReferencesByElement(@NotNull final PsiElement element, @NotNull final ProcessingContext context) {
return new PsiReference[]{new PsiReferenceBase<PsiElement>(element) {
@Override
public PsiElement resolve() {
return element;
}
@Override
@NotNull
public Object[] getVariants() {
return new Object[]{"1", "2", "3"};
}
}};
}
};
try {
registrar.registerReferenceProvider(PsiDocTag.class, provider);
configureByFile("ReferenceProvider.java");
assertStringItems("1", "2", "3");
}
finally {
registrar.unregisterReferenceProvider(PsiDocTag.class, provider);
}
}
}
@@ -1,114 +1,114 @@
/*
* 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.codeInsight.completion;
import com.intellij.JavaTestUtil;
import com.intellij.psi.codeStyle.CodeStyleSettingsManager;
import org.jetbrains.annotations.NonNls;
/**
* @author ik
* @since 20.02.2003
*/
public class KeywordCompletionTest extends LightCompletionTestCase {
private static final String BASE_PATH = "/codeInsight/completion/keywords";
private static final String[] FILE_SCOPE_KEYWORDS = new String[]{
"package", "public", "private", "import", "final", "class", "interface", "abstract", "enum", null};
private static final String[] CLASS_SCOPE_KEYWORDS = new String[]{
"public", "private", "protected", "import", "final", "class", "interface", "abstract", "enum", null};
private static final String[] CLASS_SCOPE_KEYWORDS_2 = new String[]{
"package", "public", "private", "protected", "transient", "volatile", "static", "import", "final", "class", "interface", "abstract"};
@Override
protected String getTestDataPath() {
return JavaTestUtil.getJavaTestDataPath();
}
public void testFileScope1() throws Exception { doTest(8, FILE_SCOPE_KEYWORDS); }
public void testFileScope2() throws Exception { doTest(7, CLASS_SCOPE_KEYWORDS); }
public void testClassScope1() throws Exception { doTest(5, CLASS_SCOPE_KEYWORDS); }
public void testClassScope2() throws Exception { doTest(4, CLASS_SCOPE_KEYWORDS); }
public void testClassScope3() throws Exception { doTest(0, CLASS_SCOPE_KEYWORDS); }
public void testClassScope4() throws Exception { doTest(10, CLASS_SCOPE_KEYWORDS_2); }
public void testAfterAnnotations() throws Exception { doTest(6, "public", "final", "class", "interface", "abstract", "enum", null); }
public void testExtends1() throws Exception { doTest(2, "extends", "implements", null); }
public void testExtends2() throws Exception { doTest(1, "extends", "implements", "AAA", "BBB", "instanceof"); }
public void testExtends3() throws Exception { doTest(2, "extends", "implements", "AAA", "BBB", "CCC", "instanceof"); }
public void testExtends4() throws Exception { doTest(2, "extends", "implements", "AAA", "BBB", "CCC", "instanceof"); }
public void testExtends5() throws Exception { doTest(1, "extends", "implements", "AAA", "BBB", "CCC", "instanceof"); }
public void testExtends6() throws Exception { doTest(1, "extends", "implements", "AAA", "BBB", "CCC", "instanceof"); }
public void testExtends7() throws Exception { doTest(false); }
public void testExtends8() throws Exception { doTest(false); }
public void testExtends9() throws Exception { doTest(false); }
public void testExtends10() throws Exception { doTest(false); }
public void testExtends11() throws Exception { doTest(false); }
public void testExtends12() throws Exception { doTest(false); }
public void testSynchronized1() throws Exception { doTest(false); }
public void testSynchronized2() throws Exception {
CodeStyleSettingsManager.getSettings(getProject()).SPACE_BEFORE_SYNCHRONIZED_PARENTHESES = false;
doTest(false);
}
public void testMethodScope1() throws Exception { doTest(1, "throws"); }
public void testMethodScope2() throws Exception { doTest(1, "final", "public", "static", "volatile", "abstract"); }
public void testMethodScope3() throws Exception { doTest(1, "final", "public", "static", "volatile", "abstract", "throws", "instanceof"); }
public void testMethodScope4() throws Exception { doTest(6, "final", "try", "for", "while", "return", "throw"); }
public void testMethodScope5() throws Exception { doTest(false); }
public void testExtraBracketAfterFinally1() throws Exception { doTest(true); }
public void testExtraBracketAfterFinally2() throws Exception { doTest(true); }
public void testExtendsInCastTypeParameters() throws Exception { doTest(false); }
public void testExtendsWithRightContextInClassTypeParameters() throws Exception { doTest(false); }
public void testTrueInVariableDeclaration() throws Exception { doTest(false); }
public void testNullInIf() throws Exception { doTest(false); }
public void testNullInReturn() throws Exception { doTest(false); }
public void testExtendsInMethodParameters() throws Exception { doTest(false); }
public void testInstanceOf1() throws Exception { doTest(false); }
public void testInstanceOf2() throws Exception { doTest(false); }
public void testInstanceOf3() throws Exception { doTest(false); }
public void testCatchFinally() throws Exception { doTest(2, "catch", "finally"); }
public void testSuper1() throws Exception { doTest(1, "super"); }
public void testSuper2() throws Exception { doTest(0, "super"); }
public void testContinue() throws Exception { doTest(false); }
public void testThrowsOnSeparateLine() throws Exception { doTest(false); }
public void testDefaultInAnno() throws Exception { doTest(false); }
public void testDefaultInExtMethod() throws Exception { doTest(false); }
public void testNullInMethodCall() throws Exception { doTest(false); }
public void testNullInMethodCall2() throws Exception { doTest(false); }
public void testNewInMethodRefs() throws Exception { doTest(false); }
public void testAbstractInInterface() throws Exception { doTest(1, "abstract"); }
public void testCharInAnnotatedParameter() throws Exception { doTest(1, "char"); }
public void testReturnInTernary() throws Exception { doTest(1, "return"); }
public void testTryInExpression() throws Exception {
configureByFile(BASE_PATH + "/" + getTestName(true) + ".java");
assertStringItems("toString", "this");
}
private void doTest(boolean select) throws Exception {
configureByFile(BASE_PATH + "/" + getTestName(true) + ".java");
if (select) {
selectItem(myItems[1]);
}
checkResultByFile(BASE_PATH + "/" + getTestName(true) + "_after.java");
}
protected void doTest(int finalCount, @NonNls String... values) {
configureByFile(BASE_PATH + "/" + getTestName(true) + ".java");
testByCount(finalCount, values);
}
/*
* 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.codeInsight.completion;
import com.intellij.JavaTestUtil;
import com.intellij.psi.codeStyle.CodeStyleSettingsManager;
import org.jetbrains.annotations.NonNls;
/**
* @author ik
* @since 20.02.2003
*/
public class KeywordCompletionTest extends LightCompletionTestCase {
private static final String BASE_PATH = "/codeInsight/completion/keywords";
private static final String[] FILE_SCOPE_KEYWORDS = new String[]{
"package", "public", "private", "import", "final", "class", "interface", "abstract", "enum", null};
private static final String[] CLASS_SCOPE_KEYWORDS = new String[]{
"public", "private", "protected", "import", "final", "class", "interface", "abstract", "enum", null};
private static final String[] CLASS_SCOPE_KEYWORDS_2 = new String[]{
"package", "public", "private", "protected", "transient", "volatile", "static", "import", "final", "class", "interface", "abstract"};
@Override
protected String getTestDataPath() {
return JavaTestUtil.getJavaTestDataPath();
}
public void testFileScope1() throws Exception { doTest(8, FILE_SCOPE_KEYWORDS); }
public void testFileScope2() throws Exception { doTest(7, CLASS_SCOPE_KEYWORDS); }
public void testClassScope1() throws Exception { doTest(5, CLASS_SCOPE_KEYWORDS); }
public void testClassScope2() throws Exception { doTest(4, CLASS_SCOPE_KEYWORDS); }
public void testClassScope3() throws Exception { doTest(0, CLASS_SCOPE_KEYWORDS); }
public void testClassScope4() throws Exception { doTest(10, CLASS_SCOPE_KEYWORDS_2); }
public void testAfterAnnotations() throws Exception { doTest(6, "public", "final", "class", "interface", "abstract", "enum", null); }
public void testExtends1() throws Exception { doTest(2, "extends", "implements", null); }
public void testExtends2() throws Exception { doTest(1, "extends", "implements", "AAA", "BBB", "instanceof"); }
public void testExtends3() throws Exception { doTest(2, "extends", "implements", "AAA", "BBB", "CCC", "instanceof"); }
public void testExtends4() throws Exception { doTest(2, "extends", "implements", "AAA", "BBB", "CCC", "instanceof"); }
public void testExtends5() throws Exception { doTest(1, "extends", "implements", "AAA", "BBB", "CCC", "instanceof"); }
public void testExtends6() throws Exception { doTest(1, "extends", "implements", "AAA", "BBB", "CCC", "instanceof"); }
public void testExtends7() throws Exception { doTest(false); }
public void testExtends8() throws Exception { doTest(false); }
public void testExtends9() throws Exception { doTest(false); }
public void testExtends10() throws Exception { doTest(false); }
public void testExtends11() throws Exception { doTest(false); }
public void testExtends12() throws Exception { doTest(false); }
public void testSynchronized1() throws Exception { doTest(false); }
public void testSynchronized2() throws Exception {
CodeStyleSettingsManager.getSettings(getProject()).SPACE_BEFORE_SYNCHRONIZED_PARENTHESES = false;
doTest(false);
}
public void testMethodScope1() throws Exception { doTest(1, "throws"); }
public void testMethodScope2() throws Exception { doTest(1, "final", "public", "static", "volatile", "abstract"); }
public void testMethodScope3() throws Exception { doTest(1, "final", "public", "static", "volatile", "abstract", "throws", "instanceof"); }
public void testMethodScope4() throws Exception { doTest(6, "final", "try", "for", "while", "return", "throw"); }
public void testMethodScope5() throws Exception { doTest(false); }
public void testExtraBracketAfterFinally1() throws Exception { doTest(true); }
public void testExtraBracketAfterFinally2() throws Exception { doTest(true); }
public void testExtendsInCastTypeParameters() throws Exception { doTest(false); }
public void testExtendsWithRightContextInClassTypeParameters() throws Exception { doTest(false); }
public void testTrueInVariableDeclaration() throws Exception { doTest(false); }
public void testNullInIf() throws Exception { doTest(false); }
public void testNullInReturn() throws Exception { doTest(false); }
public void testExtendsInMethodParameters() throws Exception { doTest(false); }
public void testInstanceOf1() throws Exception { doTest(false); }
public void testInstanceOf2() throws Exception { doTest(false); }
public void testInstanceOf3() throws Exception { doTest(false); }
public void testCatchFinally() throws Exception { doTest(2, "catch", "finally"); }
public void testSuper1() throws Exception { doTest(1, "super"); }
public void testSuper2() throws Exception { doTest(0, "super"); }
public void testContinue() throws Exception { doTest(false); }
public void testThrowsOnSeparateLine() throws Exception { doTest(false); }
public void testDefaultInAnno() throws Exception { doTest(false); }
public void testDefaultInExtMethod() throws Exception { doTest(false); }
public void testNullInMethodCall() throws Exception { doTest(false); }
public void testNullInMethodCall2() throws Exception { doTest(false); }
public void testNewInMethodRefs() throws Exception { doTest(false); }
public void testAbstractInInterface() throws Exception { doTest(1, "abstract"); }
public void testCharInAnnotatedParameter() throws Exception { doTest(1, "char"); }
public void testReturnInTernary() throws Exception { doTest(1, "return"); }
public void testTryInExpression() throws Exception {
configureByFile(BASE_PATH + "/" + getTestName(true) + ".java");
assertStringItems("toString", "this");
}
private void doTest(boolean select) throws Exception {
configureByFile(BASE_PATH + "/" + getTestName(true) + ".java");
if (select) {
selectItem(myItems[1]);
}
checkResultByFile(BASE_PATH + "/" + getTestName(true) + "_after.java");
}
protected void doTest(int finalCount, @NonNls String... values) {
configureByFile(BASE_PATH + "/" + getTestName(true) + ".java");
testByCount(finalCount, values);
}
}
@@ -1,386 +1,386 @@
/*
* Copyright (c) 2000-2007 JetBrains s.r.o. All Rights Reserved.
*/
package com.intellij.codeInsight.completion;
import com.intellij.JavaTestUtil
import com.intellij.codeInsight.CodeInsightSettings
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.codeInsight.lookup.LookupElementPresentation
import com.intellij.codeInsight.lookup.impl.LookupImpl
import com.intellij.ide.ui.UISettings
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiMethod
import com.intellij.openapi.fileEditor.FileDocumentManager
public class NormalCompletionOrderingTest extends CompletionSortingTestCase {
private static final String BASE_PATH = "/codeInsight/completion/normalSorting";
public NormalCompletionOrderingTest() {
super(CompletionType.BASIC);
}
protected String getBasePath() {
return JavaTestUtil.getRelativeJavaTestDataPath() + BASE_PATH;
}
public void testDontPreferRecursiveMethod() throws Throwable {
checkPreferredItems(0, "registrar", "register");
}
public void testDontPreferRecursiveMethod2() throws Throwable {
checkPreferredItems(0, "return", "register");
}
public void testPreferAnnotationMethods() throws Throwable {
checkPreferredItems(0, "name", "value", "Foo", "Anno");
}
public void testPreferSuperMethods() throws Throwable {
checkPreferredItems(0, "foo", "bar");
}
public void testSubstringVsSubSequence() throws Throwable {
checkPreferredItems(0, "substring", "substring", "subSequence");
}
public void testReturnF() throws Throwable {
checkPreferredItems(0, "false", "finalize");
}
public void testPreferDefaultTypeToExpected() throws Throwable {
checkPreferredItems(0, "getName", "getNameIdentifier");
}
public void testShorterPrefixesGoFirst() throws Throwable {
final LookupImpl lookup = invokeCompletion(getTestName(false) + ".html");
assertPreferredItems(0, "p", "param", "pre");
incUseCount(lookup, 2);
assertPreferredItems(0, "p", "pre", "param");
}
public void testUppercaseMatters2() throws Throwable {
final int old = CodeInsightSettings.getInstance().COMPLETION_CASE_SENSITIVE;
try {
CodeInsightSettings.getInstance().COMPLETION_CASE_SENSITIVE = CodeInsightSettings.ALL;
checkPreferredItems(0, "classLoader", "classLoader2");
}
finally {
CodeInsightSettings.getInstance().COMPLETION_CASE_SENSITIVE = old;
}
}
public void testShorterShouldBePreselected() throws Throwable {
checkPreferredItems(0, "foo", "fooLongButOfDefaultType");
}
public void testGenericMethodsWithBoundParametersAreStillBetterThanClassLiteral() throws Throwable {
checkPreferredItems(0, "getService", "getService", "class");
}
public void testClassStaticMembersInVoidContext() throws Throwable {
checkPreferredItems(0, "booleanMethod", "voidMethod", "AN_OBJECT", "BOOLEAN", "class");
}
public void testJComponentInstanceMembers() throws Throwable {
checkPreferredItems(0, "getAccessibleContext", "getUI");
}
public void testClassStaticMembersInBooleanContext() throws Throwable {
final String path = getTestName(false) + ".java";
myFixture.configureByFile(path);
myFixture.complete(CompletionType.BASIC, 2);
assertPreferredItems(0, "BOOLEAN", "booleanMethod", "AN_OBJECT", "voidMethod", "registerNatives");
}
public void testDispreferDeclared() throws Throwable {
checkPreferredItems(0, "aabbb", "aaa");
}
public void testDispreferDeclaredOfExpectedType() throws Throwable {
checkPreferredItems(0, "aabbb", "aaa");
}
public void testDispreferImpls() throws Throwable {
myFixture.addClass("package foo; public class Xxx {}");
configureSecondCompletion();
assertPreferredItems(0, "Xxx", "XxxEx", "XxxImpl", "Xxy");
}
public void testPreferOwnInnerClasses() throws Throwable {
checkPreferredItems(0, "YyyXxx", "YyyZzz");
}
public void testPreferTopLevelClasses() throws Throwable {
configureSecondCompletion();
assertPreferredItems(0, "XxxYyy", "XxzYyy");
}
private void configureSecondCompletion() {
configureNoCompletion(getTestName(false) + ".java");
myFixture.complete(CompletionType.BASIC, 2);
}
public void testDontDispreferImplsAfterNew() throws Throwable {
myFixture.addClass("package foo; public interface Xxx {}");
configureSecondCompletion();
assertPreferredItems(0, "Xxx", "XxxImpl");
}
public void testPreferLessHumps() throws Throwable {
myFixture.addClass("package foo; public interface XaYa {}");
myFixture.addClass("package foo; public interface XyYa {}");
configureSecondCompletion();
assertPreferredItems(0, "XaYa", "XaYaEx", "XaYaImpl", "XyYa", "XyYaXa");
}
public void testPreferLessParameters() throws Throwable {
checkPreferredItems(0, "foo", "foo", "foo", "fox");
final List<LookupElement> items = getLookup().getItems();
assertEquals(0, ((PsiMethod)items.get(0).getObject()).getParameterList().getParametersCount());
assertEquals(1, ((PsiMethod)items.get(1).getObject()).getParameterList().getParametersCount());
assertEquals(2, ((PsiMethod)items.get(2).getObject()).getParameterList().getParametersCount());
}
public void testStatsForClassNameInExpression() throws Throwable {
myFixture.addClass("package foo; public interface FooBar {}");
myFixture.addClass("package foo; public interface FooBee {}");
invokeCompletion(getTestName(false) + ".java");
configureSecondCompletion();
incUseCount(getLookup(), 1);
assertPreferredItems(0, "FooBee", "FooBar");
}
public void testSameStatsForDifferentQualifiers() throws Throwable {
invokeCompletion("SameStatsForDifferentQualifiersJLabel.java");
assertPreferredItems(0, "getComponent");
incUseCount(getLookup(), myFixture.lookupElementStrings.indexOf('getComponents'));
FileDocumentManager.instance.saveAllDocuments()
invokeCompletion("SameStatsForDifferentQualifiersJLabel.java");
assertPreferredItems(1, "getComponent", "getComponents");
invokeCompletion("SameStatsForDifferentQualifiersJComponent.java");
assertPreferredItems(1, "getComponent", "getComponents");
}
public void testSameStatsForDifferentQualifiers2() throws Throwable {
invokeCompletion("SameStatsForDifferentQualifiersJComponent.java");
assertPreferredItems(0, "getComponent");
incUseCount(getLookup(), myFixture.lookupElementStrings.indexOf('getComponents'));
FileDocumentManager.instance.saveAllDocuments()
invokeCompletion("SameStatsForDifferentQualifiersJComponent.java");
assertPreferredItems(1, "getComponent", "getComponents");
invokeCompletion("SameStatsForDifferentQualifiersJLabel.java");
assertPreferredItems(1, "getComponent", "getComponents");
}
public void testDispreferFinalize() throws Throwable {
checkPreferredItems(0, "final", "finalize");
}
public void testPreferNewExpectedInner() throws Throwable {
checkPreferredItems(0, "Foooo.Bar", "Foooo");
/*final LookupElementPresentation presentation = new LookupElementPresentation();
getLookup().getItems().get(0).renderElement(presentation);
assertEquals("Foooo.Bar", presentation.getItemText());*/
}
public void testClassInCallOfItsMethod() throws Throwable {
myFixture.addClass("package foo; public interface Foo {}");
myFixture.addClass("package bar; public interface Foo {}");
checkPreferredItems(0, "Foo", "Foo");
assertEquals("foo.Foo", ((JavaPsiClassReferenceElement)getLookup().getCurrentItem()).getQualifiedName());
}
public void testDeclaredMembersGoFirst() throws Exception {
invokeCompletion(getTestName(false) + ".java");
assertStringItems("fromThis", "overridden", "fromSuper", "equals", "getClass", "hashCode", "notify", "notifyAll", "toString", "wait",
"wait", "wait");
}
public void testLocalVarsOverMethods() {
checkPreferredItems(0, "value", "validate", "validateTree", "valueOf");
}
public void testCurrentClassBest() {
checkPreferredItems(0, "XcodeProjectTemplate", "XcodeConfigurable");
}
public void testFqnStats() {
myFixture.addClass("public interface Baaaaaaar {}");
myFixture.addClass("package zoo; public interface Baaaaaaar {}");
configureSecondCompletion();
final LookupImpl lookup = getLookup();
assertEquals("Baaaaaaar", ((JavaPsiClassReferenceElement) lookup.getItems().get(0)).getQualifiedName());
assertEquals("zoo.Baaaaaaar", ((JavaPsiClassReferenceElement) lookup.getItems().get(1)).getQualifiedName());
incUseCount(lookup, 1);
assertEquals("zoo.Baaaaaaar", ((JavaPsiClassReferenceElement) lookup.getItems().get(0)).getQualifiedName());
assertEquals("Baaaaaaar", ((JavaPsiClassReferenceElement)lookup.getItems().get(1)).getQualifiedName());
}
public void _testSkipLifted() {
checkPreferredItems(1, "hashCode", "hashCodeMine")
}
public void testDispreferInnerClasses() {
checkPreferredItems(0); //no chosen items
assertFalse(getLookup().getItems().get(0).getObject() instanceof PsiClass);
}
public void testPreferSameNamedMethods() {
checkPreferredItems(0, "foo", "boo", "doo", "hashCode");
}
public void testPreferInterfacesInImplements() {
checkPreferredItems(0, "FooIntf", "FooClass");
}
public void testPreferClassesInExtends() {
checkPreferredItems(0, "FooClass", "Foo_Intf");
}
public void testPreferClassStaticMembers() {
checkPreferredItems(0, "Zoo", "Zoo.A", "Zoo.B", "Zoo.C", "Zoo.D", "Zoo.E", "Zoo.F", "Zoo.G", "Zoo.H");
}
public void testPreferFinallyToFinal() {
checkPreferredItems(1, "final", "finally");
}
public void testPreferReturn() {
checkPreferredItems(0, "return", "rLocal", "rParam", "rMethod");
}
public void testPreferModifiers() {
checkPreferredItems(0, "private", "protected", "public", "paaa", "paab");
}
public void testPreferElse() {
checkPreferredItems(0, "else", "element");
}
public void testPreferMoreMatching() {
checkPreferredItems(0, "FooOCSomething", "FooObjectCollector");
}
public void testPreferSamePackageOverImported() {
myFixture.addClass("package bar; public class Bar1 {}");
myFixture.addClass("package bar; public class Bar2 {}");
myFixture.addClass("package bar; public class Bar3 {}");
myFixture.addClass("package bar; public class Bar4 {}");
myFixture.addClass("class Bar9 {}");
myFixture.addClass("package doo; public class Bar0 {}");
checkPreferredItems(0, "Bar9", "Bar1", "Bar2", "Bar3", "Bar4");
}
public void testPreselectMostRelevantInTheMiddleAlpha() {
UISettings.getInstance().SORT_LOOKUP_ELEMENTS_LEXICOGRAPHICALLY = true;
myFixture.addClass("package foo; public class Elxaaaaaaaaaaaaaaaaaaaa {}");
invokeCompletion(getTestName(false) + ".java");
myFixture.completeBasic();
LookupImpl lookup = getLookup();
assertPreferredItems(lookup.getList().getSelectedIndex());
assertEquals("Elxaaaaaaaaaaaaaaaaaaaa", lookup.getItems().get(0).getLookupString());
assertEquals("ELXEMENT_A", lookup.getCurrentItem().getLookupString());
}
public void testReallyAlphaSorting() {
UISettings.getInstance().SORT_LOOKUP_ELEMENTS_LEXICOGRAPHICALLY = true;
invokeCompletion(getTestName(false) + ".java");
assert myFixture.lookupElementStrings.sort() == myFixture.lookupElementStrings
}
public void testAlphaSortPackages() {
UISettings.getInstance().SORT_LOOKUP_ELEMENTS_LEXICOGRAPHICALLY = true
def pkgs = ['bar', 'foo', 'goo', 'roo', 'zoo']
for (s in pkgs) {
myFixture.addClass("package $s; public class Foox {}")
}
invokeCompletion(getTestName(false) + ".java")
for (i in 0..<pkgs.size()) {
assert LookupElementPresentation.renderElement(myFixture.lookupElements[i]).tailText?.contains(pkgs[i])
}
}
public void testSortSameNamedVariantsByProximity() {
myFixture.addClass("public class Bar {}");
for (int i = 0; i < 10; i++) {
myFixture.addClass("public class Bar" + i + " {}");
myFixture.addClass("public class Bar" + i + "Colleague {}");
}
myFixture.addClass("package bar; public class Bar {}");
myFixture.configureByFile(getTestName(false) + ".java");
myFixture.complete(CompletionType.BASIC, 2);
assertPreferredItems(0, "Bar", "Bar");
List<LookupElement> items = getLookup().getItems();
assertEquals(((JavaPsiClassReferenceElement)items.get(0)).getQualifiedName(), "Bar");
assertEquals(((JavaPsiClassReferenceElement)items.get(1)).getQualifiedName(), "bar.Bar");
}
public void testCaseInsensitivePrefixMatch() {
CodeInsightSettings.getInstance().COMPLETION_CASE_SENSITIVE = CodeInsightSettings.NONE;
checkPreferredItems(1, "Foo", "foo1", "foo2");
}
public void testExpectedTypeIsMoreImportantThanCase() {
CodeInsightSettings.getInstance().COMPLETION_CASE_SENSITIVE = CodeInsightSettings.NONE;
checkPreferredItems(0, "ENABLED", "enable");
}
public void testPreferKeywordsToVoidMethodsInExpectedTypeContext() {
checkPreferredItems 0, 'noo', 'new', 'null', 'noo2', 'notify', 'notifyAll'
}
public void testPreferBetterMatchingConstantToMethods() {
checkPreferredItems 0, 'serial', 'superExpressionInIllegalContext'
}
public void testJComponentAddNewWithStats() throws Throwable {
final LookupImpl lookup = invokeCompletion("/../smartTypeSorting/JComponentAddNew.java");
assertPreferredItems(0, "FooBean3", "JComponent", "Component");
incUseCount(lookup, 2); //Component
assertPreferredItems(0, "Component", "FooBean3", "JComponent");
}
public void testDispreferReturnBeforeStatement() {
checkPreferredItems 0, 'reaction', 'rezet', 'return'
}
public void testDoNotPreferGetClass() {
checkPreferredItems 0, 'get', 'getClass'
incUseCount(lookup, 1)
assertPreferredItems 0, 'get', 'getClass'
}
public void testPreferClassToItsConstants() {
checkPreferredItems 0, 'Calendar', 'Calendar.FIELD_COUNT'
}
public void testPreferLocalsToStaticsInSecondCompletion() {
myFixture.addClass('public class FooZoo { public static void fooBar() {} }')
myFixture.addClass('public class fooAClass {}')
configureNoCompletion(getTestName(false) + ".java");
myFixture.complete(CompletionType.BASIC, 2);
assertPreferredItems(0, 'fooy', 'foox', 'fooAClass', 'fooBar');
}
public void testUnderscoresDontMakeMatchMiddle() {
CodeInsightSettings.getInstance().COMPLETION_CASE_SENSITIVE = CodeInsightSettings.NONE;
checkPreferredItems(0, '_fooBar', 'FooBar')
}
}
/*
* Copyright (c) 2000-2007 JetBrains s.r.o. All Rights Reserved.
*/
package com.intellij.codeInsight.completion;
import com.intellij.JavaTestUtil
import com.intellij.codeInsight.CodeInsightSettings
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.codeInsight.lookup.LookupElementPresentation
import com.intellij.codeInsight.lookup.impl.LookupImpl
import com.intellij.ide.ui.UISettings
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiMethod
import com.intellij.openapi.fileEditor.FileDocumentManager
public class NormalCompletionOrderingTest extends CompletionSortingTestCase {
private static final String BASE_PATH = "/codeInsight/completion/normalSorting";
public NormalCompletionOrderingTest() {
super(CompletionType.BASIC);
}
protected String getBasePath() {
return JavaTestUtil.getRelativeJavaTestDataPath() + BASE_PATH;
}
public void testDontPreferRecursiveMethod() throws Throwable {
checkPreferredItems(0, "registrar", "register");
}
public void testDontPreferRecursiveMethod2() throws Throwable {
checkPreferredItems(0, "return", "register");
}
public void testPreferAnnotationMethods() throws Throwable {
checkPreferredItems(0, "name", "value", "Foo", "Anno");
}
public void testPreferSuperMethods() throws Throwable {
checkPreferredItems(0, "foo", "bar");
}
public void testSubstringVsSubSequence() throws Throwable {
checkPreferredItems(0, "substring", "substring", "subSequence");
}
public void testReturnF() throws Throwable {
checkPreferredItems(0, "false", "finalize");
}
public void testPreferDefaultTypeToExpected() throws Throwable {
checkPreferredItems(0, "getName", "getNameIdentifier");
}
public void testShorterPrefixesGoFirst() throws Throwable {
final LookupImpl lookup = invokeCompletion(getTestName(false) + ".html");
assertPreferredItems(0, "p", "param", "pre");
incUseCount(lookup, 2);
assertPreferredItems(0, "p", "pre", "param");
}
public void testUppercaseMatters2() throws Throwable {
final int old = CodeInsightSettings.getInstance().COMPLETION_CASE_SENSITIVE;
try {
CodeInsightSettings.getInstance().COMPLETION_CASE_SENSITIVE = CodeInsightSettings.ALL;
checkPreferredItems(0, "classLoader", "classLoader2");
}
finally {
CodeInsightSettings.getInstance().COMPLETION_CASE_SENSITIVE = old;
}
}
public void testShorterShouldBePreselected() throws Throwable {
checkPreferredItems(0, "foo", "fooLongButOfDefaultType");
}
public void testGenericMethodsWithBoundParametersAreStillBetterThanClassLiteral() throws Throwable {
checkPreferredItems(0, "getService", "getService", "class");
}
public void testClassStaticMembersInVoidContext() throws Throwable {
checkPreferredItems(0, "booleanMethod", "voidMethod", "AN_OBJECT", "BOOLEAN", "class");
}
public void testJComponentInstanceMembers() throws Throwable {
checkPreferredItems(0, "getAccessibleContext", "getUI");
}
public void testClassStaticMembersInBooleanContext() throws Throwable {
final String path = getTestName(false) + ".java";
myFixture.configureByFile(path);
myFixture.complete(CompletionType.BASIC, 2);
assertPreferredItems(0, "BOOLEAN", "booleanMethod", "AN_OBJECT", "voidMethod", "registerNatives");
}
public void testDispreferDeclared() throws Throwable {
checkPreferredItems(0, "aabbb", "aaa");
}
public void testDispreferDeclaredOfExpectedType() throws Throwable {
checkPreferredItems(0, "aabbb", "aaa");
}
public void testDispreferImpls() throws Throwable {
myFixture.addClass("package foo; public class Xxx {}");
configureSecondCompletion();
assertPreferredItems(0, "Xxx", "XxxEx", "XxxImpl", "Xxy");
}
public void testPreferOwnInnerClasses() throws Throwable {
checkPreferredItems(0, "YyyXxx", "YyyZzz");
}
public void testPreferTopLevelClasses() throws Throwable {
configureSecondCompletion();
assertPreferredItems(0, "XxxYyy", "XxzYyy");
}
private void configureSecondCompletion() {
configureNoCompletion(getTestName(false) + ".java");
myFixture.complete(CompletionType.BASIC, 2);
}
public void testDontDispreferImplsAfterNew() throws Throwable {
myFixture.addClass("package foo; public interface Xxx {}");
configureSecondCompletion();
assertPreferredItems(0, "Xxx", "XxxImpl");
}
public void testPreferLessHumps() throws Throwable {
myFixture.addClass("package foo; public interface XaYa {}");
myFixture.addClass("package foo; public interface XyYa {}");
configureSecondCompletion();
assertPreferredItems(0, "XaYa", "XaYaEx", "XaYaImpl", "XyYa", "XyYaXa");
}
public void testPreferLessParameters() throws Throwable {
checkPreferredItems(0, "foo", "foo", "foo", "fox");
final List<LookupElement> items = getLookup().getItems();
assertEquals(0, ((PsiMethod)items.get(0).getObject()).getParameterList().getParametersCount());
assertEquals(1, ((PsiMethod)items.get(1).getObject()).getParameterList().getParametersCount());
assertEquals(2, ((PsiMethod)items.get(2).getObject()).getParameterList().getParametersCount());
}
public void testStatsForClassNameInExpression() throws Throwable {
myFixture.addClass("package foo; public interface FooBar {}");
myFixture.addClass("package foo; public interface FooBee {}");
invokeCompletion(getTestName(false) + ".java");
configureSecondCompletion();
incUseCount(getLookup(), 1);
assertPreferredItems(0, "FooBee", "FooBar");
}
public void testSameStatsForDifferentQualifiers() throws Throwable {
invokeCompletion("SameStatsForDifferentQualifiersJLabel.java");
assertPreferredItems(0, "getComponent");
incUseCount(getLookup(), myFixture.lookupElementStrings.indexOf('getComponents'));
FileDocumentManager.instance.saveAllDocuments()
invokeCompletion("SameStatsForDifferentQualifiersJLabel.java");
assertPreferredItems(1, "getComponent", "getComponents");
invokeCompletion("SameStatsForDifferentQualifiersJComponent.java");
assertPreferredItems(1, "getComponent", "getComponents");
}
public void testSameStatsForDifferentQualifiers2() throws Throwable {
invokeCompletion("SameStatsForDifferentQualifiersJComponent.java");
assertPreferredItems(0, "getComponent");
incUseCount(getLookup(), myFixture.lookupElementStrings.indexOf('getComponents'));
FileDocumentManager.instance.saveAllDocuments()
invokeCompletion("SameStatsForDifferentQualifiersJComponent.java");
assertPreferredItems(1, "getComponent", "getComponents");
invokeCompletion("SameStatsForDifferentQualifiersJLabel.java");
assertPreferredItems(1, "getComponent", "getComponents");
}
public void testDispreferFinalize() throws Throwable {
checkPreferredItems(0, "final", "finalize");
}
public void testPreferNewExpectedInner() throws Throwable {
checkPreferredItems(0, "Foooo.Bar", "Foooo");
/*final LookupElementPresentation presentation = new LookupElementPresentation();
getLookup().getItems().get(0).renderElement(presentation);
assertEquals("Foooo.Bar", presentation.getItemText());*/
}
public void testClassInCallOfItsMethod() throws Throwable {
myFixture.addClass("package foo; public interface Foo {}");
myFixture.addClass("package bar; public interface Foo {}");
checkPreferredItems(0, "Foo", "Foo");
assertEquals("foo.Foo", ((JavaPsiClassReferenceElement)getLookup().getCurrentItem()).getQualifiedName());
}
public void testDeclaredMembersGoFirst() throws Exception {
invokeCompletion(getTestName(false) + ".java");
assertStringItems("fromThis", "overridden", "fromSuper", "equals", "getClass", "hashCode", "notify", "notifyAll", "toString", "wait",
"wait", "wait");
}
public void testLocalVarsOverMethods() {
checkPreferredItems(0, "value", "validate", "validateTree", "valueOf");
}
public void testCurrentClassBest() {
checkPreferredItems(0, "XcodeProjectTemplate", "XcodeConfigurable");
}
public void testFqnStats() {
myFixture.addClass("public interface Baaaaaaar {}");
myFixture.addClass("package zoo; public interface Baaaaaaar {}");
configureSecondCompletion();
final LookupImpl lookup = getLookup();
assertEquals("Baaaaaaar", ((JavaPsiClassReferenceElement) lookup.getItems().get(0)).getQualifiedName());
assertEquals("zoo.Baaaaaaar", ((JavaPsiClassReferenceElement) lookup.getItems().get(1)).getQualifiedName());
incUseCount(lookup, 1);
assertEquals("zoo.Baaaaaaar", ((JavaPsiClassReferenceElement) lookup.getItems().get(0)).getQualifiedName());
assertEquals("Baaaaaaar", ((JavaPsiClassReferenceElement)lookup.getItems().get(1)).getQualifiedName());
}
public void _testSkipLifted() {
checkPreferredItems(1, "hashCode", "hashCodeMine")
}
public void testDispreferInnerClasses() {
checkPreferredItems(0); //no chosen items
assertFalse(getLookup().getItems().get(0).getObject() instanceof PsiClass);
}
public void testPreferSameNamedMethods() {
checkPreferredItems(0, "foo", "boo", "doo", "hashCode");
}
public void testPreferInterfacesInImplements() {
checkPreferredItems(0, "FooIntf", "FooClass");
}
public void testPreferClassesInExtends() {
checkPreferredItems(0, "FooClass", "Foo_Intf");
}
public void testPreferClassStaticMembers() {
checkPreferredItems(0, "Zoo", "Zoo.A", "Zoo.B", "Zoo.C", "Zoo.D", "Zoo.E", "Zoo.F", "Zoo.G", "Zoo.H");
}
public void testPreferFinallyToFinal() {
checkPreferredItems(1, "final", "finally");
}
public void testPreferReturn() {
checkPreferredItems(0, "return", "rLocal", "rParam", "rMethod");
}
public void testPreferModifiers() {
checkPreferredItems(0, "private", "protected", "public", "paaa", "paab");
}
public void testPreferElse() {
checkPreferredItems(0, "else", "element");
}
public void testPreferMoreMatching() {
checkPreferredItems(0, "FooOCSomething", "FooObjectCollector");
}
public void testPreferSamePackageOverImported() {
myFixture.addClass("package bar; public class Bar1 {}");
myFixture.addClass("package bar; public class Bar2 {}");
myFixture.addClass("package bar; public class Bar3 {}");
myFixture.addClass("package bar; public class Bar4 {}");
myFixture.addClass("class Bar9 {}");
myFixture.addClass("package doo; public class Bar0 {}");
checkPreferredItems(0, "Bar9", "Bar1", "Bar2", "Bar3", "Bar4");
}
public void testPreselectMostRelevantInTheMiddleAlpha() {
UISettings.getInstance().SORT_LOOKUP_ELEMENTS_LEXICOGRAPHICALLY = true;
myFixture.addClass("package foo; public class Elxaaaaaaaaaaaaaaaaaaaa {}");
invokeCompletion(getTestName(false) + ".java");
myFixture.completeBasic();
LookupImpl lookup = getLookup();
assertPreferredItems(lookup.getList().getSelectedIndex());
assertEquals("Elxaaaaaaaaaaaaaaaaaaaa", lookup.getItems().get(0).getLookupString());
assertEquals("ELXEMENT_A", lookup.getCurrentItem().getLookupString());
}
public void testReallyAlphaSorting() {
UISettings.getInstance().SORT_LOOKUP_ELEMENTS_LEXICOGRAPHICALLY = true;
invokeCompletion(getTestName(false) + ".java");
assert myFixture.lookupElementStrings.sort() == myFixture.lookupElementStrings
}
public void testAlphaSortPackages() {
UISettings.getInstance().SORT_LOOKUP_ELEMENTS_LEXICOGRAPHICALLY = true
def pkgs = ['bar', 'foo', 'goo', 'roo', 'zoo']
for (s in pkgs) {
myFixture.addClass("package $s; public class Foox {}")
}
invokeCompletion(getTestName(false) + ".java")
for (i in 0..<pkgs.size()) {
assert LookupElementPresentation.renderElement(myFixture.lookupElements[i]).tailText?.contains(pkgs[i])
}
}
public void testSortSameNamedVariantsByProximity() {
myFixture.addClass("public class Bar {}");
for (int i = 0; i < 10; i++) {
myFixture.addClass("public class Bar" + i + " {}");
myFixture.addClass("public class Bar" + i + "Colleague {}");
}
myFixture.addClass("package bar; public class Bar {}");
myFixture.configureByFile(getTestName(false) + ".java");
myFixture.complete(CompletionType.BASIC, 2);
assertPreferredItems(0, "Bar", "Bar");
List<LookupElement> items = getLookup().getItems();
assertEquals(((JavaPsiClassReferenceElement)items.get(0)).getQualifiedName(), "Bar");
assertEquals(((JavaPsiClassReferenceElement)items.get(1)).getQualifiedName(), "bar.Bar");
}
public void testCaseInsensitivePrefixMatch() {
CodeInsightSettings.getInstance().COMPLETION_CASE_SENSITIVE = CodeInsightSettings.NONE;
checkPreferredItems(1, "Foo", "foo1", "foo2");
}
public void testExpectedTypeIsMoreImportantThanCase() {
CodeInsightSettings.getInstance().COMPLETION_CASE_SENSITIVE = CodeInsightSettings.NONE;
checkPreferredItems(0, "ENABLED", "enable");
}
public void testPreferKeywordsToVoidMethodsInExpectedTypeContext() {
checkPreferredItems 0, 'noo', 'new', 'null', 'noo2', 'notify', 'notifyAll'
}
public void testPreferBetterMatchingConstantToMethods() {
checkPreferredItems 0, 'serial', 'superExpressionInIllegalContext'
}
public void testJComponentAddNewWithStats() throws Throwable {
final LookupImpl lookup = invokeCompletion("/../smartTypeSorting/JComponentAddNew.java");
assertPreferredItems(0, "FooBean3", "JComponent", "Component");
incUseCount(lookup, 2); //Component
assertPreferredItems(0, "Component", "FooBean3", "JComponent");
}
public void testDispreferReturnBeforeStatement() {
checkPreferredItems 0, 'reaction', 'rezet', 'return'
}
public void testDoNotPreferGetClass() {
checkPreferredItems 0, 'get', 'getClass'
incUseCount(lookup, 1)
assertPreferredItems 0, 'get', 'getClass'
}
public void testPreferClassToItsConstants() {
checkPreferredItems 0, 'Calendar', 'Calendar.FIELD_COUNT'
}
public void testPreferLocalsToStaticsInSecondCompletion() {
myFixture.addClass('public class FooZoo { public static void fooBar() {} }')
myFixture.addClass('public class fooAClass {}')
configureNoCompletion(getTestName(false) + ".java");
myFixture.complete(CompletionType.BASIC, 2);
assertPreferredItems(0, 'fooy', 'foox', 'fooAClass', 'fooBar');
}
public void testUnderscoresDontMakeMatchMiddle() {
CodeInsightSettings.getInstance().COMPLETION_CASE_SENSITIVE = CodeInsightSettings.NONE;
checkPreferredItems(0, '_fooBar', 'FooBar')
}
}
File diff suppressed because it is too large Load Diff
@@ -2,7 +2,6 @@ package com.intellij.codeInsight.daemon;
import com.intellij.codeInsight.TargetElementUtilBase;
import com.intellij.codeInsight.hint.ImplementationViewComponent;
import com.intellij.openapi.util.Disposer;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiMethod;
@@ -1,30 +1,30 @@
/*
* 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.codeInsight.daemon.quickFix;
/**
* @author Danila Ponomarenko
*/
public class BreakStringOnLineBreaksTest extends LightQuickFixTestCase {
public void test() throws Exception { doAllTests(); }
@Override
protected String getBasePath() {
return "/codeInsight/daemonCodeAnalyzer/quickFix/breakStringOnLineBreaks";
}
/*
* 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.codeInsight.daemon.quickFix;
/**
* @author Danila Ponomarenko
*/
public class BreakStringOnLineBreaksTest extends LightQuickFixTestCase {
public void test() throws Exception { doAllTests(); }
@Override
protected String getBasePath() {
return "/codeInsight/daemonCodeAnalyzer/quickFix/breakStringOnLineBreaks";
}
}
@@ -1,123 +1,123 @@
/*
* Copyright 2000-2011 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInsight.completion;
import com.intellij.codeInsight.daemon.DaemonAnalyzerTestCase;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupManager;
import com.intellij.codeInsight.lookup.impl.LookupImpl;
import com.intellij.testFramework.PlatformTestCase;
import com.intellij.util.Function;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.Nullable;
import java.util.Arrays;
import java.util.List;
/**
* @author mike
*/
@PlatformTestCase.WrapInCommand
public abstract class CompletionTestCase extends DaemonAnalyzerTestCase {
protected String myPrefix;
protected LookupElement[] myItems;
private CompletionType myType = CompletionType.BASIC;
@Override
protected void tearDown() throws Exception {
try {
LookupManager.getInstance(myProject).hideActiveLookup();
}
finally {
super.tearDown();
}
myItems = null;
}
@Override
protected void configureByFile(String filePath) throws Exception {
super.configureByFile(filePath);
complete();
}
protected void configureByFileNoCompletion(String filePath) throws Exception {
super.configureByFile(filePath);
}
protected void complete() {
complete(1);
}
protected void complete(final int time) {
new CodeCompletionHandlerBase(myType).invokeCompletion(myProject, myEditor, time);
LookupImpl lookup = (LookupImpl)LookupManager.getActiveLookup(myEditor);
myItems = lookup == null ? null : lookup.getItems().toArray(new LookupElement[lookup.getItems().size()]);
myPrefix = lookup == null ? "" : lookup.itemPattern(lookup.getItems().get(0));
}
public void setType(CompletionType type) {
myType = type;
}
protected void selectItem(LookupElement item, char ch) {
final LookupImpl lookup = (LookupImpl)LookupManager.getInstance(myProject).getActiveLookup();
assert lookup != null;
lookup.setCurrentItem(item);
lookup.finishLookup(ch);
}
protected void selectItem(LookupElement item) {
selectItem(item, (char)0);
}
protected void doTestByCount(int finalCount, String... values) {
int index = 0;
if (myItems == null) {
assertEquals(0, finalCount);
return;
}
for (final LookupElement myItem : myItems) {
for (String value : values) {
if (value == null) {
assertFalse("Unacceptable value reached", true);
}
if (value.equals(myItem.getLookupString())) {
index++;
break;
}
}
}
assertEquals(Arrays.toString(myItems), finalCount, index);
}
@Nullable
protected LookupImpl getActiveLookup() {
return (LookupImpl)LookupManager.getActiveLookup(myEditor);
}
protected void assertStringItems(String... strings) {
assertNotNull(myItems);
List<String> actual = ContainerUtil.map(myItems, new Function<LookupElement, String>() {
@Override
public String fun(LookupElement element) {
return element.getLookupString();
}
});
assertOrderedEquals(actual, strings);
}
}
/*
* Copyright 2000-2011 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInsight.completion;
import com.intellij.codeInsight.daemon.DaemonAnalyzerTestCase;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupManager;
import com.intellij.codeInsight.lookup.impl.LookupImpl;
import com.intellij.testFramework.PlatformTestCase;
import com.intellij.util.Function;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.Nullable;
import java.util.Arrays;
import java.util.List;
/**
* @author mike
*/
@PlatformTestCase.WrapInCommand
public abstract class CompletionTestCase extends DaemonAnalyzerTestCase {
protected String myPrefix;
protected LookupElement[] myItems;
private CompletionType myType = CompletionType.BASIC;
@Override
protected void tearDown() throws Exception {
try {
LookupManager.getInstance(myProject).hideActiveLookup();
}
finally {
super.tearDown();
}
myItems = null;
}
@Override
protected void configureByFile(String filePath) throws Exception {
super.configureByFile(filePath);
complete();
}
protected void configureByFileNoCompletion(String filePath) throws Exception {
super.configureByFile(filePath);
}
protected void complete() {
complete(1);
}
protected void complete(final int time) {
new CodeCompletionHandlerBase(myType).invokeCompletion(myProject, myEditor, time);
LookupImpl lookup = (LookupImpl)LookupManager.getActiveLookup(myEditor);
myItems = lookup == null ? null : lookup.getItems().toArray(new LookupElement[lookup.getItems().size()]);
myPrefix = lookup == null ? "" : lookup.itemPattern(lookup.getItems().get(0));
}
public void setType(CompletionType type) {
myType = type;
}
protected void selectItem(LookupElement item, char ch) {
final LookupImpl lookup = (LookupImpl)LookupManager.getInstance(myProject).getActiveLookup();
assert lookup != null;
lookup.setCurrentItem(item);
lookup.finishLookup(ch);
}
protected void selectItem(LookupElement item) {
selectItem(item, (char)0);
}
protected void doTestByCount(int finalCount, String... values) {
int index = 0;
if (myItems == null) {
assertEquals(0, finalCount);
return;
}
for (final LookupElement myItem : myItems) {
for (String value : values) {
if (value == null) {
assertFalse("Unacceptable value reached", true);
}
if (value.equals(myItem.getLookupString())) {
index++;
break;
}
}
}
assertEquals(Arrays.toString(myItems), finalCount, index);
}
@Nullable
protected LookupImpl getActiveLookup() {
return (LookupImpl)LookupManager.getActiveLookup(myEditor);
}
protected void assertStringItems(String... strings) {
assertNotNull(myItems);
List<String> actual = ContainerUtil.map(myItems, new Function<LookupElement, String>() {
@Override
public String fun(LookupElement element) {
return element.getLookupString();
}
});
assertOrderedEquals(actual, strings);
}
}
@@ -1,137 +1,137 @@
/*
* Copyright 2000-2011 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInsight.completion;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupManager;
import com.intellij.codeInsight.lookup.impl.LookupImpl;
import com.intellij.testFramework.LightCodeInsightTestCase;
import com.intellij.util.containers.HashSet;
import org.jetbrains.annotations.NonNls;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Set;
/**
* @author mike
*/
public abstract class LightCompletionTestCase extends LightCodeInsightTestCase {
protected String myPrefix;
protected LookupElement[] myItems;
private CompletionType myType = CompletionType.BASIC;
@Override
protected void tearDown() throws Exception {
LookupManager.getInstance(getProject()).hideActiveLookup();
super.tearDown();
}
@Override
protected void configureByFile(String filePath) {
super.configureByFile(filePath);
complete();
}
protected void configureByFileNoComplete(String filePath) throws Exception {
super.configureByFile(filePath);
}
protected void complete() {
complete(1);
}
protected void complete(final int time) {
new CodeCompletionHandlerBase(myType).invokeCompletion(getProject(), getEditor(), time);
LookupImpl lookup = (LookupImpl)LookupManager.getActiveLookup(myEditor);
myItems = lookup == null ? null : lookup.getItems().toArray(LookupElement.EMPTY_ARRAY);
myPrefix = lookup == null ? null : lookup.itemPattern(lookup.getItems().get(0));
}
public void setType(CompletionType type) {
myType = type;
}
protected void selectItem(LookupElement item) {
selectItem(item, (char)0);
}
protected void selectItem(LookupElement item, char completionChar) {
final LookupImpl lookup = (LookupImpl)LookupManager.getInstance(getProject()).getActiveLookup();
lookup.setCurrentItem(item);
if (completionChar == 0 || completionChar == '\n' || completionChar == '\t') {
lookup.finishLookup(completionChar);
} else {
type(completionChar);
}
}
protected void testByCount(int finalCount, @NonNls String... values) {
if (myItems == null) {
assertEquals(finalCount, 0);
return;
}
int index = 0;
for (final LookupElement myItem : myItems) {
for (String value : values) {
if (value == null) {
assertFalse("Unacceptable value reached: " + myItem.getLookupString(), true);
}
if (value.equals(myItem.getLookupString())) {
index++;
break;
}
}
}
assertEquals(finalCount, index);
}
protected void assertStringItems(@NonNls String... items) {
assertEquals(getLookupStrings(new ArrayList<String>()), Arrays.asList(items));
}
protected void assertContainsItems(final String... expected) {
final Set<String> actual = getLookupStrings(new HashSet<String>());
for (String s : expected) {
assertTrue("Expected '" + s + "' not found in " + actual,
actual.contains(s));
}
}
protected void assertNotContainItems(final String... unexpected) {
final Set<String> actual = getLookupStrings(new HashSet<String>());
for (String s : unexpected) {
assertFalse("Unexpected '" + s + "' presented in " + actual,
actual.contains(s));
}
}
private <T extends Collection<String>> T getLookupStrings(T actual) {
if (myItems != null) {
for (LookupElement lookupElement : myItems) {
actual.add(lookupElement.getLookupString());
}
}
return actual;
}
protected static LookupImpl getLookup() {
return (LookupImpl)LookupManager.getActiveLookup(myEditor);
}
}
/*
* Copyright 2000-2011 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInsight.completion;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupManager;
import com.intellij.codeInsight.lookup.impl.LookupImpl;
import com.intellij.testFramework.LightCodeInsightTestCase;
import com.intellij.util.containers.HashSet;
import org.jetbrains.annotations.NonNls;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Set;
/**
* @author mike
*/
public abstract class LightCompletionTestCase extends LightCodeInsightTestCase {
protected String myPrefix;
protected LookupElement[] myItems;
private CompletionType myType = CompletionType.BASIC;
@Override
protected void tearDown() throws Exception {
LookupManager.getInstance(getProject()).hideActiveLookup();
super.tearDown();
}
@Override
protected void configureByFile(String filePath) {
super.configureByFile(filePath);
complete();
}
protected void configureByFileNoComplete(String filePath) throws Exception {
super.configureByFile(filePath);
}
protected void complete() {
complete(1);
}
protected void complete(final int time) {
new CodeCompletionHandlerBase(myType).invokeCompletion(getProject(), getEditor(), time);
LookupImpl lookup = (LookupImpl)LookupManager.getActiveLookup(myEditor);
myItems = lookup == null ? null : lookup.getItems().toArray(LookupElement.EMPTY_ARRAY);
myPrefix = lookup == null ? null : lookup.itemPattern(lookup.getItems().get(0));
}
public void setType(CompletionType type) {
myType = type;
}
protected void selectItem(LookupElement item) {
selectItem(item, (char)0);
}
protected void selectItem(LookupElement item, char completionChar) {
final LookupImpl lookup = (LookupImpl)LookupManager.getInstance(getProject()).getActiveLookup();
lookup.setCurrentItem(item);
if (completionChar == 0 || completionChar == '\n' || completionChar == '\t') {
lookup.finishLookup(completionChar);
} else {
type(completionChar);
}
}
protected void testByCount(int finalCount, @NonNls String... values) {
if (myItems == null) {
assertEquals(finalCount, 0);
return;
}
int index = 0;
for (final LookupElement myItem : myItems) {
for (String value : values) {
if (value == null) {
assertFalse("Unacceptable value reached: " + myItem.getLookupString(), true);
}
if (value.equals(myItem.getLookupString())) {
index++;
break;
}
}
}
assertEquals(finalCount, index);
}
protected void assertStringItems(@NonNls String... items) {
assertEquals(getLookupStrings(new ArrayList<String>()), Arrays.asList(items));
}
protected void assertContainsItems(final String... expected) {
final Set<String> actual = getLookupStrings(new HashSet<String>());
for (String s : expected) {
assertTrue("Expected '" + s + "' not found in " + actual,
actual.contains(s));
}
}
protected void assertNotContainItems(final String... unexpected) {
final Set<String> actual = getLookupStrings(new HashSet<String>());
for (String s : unexpected) {
assertFalse("Unexpected '" + s + "' presented in " + actual,
actual.contains(s));
}
}
private <T extends Collection<String>> T getLookupStrings(T actual) {
if (myItems != null) {
for (LookupElement lookupElement : myItems) {
actual.add(lookupElement.getLookupString());
}
}
return actual;
}
protected static LookupImpl getLookup() {
return (LookupImpl)LookupManager.getActiveLookup(myEditor);
}
}