Merge remote branch 'origin/master'

This commit is contained in:
irengrig
2012-06-28 17:33:56 +04:00
333 changed files with 4641 additions and 1661 deletions
+14
View File
@@ -0,0 +1,14 @@
<component name="libraryTable">
<library name="Snappy-Java">
<CLASSES>
<root url="jar://$PROJECT_DIR$/lib/snappy-java-1.0.4.1.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$PROJECT_DIR$/lib/src/snappy-java-1.0.4.1-src.zip!/snappy-java-1.0.4.1/wiki/apidocs" />
</JAVADOC>
<SOURCES>
<root url="jar://$PROJECT_DIR$/lib/src/snappy-java-1.0.4.1-src.zip!/snappy-java-1.0.4.1/src/main/resources" />
<root url="jar://$PROJECT_DIR$/lib/src/snappy-java-1.0.4.1-src.zip!/snappy-java-1.0.4.1/src/main/java" />
</SOURCES>
</library>
</component>
@@ -23,7 +23,7 @@ import com.intellij.lang.ParserDefinition;
import com.intellij.lang.injection.InjectedLanguageManager;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiElementVisitor;
import com.intellij.psi.impl.source.tree.injected.InjectedLanguageFacadeImpl;
import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil;
import com.intellij.psi.tree.IElementType;
import com.intellij.util.IncorrectOperationException;
import org.intellij.lang.regexp.RegExpLanguage;
@@ -76,7 +76,7 @@ public abstract class RegExpElementImpl extends ASTWrapperPsiElement implements
}
public final String getUnescapedText() {
if (InjectedLanguageFacadeImpl.isInInjectedLanguagePrefixSuffix(this)) {
if (InjectedLanguageUtil.isInInjectedLanguagePrefixSuffix(this)) {
// do not attempt to decode text if PsiElement is part of prefix/suffix
return getText();
}
+2 -1
View File
@@ -181,7 +181,7 @@ libraryLicense(name: "Apache Commons HTTPCore", libraryName: "httpcore-4.1.jar",
url: "http://hc.apache.org/httpcomponents-core-ga/", licenseUrl: "http://www.apache.org/licenses/LICENSE-2.0")
libraryLicense(name: "Antlr", libraryName: "antlr.jar", version: "3.1.3", license: "BSD", url: "http://www.antlr.org",
licenseUrl: "http://www.antlr.org/license.html")
libraryLicense(name: "Guava", version: "R8", license: "Apache 2.0", url: "http://code.google.com/p/guava-libraries/", licenseUrl: "http://ant.apache.org/license.html")
libraryLicense(name: "Guava", version: "12.0", license: "Apache 2.0", url: "http://code.google.com/p/guava-libraries/", licenseUrl: "http://ant.apache.org/license.html")
libraryLicense(name: "Groovy", version: "1.7.3", license: "Apache 2.0", url: "http://groovy.codehaus.org/")
libraryLicense(name: "Gson", libraryName: "gson", license: "Apache 2.0", url: "http://code.google.com/p/google-gson/")
libraryLicense(name: "ini4j", libraryName: "ini4j-0.5.2-patched", version: "0.5.2 (with a patch by JetBrains)", license: "Apache 2.0", url: "http://ini4j.sourceforge.net/", attachedTo: "git4idea")
@@ -238,6 +238,7 @@ libraryLicense(name: "YourKit Java Profiler", libraryName: "yjp-controller-api-r
libraryLicense(name: "protobuf", version: "2.3.0", license: "New BSD", url: "http://code.google.com/p/protobuf/", licenseUrl: "http://code.google.com/p/protobuf/source/browse/trunk/COPYING.txt?r=367")
libraryLicense(name: "Netty", libraryName: "Netty", version: "3.3.1", license: "Apache 2.0", url: "http://netty.io", licenseUrl: "http://www.apache.org/licenses/LICENSE-2.0")
libraryLicense(name: "Kryo", libraryName: "Kryo", version: "1.04", license: "New BSD License", url: "http://code.google.com/p/kryo/", licenseUrl: "http://www.opensource.org/licenses/bsd-license.php")
libraryLicense(name: "Snappy-Java", libraryName: "Snappy-Java", version: "1.0.4.1", license: "Apache 2.0", url: "http://code.google.com/p/snappy-java/", licenseUrl: "http://www.apache.org/licenses/LICENSE-2.0")
jetbrainsLibrary("JPS")
jetbrainsLibrary("Maven Embedder")
jetbrainsLibrary("tcServiceMessages")
Binary file not shown.

Before

Width:  |  Height:  |  Size: 46 KiB

After

Width:  |  Height:  |  Size: 63 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 99 KiB

After

Width:  |  Height:  |  Size: 138 KiB

@@ -81,7 +81,10 @@ import com.intellij.packaging.impl.compiler.ArtifactCompileScope;
import com.intellij.packaging.impl.compiler.ArtifactCompilerUtil;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.util.*;
import com.intellij.util.Chunk;
import com.intellij.util.Function;
import com.intellij.util.StringBuilderSpinAllocator;
import com.intellij.util.ThrowableRunnable;
import com.intellij.util.concurrency.Semaphore;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.HashMap;
@@ -628,7 +631,6 @@ public class CompileDriver {
}
public static final Key<Long> COMPILATION_START_TIMESTAMP = Key.create("COMPILATION_START_TIMESTAMP");
public static final Key<ExitStatus> COMPILE_SERVER_BUILD_STATUS = Key.create("COMPILE_SERVER_BUILD_STATUS");
private void startup(final CompileScope scope,
@@ -658,7 +660,6 @@ public class CompileDriver {
final DependencyCache dependencyCache = useExtProcessBuild ? null: createDependencyCache();
final CompileContextImpl compileContext =
new CompileContextImpl(myProject, compileTask, scope, dependencyCache, !isRebuild && !forceCompile, isRebuild);
compileContext.putUserData(COMPILATION_START_TIMESTAMP, LocalTimeCounter.currentTime());
if (!useExtProcessBuild) {
for (Map.Entry<Pair<IntermediateOutputCompiler, Module>, Pair<VirtualFile, VirtualFile>> entry : myGenerationCompilerModuleToOutputDirMap.entrySet()) {
@@ -889,12 +890,12 @@ public class CompileDriver {
errorCount = compileContext.getMessageCount(CompilerMessageCategory.ERROR);
warningCount = compileContext.getMessageCount(CompilerMessageCategory.WARNING);
if (!myProject.isDisposed()) {
final String statusMessage = createStatusMessage(_status, warningCount, errorCount);
final String statusMessage = createStatusMessage(_status, warningCount, errorCount, duration);
final MessageType messageType = errorCount > 0 ? MessageType.ERROR : warningCount > 0 ? MessageType.WARNING : MessageType.INFO;
if (duration > ONE_MINUTE_MS) {
ToolWindowManager.getInstance(myProject).notifyByBalloon(ToolWindowId.MESSAGES_WINDOW, messageType, statusMessage);
}
CompilerManager.NOTIFICATION_GROUP.createNotification(_status == ExitStatus.UP_TO_DATE ? "Compilation: all files are up to date" : statusMessage, messageType).notify(myProject);
CompilerManager.NOTIFICATION_GROUP.createNotification(statusMessage, messageType).notify(myProject);
if (_status != ExitStatus.UP_TO_DATE && compileContext.getMessageCount(null) > 0) {
compileContext.addMessage(CompilerMessageCategory.INFORMATION, statusMessage, null, -1, -1);
}
@@ -932,19 +933,35 @@ public class CompileDriver {
}
}
private static String createStatusMessage(final ExitStatus status, final int warningCount, final int errorCount) {
private static String createStatusMessage(final ExitStatus status, final int warningCount, final int errorCount, long duration) {
String message;
if (status == ExitStatus.CANCELLED) {
return CompilerBundle.message("status.compilation.aborted");
message = CompilerBundle.message("status.compilation.aborted");
}
if (status == ExitStatus.UP_TO_DATE) {
return CompilerBundle.message("status.all.up.to.date");
else if (status == ExitStatus.UP_TO_DATE) {
message = CompilerBundle.message("status.all.up.to.date");
}
if (status == ExitStatus.SUCCESS) {
return warningCount > 0
? CompilerBundle.message("status.compilation.completed.successfully.with.warnings", warningCount)
: CompilerBundle.message("status.compilation.completed.successfully");
else {
if (status == ExitStatus.SUCCESS) {
message = warningCount > 0
? CompilerBundle.message("status.compilation.completed.successfully.with.warnings", warningCount)
: CompilerBundle.message("status.compilation.completed.successfully");
}
else {
message = CompilerBundle.message("status.compilation.completed.successfully.with.warnings.and.errors", errorCount, warningCount);
}
message = message + " in " + formatDuration(duration);
}
return CompilerBundle.message("status.compilation.completed.successfully.with.warnings.and.errors", errorCount, warningCount);
return message;
}
public static String formatDuration(long duration) {
final long minutes = duration / 60000;
final long seconds = (duration % 60000) / 1000;
if (minutes > 0L) {
return minutes + " min " + seconds + " sec";
}
return seconds + " sec";
}
private ExitStatus doCompile(final CompileContextEx context, boolean isRebuild, final boolean forceCompile, final boolean onlyCheckStatus) {
@@ -82,7 +82,7 @@
<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 out-of-process build for project compilation"/>
<text value="Use external build for compilation"/>
</properties>
</component>
<component id="b9b2d" class="javax.swing.JCheckBox" binding="myCbMakeProjectOnSave">
@@ -98,7 +98,7 @@
<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 run configuration is active"/>
<text value="Allow auto-make while a run configuration is active"/>
</properties>
</component>
</children>
@@ -18,20 +18,21 @@ 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.application.ApplicationManager;
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.registry.Registry;
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 {
@@ -49,10 +50,6 @@ public class CompilerUIConfigurable implements SearchableConfigurable, Configura
public CompilerUIConfigurable(final Project project) {
myProject = project;
final boolean isServerOptionEnabled = Registry.is("compiler.out-of-process.build.enabled") || ApplicationManager.getApplication().isInternal();
myCbUseCompileServer.setVisible(isServerOptionEnabled);
myCbMakeProjectOnSave.setVisible(isServerOptionEnabled);
myCbAllowAutomakeWhileRunningApplication.setVisible(isServerOptionEnabled);
myPatternLegendLabel.setText("<html>" +
"Use <b>;</b> to separate patterns and <b>!</b> to negate a pattern. " +
@@ -60,6 +57,7 @@ public class CompilerUIConfigurable implements SearchableConfigurable, Configura
"<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) {
@@ -103,7 +101,7 @@ public class CompilerUIConfigurable implements SearchableConfigurable, Configura
final CompilerWorkspaceConfiguration workspaceConfiguration = CompilerWorkspaceConfiguration.getInstance(myProject);
workspaceConfiguration.AUTO_SHOW_ERRORS_IN_EDITOR = myCbAutoShowFirstError.isSelected();
workspaceConfiguration.CLEAR_OUTPUT_DIRECTORY = myCbClearOutputDirectory.isSelected();
boolean wasUsing = workspaceConfiguration.USE_COMPILE_SERVER;
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();
@@ -115,14 +113,7 @@ public class CompilerUIConfigurable implements SearchableConfigurable, Configura
// 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) {
if (wasUsing) {
CompileServerManager.getInstance().shutdownServer();
monitor.watchProject(myProject);
monitor.scanSourcesForCompilableFiles(myProject);
}
}
else {
if (workspaceConfiguration.USE_COMPILE_SERVER) {
monitor.suspendProject(myProject);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
@@ -131,6 +122,26 @@ public class CompilerUIConfigurable implements SearchableConfigurable, Configura
}
});
}
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)
@@ -170,7 +181,7 @@ public class CompilerUIConfigurable implements SearchableConfigurable, Configura
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.ALLOW_AUTOMAKE_WHILE_RUNNING_APPLICATION);
isModified |= ComparingUtils.isModified(myCbAllowAutomakeWhileRunningApplication, workspaceConfiguration.allowAutoMakeWhileRunningApplication());
final CompilerConfigurationImpl compilerConfiguration = (CompilerConfigurationImpl)CompilerConfiguration.getInstance(myProject);
isModified |= ComparingUtils.isModified(myCbAssertNotNull, compilerConfiguration.isAddNotNullAssertions());
@@ -294,7 +294,7 @@ public class BuildManager implements ApplicationComponent{
if (!config.useOutOfProcessBuild() || !config.MAKE_PROJECT_ON_SAVE) {
continue;
}
if (!config.ALLOW_AUTOMAKE_WHILE_RUNNING_APPLICATION) {
if (!config.allowAutoMakeWhileRunningApplication()) {
final RunContentManager contentManager = ExecutionManager.getInstance(project).getContentManager();
boolean hasRunningProcesses = false;
for (RunContentDescriptor descriptor : contentManager.getAllDescriptors()) {
@@ -746,7 +746,7 @@ public class BuildManager implements ApplicationComponent{
cmdLine.addParameter(Integer.toString(port));
cmdLine.addParameter(sessionId.toString());
final File workDirectory = new File(mySystemDirectory, SYSTEM_ROOT);
final File workDirectory = getBuildSystemDirectory();
workDirectory.mkdirs();
ensureLogConfigExists(workDirectory);
@@ -757,6 +757,10 @@ public class BuildManager implements ApplicationComponent{
return cmdLine.createProcess();
}
public File getBuildSystemDirectory() {
return new File(mySystemDirectory, SYSTEM_ROOT);
}
private static int getMinorVersion(String vs) {
final int dashIndex = vs.lastIndexOf('_');
if (dashIndex >= 0) {
@@ -58,4 +58,7 @@ public class CompilerWorkspaceConfiguration implements PersistentStateComponent<
public static boolean useServerlessOutOfProcessBuild() {
return true/*!Registry.is("compiler.out-of-process.as-server")*/;
}
public boolean allowAutoMakeWhileRunningApplication() {
return false;/*ALLOW_AUTOMAKE_WHILE_RUNNING_APPLICATION*/
}
}
@@ -369,18 +369,20 @@ public abstract class BreakpointPropertiesPanel {
insert(myClassFiltersFieldPanel, myClassFiltersField);
DebuggerUIUtil.enableEditorOnCheck(myLogExpressionCheckBox, myLogExpressionCombo);
ActionListener listener = new ActionListener() {
ActionListener updateListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
updateCheckboxes();
}
};
myPassCountCheckbox.addActionListener(listener);
myInstanceFiltersCheckBox.addActionListener(listener);
myClassFiltersCheckBox.addActionListener(listener);
myPassCountCheckbox.addActionListener(updateListener);
myInstanceFiltersCheckBox.addActionListener(updateListener);
myClassFiltersCheckBox.addActionListener(updateListener);
myConditionCheckbox.addActionListener(updateListener);
DebuggerUIUtil.focusEditorOnCheck(myPassCountCheckbox, myPassCountField);
DebuggerUIUtil.focusEditorOnCheck(myLogExpressionCheckBox, myLogExpressionCombo);
DebuggerUIUtil.focusEditorOnCheck(myInstanceFiltersCheckBox, myInstanceFiltersField.getTextField());
DebuggerUIUtil.focusEditorOnCheck(myClassFiltersCheckBox, myClassFiltersField.getTextField());
DebuggerUIUtil.focusEditorOnCheck(myConditionCheckbox, myConditionCombo);
IJSwingUtilities.adjustComponentsOnMac(mySuspendJBCheckBox);
IJSwingUtilities.adjustComponentsOnMac(myLogExpressionCheckBox);
@@ -873,7 +875,7 @@ public abstract class BreakpointPropertiesPanel {
break;
}
}
if(selected != null || !myConditionCombo.getText().isEmpty()){
if(selected != null || !myConditionCheckbox.isSelected()){
myPassCountCheckbox.setEnabled(false);
} else {
myPassCountCheckbox.setEnabled(true);
@@ -886,8 +888,8 @@ public abstract class BreakpointPropertiesPanel {
myPassCountField.setEditable(myPassCountCheckbox.isSelected());
myPassCountField.setEnabled (myPassCountCheckbox.isSelected());
myConditionCombo.setEnabled(true);
myConditionMagnifierButton.setEnabled(true);
myConditionCombo.setEnabled(myConditionCheckbox.isSelected());
myConditionMagnifierButton.setEnabled(myConditionCheckbox.isSelected());
myInstanceFiltersField.setEnabled(myInstanceFiltersCheckBox.isSelected());
myInstanceFiltersField.getTextField().setEditable(myInstanceFiltersCheckBox.isSelected());
@@ -136,7 +136,7 @@ public class ExpectedTypesProvider {
public static PsiType[] processExpectedTypes(@NotNull ExpectedTypeInfo[] infos,
@NotNull PsiTypeVisitor<PsiType> visitor, @NotNull Project project) {
Set<PsiType> set = new LinkedHashSet<PsiType>();
LinkedHashSet<PsiType> set = new LinkedHashSet<PsiType>();
for (ExpectedTypeInfo info : infos) {
ExpectedTypeInfoImpl infoImpl = (ExpectedTypeInfoImpl)info;
@@ -105,11 +105,10 @@ public class ConstructorInsertHandler implements InsertHandler<LookupElementDeco
return;
}
if (mySmart) {
FeatureUsageTracker.getInstance().triggerFeatureUsed(JavaCompletionFeatures.AFTER_NEW);
}
if (isAbstract) {
if (mySmart) {
FeatureUsageTracker.getInstance().triggerFeatureUsed(JavaCompletionFeatures.AFTER_NEW_ANONYMOUS);
}
PostprocessReformattingAspect.getInstance(context.getProject()).doPostponedFormatting(context.getFile().getViewProvider());
final Editor editor = context.getEditor();
@@ -34,7 +34,6 @@ import com.intellij.psi.filters.types.AssignableFromFilter;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.util.Consumer;
import com.intellij.util.ProcessingContext;
import com.intellij.util.SmartList;
import org.jetbrains.annotations.NotNull;
@@ -51,24 +50,18 @@ public class JavaClassNameCompletionContributor extends CompletionContributor {
psiElement().afterLeaf(PsiKeyword.EXTENDS, PsiKeyword.SUPER, "&").withParent(
psiElement(PsiReferenceList.class).withParent(PsiTypeParameter.class));
public JavaClassNameCompletionContributor() {
extend(CompletionType.CLASS_NAME, psiElement(), new CompletionProvider<CompletionParameters>() {
public void addCompletions(@NotNull final CompletionParameters parameters, final ProcessingContext matchingContext, @NotNull final CompletionResultSet _result) {
if (shouldShowSecondSmartCompletionHint(parameters) &&
CompletionUtil.shouldShowFeature(parameters, CodeCompletionFeatures.SECOND_CLASS_NAME_COMPLETION)) {
CompletionService.getCompletionService().setAdvertisementText(CompletionBundle.message("completion.class.name.hint.2", getActionShortcut(IdeActions.ACTION_CLASS_NAME_COMPLETION)));
@Override
public void fillCompletionVariants(CompletionParameters parameters, final CompletionResultSet _result) {
if (parameters.isExtendedCompletion()) {
CompletionResultSet result = _result.withPrefixMatcher(CompletionUtil.findReferenceOrAlphanumericPrefix(parameters));
addAllClasses(parameters, parameters.getInvocationCount() <= 1,
JavaCompletionSorting.addJavaSorting(parameters, result).getPrefixMatcher(), new Consumer<LookupElement>() {
@Override
public void consume(LookupElement element) {
_result.addElement(element);
}
CompletionResultSet result = _result.withPrefixMatcher(CompletionUtil.findReferenceOrAlphanumericPrefix(parameters));
addAllClasses(parameters, parameters.getInvocationCount() <= 1,
JavaCompletionSorting.addJavaSorting(parameters, result).getPrefixMatcher(), new Consumer<LookupElement>() {
@Override
public void consume(LookupElement element) {
_result.addElement(element);
}
});
}
});
});
}
}
public static void addAllClasses(CompletionParameters parameters,
@@ -179,7 +172,7 @@ public class JavaClassNameCompletionContributor extends CompletionContributor {
return LangBundle.message("completion.no.suggestions") +
"; " +
StringUtil.decapitalize(
CompletionBundle.message("completion.class.name.hint.2", getActionShortcut(IdeActions.ACTION_CLASS_NAME_COMPLETION)));
CompletionBundle.message("completion.class.name.hint.2", getActionShortcut(IdeActions.ACTION_CODE_COMPLETION)));
}
return null;
@@ -257,7 +257,10 @@ public class JavaCompletionContributor extends CompletionContributor {
public static void addAllClasses(CompletionParameters parameters,
final CompletionResultSet result,
final InheritorsHolder inheritors) {
if (!isClassNamePossible(parameters.getPosition()) || !mayStartClassName(result)) return;
if (!isClassNamePossible(parameters.getPosition()) && parameters.getInvocationCount() <= 1 ||
!mayStartClassName(result)) {
return;
}
if (mayShowAllClasses(parameters)) {
JavaClassNameCompletionContributor.addAllClasses(parameters, parameters.getInvocationCount() <= 2, result.getPrefixMatcher(), new Consumer<LookupElement>() {
@@ -471,9 +474,9 @@ public class JavaCompletionContributor extends CompletionContributor {
PsiElement position = parameters.getPosition();
if (psiElement().withParent(psiReferenceExpression().withFirstChild(psiReferenceExpression().referencing(psiClass()))).accepts(position)) {
if (CompletionUtil.shouldShowFeature(parameters, JavaCompletionFeatures.GLOBAL_MEMBER_NAME)) {
final String shortcut = getActionShortcut(IdeActions.ACTION_CLASS_NAME_COMPLETION);
final String shortcut = getActionShortcut(IdeActions.ACTION_CODE_COMPLETION);
if (shortcut != null) {
return "Pressing " + shortcut + " without a class qualifier would show all accessible static methods";
return "Pressing " + shortcut + " twice without a class qualifier would show all accessible static methods";
}
}
}
@@ -488,15 +491,6 @@ public class JavaCompletionContributor extends CompletionContributor {
}
}
if (parameters.getCompletionType() != CompletionType.CLASS_NAME && shouldSuggestClassNameCompletion(parameters.getPosition())) {
if (CompletionUtil.shouldShowFeature(parameters, CodeCompletionFeatures.EDITING_COMPLETION_CLASSNAME)) {
final String shortcut = getActionShortcut(IdeActions.ACTION_CLASS_NAME_COMPLETION);
if (shortcut != null) {
return CompletionBundle.message("completion.class.name.hint", shortcut);
}
}
}
if (parameters.getCompletionType() == CompletionType.SMART && parameters.getInvocationCount() == 1) {
final PsiType[] psiTypes = ExpectedTypesGetter.getExpectedTypes(parameters.getPosition(), true);
if (psiTypes.length > 0) {
@@ -27,5 +27,4 @@ public interface JavaCompletionFeatures {
@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";
@NonNls String AFTER_NEW_ANONYMOUS = "editing.completion.smarttype.afternew";
}
@@ -1,5 +1,6 @@
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.*;
@@ -15,7 +16,7 @@ public class JavaGlobalMemberNameCompletionContributor extends CompletionContrib
@Override
public void fillCompletionVariants(CompletionParameters parameters, final CompletionResultSet result) {
if (parameters.getCompletionType() != CompletionType.CLASS_NAME) {
if (!parameters.isExtendedCompletion()) {
return;
}
@@ -46,9 +47,9 @@ public class JavaGlobalMemberNameCompletionContributor extends CompletionContrib
shouldImport |= originalPosition != null && PsiTreeUtil.isAncestor(containingClass, originalPosition, false);
if (member instanceof PsiMethod) {
return new JavaMethodCallElement((PsiMethod)member, shouldImport, false);
return AutoCompletionPolicy.NEVER_AUTOCOMPLETE.applyPolicy(new JavaMethodCallElement((PsiMethod)member, shouldImport, false));
}
return new VariableLookupItem((PsiField)member, shouldImport);
return AutoCompletionPolicy.NEVER_AUTOCOMPLETE.applyPolicy(new VariableLookupItem((PsiField)member, shouldImport));
}
@Override
@@ -34,7 +34,7 @@ import com.intellij.psi.*;
import com.intellij.psi.controlFlow.ControlFlowUtil;
import com.intellij.psi.impl.source.javadoc.PsiDocMethodOrFieldRef;
import com.intellij.psi.impl.source.jsp.jspJava.JspClass;
import com.intellij.psi.impl.source.tree.injected.InjectedLanguageFacadeImpl;
import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil;
import com.intellij.psi.javadoc.PsiDocComment;
import com.intellij.psi.javadoc.PsiDocTagValue;
import com.intellij.psi.util.MethodSignatureBackedByPsiMethod;
@@ -106,7 +106,7 @@ public class HighlightVisitorImpl extends JavaElementVisitor implements Highligh
}
private void registerReferencesFromInjectedFragments(final PsiElement element) {
InjectedLanguageFacadeImpl.enumerate(element, myFile, false, new PsiLanguageInjectionHost.InjectedPsiVisitor() {
InjectedLanguageUtil.enumerate(element, myFile, false, new PsiLanguageInjectionHost.InjectedPsiVisitor() {
@Override
public void visit(@NotNull final PsiFile injectedPsi, @NotNull final List<PsiLanguageInjectionHost.Shred> places) {
injectedPsi.accept(REGISTER_REFERENCES_VISITOR);
@@ -20,7 +20,6 @@ import com.intellij.codeInsight.daemon.QuickFixBundle;
import com.intellij.codeInsight.template.Template;
import com.intellij.codeInsight.template.TemplateEditingAdapter;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
@@ -33,7 +32,6 @@ import org.jetbrains.annotations.NotNull;
* @author Mike
*/
public class CreateFieldFromUsageFix extends CreateVarFromUsageFix {
private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.daemon.impl.quickfix.CreateFieldFromUsageFix");
public CreateFieldFromUsageFix(PsiReferenceExpression referenceElement) {
super(referenceElement);
@@ -623,6 +623,7 @@ public class CreateFromUsageUtils {
getExpectedInformation(expression, typesList, expectedMethodNames, expectedFieldNames);
if (typesList.size() == 1 && (!expectedFieldNames.isEmpty() || !expectedMethodNames.isEmpty())) {
ExpectedTypeInfo[] infos = typesList.get(0);
if (infos.length == 1 && infos[0].getKind() == ExpectedTypeInfo.TYPE_OR_SUBTYPE &&
@@ -0,0 +1,80 @@
/*
* 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.intention.HighPriorityAction;
import com.intellij.codeInsight.intention.PsiElementBaseIntentionAction;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.util.PsiTreeUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import static com.intellij.patterns.PlatformPatterns.psiElement;
/**
* @author Danila Ponomarenko
*/
public abstract class BaseColorIntentionAction extends PsiElementBaseIntentionAction implements HighPriorityAction {
protected static final String JAVA_AWT_COLOR = "java.awt.Color";
@Override
public boolean isAvailable(@NotNull Project project, Editor editor, @NotNull PsiElement element) {
if (!psiElement().inside(psiElement(PsiNewExpression.class)).accepts(element)) {
return false;
}
final PsiNewExpression expression = PsiTreeUtil.getParentOfType(element, PsiNewExpression.class, false);
if (expression == null) {
return false;
}
return isJavaAwtColor(expression.getClassOrAnonymousClassReference()) && isValueArguments(expression.getArgumentList());
}
private static boolean isJavaAwtColor(@Nullable PsiJavaCodeReferenceElement ref) {
if (ref == null) {
return false;
}
final PsiReference reference = ref.getReference();
if (reference == null) {
return false;
}
final PsiElement psiElement = reference.resolve();
if (psiElement instanceof PsiClass && JAVA_AWT_COLOR.equals(((PsiClass)psiElement).getQualifiedName())) {
return true;
}
return false;
}
private static boolean isValueArguments(@Nullable PsiExpressionList arguments) {
if (arguments == null) {
return false;
}
for (PsiExpression argument : arguments.getExpressions()) {
if (argument instanceof PsiReferenceExpression) {
return false;
}
}
return true;
}
}
@@ -0,0 +1,110 @@
/*
* 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");
final int indexOfSlashNSlashR = text.indexOf("\\n\\r");
if (indexOfSlashN == -1 || Comparing.equal(text.substring(indexOfSlashN, text.length()), "\\n\"")){
return false;
}
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();
}
}
@@ -46,9 +46,7 @@ import static com.intellij.patterns.PlatformPatterns.psiElement;
* @author spleaner
* @author Konstantin Bulenkov
*/
public class ColorChooserIntentionAction extends PsiElementBaseIntentionAction {
private static final String JAVA_AWT_COLOR = "java.awt.Color";
public class ColorChooserIntentionAction extends BaseColorIntentionAction {
private static final PsiMethodPattern DECODE_METHOD = PsiJavaPatterns.psiMethod()
.definedInClass(JAVA_AWT_COLOR)
.withName("decode");
@@ -64,20 +62,7 @@ public class ColorChooserIntentionAction extends PsiElementBaseIntentionAction {
@Override
public boolean isAvailable(@NotNull final Project project, final Editor editor, @NotNull final PsiElement element) {
// new Color(...)
if (psiElement().inside(psiElement(PsiNewExpression.class)).accepts(element)) {
final PsiNewExpression expression = PsiTreeUtil.getParentOfType(element, PsiNewExpression.class, false);
if (expression != null) {
final PsiJavaCodeReferenceElement ref = PsiTreeUtil.getChildOfType(expression, PsiJavaCodeReferenceElement.class);
if (isJavaAwtColor(ref)) return true;
}
}
// Color.decode("...")
if (isInsideDecodeOrGetColorMethod(element)) {
return true;
}
return false;
return super.isAvailable(project, editor, element) || isInsideDecodeOrGetColorMethod(element);
}
public static boolean isInsideDecodeOrGetColorMethod(PsiElement element) {
@@ -85,24 +70,10 @@ public class ColorChooserIntentionAction extends PsiElementBaseIntentionAction {
element = element.getParent();
}
return PsiJavaPatterns.psiExpression().methodCallParameter(0, DECODE_METHOD).accepts(element)
||
return PsiJavaPatterns.psiExpression().methodCallParameter(0, DECODE_METHOD).accepts(element) ||
PsiJavaPatterns.psiExpression().methodCallParameter(0, GET_COLOR_METHOD).accepts(element);
}
private static boolean isJavaAwtColor(final PsiJavaCodeReferenceElement ref) {
if (ref != null) {
final PsiReference reference = ref.getReference();
if (reference != null) {
final PsiElement psiElement = reference.resolve();
if (psiElement instanceof PsiClass && JAVA_AWT_COLOR.equals(((PsiClass)psiElement).getQualifiedName())) {
return true;
}
}
}
return false;
}
@Override
@NotNull
public String getFamilyName() {
@@ -116,7 +87,8 @@ public class ColorChooserIntentionAction extends PsiElementBaseIntentionAction {
final JComponent editorComponent = editor.getComponent();
if (isInsideDecodeOrGetColorMethod(element)) {
invokeForMethodParam(editorComponent, element);
} else {
}
else {
invokeForConstructor(editorComponent, element);
}
}
@@ -139,9 +111,9 @@ public class ColorChooserIntentionAction extends PsiElementBaseIntentionAction {
if (color == null) return;
final int rgb = color.getRGB() - ((255 & 0xFF) << 24);
if (color != null && rgb != oldColor.getRGB()) {
final String newText = radix == 16 ? hexPrefix + String.format("%6s" ,Integer.toHexString(rgb)).replace(' ', '0')
: radix == 8 ? "0" + Integer.toOctalString(rgb)
: Integer.toString(rgb);
final String newText = radix == 16 ? hexPrefix + String.format("%6s", Integer.toHexString(rgb)).replace(' ', '0')
: radix == 8 ? "0" + Integer.toOctalString(rgb)
: Integer.toString(rgb);
final PsiManager manager = literal.getManager();
final PsiElementFactory factory = JavaPsiFacade.getInstance(manager.getProject()).getElementFactory();
final PsiExpression newLiteral = factory.createExpressionFromText("\"" + newText + "\"", literal);
@@ -221,12 +193,12 @@ public class ColorChooserIntentionAction extends PsiElementBaseIntentionAction {
final PsiManager manager = expression.getManager();
final PsiElementFactory factory = JavaPsiFacade.getInstance(manager.getProject()).getElementFactory();
final PsiExpression newCall = factory.createExpressionFromText(
"new " + JAVA_AWT_COLOR +"("
+ color.getRed() + ", "
+ color.getGreen() + ", "
+ color.getBlue()
+ (color.getAlpha() < 255 ? ", " + color.getAlpha() : "")
+")", expression);
"new " + JAVA_AWT_COLOR + "("
+ color.getRed() + ", "
+ color.getGreen() + ", "
+ color.getBlue()
+ (color.getAlpha() < 255 ? ", " + color.getAlpha() : "")
+ ")", expression);
final PsiElement insertedElement = expression.replace(newCall);
final CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(manager.getProject());
codeStyleManager.reformat(insertedElement);
@@ -15,6 +15,7 @@
*/
package com.intellij.codeInsight.intention.impl;
import com.intellij.codeInsight.CodeInsightUtilBase;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiFile;
@@ -38,7 +39,6 @@ public class ConvertAbsolutePathToRelativeIntentionAction extends BaseIntentionA
@Override
public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
final PsiReference reference = file.findReferenceAt(editor.getCaretModel().getOffset());
final FileReference fileReference = reference == null ? null : findFileReference(reference);
@@ -81,6 +81,8 @@ public class ConvertAbsolutePathToRelativeIntentionAction extends BaseIntentionA
@Override
public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException {
if (!CodeInsightUtilBase.prepareFileForWrite(file)) return;
final PsiReference reference = file.findReferenceAt(editor.getCaretModel().getOffset());
final FileReference fileReference = reference == null ? null : findFileReference(reference);
if (fileReference != null) {
@@ -0,0 +1,226 @@
/*
* 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.CodeInsightUtilBase;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.impl.JavaConstantExpressionEvaluator;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* @author Danila Ponomarenko
*/
public class ConvertColorRepresentationIntentionAction extends BaseColorIntentionAction {
@Override
public boolean isAvailable(@NotNull Project project, Editor editor, @NotNull PsiElement element) {
if (!super.isAvailable(project, editor, element)) {
return false;
}
final PsiNewExpression expression = PsiTreeUtil.getParentOfType(element, PsiNewExpression.class, false);
if (expression == null) {
return false;
}
final PsiExpressionList arguments = expression.getArgumentList();
if (arguments == null) {
return false;
}
final PsiMethod constructor = expression.resolveConstructor();
if (constructor == null) {
return false;
}
final PsiExpressionList newArguments = createNewArguments(JavaPsiFacade.getElementFactory(project), constructor.getParameterList().getParameters(), arguments.getExpressions());
if (newArguments == null) {
return false;
}
setText(CodeInsightBundle.message("intention.convert.color.representation.text", newArguments.getText()));
return true;
}
@Override
public void invoke(@NotNull Project project, Editor editor, @NotNull PsiElement element) throws IncorrectOperationException {
if (!CodeInsightUtilBase.preparePsiElementForWrite(element)) return;
final PsiNewExpression expression = PsiTreeUtil.getParentOfType(element, PsiNewExpression.class, false);
if (expression == null) {
return;
}
final PsiExpressionList arguments = expression.getArgumentList();
if (arguments == null) {
return;
}
final PsiMethod constructor = expression.resolveConstructor();
if (constructor == null) {
return;
}
final PsiExpressionList newArguments = createNewArguments(
JavaPsiFacade.getElementFactory(project),
constructor.getParameterList().getParameters(),
arguments.getExpressions()
);
if (newArguments == null) {
return;
}
arguments.replace(newArguments);
}
@Nullable
private static PsiExpressionList createNewArguments(@NotNull PsiElementFactory factory,
@NotNull PsiParameter[] parameters,
@NotNull PsiExpression[] arguments) {
final String[] newValues = createArguments(parameters, arguments);
if (newValues == null) {
return null;
}
final PsiExpressionList result = ((PsiNewExpression)factory.createExpressionFromText("new Object()", parameters[0])).getArgumentList();
if (result == null) {
return null;
}
for (String value : newValues) {
result.add(factory.createExpressionFromText(value, parameters[0]));
}
return result;
}
@Nullable
private static String[] createArguments(@NotNull PsiParameter[] parameters,
@NotNull PsiExpression[] arguments) {
if (parameters.length != arguments.length) {
return null;
}
switch (parameters.length) {
default:
return null;
case 1:
return createArguments(arguments[0]);
case 2:
return createArguments(arguments[0], arguments[1]);
case 3:
return createArguments(arguments[0], arguments[1], arguments[2]);
case 4:
return createArguments(arguments[0], arguments[1], arguments[2], arguments[3]);
}
}
@Nullable
private static String[] createArguments(@NotNull PsiExpression rgbExpression) {
return createArguments(rgbExpression, 3);
}
@Nullable
private static String[] createArguments(@NotNull PsiExpression rgbExpression,
@NotNull PsiExpression hasAlphaExpression) {
final Boolean hasAlpha = computeBoolean(hasAlphaExpression);
if (hasAlpha == null) {
return null;
}
return hasAlpha ? createArguments(rgbExpression, 4) : createArguments(rgbExpression);
}
@Nullable
private static String[] createArguments(@NotNull PsiExpression rExpression,
@NotNull PsiExpression gExpression,
@NotNull PsiExpression bExpression) {
final Integer value = createInt(computeInteger(rExpression), computeInteger(gExpression), computeInteger(bExpression));
return value != null ? new String[]{"0x" + Integer.toHexString(value)} : null;
}
@Nullable
private static String[] createArguments(@NotNull PsiExpression rExpression,
@NotNull PsiExpression gExpression,
@NotNull PsiExpression bExpression,
@NotNull PsiExpression aExpression) {
final Integer value = createInt(computeInteger(rExpression), computeInteger(gExpression), computeInteger(bExpression), computeInteger(aExpression));
if (value == null) {
return null;
}
return new String[]{
"0x" + Integer.toHexString(value),
"true",
};
}
@Nullable
private static String[] createArguments(@NotNull PsiExpression rgbExpression,
int parts) {
final Integer rgb = computeInteger(rgbExpression);
if (rgb == null) {
return null;
}
final String[] result = new String[parts];
for (int i = 0; i < result.length; i++) {
result[result.length - i - 1] = String.valueOf(rgb >> (i * Byte.SIZE) & 0xFF);
}
return result;
}
@Nullable
private static Integer createInt(Integer... ints) {
int result = 0;
for (Integer i : ints) {
if (i == null) {
return null;
}
result = result << Byte.SIZE | (i & 0xFF);
}
return result;
}
@Nullable
public static Integer computeInteger(@NotNull PsiExpression expr) {
final Object result = compute(expr);
return result instanceof Integer ? (Integer)result : null;
}
@Nullable
public static Boolean computeBoolean(@NotNull PsiExpression expr) {
final Object result = compute(expr);
return result instanceof Boolean ? (Boolean)result : null;
}
@Nullable
private static Object compute(@NotNull PsiExpression expr) {
return JavaConstantExpressionEvaluator.computeConstantExpression(expr, true);
}
@NotNull
@Override
public String getFamilyName() {
return CodeInsightBundle.message("intention.convert.color.representation.family");
}
}
@@ -28,10 +28,9 @@ import com.intellij.psi.*;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
public class TypeExpression extends Expression {
private final Set<SmartTypePointer> myItems;
private final LinkedHashSet<SmartTypePointer> myItems;
public TypeExpression(final Project project, PsiType[] types) {
final SmartTypePointerManager manager = SmartTypePointerManager.getInstance(project);
@@ -16,6 +16,7 @@
package com.intellij.codeInsight.lookup;
import com.intellij.codeInsight.completion.*;
import com.intellij.ide.highlighter.XmlLikeFileType;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.ScrollType;
import com.intellij.openapi.util.ClassConditionKey;
@@ -79,7 +80,11 @@ public class PsiTypeLookupItem extends LookupItem {
PsiElement position = context.getFile().findElementAt(context.getStartOffset());
assert position != null;
int genericsStart = context.getTailOffset();
context.getDocument().insertString(genericsStart, calcGenerics(position, context));
String generics = calcGenerics(position, context);
if (context.getFile().getFileType() instanceof XmlLikeFileType) {
generics = StringUtil.escapeXml(generics);
}
context.getDocument().insertString(genericsStart, generics);
JavaCompletionUtil.shortenReference(context.getFile(), genericsStart - 1);
int tail = context.getTailOffset();
@@ -34,6 +34,7 @@ import com.intellij.codeInspection.*;
import com.intellij.codeInspection.dataFlow.instructions.*;
import com.intellij.codeInspection.ex.BaseLocalInspectionTool;
import com.intellij.ide.DataManager;
import com.intellij.lang.ASTFactory;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
@@ -41,6 +42,8 @@ import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.util.Pair;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.psi.*;
import com.intellij.psi.impl.source.codeStyle.CodeFormatterFacade;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.util.ArrayUtil;
import com.intellij.util.IncorrectOperationException;
@@ -230,8 +233,11 @@ public class DataFlowInspection extends BaseLocalInspectionTool {
else if (psiAnchor != null && !reportedAnchors.contains(psiAnchor) && !isCompileConstantInIfCondition(psiAnchor)) {
boolean evaluatesToTrue = trueSet.contains(instruction);
if (onTheLeftSideOfConditionalAssignemnt(psiAnchor)) {
holder.registerProblem(psiAnchor, InspectionsBundle.message("dataflow.message.pointless.assignment.expression",
Boolean.toString(evaluatesToTrue)));
holder.registerProblem(
psiAnchor,
InspectionsBundle.message("dataflow.message.pointless.assignment.expression", Boolean.toString(evaluatesToTrue)),
createSimplifyToAssignmentFix()
);
}
else {
boolean report = !(psiAnchor.getParent() instanceof PsiAssertStatement) || !DONT_REPORT_TRUE_ASSERT_STATEMENTS || !evaluatesToTrue;
@@ -370,6 +376,40 @@ public class DataFlowInspection extends BaseLocalInspectionTool {
};
}
@NotNull
private static LocalQuickFix createSimplifyToAssignmentFix() {
return new LocalQuickFix() {
@NotNull
@Override
public String getName() {
return InspectionsBundle.message("inspection.data.flow.simplify.to.assignment.quickfix.name");
}
@NotNull
@Override
public String getFamilyName() {
return InspectionsBundle.message("inspection.data.flow.simplify.boolean.expression.quickfix");
}
@Override
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
final PsiElement psiElement = descriptor.getPsiElement();
if (psiElement == null) return;
final PsiAssignmentExpression assignmentExpression = PsiTreeUtil.getParentOfType(psiElement, PsiAssignmentExpression.class);
if (assignmentExpression == null) {
return;
}
final PsiElementFactory factory = JavaPsiFacade.getElementFactory(project);
final String lExpressionText = assignmentExpression.getLExpression().getText();
final PsiExpression rExpression = assignmentExpression.getRExpression();
final String rExpressionText = rExpression != null ? rExpression.getText() : "";
assignmentExpression.replace(factory.createExpressionFromText(lExpressionText + " = " + rExpressionText, psiElement));
}
};
}
private static SimplifyBooleanExpressionFix createIntention(PsiElement element, boolean value) {
if (!(element instanceof PsiExpression)) return null;
final PsiExpression expression = (PsiExpression)element;
@@ -27,14 +27,15 @@ package com.intellij.codeInspection.dataFlow;
import com.intellij.codeInsight.NullableNotNullManager;
import com.intellij.codeInspection.dataFlow.value.DfaTypeValue;
import com.intellij.codeInspection.dataFlow.value.DfaValue;
import com.intellij.psi.PsiPrimitiveType;
import com.intellij.psi.PsiVariable;
import com.intellij.codeInspection.nullable.NullableStuffInspection;
import com.intellij.psi.*;
import gnu.trove.THashSet;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.Nullable;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
public class DfaVariableState implements Cloneable {
@@ -48,8 +49,36 @@ public class DfaVariableState implements Cloneable {
myVar = var;
myInstanceofValues = new HashSet<DfaTypeValue>();
myNotInstanceofValues = new HashSet<DfaTypeValue>();
myNullable = var != null && NullableNotNullManager.isNullable(var);
myVariableIsDeclaredNotNull = var != null && NullableNotNullManager.isNotNull(var);
myNullable = var != null && (NullableNotNullManager.isNullable(var) || isNullableInitialized(var, true));
myVariableIsDeclaredNotNull = var != null && (NullableNotNullManager.isNotNull(var) || isNullableInitialized(var, false));
}
private static boolean isNullableInitialized(PsiVariable var, boolean nullable) {
if (!var.hasModifierProperty(PsiModifier.FINAL) || !(var instanceof PsiField)) {
return false;
}
List<PsiExpression> initializers = NullableStuffInspection.findAllConstructorInitializers((PsiField)var);
if (initializers.isEmpty()) {
return false;
}
for (PsiExpression expression : initializers) {
if (!(expression instanceof PsiReferenceExpression)) {
return false;
}
PsiElement target = ((PsiReferenceExpression)expression).resolve();
if (!(target instanceof PsiParameter)) {
return false;
}
if (nullable && NullableNotNullManager.isNullable((PsiParameter)target)) {
return true;
}
if (!nullable && !NullableNotNullManager.isNotNull((PsiParameter)target)) {
return false;
}
}
return !nullable;
}
protected DfaVariableState(final DfaVariableState toClone) {
@@ -42,8 +42,8 @@ import com.intellij.psi.util.*;
import com.intellij.refactoring.psi.PropertyUtils;
import com.intellij.util.ArrayUtil;
import com.intellij.util.Processor;
import com.intellij.util.Query;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
@@ -51,6 +51,9 @@ import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import static com.intellij.util.containers.ContainerUtil.addIfNotNull;
import static com.intellij.util.containers.ContainerUtilRt.createEmptyCOWList;
public class NullableStuffInspection extends BaseLocalInspectionTool {
// deprecated fields remain to minimize changes to users inspection profiles (which are often located in version control).
@Deprecated @SuppressWarnings({"WeakerAccess"}) public boolean REPORT_NULLABLE_METHOD_OVERRIDES_NOTNULL = true;
@@ -173,40 +176,13 @@ public class NullableStuffInspection extends BaseLocalInspectionTool {
new AddAnnotationFix(anno, parameter, ArrayUtil.toStringArray(annoToRemove)));
}
}
if (containingClass == null) {
return;
}
final PsiMethod[] constructors = containingClass.getConstructors();
final Query<PsiReference> search = ReferencesSearch.search(field, new LocalSearchScope(constructors), false);
search.forEach(new Processor<PsiReference>() {
@Override
public boolean process(PsiReference reference) {
final PsiElement element = reference.getElement();
if (!(element instanceof PsiReferenceExpression)) {
return true;
}
PsiReferenceExpression referenceExpression = (PsiReferenceExpression)element;
final PsiAssignmentExpression assignmentExpression = getAssignmentExpressionIfOnAssignmentLefthand(referenceExpression);
final PsiMethod method = PsiTreeUtil.getParentOfType(assignmentExpression, PsiMethod.class);
if (method == null || !method.isConstructor()) {
return true;
}
if (assignmentExpression == null) {
return true;
}
final PsiExpression rhs = assignmentExpression.getRExpression();
if (!(rhs instanceof PsiReferenceExpression)) {
return true;
}
PsiReferenceExpression expression = (PsiReferenceExpression)rhs;
final PsiElement target = expression.resolve();
if (!(target instanceof PsiParameter)) {
return true;
}
final PsiParameter parameter = (PsiParameter)target;
if (!method.equals(parameter.getDeclarationScope())) {
return true;
}
}
for (PsiExpression rhs : findAllConstructorInitializers(field)) {
if (rhs instanceof PsiReferenceExpression) {
PsiElement target = ((PsiReferenceExpression)rhs).resolve();
if (target instanceof PsiParameter) {
PsiParameter parameter = (PsiParameter)target;
if (REPORT_NOT_ANNOTATED_GETTER && !AnnotationUtil.isAnnotated(parameter, manager.getAllAnnotations()) && !TypeConversionUtil.isPrimitiveAndNotNull(parameter.getType())) {
final PsiIdentifier nameIdentifier2 = parameter.getNameIdentifier();
assert nameIdentifier2 != null : parameter;
@@ -214,7 +190,7 @@ public class NullableStuffInspection extends BaseLocalInspectionTool {
.message("inspection.nullable.problems.annotated.field.constructor.parameter.not.annotated",
StringUtil.getShortName(anno)),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING, new AddAnnotationFix(anno, parameter, ArrayUtil.toStringArray(annoToRemove)));
return true;
continue;
}
if (annotated.isDeclaredNotNull && manager.isNullable(parameter, false)) {
final PsiIdentifier nameIdentifier2 = parameter.getNameIdentifier();
@@ -234,9 +210,9 @@ public class NullableStuffInspection extends BaseLocalInspectionTool {
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
new AddAnnotationFix(anno, parameter, ArrayUtil.toStringArray(annoToRemove)));
}
return true;
}
});
}
}
}
}
@@ -246,18 +222,6 @@ public class NullableStuffInspection extends BaseLocalInspectionTool {
LOG.assertTrue(parameter.isPhysical(), setter.getText());
}
public PsiAssignmentExpression getAssignmentExpressionIfOnAssignmentLefthand(PsiExpression expression) {
PsiElement parent = PsiTreeUtil.skipParentsOfType(expression, PsiParenthesizedExpression.class);
if (!(parent instanceof PsiAssignmentExpression)) {
return null;
}
final PsiAssignmentExpression assignmentExpression = (PsiAssignmentExpression)parent;
if (!PsiTreeUtil.isAncestor(assignmentExpression.getLExpression(), expression, false)) {
return null;
}
return assignmentExpression;
}
@Override public void visitParameter(PsiParameter parameter) {
if (!PsiUtil.isLanguageLevel5OrHigher(parameter)) return;
check(parameter, holder, parameter.getType());
@@ -519,4 +483,42 @@ public class NullableStuffInspection extends BaseLocalInspectionTool {
REPORT_NULLS_PASSED_TO_NON_ANNOTATED_METHOD = myReportNullsPassedToNonAnnotatedParameter.isSelected();
}
}
public static List<PsiExpression> findAllConstructorInitializers(PsiField field) {
final List<PsiExpression> result = createEmptyCOWList();
addIfNotNull(result, field.getInitializer());
PsiClass containingClass = field.getContainingClass();
if (containingClass != null) {
LocalSearchScope scope = new LocalSearchScope(containingClass.getConstructors());
ReferencesSearch.search(field, scope, false).forEach(new Processor<PsiReference>() {
@Override
public boolean process(PsiReference reference) {
final PsiElement element = reference.getElement();
if (element instanceof PsiReferenceExpression) {
final PsiAssignmentExpression assignment = getAssignmentExpressionIfOnAssignmentLhs(element);
final PsiMethod method = PsiTreeUtil.getParentOfType(assignment, PsiMethod.class);
if (method != null && method.isConstructor() && assignment != null) {
addIfNotNull(result, assignment.getRExpression());
}
}
return true;
}
});
}
return result;
}
@Nullable
private static PsiAssignmentExpression getAssignmentExpressionIfOnAssignmentLhs(PsiElement expression) {
PsiElement parent = PsiTreeUtil.skipParentsOfType(expression, PsiParenthesizedExpression.class);
if (!(parent instanceof PsiAssignmentExpression)) {
return null;
}
final PsiAssignmentExpression assignmentExpression = (PsiAssignmentExpression)parent;
if (!PsiTreeUtil.isAncestor(assignmentExpression.getLExpression(), expression, false)) {
return null;
}
return assignmentExpression;
}
}
@@ -34,7 +34,7 @@ import com.intellij.psi.formatter.java.wrap.ReservedWrapsProvider;
import com.intellij.psi.impl.source.SourceTreeToPsiMap;
import com.intellij.psi.impl.source.codeStyle.ShiftIndentInsideHelper;
import com.intellij.psi.impl.source.tree.*;
import com.intellij.psi.impl.source.tree.injected.InjectedLanguageFacadeImpl;
import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil;
import com.intellij.psi.impl.source.tree.java.ClassElement;
import com.intellij.psi.jsp.JspElementType;
import com.intellij.psi.tree.IElementType;
@@ -172,7 +172,7 @@ public abstract class AbstractJavaBlock extends AbstractBlock implements JavaBlo
if (isStatement(child, child.getTreeParent())) {
return new CodeBlockBlock(child, wrap, alignment, actualIndent, settings);
}
if (child instanceof PsiComment && child instanceof PsiLanguageInjectionHost && InjectedLanguageFacadeImpl
if (child instanceof PsiComment && child instanceof PsiLanguageInjectionHost && InjectedLanguageUtil
.hasInjections((PsiLanguageInjectionHost)child)) {
return new CommentWithInjectionBlock(child, wrap, alignment, indent, settings);
}
@@ -25,7 +25,7 @@ import com.intellij.openapi.util.Iconable;
import com.intellij.openapi.vcs.FileStatus;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import com.intellij.psi.impl.source.tree.injected.InjectedLanguageFacadeImpl;
import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil;
import com.intellij.psi.jsp.JspFile;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.usageView.UsageInfo;
@@ -48,7 +48,7 @@ public class ClassGroupingRule implements UsageGroupingRule {
}
final PsiElement psiElement = ((PsiElementUsage)usage).getElement();
final PsiFile containingFile = psiElement.getContainingFile();
PsiFile topLevelFile = InjectedLanguageFacadeImpl.getTopLevelFile(containingFile);
PsiFile topLevelFile = InjectedLanguageUtil.getTopLevelFile(containingFile);
if (!(topLevelFile instanceof PsiJavaFile) || topLevelFile instanceof JspFile) {
return null;
@@ -28,7 +28,7 @@ import com.intellij.openapi.util.Iconable;
import com.intellij.openapi.util.Segment;
import com.intellij.openapi.vcs.FileStatus;
import com.intellij.psi.*;
import com.intellij.psi.impl.source.tree.injected.InjectedLanguageFacadeImpl;
import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil;
import com.intellij.psi.util.PsiFormatUtil;
import com.intellij.psi.util.PsiFormatUtilBase;
import com.intellij.psi.util.PsiTreeUtil;
@@ -51,7 +51,7 @@ public class MethodGroupingRule implements UsageGroupingRule {
if (!(usage instanceof PsiElementUsage)) return null;
PsiElement psiElement = ((PsiElementUsage)usage).getElement();
PsiFile containingFile = psiElement.getContainingFile();
PsiFile topLevelFile = InjectedLanguageFacadeImpl.getTopLevelFile(containingFile);
PsiFile topLevelFile = InjectedLanguageUtil.getTopLevelFile(containingFile);
if (topLevelFile instanceof PsiJavaFile) {
PsiElement containingMethod = topLevelFile == containingFile ? psiElement : InjectedLanguageManager
.getInstance(containingFile.getProject()).getInjectionHost(containingFile);
@@ -24,31 +24,31 @@ import org.jetbrains.annotations.Nullable;
import java.util.Map;
public class PsiTypesUtil {
@NonNls private static final Map<String, String> ourUnboxedTypes = new THashMap<String, String>();
@NonNls private static final Map<String, String> ourBoxedTypes = new THashMap<String, String>();
@NonNls private static final Map<String, String> ourUnboxedTypes = new THashMap<String, String>() {{
put(CommonClassNames.JAVA_LANG_BOOLEAN, "boolean");
put(CommonClassNames.JAVA_LANG_BYTE, "byte");
put(CommonClassNames.JAVA_LANG_SHORT, "short");
put(CommonClassNames.JAVA_LANG_INTEGER, "int");
put(CommonClassNames.JAVA_LANG_LONG, "long");
put(CommonClassNames.JAVA_LANG_FLOAT, "float");
put(CommonClassNames.JAVA_LANG_DOUBLE, "double");
put(CommonClassNames.JAVA_LANG_CHARACTER, "char");
}};
static {
ourUnboxedTypes.put(CommonClassNames.JAVA_LANG_BOOLEAN, "boolean");
ourUnboxedTypes.put(CommonClassNames.JAVA_LANG_BYTE, "byte");
ourUnboxedTypes.put(CommonClassNames.JAVA_LANG_SHORT, "short");
ourUnboxedTypes.put(CommonClassNames.JAVA_LANG_INTEGER, "int");
ourUnboxedTypes.put(CommonClassNames.JAVA_LANG_LONG, "long");
ourUnboxedTypes.put(CommonClassNames.JAVA_LANG_FLOAT, "float");
ourUnboxedTypes.put(CommonClassNames.JAVA_LANG_DOUBLE, "double");
ourUnboxedTypes.put(CommonClassNames.JAVA_LANG_CHARACTER, "char");
@NonNls private static final Map<String, String> ourBoxedTypes = new THashMap<String, String>() {{
put("boolean", CommonClassNames.JAVA_LANG_BOOLEAN);
put("byte", CommonClassNames.JAVA_LANG_BYTE);
put("short", CommonClassNames.JAVA_LANG_SHORT);
put("int", CommonClassNames.JAVA_LANG_INTEGER);
put("long", CommonClassNames.JAVA_LANG_LONG);
put("float", CommonClassNames.JAVA_LANG_FLOAT);
put("double", CommonClassNames.JAVA_LANG_DOUBLE);
put("char", CommonClassNames.JAVA_LANG_CHARACTER);
}};
ourBoxedTypes.put("boolean", CommonClassNames.JAVA_LANG_BOOLEAN);
ourBoxedTypes.put("byte", CommonClassNames.JAVA_LANG_BYTE);
ourBoxedTypes.put("short", CommonClassNames.JAVA_LANG_SHORT);
ourBoxedTypes.put("int", CommonClassNames.JAVA_LANG_INTEGER);
ourBoxedTypes.put("long", CommonClassNames.JAVA_LANG_LONG);
ourBoxedTypes.put("float", CommonClassNames.JAVA_LANG_FLOAT);
ourBoxedTypes.put("double", CommonClassNames.JAVA_LANG_DOUBLE);
ourBoxedTypes.put("char", CommonClassNames.JAVA_LANG_CHARACTER);
private PsiTypesUtil() {
}
private PsiTypesUtil() { }
public static String getDefaultValueOfType(PsiType type) {
if (type instanceof PsiArrayType) {
int count = type.getArrayDimensions() - 1;
@@ -86,6 +86,7 @@ public class PsiTypesUtil {
/**
* Returns the unboxed type name or parameter.
*
* @param type boxed java type name
* @return unboxed type name if available; same value otherwise
*/
@@ -93,11 +94,12 @@ public class PsiTypesUtil {
public static String unboxIfPossible(final String type) {
if (type == null) return null;
final String s = ourUnboxedTypes.get(type);
return s == null? type : s;
return s == null ? type : s;
}
/**
* Returns the boxed type name or parameter.
*
* @param type primitive java type name
* @return boxed type name if available; same value otherwise
*/
@@ -110,7 +112,7 @@ public class PsiTypesUtil {
@Nullable
public static PsiClass getPsiClass(final PsiType psiType) {
return psiType instanceof PsiClassType? ((PsiClassType)psiType).resolve() : null;
return psiType instanceof PsiClassType ? ((PsiClassType)psiType).resolve() : null;
}
public static PsiClassType getClassType(@NotNull PsiClass psiClass) {
@@ -1,17 +1,17 @@
class Foo {
int ELEMENT_A = 1;
int ELEMENT_B = 1;
int ELEMENT_C = 1;
int ELEMENT_D = 1;
int ELEMENT_E = 1;
int ELEMENT_F = 1;
int ELEMENT_G = 1;
int ELEMENT_H = 1;
int ELEMENT_I = 1;
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;
{
El<caret>
Elx<caret>
}
}
@@ -0,0 +1,7 @@
// "Break string on '\n'" "true"
class A {
String s = "Hello,\n\r" +
"world\n" +
"!\n";
}
@@ -0,0 +1,5 @@
// "Break string on '\n'" "true"
class A {
String s = "Hello,\n\rwor<caret>ld\n!\n";
}
@@ -0,0 +1,5 @@
// "Break string on '\n'" "false"
class A {
String s = "Hello!\n";
}
@@ -0,0 +1,5 @@
// "Break string on '\n'" "false"
class A {
String s = "Hello!\n\r";
}
@@ -0,0 +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) {
}
}
@@ -0,0 +1,21 @@
// "Convert to 'new Color(37, 100, 120)'" "true"
package java.awt;
public class A {
private Color color = new Color(37, 100, 120);
}
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) {
}
}
@@ -0,0 +1,21 @@
// "Convert to 'new Color(37, 100, 120, 140)'" "true"
package java.awt;
class A {
private Color color = new Color(37, 100, 120, 140);
}
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) {
}
}
@@ -0,0 +1,21 @@
// "Convert to 'new Color(0x256478)'" "true"
package java.awt;
class A {
private Color color = new Color(0x256478);
}
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) {
}
}
@@ -0,0 +1,21 @@
// "Convert to 'new Color(0x2564788c,true)'" "true"
package java.awt;
class A {
private Color color = new Color(0x2564788c, true);
}
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) {
}
}
@@ -0,0 +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) {
}
}
@@ -0,0 +1,21 @@
// "Convert to 'new Color(37, 100, 120)'" "true"
package java.awt;
public class A {
private Color color = new Color(0x25<caret>6478);
}
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) {
}
}
@@ -0,0 +1,21 @@
// "Convert to 'new Color(37, 100, 120, 140)'" "true"
package java.awt;
class A {
private Color color = new Color(0x25647<caret>88c, true);
}
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) {
}
}
@@ -0,0 +1,21 @@
// "Convert to 'new Color(0x256478)'" "true"
package java.awt;
class A {
private Color color = new Color(37, 100,<caret> 120);
}
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) {
}
}
@@ -0,0 +1,21 @@
// "Convert to 'new Color(0x2564788c,true)'" "true"
package java.awt;
class A {
private Color color = new Color(37, 100,<caret> 120, 140);
}
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) {
}
}
@@ -0,0 +1,30 @@
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.lang.Object;
public class Doo {
private final Object myA;
private final Object myB;
private final Object myC;
public Doo(@Nullable Object myA, @NotNull Object myB, Object c) {
this.myA = myA;
this.myB = myB;
myC = c;
}
int bar() {
return myC.hashCode();
}
int foo() {
if (<warning descr="Condition 'myB != null' is always 'true'">myB != null</warning> &&
<warning descr="Method invocation 'myA.equals(myB)' may produce 'java.lang.NullPointerException'">myA.equals(myB)</warning>) {
return 2;
}
return myA.hashCode();
}
}
@@ -62,4 +62,12 @@
<description>Constructor parameter for @NotNull field might be annotated @NotNull itself</description>
</problem>
<problem>
<file>Test.java</file>
<line>63</line>
<problem_class severity="WARNING" attribute_key="WARNING_ATTRIBUTES">@NotNull/@Nullable problems</problem_class>
<description>Constructor parameter for @NotNull field might be annotated @NotNull itself</description>
</problem>
</problems>
@@ -55,4 +55,13 @@ class D {
D(long l) {
myL = l;
}
}
class E {
final @NotNull C c;
E(C c) {
this.c = c;
}
}
@@ -10,6 +10,8 @@ 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;
@@ -25,6 +27,12 @@ public abstract class CompletionSortingTestCase extends LightFixtureCompletionTe
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();
@@ -10,8 +10,6 @@ import com.intellij.openapi.roots.LanguageLevelProjectExtension;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.psi.codeStyle.CodeStyleSettingsManager;
import com.intellij.psi.codeStyle.CommonCodeStyleSettings;
import com.intellij.psi.statistics.StatisticsManager;
import com.intellij.psi.statistics.impl.StatisticsManagerImpl;
import com.intellij.testFramework.LightCodeInsightTestCase;
import com.intellij.testFramework.TestDataPath;
@@ -26,12 +24,6 @@ import com.intellij.testFramework.TestDataPath;
public class CompletionStyleTest extends LightCodeInsightTestCase{
private static final String BASE_PATH = "/codeInsight/completion/style";
@Override
protected void setUp() throws Exception {
super.setUp();
((StatisticsManagerImpl)StatisticsManager.getInstance()).clearStatistics();
}
@Override
protected LanguageLevel getLanguageLevel() {
return LanguageLevel.JDK_1_6;
@@ -3,7 +3,8 @@ 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.LookupElementPresentation
import com.intellij.codeInsight.lookup.LookupElement;
/**
* @author peter
@@ -65,7 +66,7 @@ public class Foo {
}
""")
myFixture.configureByText "a.java", "class Bar {{ abcf<caret> }}"
def element = myFixture.complete(CompletionType.CLASS_NAME)[0]
def element = complete()[0]
def presentation = new LookupElementPresentation()
element.renderElement(presentation)
assert 'Foo.abcfield' == presentation.itemText
@@ -73,6 +74,10 @@ public class Foo {
assert 'int' == presentation.typeText
}
private LookupElement[] complete() {
myFixture.complete(CompletionType.BASIC, 2)
}
public void testQualifiedMethodName() throws Exception {
myFixture.addClass("""
package foo;
@@ -157,7 +162,7 @@ class Bar {{ abcmethod1()<caret> }}"""
""")
myFixture.configureByText("a.java", "class Bar {{ abcm<caret> }}")
myFixture.complete(CompletionType.CLASS_NAME)
complete()
assertOrderedEquals myFixture.lookupElementStrings, "abcmethod", "abcmethod1"
}
@@ -171,7 +176,7 @@ class A {
}
}
""")
def element = myFixture.complete(CompletionType.CLASS_NAME)[0]
def element = complete()[0]
def presentation = new LookupElementPresentation()
element.renderElement(presentation)
assert 'foo' == presentation.itemText
@@ -190,7 +195,7 @@ class A {
private void doTest(String input, boolean importStatic, String output) {
myFixture.configureByText("a.java", input)
def item = assertOneElement(myFixture.complete(CompletionType.CLASS_NAME))
def item = assertOneElement(complete())
if (importStatic) {
item.'as'(StaticallyImportable).shouldBeImported = true
}
@@ -5,8 +5,6 @@ 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.psi.statistics.StatisticsManager;
import com.intellij.psi.statistics.impl.StatisticsManagerImpl;
import com.intellij.testFramework.LightProjectDescriptor;
import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase;
import org.jetbrains.annotations.NotNull;
@@ -17,12 +15,6 @@ import org.jetbrains.annotations.NotNull;
public abstract class LightFixtureCompletionTestCase extends LightCodeInsightFixtureTestCase {
protected LookupElement[] myItems;
@Override
protected void setUp() throws Exception {
super.setUp();
((StatisticsManagerImpl)StatisticsManager.getInstance()).clearStatistics();
}
@NotNull
@Override
protected LightProjectDescriptor getProjectDescriptor() {
@@ -287,13 +287,13 @@ public class NormalCompletionOrderingTest extends CompletionSortingTestCase {
public void testPreselectMostRelevantInTheMiddleAlpha() {
UISettings.getInstance().SORT_LOOKUP_ELEMENTS_LEXICOGRAPHICALLY = true;
myFixture.addClass("package foo; public class Elaaaaaaaaaaaaaaaaaaaa {}");
myFixture.addClass("package foo; public class Elxaaaaaaaaaaaaaaaaaaaa {}");
invokeCompletion(getTestName(false) + ".java");
myFixture.completeBasic();
LookupImpl lookup = getLookup();
assertPreferredItems(lookup.getList().getSelectedIndex());
assertEquals("Elaaaaaaaaaaaaaaaaaaaa", lookup.getItems().get(0).getLookupString());
assertEquals("ELEMENT_A", lookup.getCurrentItem().getLookupString());
assertEquals("Elxaaaaaaaaaaaaaaaaaaaa", lookup.getItems().get(0).getLookupString());
assertEquals("ELXEMENT_A", lookup.getCurrentItem().getLookupString());
}
public void testReallyAlphaSorting() {
@@ -1110,7 +1110,7 @@ public class ListUtils {
public static void bar() {}
}
""")
doTest()
doTest('\n')
}
public void testSuggestMembersOfStaticallyImportedClassesUnqualifiedOnly() throws Exception {
@@ -1338,7 +1338,7 @@ public class ListUtils {
public void testListArrayListCast() { doTest('\n') }
public void testInterfaceImplementationNoCast() { doTest() }
public void testStaticallyImportedMethodsBeforeExpression() { doTest() }
public void testStaticallyImportedMethodsBeforeExpression() { doTest('\n') }
public void testInnerChainedReturnType() { doTest() }
public void testOverwriteGenericsAfterNew() { doTest('\n') }
@@ -0,0 +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";
}
}
@@ -0,0 +1,29 @@
/*
* 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 ConvertColorRepresentationTest extends LightQuickFix15TestCase {
public void test() throws Exception { doAllTests(); }
@Override
protected String getBasePath() {
return "/codeInsight/daemonCodeAnalyzer/quickFix/convertColorRepresentation";
}
}
@@ -65,5 +65,6 @@ public class DataFlowInspectionFixtureTest extends JavaCodeInsightFixtureTestCas
public void testStringTernaryAlwaysTrue() throws Throwable { doTest(); }
public void testBoxing128() throws Throwable { doTest(); }
public void testFinalFieldsInitializedByAnnotatedParameters() throws Throwable { doTest(); }
}
@@ -19,8 +19,6 @@ 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.psi.statistics.StatisticsManager;
import com.intellij.psi.statistics.impl.StatisticsManagerImpl;
import com.intellij.testFramework.PlatformTestCase;
import com.intellij.util.Function;
import com.intellij.util.containers.ContainerUtil;
@@ -38,12 +36,6 @@ public abstract class CompletionTestCase extends DaemonAnalyzerTestCase {
protected LookupElement[] myItems;
private CompletionType myType = CompletionType.BASIC;
@Override
protected void setUp() throws Exception {
super.setUp();
((StatisticsManagerImpl)StatisticsManager.getInstance()).clearStatistics();
}
@Override
protected void tearDown() throws Exception {
try {
@@ -19,8 +19,6 @@ 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.psi.statistics.impl.StatisticsManagerImpl;
import com.intellij.psi.statistics.StatisticsManager;
import com.intellij.util.containers.HashSet;
import org.jetbrains.annotations.NonNls;
@@ -37,12 +35,6 @@ public abstract class LightCompletionTestCase extends LightCodeInsightTestCase {
protected LookupElement[] myItems;
private CompletionType myType = CompletionType.BASIC;
@Override
protected void setUp() throws Exception {
super.setUp();
((StatisticsManagerImpl)StatisticsManager.getInstance()).clearStatistics();
}
@Override
protected void tearDown() throws Exception {
LookupManager.getInstance(getProject()).hideActiveLookup();
@@ -25,7 +25,7 @@ import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.vfs.VirtualFileFilter;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiFile;
import com.intellij.psi.impl.source.tree.injected.InjectedLanguageFacadeImpl;
import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil;
import com.intellij.testFramework.ExpectedHighlightingData;
import com.intellij.testFramework.FileTreeAccessFilter;
import com.intellij.testFramework.HighlightTestInfo;
@@ -144,7 +144,7 @@ public abstract class LightDaemonAnalyzerTestCase extends LightCodeInsightTestCa
PsiFile file = getFile();
if (editor instanceof EditorWindow) {
editor = ((EditorWindow)editor).getDelegate();
file = InjectedLanguageFacadeImpl.getTopLevelFile(file);
file = InjectedLanguageUtil.getTopLevelFile(file);
}
return CodeInsightTestFixtureImpl.instantiateAndRun(file, editor, toIgnore, false);
@@ -29,7 +29,7 @@ import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.CharsetToolkit;
import com.intellij.psi.PsiFile;
import com.intellij.psi.impl.source.tree.injected.InjectedLanguageFacadeImpl;
import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil;
import com.intellij.rt.execution.junit.FileComparisonFailure;
import com.intellij.testFramework.fixtures.impl.CodeInsightTestFixtureImpl;
import com.intellij.util.IncorrectOperationException;
@@ -107,7 +107,7 @@ public abstract class LightQuickFixTestCase extends LightDaemonAnalyzerTestCase
}
public static Pair<String, Boolean> parseActionHint(final PsiFile file, String contents, @NonNls @RegExp String actionPattern) {
PsiFile hostFile = InjectedLanguageFacadeImpl.getTopLevelFile(file);
PsiFile hostFile = InjectedLanguageUtil.getTopLevelFile(file);
final Commenter commenter = LanguageCommenters.INSTANCE.forLanguage(hostFile.getLanguage());
String comment = commenter.getLineCommentPrefix();
@@ -164,7 +164,12 @@ final class BuildSession implements Runnable, CanceledStatus {
boolean forceCleanCaches = false;
ProjectDescriptor pd;
final Project project = loadProject(projectPath);
final File dataStorageRoot = Utils.getDataStorageRoot(project);
if (!dataStorageRoot.exists()) {
// invoked the very first time for this project. Force full rebuild
buildType = BuildType.PROJECT_REBUILD;
}
final boolean inMemoryMappingsDelta = System.getProperty(GlobalOptions.USE_MEMORY_TEMP_CACHE_OPTION) != null;
ProjectTimestamps projectTimestamps = null;
@@ -161,7 +161,7 @@ public class IncProjectBuilder {
}
ExternalJavacDescriptor.KEY.set(context, null);
}
cleanupJavacNameTable();
//cleanupJavacNameTable();
}
private static boolean ourClenupFailed = false;
@@ -34,11 +34,6 @@ public class BuildFSState extends FSState {
myAlwaysScanFS = alwaysScanFS;
}
@Override
public boolean isInitialized(String moduleName) {
return myAlwaysScanFS || super.isInitialized(moduleName);
}
@Override
public boolean markInitialScanPerformed(String moduleName, boolean forTests) {
return myAlwaysScanFS || super.markInitialScanPerformed(moduleName, forTests);
@@ -133,10 +133,6 @@ public class FSState {
}
}
public boolean isInitialized(String moduleName) {
return myInitialTestsScanPerformed.contains(moduleName) && myInitialProductionScanPerformed.contains(moduleName);
}
public boolean markInitialScanPerformed(final String moduleName, boolean forTests) {
return (forTests ? myInitialTestsScanPerformed : myInitialProductionScanPerformed).add(moduleName);
}
@@ -38,7 +38,8 @@ import org.jetbrains.jps.incremental.storage.BuildDataManager;
import org.jetbrains.jps.incremental.storage.SourceToFormMapping;
import org.jetbrains.jps.javac.*;
import javax.tools.*;
import javax.tools.Diagnostic;
import javax.tools.JavaFileObject;
import java.io.*;
import java.net.MalformedURLException;
import java.net.ServerSocket;
@@ -809,13 +810,17 @@ public class JavaBuilder extends ModuleLevelBuilder {
final Map<File, Set<File>> map = new LinkedHashMap<File, Set<File>>();
final boolean compilingTests = context.isCompilingTests();
for (Module module : chunk.getModules()) {
final String output = compilingTests ? module.getTestOutputPath() : module.getOutputPath();
if (output == null) {
continue;
}
final Set<File> roots = new LinkedHashSet<File>();
for (RootDescriptor descriptor : context.getModuleRoots(module)) {
if (descriptor.isTestRoot == compilingTests) {
roots.add(descriptor.root);
}
}
map.put(new File(compilingTests ? module.getTestOutputPath() : module.getOutputPath()), roots);
map.put(new File(output), roots);
}
return map;
}
@@ -71,6 +71,9 @@ public class ResourcesBuilder extends ModuleLevelBuilder {
String sourceRoot,
final SourceToOutputMapping outputToSourceMapping) throws IOException {
final String outputRoot = context.isCompilingTests() ? module.getTestOutputPath() : module.getOutputPath();
if (outputRoot == null) {
return;
}
final String relativePath = FileUtil.getRelativePath(sourceRoot, FileUtil.toSystemIndependentName(file.getPath()), '/');
final String prefix = module.getSourceRootPrefixes().get(sourceRoot);
@@ -18,7 +18,7 @@ import java.util.Map;
* Date: 10/7/11
*/
public class BuildDataManager implements StorageOwner {
private static final int VERSION = 5;
private static final int VERSION = 6;
private static final Logger LOG = Logger.getInstance("#org.jetbrains.jps.incremental.storage.BuildDataManager");
private static final String SRC_TO_OUTPUTS_STORAGE = "src-out";
private static final String SRC_TO_FORM_STORAGE = "src-form";
@@ -6,7 +6,8 @@ import com.sun.tools.javac.util.*;
import com.sun.tools.javac.util.List;
import javax.lang.model.SourceVersion;
import javax.tools.*;
import javax.tools.FileObject;
import javax.tools.JavaFileObject;
import java.io.*;
import java.lang.ref.SoftReference;
import java.lang.reflect.Field;
@@ -152,8 +153,12 @@ class OptimizedFileManager extends DefaultFileManager {
private void collectFromDirectory(File directory, Set<JavaFileObject.Kind> fileKinds, boolean recurse, ListBuffer<JavaFileObject> result) {
final File[] children = directory.listFiles();
if (children != null) {
final boolean acceptUnknownFiles = fileKinds.contains(JavaFileObject.Kind.OTHER);
for (File child : children) {
if (isValidFile(child.getName(), fileKinds) && isFile(child)) {
if (isValidFile(child.getName(), fileKinds)) {
if (acceptUnknownFiles && !isFile(child)) {
continue;
}
final JavaFileObject fe = new InputFileObject(child);
result.append(fe);
}
@@ -8,7 +8,7 @@ import com.sun.tools.javac.util.List;
import com.sun.tools.javac.util.ListBuffer;
import javax.lang.model.SourceVersion;
import javax.tools.*;
import javax.tools.JavaFileObject;
import java.io.*;
import java.lang.ref.Reference;
import java.lang.ref.SoftReference;
@@ -129,11 +129,14 @@ class OptimizedFileManager17 extends com.sun.tools.javac.file.JavacFileManager {
if (sortFiles != null) {
Arrays.sort(files, sortFiles);
}
final boolean acceptUnknownFiles = fileKinds.contains(JavaFileObject.Kind.OTHER);
for (File f: files) {
String fileName = f.getName();
if (isValidFile(fileName, fileKinds) && isFile(f)) {
JavaFileObject fe = new InputFileObject(this, f);
final String fileName = f.getName();
if (isValidFile(fileName, fileKinds)) {
if (acceptUnknownFiles && !isFile(f)) {
continue;
}
final JavaFileObject fe = new InputFileObject(this, f);
resultList.append(fe);
}
}
@@ -271,7 +271,7 @@ public abstract class IncrementalTestCase extends TestCase {
rebuildDump.close();
// assertEquals(rebuildDump.toString(), makeDump.toString());
assertEquals(rebuildDump.toString(), makeDump.toString());
}
}
finally {
Binary file not shown.
@@ -74,10 +74,6 @@ abstract class IntIntMultiMaplet implements Streamable {
for (final int a : keys) {
final TIntHashSet b = get(a);
if (b.size() == 0) {
continue;
}
stream.print(" Key: ");
stream.println(context.getValue(a));
stream.println(" Values:");
@@ -78,7 +78,7 @@ class IntIntPersistentMultiMaplet extends IntIntMultiMaplet {
public void replace(int key, TIntHashSet value) {
try {
myCache.remove(key);
if (value == null) {
if (value == null || value.isEmpty()) {
myMap.remove(key);
}
else {
@@ -56,7 +56,7 @@ class IntIntTransientMultiMaplet extends IntIntMultiMaplet {
@Override
public void replace(int key, TIntHashSet value) {
if (value == null) {
if (value == null || value.isEmpty()) {
myMap.remove(key);
}
else {
@@ -74,10 +74,6 @@ abstract class IntObjectMultiMaplet<V extends Streamable> implements Streamable
for (final int a : keys) {
final Collection<V> b = get(a);
if (b.size() == 0) {
continue;
}
stream.print(" Key: ");
stream.println(context.getValue(a));
stream.println(" Values:");
@@ -83,7 +83,7 @@ class IntObjectPersistentMultiMaplet<V extends Streamable> extends IntObjectMult
public void replace(int key, Collection<V> value) {
try {
myCache.remove(key);
if (value == null) {
if (value == null || value.isEmpty()) {
myMap.remove(key);
}
else {
@@ -55,7 +55,7 @@ class IntObjectTransientMultiMaplet<V extends Streamable> extends IntObjectMulti
@Override
public void replace(int key, Collection<V> value) {
if (value == null) {
if (value == null || value.isEmpty()) {
myMap.remove(key);
}
else {
@@ -1027,7 +1027,6 @@ public class Mappings {
}
private void processDisappearedClasses() {
myDelta.runPostPasses();
myDelta.compensateRemovedContent(myFilesToCompile);
final Collection<String> removed = myDelta.getRemovedFiles();
@@ -1920,11 +1919,18 @@ public class Mappings {
return new Differential(delta, removed, filesToCompile, compiledFiles, affectedFiles, filter, constantSearch).differentiate();
}
private void cleanupBackDependency(final int className, @Nullable Collection<UsageRepr.Cluster> clusters, IntIntMultiMaplet buffer) {
private void cleanupBackDependency(final int className, @Nullable Collection<UsageRepr.Cluster> clusters, @Nullable Collection<UsageRepr.Usage> annotationUsages, final IntIntMultiMaplet buffer) {
if (clusters == null) {
final int sourceFile = myClassToSourceFile.get(className);
if (sourceFile > 0) {
clusters = mySourceFileToUsages.get(sourceFile);
annotationUsages = mySourceFileToAnnotationUsages.get(sourceFile);
}
}
if (annotationUsages != null) {
for (final UsageRepr.Usage usage : annotationUsages) {
buffer.put(usage.getOwner(), className);
}
}
@@ -1943,6 +1949,7 @@ public class Mappings {
private void cleanupRemovedClass(final Mappings delta,
@NotNull final ClassRepr cr,
final Collection<UsageRepr.Cluster> clusters,
final Collection<UsageRepr.Usage> annotationUsages,
final IntIntMultiMaplet dependenciesTrashBin) {
final int className = cr.name;
@@ -1950,7 +1957,7 @@ public class Mappings {
delta.registerRemovedSuperClass(className, superSomething);
}
cleanupBackDependency(className, clusters, dependenciesTrashBin);
cleanupBackDependency(className, clusters, annotationUsages, dependenciesTrashBin);
myClassToClassDependency.remove(className);
myClassToSubclasses.remove(className);
@@ -1972,11 +1979,10 @@ public class Mappings {
for (final String file : removed) {
final int fileName = myContext.get(file);
final Set<ClassRepr> fileClasses = (Set<ClassRepr>)mySourceFileToClasses.get(fileName);
final Collection<UsageRepr.Cluster> fileUsages = mySourceFileToUsages.get(fileName);
if (fileClasses != null) {
for (final ClassRepr aClass : fileClasses) {
cleanupRemovedClass(delta, aClass, fileUsages, dependenciesTrashBin);
cleanupRemovedClass(delta, aClass, mySourceFileToUsages.get(fileName), mySourceFileToAnnotationUsages.get(fileName), dependenciesTrashBin);
}
}
@@ -1986,19 +1992,21 @@ public class Mappings {
}
}
final TIntHashSet compiledClasses = new TIntHashSet();
final TIntHashSet compiledFiles = new TIntHashSet();
delta.myClassToSourceFile.forEachEntry(new TIntIntProcedure() {
@Override
public boolean execute(final int key, final int file) {
compiledClasses.add(key);
compiledFiles.add(file);
return true;
}
});
if (!delta.isRebuild()) {
final TIntHashSet compiledClasses = new TIntHashSet();
delta.myClassToSourceFile.forEachEntry(new TIntIntProcedure() {
@Override
public boolean execute(final int a, final int b) {
compiledClasses.add(a);
return true;
}
});
for (ClassRepr repr : delta.getDeletedClasses()) {
cleanupRemovedClass(delta, repr, null, dependenciesTrashBin);
cleanupRemovedClass(delta, repr, null, null, dependenciesTrashBin);
}
delta.getRemovedSuperClasses().forEachEntry(new TIntObjectProcedure<TIntHashSet>() {
@@ -2047,11 +2055,9 @@ public class Mappings {
}
});
delta.getChangedClasses().forEach(new TIntProcedure() {
compiledClasses.forEach(new TIntProcedure() {
@Override
public boolean execute(final int className) {
final TIntHashSet s = delta.myClassToSubclasses.get(className);
final int sourceFile = delta.myClassToSourceFile.get(className);
if (sourceFile > 0) {
myClassToSourceFile.put(className, sourceFile);
@@ -2060,13 +2066,13 @@ public class Mappings {
myClassToSourceFile.remove(className);
}
cleanupBackDependency(className, null, dependenciesTrashBin);
cleanupBackDependency(className, null, null, dependenciesTrashBin);
return true;
}
});
delta.getChangedFiles().forEach(new TIntProcedure() {
compiledFiles.forEach(new TIntProcedure() {
@Override
public boolean execute(final int fileName) {
final Collection<ClassRepr> classes = delta.mySourceFileToClasses.get(fileName);
@@ -2094,6 +2100,7 @@ public class Mappings {
else {
mySourceFileToAnnotationUsages.remove(fileName);
}
return true;
}
});
@@ -2309,7 +2316,7 @@ public class Mappings {
return changed.get();
}
private static void addAllKeys(final TIntHashSet whereToAdd, IntIntMultiMaplet maplet) {
private static void addAllKeys(final TIntHashSet whereToAdd, final IntIntMultiMaplet maplet) {
maplet.forEachEntry(new TIntObjectProcedure<TIntHashSet>() {
@Override
public boolean execute(int key, TIntHashSet b) {
@@ -2319,6 +2326,16 @@ public class Mappings {
});
}
private static void addAllKeys(final TIntHashSet whereToAdd, final IntIntMaplet maplet) {
maplet.forEachEntry(new TIntIntProcedure() {
@Override
public boolean execute(int key, int b) {
whereToAdd.add(key);
return true;
}
});
}
private void registerRemovedSuperClass(final int aClass, final int superClass) {
assert (myRemovedSuperClasses != null);
myRemovedSuperClasses.put(superClass, aClass);
@@ -2389,18 +2406,18 @@ public class Mappings {
myClassToSubclasses,
myClassToClassDependency,
mySourceFileToClasses,
myClassToSourceFile,
mySourceFileToAnnotationUsages,
mySourceFileToUsages,
myClassToSourceFile
mySourceFileToUsages
};
final String[] info = {
"ClassToSubclasses",
"ClassToClassDependency",
"SourceFileToClasses",
"ClassToSourceFile",
"SourceFileToAnnotationUsages",
"SourceFileToUsages",
"ClassToSourceFile"
"SourceFileToUsages"
};
for (int i = 0; i < data.length; i++) {
@@ -2,14 +2,12 @@ package org.jetbrains.ether.dependencyView;
import com.intellij.util.io.DataExternalizer;
import gnu.trove.TIntHashSet;
import gnu.trove.TIntProcedure;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.asm4.Type;
import org.jetbrains.ether.RW;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.io.PrintStream;
import java.io.*;
import java.util.*;
/**
@@ -37,7 +35,8 @@ class UsageRepr {
}
public static class Cluster implements RW.Savable, Streamable {
private final Map<Usage, TIntHashSet> myUsageToDependenciesMap = new HashMap<Usage, TIntHashSet>(DEFAULT_SET_CAPACITY, DEFAULT_SET_LOAD_FACTOR);
private final Map<Usage, TIntHashSet> myUsageToDependenciesMap =
new HashMap<Usage, TIntHashSet>(DEFAULT_SET_CAPACITY, DEFAULT_SET_LOAD_FACTOR);
public Cluster() {
}
@@ -129,24 +128,72 @@ class UsageRepr {
}
@Override
public void toStream(DependencyContext context, PrintStream stream) {
//To change body of implemented methods use File | Settings | File Templates.
public void toStream(final DependencyContext context, final PrintStream stream) {
stream.println(" Cluster:");
final List<String> mapped = new LinkedList<String> ();
for (final Map.Entry<Usage, TIntHashSet> e : myUsageToDependenciesMap.entrySet()) {
final ByteArrayOutputStream bas = new ByteArrayOutputStream();
final PrintStream s = new PrintStream(bas);
s.println(" Usage : ");
s.print (" ");
e.getKey().toStream(context, s);
s.println(" Residence:");
final List<String> r = new LinkedList<String>();
e.getValue().forEach(new TIntProcedure() {
@Override
public boolean execute(final int value) {
r.add(" " + context.getValue(value));
return true;
}
});
Collections.sort(r);
for (final String sr : r) {
s.println(sr);
}
try {
bas.close();
}
catch (Exception x) {
throw new RuntimeException(x);
}
mapped.add(bas.toString());
}
Collections.sort(mapped);
for (final String s : mapped) {
stream.print(s);
}
}
}
public static abstract class Usage implements RW.Savable, Streamable {
public abstract int getOwner();
@Override
public void toStream(DependencyContext context, PrintStream stream) {
//To change body of implemented methods use File | Settings | File Templates.
}
}
public static abstract class FMUsage extends Usage {
public final int name;
public final int owner;
abstract void kindToStream (PrintStream stream);
@Override
public void toStream(final DependencyContext context, final PrintStream stream) {
kindToStream(stream);
stream.println(" Name : " + context.getValue(name));
stream.println(" Owner: " + context.getValue(owner));
}
@Override
public int getOwner() {
return owner;
@@ -215,6 +262,16 @@ class UsageRepr {
}
}
protected void kindToStream(final PrintStream stream) {
stream.println("FieldUsage:");
}
@Override
public void toStream(final DependencyContext context, final PrintStream stream) {
super.toStream(context, stream);
stream.println(" Type: " + type.getDescr(context));
}
@Override
public void save(final DataOutput out) {
save(FIELD_USAGE, out);
@@ -246,6 +303,11 @@ class UsageRepr {
super(context, in);
}
@Override
protected void kindToStream(final PrintStream stream) {
stream.println("FieldAssignUsage:");
}
@Override
public void save(final DataOutput out) {
save(FIELD_ASSIGN_USAGE, out);
@@ -319,6 +381,25 @@ class UsageRepr {
public int hashCode() {
return ((31 * Arrays.hashCode(argumentTypes) + (returnType.hashCode())) * 31 + (name)) * 31 + (owner);
}
@Override
void kindToStream(final PrintStream stream) {
stream.println("MethodUsage:");
}
@Override
public void toStream(DependencyContext context, PrintStream stream) {
super.toStream(context, stream);
stream.println(" Arguments:");
for (final TypeRepr.AbstractType at : argumentTypes) {
stream.println(" " + at.getDescr(context));
}
stream.println(" Return type:");
stream.println(" " + returnType.getDescr(context));
}
}
public static class MetaMethodUsage extends FMUsage {
@@ -369,6 +450,17 @@ class UsageRepr {
result = 31 * result + myArity;
return result;
}
@Override
void kindToStream(final PrintStream stream) {
stream.println("MetaMethodUsage:");
}
@Override
public void toStream(DependencyContext context, PrintStream stream) {
super.toStream(context, stream);
stream.println(" Arity: " + Integer.toString(myArity));
}
}
public static class ClassUsage extends Usage {
@@ -417,6 +509,11 @@ class UsageRepr {
public int hashCode() {
return myClassName;
}
@Override
public void toStream(final DependencyContext context, final PrintStream stream) {
stream.println("ClassUsage: " + context.getValue(myClassName));
}
}
public static class ClassExtendsUsage extends Usage {
@@ -467,6 +564,11 @@ class UsageRepr {
return true;
}
@Override
public void toStream(final DependencyContext context, final PrintStream stream) {
stream.println("ClassExtendsUsage: " + context.getValue(className));
}
}
public static class ClassNewUsage extends ClassExtendsUsage {
@@ -493,6 +595,11 @@ class UsageRepr {
public int hashCode() {
return className + 2;
}
@Override
public void toStream(final DependencyContext context, final PrintStream stream) {
stream.println("ClassNewUsage: " + context.getValue(className));
}
}
public static class AnnotationUsage extends Usage {
@@ -610,6 +717,48 @@ class UsageRepr {
result = 31 * result + (usedTargets != null ? usedTargets.hashCode() : 0);
return result;
}
@Override
public void toStream(final DependencyContext context, final PrintStream stream) {
stream.println(" AnnotationUsage:");
stream.println(" Type : " + type.getDescr(context));
final List<String> arguments = new LinkedList<String>();
if (usedArguments != null) {
usedArguments.forEach(new TIntProcedure() {
@Override
public boolean execute(final int value) {
arguments.add(context.getValue(value));
return true;
}
});
}
Collections.sort(arguments);
final List<String> targets = new LinkedList<String>();
if (usedTargets != null) {
for (final ElemType e : usedTargets) {
targets.add(e.toString());
}
}
Collections.sort(targets);
stream.println(" Arguments:");
for (final String s : arguments) {
stream.println(" " + s);
}
stream.println(" Targets :");
for (final String s : targets) {
stream.println(" " + s);
}
}
}
public static Usage createFieldUsage(final DependencyContext context, final int name, final int owner, final int descr) {
@@ -641,7 +790,10 @@ class UsageRepr {
return context.getUsage(new ClassNewUsage(name));
}
public static Usage createAnnotationUsage(final DependencyContext context, final TypeRepr.ClassType type, final TIntHashSet usedArguments, final Set<ElemType> targets) {
public static Usage createAnnotationUsage(final DependencyContext context,
final TypeRepr.ClassType type,
final TIntHashSet usedArguments,
final Set<ElemType> targets) {
return context.getUsage(new AnnotationUsage(type, usedArguments, targets));
}
@@ -104,7 +104,9 @@ public class ProjectPaths {
private static void addFiles(Set<File> files, final Collection<String> paths) {
for (String root : paths) {
files.add(new File(root));
if (root != null) {
files.add(new File(root));
}
}
}
+1
View File
@@ -37,6 +37,7 @@ picocontainer.jar
resolver.jar
sanselan-0.98-snapshot.jar
serviceMessages.jar
snappy-java-1.0.4.1.jar
trove4j.jar
velocity.jar
winp-1.16-patched.jar
Binary file not shown.
Binary file not shown.
@@ -17,15 +17,20 @@ package com.intellij.psi.stubs;
import com.intellij.openapi.diagnostic.LogUtil;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.io.BufferExposingByteArrayOutputStream;
import com.intellij.util.io.AbstractStringEnumerator;
import com.intellij.util.io.DataInputOutputUtil;
import com.intellij.util.io.IOUtil;
import gnu.trove.TIntObjectHashMap;
import gnu.trove.TObjectIntHashMap;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
/**
@@ -73,8 +78,18 @@ public class StubSerializationHelper {
}
public void serialize(StubElement rootStub, OutputStream stream) throws IOException {
StubOutputStream stubOutputStream = new StubOutputStream(stream, myNameStorage);
BufferExposingByteArrayOutputStream out = new BufferExposingByteArrayOutputStream();
FileLocalStringEnumerator storage = new FileLocalStringEnumerator();
StubOutputStream stubOutputStream = new StubOutputStream(out, storage);
doSerialize(rootStub, stubOutputStream);
DataOutputStream resultStream = new DataOutputStream(stream);
DataInputOutputUtil.writeINT(resultStream, storage.myStrings.size());
byte[] buffer = IOUtil.allocReadWriteUTFBuffer();
for(String s:storage.myStrings) {
IOUtil.writeUTFFast(buffer, resultStream, s);
}
resultStream.write(out.getInternalBuffer(), 0, out.size());
}
private int getClassId(final StubSerializer serializer) {
@@ -84,7 +99,18 @@ public class StubSerializationHelper {
}
public StubElement deserialize(InputStream stream) throws IOException {
StubInputStream inputStream = new StubInputStream(stream, myNameStorage);
FileLocalStringEnumerator storage = new FileLocalStringEnumerator();
StubInputStream inputStream = new StubInputStream(stream, storage);
final int size = DataInputOutputUtil.readINT(inputStream);
byte[] buffer = IOUtil.allocReadWriteUTFBuffer();
int i = 1;
while(i <= size) {
String s = IOUtil.readUTFFast(buffer, inputStream);
storage.myStrings.add(s);
storage.myEnumerates.put(s, i);
++i;
}
return deserialize(inputStream, null);
}
@@ -106,4 +132,46 @@ public class StubSerializationHelper {
private StubSerializer getClassById(int id) {
return myIdToSerializer.get(id);
}
private static class FileLocalStringEnumerator implements AbstractStringEnumerator {
private final TObjectIntHashMap<String> myEnumerates = new TObjectIntHashMap<String>();
private final ArrayList<String> myStrings = new ArrayList<String>();
@Override
public int enumerate(@Nullable String value) throws IOException {
if (value == null) return 0;
int i = myEnumerates.get(value);
if (i == 0) {
if (myEnumerates.containsKey(value)) {
int a = 1;
}
myEnumerates.put(value, i = myStrings.size() + 1);
myStrings.add(value);
}
return i;
}
@Override
public String valueOf(int idx) throws IOException {
if (idx == 0) return null;
return myStrings.get(idx - 1);
}
@Override
public void markCorrupted() {
}
@Override
public void close() throws IOException {
}
@Override
public boolean isDirty() {
return false;
}
@Override
public void force() {
}
}
}
@@ -14,7 +14,6 @@
<feature id="codeassists.javadoc.external" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
<feature id="tag.name.completion" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
<feature id="ui.recentchanges" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
<feature id="editing.completion.smarttype.anonymous" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
<feature id="diagram.show" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
<feature id="refactoring.introduceVariable" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
<feature id="ui.tree.speedsearch" count="5" last-shown="0" last-used="1317813527648" average-frequency="2666" shown-count="0" />
@@ -57,7 +56,6 @@
<feature id="editing.completion.replace" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
<feature id="editing.select.word" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
<feature id="codeassists.comment.block" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
<feature id="editing.completion.classname" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
<feature id="editing.completion.cancelByControlArrows" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
<feature id="codeassists.highlight.implements" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
<feature id="codeassists.quickdefinition" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
@@ -65,7 +63,6 @@
<feature id="jar.diff" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
<feature id="navigation.recent.files" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
<feature id="codeassists.highlight.return" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
<feature id="editing.completion.second.classname" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
<feature id="editing.completion.smarttype.general" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
<feature id="editing.completion.camelHumps" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
<feature id="codeassists.overrideimplement" count="0" last-shown="0" last-used="0" average-frequency="0" shown-count="0" />
@@ -98,4 +98,8 @@ public final class CompletionParameters {
public CompletionParameters withPosition(PsiElement element, int offset) {
return new CompletionParameters(element, myOriginalFile, myCompletionType, offset, myInvocationCount, myLookup);
}
public boolean isExtendedCompletion() {
return myCompletionType == CompletionType.CLASS_NAME || myCompletionType == CompletionType.BASIC && myInvocationCount >= 2;
}
}
@@ -35,6 +35,7 @@ import org.jetbrains.annotations.Nullable;
public abstract class PsiElementBaseIntentionAction extends BaseIntentionAction {
@Override
public final void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException {
if (!file.getManager().isInProject(file)) return;
final PsiElement element = getElement(editor, file);
if (element != null) {
invoke(project, editor, element);
@@ -54,6 +55,7 @@ public abstract class PsiElementBaseIntentionAction extends BaseIntentionAction
@Override
public final boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
if (!file.getManager().isInProject(file)) return false;
final PsiElement element = getElement(editor, file);
return element != null && isAvailable(project, editor, element);
}
@@ -71,7 +73,6 @@ public abstract class PsiElementBaseIntentionAction extends BaseIntentionAction
@Nullable
protected static PsiElement getElement(Editor editor, @NotNull PsiFile file) {
if (!file.getManager().isInProject(file)) return null;
CaretModel caretModel = editor.getCaretModel();
int position = caretModel.getOffset();
return file.findElementAt(position);
@@ -0,0 +1,95 @@
/*
* 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.formatting;
import com.intellij.openapi.util.TextRange;
import gnu.trove.TObjectIntHashMap;
import org.jetbrains.annotations.NotNull;
/**
* Holds settings that should be used if
* {@link Spacing#createDependentLFSpacing(int, int, TextRange, boolean, int, DependentSpacingRule) dependent spacing}
* target region changes its 'contains line feeds' status.
*
* @author Denis Zhdanov
* @since 6/28/12 1:08 PM
*/
public class DependentSpacingRule {
enum Anchor {
MIN_LINE_FEEDS, MAX_LINE_FEEDS
}
enum Trigger {
HAS_LINE_FEEDS, DOES_NOT_HAVE_LINE_FEEDS
}
public static final DependentSpacingRule DEFAULT =
new DependentSpacingRule(Trigger.HAS_LINE_FEEDS).registerData(Anchor.MIN_LINE_FEEDS, 1);
private final TObjectIntHashMap<Anchor> myData = new TObjectIntHashMap<Anchor>();
@NotNull private final Trigger myTrigger;
public DependentSpacingRule(@NotNull Trigger trigger) {
myTrigger = trigger;
}
@NotNull
public Trigger getTrigger() {
return myTrigger;
}
/**
* Allows to register given data for the given anchor within the current rule.
*
* @param anchor target anchor
* @param data data to register for the given anchor
* @param <T> data's type
* @see #getData(Anchor)
*/
public DependentSpacingRule registerData(@NotNull Anchor anchor, int data) {
myData.put(anchor, data);
return this;
}
/**
* @param anchor target data anchor
* @return <code>true</code> if there is a data registered for the given anchor within the current rule;
* <code>false</code> otherwise
*/
public boolean hasData(@NotNull Anchor anchor) {
return myData.containsKey(anchor);
}
/**
* Allows to retrieve data associated with the given anchor.
*
* @param anchor target anchor
* @param <T> data's type
* @return data associated for the given anchor
* @throws IllegalArgumentException if no data is registered for the given anchor
* (use {@link #hasData(Anchor)} for the preliminary examination)
*/
public int getData(@NotNull Anchor anchor) throws IllegalArgumentException {
if (!myData.containsKey(anchor)) {
throw new IllegalArgumentException(String.format(
"No data is registered for the dependent spacing rule %s. Registered: %s", anchor, myData
));
}
return myData.get(anchor);
}
}
@@ -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.
@@ -16,6 +16,7 @@
package com.intellij.formatting;
import com.intellij.openapi.util.TextRange;
import org.jetbrains.annotations.NotNull;
/**
* The spacing setting for a formatting model block. Indicates the number of spaces and/or
@@ -100,19 +101,50 @@ public abstract class Spacing {
* to which the spacing setting instance is related, or <code>Integer.MAX_VALUE</code>
* if the number of spaces is not limited. Spaces are deleted if there are
* more than this amount of spaces in the document.
* @param dependance The text range checked for the presense of line breaks.
* @param dependency The text range checked for the presence of line breaks.
* @param keepLineBreaks Whether the existing line breaks between the blocks should be preserved.
* @param keepBlankLines Whether the existing blank lines between the blocks should be preserved.
* @return the spacing setting instance.
*/
public static Spacing createDependentLFSpacing(int minSpaces,
int maxSpaces,
TextRange dependance,
TextRange dependency,
boolean keepLineBreaks,
int keepBlankLines) {
return myFactory.createDependentLFSpacing(minSpaces, maxSpaces, dependance, keepLineBreaks, keepBlankLines);
int keepBlankLines)
{
return createDependentLFSpacing(minSpaces, maxSpaces, dependency, keepLineBreaks, keepBlankLines, DependentSpacingRule.DEFAULT);
}
/**
* Creates a spacing setting instance which uses settings from the given dependent spacing rule if the specified text range changes
* its 'has line feed' status during formatting (new line feed is added and the range hasn't contained them before
* or it contained line feed(s) and it was removed during formatting).
* <p/>
* Used for formatting rules like the "next line if wrapped" brace placement.
*
* @param minSpaces The minimum number of spaces that should be present between the blocks
* to which the spacing setting instance is related. Spaces are inserted
* if there are less than this amount of spaces in the document.
* @param maxSpaces The maximum number of spaces that should be present between the blocks
* to which the spacing setting instance is related, or <code>Integer.MAX_VALUE</code>
* if the number of spaces is not limited. Spaces are deleted if there are
* more than this amount of spaces in the document.
* @param dependencyRange The text range checked for the presence of line breaks.
* @param keepLineBreaks Whether the existing line breaks between the blocks should be preserved.
* @param keepBlankLines Whether the existing blank lines between the blocks should be preserved.
* @param rule settings to use if dependent region changes its 'contains line feed' status during formatting
* @return the spacing setting instance for the given parameters
*/
public static Spacing createDependentLFSpacing(int minSpaces,
int maxSpaces,
@NotNull TextRange dependencyRange,
boolean keepLineBreaks,
int keepBlankLines,
@NotNull DependentSpacingRule rule)
{
return myFactory.createDependentLFSpacing(minSpaces, maxSpaces, dependencyRange, keepLineBreaks, keepBlankLines, rule);
}
/**
* Creates a spacing setting instance which preserves the presence of spaces between the blocks but,
* if spaces are present, may insert or delete the spaces. Used, for example, for HTML formatting
@@ -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.
@@ -16,34 +16,43 @@
package com.intellij.formatting;
import com.intellij.openapi.util.TextRange;
import org.jetbrains.annotations.NotNull;
/**
* Internal interface for creating spacing instances.
*/
interface SpacingFactory {
public Spacing createSpacing(int minSpaces,
@NotNull
Spacing createSpacing(int minSpaces,
int maxSpaces,
int minLineFeeds,
boolean keepLineBreaks,
int keepBlankLines);
public Spacing getReadOnlySpacing();
@NotNull
Spacing getReadOnlySpacing();
@NotNull
Spacing createDependentLFSpacing(int minSpaces,
int maxSpaces,
@NotNull TextRange dependencyRange,
boolean keepLineBreaks,
int keepBlankLines,
@NotNull DependentSpacingRule rule);
public Spacing createDependentLFSpacing(int minSpaces,
int maxSpaces,
TextRange dependance,
boolean keepLineBreaks,
int keepBlankLines);
@NotNull
Spacing createSafeSpacing(boolean keepLineBreaks,
int keepBlankLines);
public Spacing createSafeSpacing(boolean keepLineBreaks,
int keepBlankLines);
public Spacing createKeepingFirstColumnSpacing(final int minSpaces,
final int maxSpaces,
final boolean keepLineBreaks,
final int keepBlankLines);
@NotNull
Spacing createKeepingFirstColumnSpacing(final int minSpaces,
final int maxSpaces,
final boolean keepLineBreaks,
final int keepBlankLines);
@NotNull
Spacing createSpacing(final int minSpaces, final int maxSpaces, final int minLineFeeds, final boolean keepLineBreaks,
final int keepBlankLines, final int prefLineFeeds);
}
@@ -6,7 +6,6 @@ import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiComment;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.util.containers.Stack;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -132,7 +131,7 @@ public abstract class CustomFoldingBuilder extends FoldingBuilderEx implements D
* @param node The node which may contain custom region start.
* @return True if the node marks a custom region start.
*/
protected final boolean isCustomRegionStart(ASTNode node) {
public final boolean isCustomRegionStart(ASTNode node) {
if (isCustomFoldingCandidate(node)) {
String nodeText = node.getText();
CustomFoldingProvider defaultProvider = getDefaultProvider(nodeText);
+1
View File
@@ -23,6 +23,7 @@
<orderEntry type="library" name="http-client-3.1" level="project" />
<orderEntry type="module" module-name="indexing-api" />
<orderEntry type="module" module-name="indexing-impl" exported="" />
<orderEntry type="library" name="Snappy-Java" level="project" />
<orderEntry type="module" module-name="projectModel-impl" exported="" />
</component>
</module>
@@ -40,7 +40,7 @@ import com.intellij.openapi.util.Condition;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.impl.source.tree.injected.InjectedLanguageFacadeImpl;
import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil;
import com.intellij.util.Alarm;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.Nullable;
@@ -157,7 +157,7 @@ public class AutoPopupController implements Disposable {
if (file == null) return;
if (!documentManager.isUncommited(editor.getDocument())) {
file = documentManager.getPsiFile(InjectedLanguageFacadeImpl.getEditorForInjectedLanguageNoCommit(editor, file).getDocument());
file = documentManager.getPsiFile(InjectedLanguageUtil.getEditorForInjectedLanguageNoCommit(editor, file).getDocument());
if (file == null) return;
}
@@ -26,7 +26,7 @@ import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiFile;
import com.intellij.psi.impl.source.tree.injected.InjectedLanguageFacadeImpl;
import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -59,7 +59,7 @@ public abstract class BaseCodeInsightAction extends CodeInsightAction {
PsiFile psiFile = documentManager.getCachedPsiFile(editor.getDocument());
if (psiFile != null) {
if (commit) documentManager.commitAllDocuments();
injectedEditor = InjectedLanguageFacadeImpl.getEditorForInjectedLanguageNoCommit(editor, psiFile);
injectedEditor = InjectedLanguageUtil.getEditorForInjectedLanguageNoCommit(editor, psiFile);
}
}
return injectedEditor;
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2011 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.
@@ -144,12 +144,14 @@ public class ReformatCodeAction extends AnAction implements DumbAware {
boolean optimizeImports = ReformatFilesDialog.isOptmizeImportsOptionOn();
boolean processWholeFile = false;
boolean processChangedTextOnly = false;
if (EditorSettingsExternalizable.getInstance().getOptions().SHOW_REFORMAT_DIALOG || (file == null && dir != null)) {
final boolean showDialog = EditorSettingsExternalizable.getInstance().getOptions().SHOW_REFORMAT_DIALOG;
if (showDialog || (file == null && dir != null)) {
final LayoutCodeDialog dialog = new LayoutCodeDialog(project, CodeInsightBundle.message("process.reformat.code"), file, dir,
hasSelection ? Boolean.TRUE : Boolean.FALSE, HELP_ID);
dialog.show();
if (!dialog.isOK()) return;
EditorSettingsExternalizable.getInstance().getOptions().SHOW_REFORMAT_DIALOG = !dialog.isDoNotAskMe();
final boolean showDialogAtFuture = dir == null ? !dialog.isDoNotAskMe() : processChangedTextOnly;
EditorSettingsExternalizable.getInstance().getOptions().SHOW_REFORMAT_DIALOG = showDialogAtFuture;
updateShowDialogSetting(dialog, "\"Reformat Code\" dialog disabled");
optimizeImports = dialog.isOptimizeImports();
processWholeFile = dialog.isProcessWholeFile();

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