diff options
author | Tor Norbye <tnorbye@google.com> | 2013-06-20 15:12:35 -0700 |
---|---|---|
committer | Tor Norbye <tnorbye@google.com> | 2013-06-20 15:12:35 -0700 |
commit | 0e154c74931b6ff5ad6e0ec512b32e30df3cb068 (patch) | |
tree | f11327e8a38cd36b012c743a78e3dbf856b857f0 /java | |
parent | 9a718963c1d41c5bcd3a1bdd5e518d497964ccdf (diff) | |
download | idea-0e154c74931b6ff5ad6e0ec512b32e30df3cb068.tar.gz |
Snapshot 4a019151cb9b5542ea5ba9ed2f07b29cee0951f0 from master branch of git://git.jetbrains.org/idea/community.git
Change-Id: I2fd287fc46a5378a4c437af4c884c3a3be94c330
Diffstat (limited to 'java')
81 files changed, 1232 insertions, 447 deletions
diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/ProblemsViewImpl.java b/java/compiler/impl/src/com/intellij/compiler/impl/ProblemsViewImpl.java index 320898a02a6a..e625dc16e5a3 100644 --- a/java/compiler/impl/src/com/intellij/compiler/impl/ProblemsViewImpl.java +++ b/java/compiler/impl/src/com/intellij/compiler/impl/ProblemsViewImpl.java @@ -70,7 +70,7 @@ public class ProblemsViewImpl extends ProblemsView{ if (project.isDisposed()) { return; } - final ToolWindow tw = wm.registerToolWindow(PROBLEMS_TOOLWINDOW_ID, false, ToolWindowAnchor.BOTTOM, project); + final ToolWindow tw = wm.registerToolWindow(PROBLEMS_TOOLWINDOW_ID, false, ToolWindowAnchor.BOTTOM, project, true); tw.setIcon(AllIcons.Toolwindows.Problems); final Content content = ContentFactory.SERVICE.getInstance().createContent(myPanel, "", false); // todo: setup content? diff --git a/java/compiler/impl/src/com/intellij/compiler/server/BuildManager.java b/java/compiler/impl/src/com/intellij/compiler/server/BuildManager.java index a9ad726ab623..91697e246338 100644 --- a/java/compiler/impl/src/com/intellij/compiler/server/BuildManager.java +++ b/java/compiler/impl/src/com/intellij/compiler/server/BuildManager.java @@ -69,11 +69,13 @@ import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileManager; import com.intellij.openapi.vfs.newvfs.BulkFileListener; import com.intellij.openapi.vfs.newvfs.events.VFileEvent; +import com.intellij.openapi.vfs.newvfs.impl.FileNameCache; import com.intellij.util.Alarm; import com.intellij.util.Function; import com.intellij.util.SmartList; import com.intellij.util.concurrency.Semaphore; import com.intellij.util.concurrency.SequentialTaskExecutor; +import com.intellij.util.containers.IntArrayList; import com.intellij.util.io.storage.HeavyProcessLatch; import com.intellij.util.messages.MessageBusConnection; import com.intellij.util.net.NetUtils; @@ -391,12 +393,20 @@ public class BuildManager implements ApplicationComponent{ synchronized (myProjectDataMap) { ProjectData data = myProjectDataMap.get(projectPath); if (data != null && !data.myNeedRescan) { - return new ArrayList<String>(data.myChanged); + return convertToStringPaths(data.myChanged); } return null; } } + private static List<String> convertToStringPaths(final Collection<InternedPath> interned) { + final ArrayList<String> list = new ArrayList<String>(interned.size()); + for (InternedPath path : interned) { + list.add(path.getValue()); + } + return list; + } + @Nullable private static String getProjectPath(final Project project) { final String url = project.getPresentableUrl(); @@ -548,9 +558,9 @@ public class BuildManager implements ApplicationComponent{ LOG.info("Scheduling build for " + projectPath + "; CHANGED: " + - new HashSet<String>(data.myChanged) + + new HashSet<String>(convertToStringPaths(data.myChanged)) + "; DELETED: " + - new HashSet<String>(data.myDeleted)); + new HashSet<String>(convertToStringPaths(data.myDeleted))); } currentFSChanges = data.getAndResetRescanFlag() ? null : data.createNextEvent(); projectTaskQueue = data.taskQueue; @@ -1107,8 +1117,8 @@ public class BuildManager implements ApplicationComponent{ private static class ProjectData { final SequentialTaskExecutor taskQueue; - private final Set<String> myChanged = new THashSet<String>(FileUtil.PATH_HASHING_STRATEGY); - private final Set<String> myDeleted = new THashSet<String>(FileUtil.PATH_HASHING_STRATEGY); + private final Set<InternedPath> myChanged = new THashSet<InternedPath>(); + private final Set<InternedPath> myDeleted = new THashSet<InternedPath>(); private long myNextEventOrdinal = 0L; private boolean myNeedRescan = true; @@ -1118,15 +1128,21 @@ public class BuildManager implements ApplicationComponent{ public void addChanged(Collection<String> paths) { if (!myNeedRescan) { - myDeleted.removeAll(paths); - myChanged.addAll(paths); + for (String path : paths) { + final InternedPath _path = InternedPath.create(path); + myDeleted.remove(_path); + myChanged.add(_path); + } } } public void addDeleted(Collection<String> paths) { if (!myNeedRescan) { - myChanged.removeAll(paths); - myDeleted.addAll(paths); + for (String path : paths) { + final InternedPath _path = InternedPath.create(path); + myChanged.remove(_path); + myDeleted.add(_path); + } } } @@ -1134,10 +1150,17 @@ public class BuildManager implements ApplicationComponent{ final CmdlineRemoteProto.Message.ControllerMessage.FSEvent.Builder builder = CmdlineRemoteProto.Message.ControllerMessage.FSEvent.newBuilder(); builder.setOrdinal(++myNextEventOrdinal); - builder.addAllChangedPaths(myChanged); + + for (InternedPath path : myChanged) { + builder.addChangedPaths(path.getValue()); + } myChanged.clear(); - builder.addAllDeletedPaths(myDeleted); + + for (InternedPath path : myDeleted) { + builder.addDeletedPaths(path.getValue()); + } myDeleted.clear(); + return builder.build(); } @@ -1155,4 +1178,84 @@ public class BuildManager implements ApplicationComponent{ } } + private static abstract class InternedPath { + protected final int[] myPath; + + /** + * @param path assuming system-independent path with forward slashes + */ + protected InternedPath(String path) { + final IntArrayList list = new IntArrayList(); + final StringTokenizer tokenizer = new StringTokenizer(path, "/", false); + while(tokenizer.hasMoreTokens()) { + final String element = tokenizer.nextToken(); + list.add(FileNameCache.storeName(element)); + } + myPath = list.toArray(); + } + + public abstract String getValue(); + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + InternedPath path = (InternedPath)o; + + if (!Arrays.equals(myPath, path.myPath)) return false; + + return true; + } + + @Override + public int hashCode() { + return Arrays.hashCode(myPath); + } + + public static InternedPath create(String path) { + return path.startsWith("/")? new XInternedPath(path) : new WinInternedPath(path); + } + } + + private static class WinInternedPath extends InternedPath { + private WinInternedPath(String path) { + super(path); + } + + public String getValue() { + if (myPath.length == 1) { + final String name = FileNameCache.getVFileName(myPath[0]); + // handle case of windows drive letter + return name.length() == 2 && name.endsWith(":")? name + "/" : name; + } + + final StringBuilder buf = new StringBuilder(); + for (int element : myPath) { + if (buf.length() > 0) { + buf.append("/"); + } + buf.append(FileNameCache.getVFileName(element)); + } + return buf.toString(); + } + } + + private static class XInternedPath extends InternedPath { + private XInternedPath(String path) { + super(path); + } + + public String getValue() { + if (myPath.length > 0) { + final StringBuilder buf = new StringBuilder(); + for (int element : myPath) { + buf.append("/").append(FileNameCache.getVFileName(element)); + } + return buf.toString(); + } + return "/"; + } + } + } diff --git a/java/compiler/instrumentation-util/src/com/intellij/compiler/instrumentation/InstrumentationClassFinder.java b/java/compiler/instrumentation-util/src/com/intellij/compiler/instrumentation/InstrumentationClassFinder.java index 77a13ad1d844..3716f4d540ef 100644 --- a/java/compiler/instrumentation-util/src/com/intellij/compiler/instrumentation/InstrumentationClassFinder.java +++ b/java/compiler/instrumentation-util/src/com/intellij/compiler/instrumentation/InstrumentationClassFinder.java @@ -101,7 +101,7 @@ public class InstrumentationClassFinder { return aClass; } - final InputStream is = aClass == null? getClassBytesAsStream(internalName) : null; + final InputStream is = aClass == null? getClassBytesStream(internalName) : null; if (is == null) { if (aClass == null) { @@ -132,6 +132,23 @@ public class InstrumentationClassFinder { public InputStream getClassBytesAsStream(String className) throws IOException { final String internalName = className.replace('.', '/'); // normalize + final PseudoClass aClass = myLoaded.get(internalName); + if (aClass == PseudoClass.NULL_OBJ) { + return null; + } + InputStream bytes = null; + try { + bytes = getClassBytesStream(internalName); + } + finally { + if (aClass == null && bytes == null) { + myLoaded.put(internalName, PseudoClass.NULL_OBJ); + } + } + return bytes; + } + + private InputStream getClassBytesStream(String internalName) throws IOException { InputStream is = null; // first look into platformCp final String resourceName = internalName + CLASS_RESOURCE_EXTENSION; diff --git a/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/LineBreakpoint.java b/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/LineBreakpoint.java index 76f1b7982319..9ca1bd12f697 100644 --- a/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/LineBreakpoint.java +++ b/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/LineBreakpoint.java @@ -36,6 +36,7 @@ import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.markup.RangeHighlighter; import com.intellij.openapi.fileEditor.FileDocumentManager; +import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ProjectFileIndex; import com.intellij.openapi.roots.ProjectRootManager; @@ -44,12 +45,16 @@ import com.intellij.openapi.util.Key; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; +import com.intellij.psi.impl.java.stubs.index.JavaFullClassNameIndex; import com.intellij.psi.jsp.JspFile; +import com.intellij.psi.search.EverythingGlobalScope; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.ui.classFilter.ClassFilter; +import com.intellij.util.Function; import com.intellij.util.Processor; import com.intellij.util.StringBuilderSpinAllocator; +import com.intellij.util.containers.ContainerUtil; import com.intellij.xdebugger.XDebuggerUtil; import com.sun.jdi.*; import com.sun.jdi.event.LocatableEvent; @@ -203,6 +208,37 @@ public class LineBreakpoint extends BreakpointWithHighlighter { return true; } } + if (LOG.isDebugEnabled()) { + final GlobalSearchScope scope = debugProcess.getSearchScope(); + final boolean contains = scope.contains(breakpointFile); + final Project project = getProject(); + final List<VirtualFile> files = ContainerUtil.map( + JavaFullClassNameIndex.getInstance().get(className.hashCode(), project, scope), new Function<PsiClass, VirtualFile>() { + @Override + public VirtualFile fun(PsiClass aClass) { + return aClass.getContainingFile().getVirtualFile(); + } + }); + final List<VirtualFile> allFiles = ContainerUtil.map( + JavaFullClassNameIndex.getInstance().get(className.hashCode(), project, new EverythingGlobalScope(project)), new Function<PsiClass, VirtualFile>() { + @Override + public VirtualFile fun(PsiClass aClass) { + return aClass.getContainingFile().getVirtualFile(); + } + }); + final VirtualFile contentRoot = fileIndex.getContentRootForFile(breakpointFile); + final Module module = fileIndex.getModuleForFile(breakpointFile); + + LOG.debug("Did not find '" + + className + "' in " + scope + + "; contains=" + contains + + "; contentRoot=" + contentRoot + + "; module = " + module + + "; all files in index are: " + files+ + "; all possible files are: " + allFiles + ); + } + return false; } } @@ -218,7 +254,7 @@ public class LineBreakpoint extends BreakpointWithHighlighter { public Collection<VirtualFile> compute() { final PsiClass[] classes = JavaPsiFacade.getInstance(myProject).findClasses(topLevelClassName, scope); if (LOG.isDebugEnabled()) { - LOG.debug("Found "+ classes.length + " classes " + topLevelClassName + " in scope"); + LOG.debug("Found "+ classes.length + " classes " + topLevelClassName + " in scope "+scope); } if (classes.length == 0) { return null; @@ -241,12 +277,14 @@ public class LineBreakpoint extends BreakpointWithHighlighter { LOG.debug(msg.toString()); } - if (psiFile != null) { - final VirtualFile vFile = psiFile.getVirtualFile(); - if (vFile != null && fileIndex.isInSourceContent(vFile)) { - list.add(vFile); - } + if (psiFile == null) { + return null; + } + final VirtualFile vFile = psiFile.getVirtualFile(); + if (vFile == null || !fileIndex.isInSourceContent(vFile)) { + return null; // this will switch off the check if at least one class is from libraries } + list.add(vFile); } return list; } diff --git a/java/debugger/openapi/src/com/intellij/debugger/engine/DebuggerUtils.java b/java/debugger/openapi/src/com/intellij/debugger/engine/DebuggerUtils.java index 1dc06107b090..9fcc7d7a7d8d 100644 --- a/java/debugger/openapi/src/com/intellij/debugger/engine/DebuggerUtils.java +++ b/java/debugger/openapi/src/com/intellij/debugger/engine/DebuggerUtils.java @@ -130,7 +130,7 @@ public abstract class DebuggerUtils { } } - public static final int MAX_DISPLAY_LABEL_LENGTH = 1024/*kb*/ *1024 /*bytes*/ / 2; // 1 Mb string + public static final int MAX_DISPLAY_LABEL_LENGTH = 1024 * 5; public static String convertToPresentationString(String str) { if (str.length() > MAX_DISPLAY_LABEL_LENGTH) { diff --git a/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/SelectTemplateStep.java b/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/SelectTemplateStep.java index cfdcf817dccf..13b4fcda9964 100644 --- a/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/SelectTemplateStep.java +++ b/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/SelectTemplateStep.java @@ -156,7 +156,16 @@ public class SelectTemplateStep extends ModuleWizardStep implements SettingsStep @Override public String getHelpId() { - return myWizardContext.isCreatingNewProject() ? "New_Project_Main_Settings" : "Add_Module_Main_Settings"; + String helpId = myWizardContext.isCreatingNewProject() ? "New_Project_Main_Settings" : "Add_Module_Main_Settings"; + ProjectTemplate projectTemplate = getSelectedTemplate(); + if (projectTemplate instanceof WebProjectTemplate) { + WebProjectTemplate webProjectTemplate = (WebProjectTemplate) projectTemplate; + String subHelpId = webProjectTemplate.getHelpId(); + if (subHelpId != null) { + helpId = helpId + ":" + subHelpId; + } + } + return helpId; } private static NamePathComponent initNamePathComponent(WizardContext context) { diff --git a/java/idea-ui/src/com/intellij/platform/templates/LocalArchivedTemplate.java b/java/idea-ui/src/com/intellij/platform/templates/LocalArchivedTemplate.java index 1b9f3c2ef6c1..f671335e6d7e 100644 --- a/java/idea-ui/src/com/intellij/platform/templates/LocalArchivedTemplate.java +++ b/java/idea-ui/src/com/intellij/platform/templates/LocalArchivedTemplate.java @@ -19,6 +19,7 @@ import com.intellij.ide.util.projectWizard.WizardInputField; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleType; import com.intellij.openapi.module.ModuleTypeManager; +import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.IconLoader; import com.intellij.openapi.util.JDOMUtil; @@ -43,8 +44,8 @@ import java.util.zip.ZipInputStream; */ public class LocalArchivedTemplate extends ArchivedProjectTemplate { - public static final String DESCRIPTION_PATH = ".idea/description.html"; - static final String IDEA_INPUT_FIELDS_XML = ".idea/project-template.xml"; + public static final String DESCRIPTION_PATH = Project.DIRECTORY_STORE_FOLDER + "/description.html"; + static final String IDEA_INPUT_FIELDS_XML = Project.DIRECTORY_STORE_FOLDER + "/project-template.xml"; private final URL myArchivePath; private final ModuleType myModuleType; diff --git a/java/idea-ui/src/com/intellij/platform/templates/SaveProjectAsTemplateAction.java b/java/idea-ui/src/com/intellij/platform/templates/SaveProjectAsTemplateAction.java index e6cb2a3ed94e..54c0b7c02516 100644 --- a/java/idea-ui/src/com/intellij/platform/templates/SaveProjectAsTemplateAction.java +++ b/java/idea-ui/src/com/intellij/platform/templates/SaveProjectAsTemplateAction.java @@ -162,7 +162,7 @@ public class SaveProjectAsTemplateAction extends AnAction { if (relativePath == null) { throw new RuntimeException("Can't find relative path for " + virtualFile); } - final boolean system = ".idea".equals(virtualFile.getParent().getName()); + final boolean system = Project.DIRECTORY_STORE_FOLDER.equals(virtualFile.getParent().getName()); if (system) { if (!fileName.equals("description.html") && !fileName.equals(PROJECT_TEMPLATE_XML) && diff --git a/java/idea-ui/src/com/intellij/platform/templates/SystemFileProcessor.java b/java/idea-ui/src/com/intellij/platform/templates/SystemFileProcessor.java index f57c954c20b6..29f21b4203de 100644 --- a/java/idea-ui/src/com/intellij/platform/templates/SystemFileProcessor.java +++ b/java/idea-ui/src/com/intellij/platform/templates/SystemFileProcessor.java @@ -53,7 +53,7 @@ public class SystemFileProcessor extends ProjectTemplateFileProcessor { @Override protected String encodeFileText(String content, VirtualFile file, Project project) throws IOException { final String fileName = file.getName(); - if (file.getParent().getName().equals(".idea") && fileName.equals("workspace.xml")) { + if (file.getParent().getName().equals(Project.DIRECTORY_STORE_FOLDER) && fileName.equals("workspace.xml")) { List<Object> componentList = new ArrayList<Object>(); for (String componentName : COMPONENT_NAMES) { diff --git a/java/idea-ui/src/com/intellij/platform/templates/TemplateModuleBuilder.java b/java/idea-ui/src/com/intellij/platform/templates/TemplateModuleBuilder.java index 61bf78feed89..4b0727abd148 100644 --- a/java/idea-ui/src/com/intellij/platform/templates/TemplateModuleBuilder.java +++ b/java/idea-ui/src/com/intellij/platform/templates/TemplateModuleBuilder.java @@ -205,7 +205,7 @@ public class TemplateModuleBuilder extends ModuleBuilder { @Nullable @Override public String fun(String path) { - if (moduleMode && path.contains(".idea")) return null; + if (moduleMode && path.contains(Project.DIRECTORY_STORE_FOLDER)) return null; if (basePackage != null) { return path.replace(getPathFragment(basePackage.getDefaultValue()), getPathFragment(basePackage.getValue())); } @@ -218,7 +218,7 @@ public class TemplateModuleBuilder extends ModuleBuilder { FileType fileType = FileTypeManager.getInstance().getFileTypeByExtension(FileUtilRt.getExtension(file.getName())); return fileType.isBinary() ? content : processTemplates(projectName, new String(content), file); } - }); + }, true); String iml = ContainerUtil.find(dir.list(), new Condition<String>() { @Override public boolean value(String s) { diff --git a/java/idea-ui/src/com/intellij/projectImport/ProjectFormatPanel.java b/java/idea-ui/src/com/intellij/projectImport/ProjectFormatPanel.java index e367ce765f98..9b7795d91e4b 100644 --- a/java/idea-ui/src/com/intellij/projectImport/ProjectFormatPanel.java +++ b/java/idea-ui/src/com/intellij/projectImport/ProjectFormatPanel.java @@ -23,13 +23,14 @@ package com.intellij.projectImport; import com.intellij.ide.util.PropertiesComponent; import com.intellij.ide.util.projectWizard.WizardContext; import com.intellij.openapi.components.StorageScheme; +import com.intellij.openapi.project.Project; import javax.swing.*; public class ProjectFormatPanel { private static final String STORAGE_FORMAT_PROPERTY = "default.storage.format"; - public static final String DIR_BASED = ".idea (directory based)"; + public static final String DIR_BASED = Project.DIRECTORY_STORE_FOLDER + " (directory based)"; private static final String FILE_BASED = ".ipr (file based)"; private JComboBox myStorageFormatCombo; diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/ControlFlowAnalyzer.java b/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/ControlFlowAnalyzer.java index 369f6ece05d4..24850aa689c5 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/ControlFlowAnalyzer.java +++ b/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/ControlFlowAnalyzer.java @@ -29,6 +29,7 @@ import com.intellij.psi.util.*; import com.intellij.util.IncorrectOperationException; import com.intellij.util.containers.Stack; import org.jetbrains.annotations.NonNls; +import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; @@ -38,6 +39,7 @@ import static com.intellij.psi.CommonClassNames.*; class ControlFlowAnalyzer extends JavaElementVisitor { private static final Logger LOG = Logger.getInstance("#com.intellij.codeInspection.dataFlow.ControlFlowAnalyzer"); private static final int NOT_FOUND = -10; + private boolean myIgnoreAssertions; private static class CannotAnalyzeException extends RuntimeException { } @@ -54,9 +56,8 @@ class ControlFlowAnalyzer extends JavaElementVisitor { myFactory = valueFactory; } - public ControlFlow buildControlFlow(PsiElement codeFragment) { - if (codeFragment == null) return null; - + public ControlFlow buildControlFlow(@NotNull PsiElement codeFragment, boolean ignoreAssertions) { + myIgnoreAssertions = ignoreAssertions; PsiManager manager = codeFragment.getManager(); GlobalSearchScope scope = codeFragment.getResolveScope(); myRuntimeException = myFactory.getNotNullFactory().create(PsiType.getJavaLangRuntimeException(manager, scope)); @@ -203,6 +204,10 @@ class ControlFlowAnalyzer extends JavaElementVisitor { } @Override public void visitAssertStatement(PsiAssertStatement statement) { + if (myIgnoreAssertions) { + return; + } + startElement(statement); final PsiExpression condition = statement.getAssertCondition(); final PsiExpression description = statement.getAssertDescription(); diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/DataFlowInspectionBase.java b/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/DataFlowInspectionBase.java index 391fa1b5a8dc..a5028fc37792 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/DataFlowInspectionBase.java +++ b/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/DataFlowInspectionBase.java @@ -35,6 +35,7 @@ import com.intellij.codeInspection.dataFlow.instructions.*; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Pair; +import com.intellij.openapi.util.WriteExternalException; import com.intellij.pom.java.LanguageLevel; import com.intellij.psi.*; import com.intellij.psi.util.PsiTreeUtil; @@ -42,6 +43,7 @@ import com.intellij.psi.util.PsiUtil; import com.intellij.util.ArrayUtil; import com.intellij.util.IncorrectOperationException; import com.intellij.util.SmartList; +import org.jdom.Element; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -54,6 +56,7 @@ public class DataFlowInspectionBase extends BaseJavaBatchLocalInspectionTool { @NonNls private static final String SHORT_NAME = "ConstantConditions"; public boolean SUGGEST_NULLABLE_ANNOTATIONS = false; public boolean DONT_REPORT_TRUE_ASSERT_STATEMENTS = false; + public boolean IGNORE_ASSERT_STATEMENTS = false; @Override public JComponent createOptionsPanel() { @@ -61,6 +64,15 @@ public class DataFlowInspectionBase extends BaseJavaBatchLocalInspectionTool { } @Override + public void writeSettings(@NotNull Element node) throws WriteExternalException { + node.addContent(new Element("option").setAttribute("name", "SUGGEST_NULLABLE_ANNOTATIONS").setAttribute("value", String.valueOf(SUGGEST_NULLABLE_ANNOTATIONS))); + node.addContent(new Element("option").setAttribute("name", "DONT_REPORT_TRUE_ASSERT_STATEMENTS").setAttribute("value", String.valueOf(DONT_REPORT_TRUE_ASSERT_STATEMENTS))); + if (IGNORE_ASSERT_STATEMENTS) { + node.addContent(new Element("option").setAttribute("name", "IGNORE_ASSERT_STATEMENTS").setAttribute("value", "true")); + } + } + + @Override @NotNull public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, boolean isOnTheFly) { return new JavaElementVisitor() { @@ -85,7 +97,7 @@ public class DataFlowInspectionBase extends BaseJavaBatchLocalInspectionTool { if (scope == null) return; final StandardDataFlowRunner dfaRunner = new StandardDataFlowRunner(SUGGEST_NULLABLE_ANNOTATIONS); final StandardInstructionVisitor visitor = new DataFlowInstructionVisitor(dfaRunner); - final RunnerResult rc = dfaRunner.analyzeMethod(scope, visitor); + final RunnerResult rc = dfaRunner.analyzeMethod(scope, visitor, IGNORE_ASSERT_STATEMENTS); if (rc == RunnerResult.OK) { if (dfaRunner.problemsDetected(visitor)) { createDescription(dfaRunner, holder, visitor); diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/DataFlowRunner.java b/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/DataFlowRunner.java index 4e30cdd0964c..a01901ce386c 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/DataFlowRunner.java +++ b/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/DataFlowRunner.java @@ -91,11 +91,15 @@ public class DataFlowRunner { } public final RunnerResult analyzeMethod(@NotNull PsiElement psiBlock, InstructionVisitor visitor) { + return analyzeMethod(psiBlock, visitor, false); + } + + public final RunnerResult analyzeMethod(@NotNull PsiElement psiBlock, InstructionVisitor visitor, boolean ignoreAssertions) { try { final Collection<DfaMemoryState> initialStates = createInitialStates(psiBlock, visitor); if (initialStates == null) return RunnerResult.NOT_APPLICABLE; - final ControlFlow flow = createControlFlowAnalyzer().buildControlFlow(psiBlock); + final ControlFlow flow = createControlFlowAnalyzer().buildControlFlow(psiBlock, ignoreAssertions); if (flow == null) return RunnerResult.NOT_APPLICABLE; int endOffset = flow.getInstructionCount(); diff --git a/java/java-impl/src/com/intellij/application/options/CodeStyleGenerationConfigurable.java b/java/java-impl/src/com/intellij/application/options/CodeStyleGenerationConfigurable.java index 44ccf4985b95..aebfb44da1ca 100644 --- a/java/java-impl/src/com/intellij/application/options/CodeStyleGenerationConfigurable.java +++ b/java/java-impl/src/com/intellij/application/options/CodeStyleGenerationConfigurable.java @@ -18,8 +18,10 @@ package com.intellij.application.options; import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer; import com.intellij.openapi.application.ApplicationBundle; import com.intellij.openapi.options.Configurable; +import com.intellij.openapi.options.ConfigurationException; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectManager; +import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.codeStyle.CodeStyleSettings; import com.intellij.ui.IdeBorderFactory; import com.intellij.ui.ToolbarDecorator; @@ -230,18 +232,18 @@ public class CodeStyleGenerationConfigurable implements Configurable { reset(mySettings); } - public void apply(CodeStyleSettings settings) { + public void apply(CodeStyleSettings settings) throws ConfigurationException { settings.PREFER_LONGER_NAMES = myCbPreferLongerNames.isSelected(); - settings.FIELD_NAME_PREFIX = myFieldPrefixField.getText().trim(); - settings.STATIC_FIELD_NAME_PREFIX = myStaticFieldPrefixField.getText().trim(); - settings.PARAMETER_NAME_PREFIX = myParameterPrefixField.getText().trim(); - settings.LOCAL_VARIABLE_NAME_PREFIX = myLocalVariablePrefixField.getText().trim(); + settings.FIELD_NAME_PREFIX = setPrefixSuffix(myFieldPrefixField.getText(), true); + settings.STATIC_FIELD_NAME_PREFIX = setPrefixSuffix(myStaticFieldPrefixField.getText(), true); + settings.PARAMETER_NAME_PREFIX = setPrefixSuffix(myParameterPrefixField.getText(), true); + settings.LOCAL_VARIABLE_NAME_PREFIX = setPrefixSuffix(myLocalVariablePrefixField.getText(), true); - settings.FIELD_NAME_SUFFIX = myFieldSuffixField.getText().trim(); - settings.STATIC_FIELD_NAME_SUFFIX = myStaticFieldSuffixField.getText().trim(); - settings.PARAMETER_NAME_SUFFIX = myParameterSuffixField.getText().trim(); - settings.LOCAL_VARIABLE_NAME_SUFFIX = myLocalVariableSuffixField.getText().trim(); + settings.FIELD_NAME_SUFFIX = setPrefixSuffix(myFieldSuffixField.getText(), false); + settings.STATIC_FIELD_NAME_SUFFIX = setPrefixSuffix(myStaticFieldSuffixField.getText(), false); + settings.PARAMETER_NAME_SUFFIX = setPrefixSuffix(myParameterSuffixField.getText(), false); + settings.LOCAL_VARIABLE_NAME_SUFFIX = setPrefixSuffix(myLocalVariableSuffixField.getText(), false); settings.LINE_COMMENT_AT_FIRST_COLUMN = myCbLineCommentAtFirstColumn.isSelected(); settings.BLOCK_COMMENT_AT_FIRST_COLUMN = myCbBlockCommentAtFirstColumn.isSelected(); @@ -260,7 +262,16 @@ public class CodeStyleGenerationConfigurable implements Configurable { } } - public void apply() { + private static String setPrefixSuffix(String text, boolean prefix) throws ConfigurationException { + text = text.trim(); + if (text.isEmpty()) return text; + if (!StringUtil.isJavaIdentifier(text)) { + throw new ConfigurationException("Not a valid java identifier part in " + (prefix ? "prefix" : "suffix") + " \'" + text + "\'"); + } + return text; + } + + public void apply() throws ConfigurationException { apply(mySettings); } diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/JavaAwareInspectionProfileCoverter.java b/java/java-impl/src/com/intellij/codeInsight/daemon/JavaAwareInspectionProfileCoverter.java index e79fdbe14ed9..e411fc11add3 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/JavaAwareInspectionProfileCoverter.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/JavaAwareInspectionProfileCoverter.java @@ -20,9 +20,8 @@ */ package com.intellij.codeInsight.daemon; -import com.intellij.codeInspection.InspectionProfileEntry; import com.intellij.codeInspection.ModifiableModel; -import com.intellij.codeInspection.ex.LocalInspectionToolWrapper; +import com.intellij.codeInspection.ex.InspectionToolWrapper; import com.intellij.codeInspection.javaDoc.JavaDocLocalInspection; import com.intellij.profile.codeInspection.InspectionProfileManager; import org.jdom.Element; @@ -53,8 +52,8 @@ public class JavaAwareInspectionProfileCoverter extends InspectionProfileConvert super.fillErrorLevels(profile); //javadoc attributes - final InspectionProfileEntry inspectionTool = profile.getInspectionTool(JavaDocLocalInspection.SHORT_NAME, null); - JavaDocLocalInspection inspection = (JavaDocLocalInspection)((LocalInspectionToolWrapper)inspectionTool).getTool(); + final InspectionToolWrapper toolWrapper = (InspectionToolWrapper)profile.getInspectionTool(JavaDocLocalInspection.SHORT_NAME, null); + JavaDocLocalInspection inspection = (JavaDocLocalInspection)toolWrapper.getTool(); inspection.myAdditionalJavadocTags = myAdditionalJavadocTags; } }
\ No newline at end of file diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightClassUtil.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightClassUtil.java index 4f6f0996ad29..5bcc31079aab 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightClassUtil.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightClassUtil.java @@ -94,19 +94,32 @@ public class HighlightClassUtil { static HighlightInfo checkClassWithAbstractMethods(PsiClass aClass, PsiElement implementsFixElement, TextRange range) { PsiMethod abstractMethod = ClassUtil.getAnyAbstractMethod(aClass); - if (abstractMethod == null || abstractMethod.getContainingClass() == null) { + if (abstractMethod == null) { return null; } + + final PsiClass superClass = abstractMethod.getContainingClass(); + if (superClass == null) { + return null; + } + String baseClassName = HighlightUtil.formatClass(aClass, false); String methodName = JavaHighlightUtil.formatMethod(abstractMethod); String message = JavaErrorMessages.message(aClass instanceof PsiEnumConstantInitializer || implementsFixElement instanceof PsiEnumConstant ? "enum.constant.should.implement.method" : "class.must.be.abstract", baseClassName, methodName, - HighlightUtil.formatClass(abstractMethod.getContainingClass(), false)); + HighlightUtil.formatClass(superClass, false)); HighlightInfo errorResult = HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(range).descriptionAndTooltip(message).create(); - if (ClassUtil.getAnyMethodToImplement(aClass) != null) { - QuickFixAction.registerQuickFixAction(errorResult, QUICK_FIX_FACTORY.createImplementMethodsFix(implementsFixElement)); + final PsiMethod anyMethodToImplement = ClassUtil.getAnyMethodToImplement(aClass); + if (anyMethodToImplement != null) { + if (!anyMethodToImplement.hasModifierProperty(PsiModifier.PACKAGE_LOCAL) || + JavaPsiFacade.getInstance(aClass.getProject()).arePackagesTheSame(aClass, superClass)) { + QuickFixAction.registerQuickFixAction(errorResult, QUICK_FIX_FACTORY.createImplementMethodsFix(implementsFixElement)); + } else { + QuickFixAction.registerQuickFixAction(errorResult, QUICK_FIX_FACTORY.createModifierListFix(anyMethodToImplement, PsiModifier.PROTECTED, true, true)); + QuickFixAction.registerQuickFixAction(errorResult, QUICK_FIX_FACTORY.createModifierListFix(anyMethodToImplement, PsiModifier.PUBLIC, true, true)); + } } if (!(aClass instanceof PsiAnonymousClass) && HighlightUtil.getIncompatibleModifier(PsiModifier.ABSTRACT, aClass.getModifierList()) == null) { diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/ImportClassFix.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/ImportClassFix.java index a2bebf63ac18..2e23f7ef65e4 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/ImportClassFix.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/ImportClassFix.java @@ -107,6 +107,7 @@ public class ImportClassFix extends ImportClassFixBase<PsiJavaCodeReferenceEleme return super.getRequiredMemberName(reference); } + @NotNull @Override protected List<PsiClass> filterByContext(@NotNull List<PsiClass> candidates, @NotNull PsiJavaCodeReferenceElement ref) { PsiElement typeElement = ref.getParent(); diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/ImportClassFixBase.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/ImportClassFixBase.java index e34ad1820c89..bfb7c45bf3c8 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/ImportClassFixBase.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/ImportClassFixBase.java @@ -184,6 +184,7 @@ public abstract class ImportClassFixBase<T extends PsiElement, R extends PsiRefe return null; } + @NotNull protected List<PsiClass> filterByContext(@NotNull List<PsiClass> candidates, @NotNull T ref) { return candidates; } diff --git a/java/java-impl/src/com/intellij/codeInsight/generation/OverrideImplementUtil.java b/java/java-impl/src/com/intellij/codeInsight/generation/OverrideImplementUtil.java index 68c3684ff662..4f45ac344e73 100644 --- a/java/java-impl/src/com/intellij/codeInsight/generation/OverrideImplementUtil.java +++ b/java/java-impl/src/com/intellij/codeInsight/generation/OverrideImplementUtil.java @@ -612,7 +612,7 @@ public class OverrideImplementUtil extends OverrideImplementExploreUtil { finally { PsiFile psiFile = psiClass.getContainingFile(); - Editor editor = fileEditorManager.openTextEditor(new OpenFileDescriptor(psiFile.getProject(), psiFile.getVirtualFile()), false); + Editor editor = fileEditorManager.openTextEditor(new OpenFileDescriptor(psiFile.getProject(), psiFile.getVirtualFile()), true); if (editor != null && !results.isEmpty()) { results.get(0).positionCaret(editor, true); editor.getScrollingModel().scrollToCaret(ScrollType.CENTER); diff --git a/java/java-impl/src/com/intellij/codeInsight/highlighting/HighlightSuppressedWarningsHandler.java b/java/java-impl/src/com/intellij/codeInsight/highlighting/HighlightSuppressedWarningsHandler.java index 2e92545483f9..85835a8fcff1 100644 --- a/java/java-impl/src/com/intellij/codeInsight/highlighting/HighlightSuppressedWarningsHandler.java +++ b/java/java-impl/src/com/intellij/codeInsight/highlighting/HighlightSuppressedWarningsHandler.java @@ -25,11 +25,7 @@ import com.intellij.codeInsight.daemon.impl.HighlightInfo; import com.intellij.codeInsight.daemon.impl.LocalInspectionsPass; import com.intellij.codeInspection.InspectionManager; import com.intellij.codeInspection.InspectionProfile; -import com.intellij.codeInspection.InspectionProfileEntry; -import com.intellij.codeInspection.ex.GlobalInspectionContextImpl; -import com.intellij.codeInspection.ex.InspectionManagerEx; -import com.intellij.codeInspection.ex.InspectionProfileImpl; -import com.intellij.codeInspection.ex.LocalInspectionToolWrapper; +import com.intellij.codeInspection.ex.*; import com.intellij.codeInspection.reference.RefManagerImpl; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Editor; @@ -122,20 +118,20 @@ public class HighlightSuppressedWarningsHandler extends HighlightUsagesHandlerBa if (!(value instanceof String)) { continue; } - final InspectionProfileEntry toolById = ((InspectionProfileImpl)inspectionProfile).getToolById((String)value, target); + InspectionToolWrapper toolById = ((InspectionProfileImpl)inspectionProfile).getToolById((String)value, target); if (!(toolById instanceof LocalInspectionToolWrapper)) { continue; } - final LocalInspectionToolWrapper tool = ((LocalInspectionToolWrapper)toolById).createCopy(); + final LocalInspectionToolWrapper toolWrapper = ((LocalInspectionToolWrapper)toolById).createCopy(); final InspectionManagerEx managerEx = (InspectionManagerEx)InspectionManager.getInstance(project); final GlobalInspectionContextImpl context = managerEx.createNewGlobalContext(false); - tool.initialize(context); + toolWrapper.initialize(context); ((RefManagerImpl)context.getRefManager()).inspectionReadActionStarted(); ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator(); Runnable inspect = new Runnable() { @Override public void run() { - pass.doInspectInBatch(managerEx, Collections.<LocalInspectionToolWrapper>singletonList(tool)); + pass.doInspectInBatch(managerEx, Collections.<LocalInspectionToolWrapper>singletonList(toolWrapper)); } }; if (indicator == null) { diff --git a/java/java-impl/src/com/intellij/codeInsight/intention/impl/ConcatenationToMessageFormatAction.java b/java/java-impl/src/com/intellij/codeInsight/intention/impl/ConcatenationToMessageFormatAction.java index 544440fa3e21..9bc47e30f1fa 100644 --- a/java/java-impl/src/com/intellij/codeInsight/intention/impl/ConcatenationToMessageFormatAction.java +++ b/java/java-impl/src/com/intellij/codeInsight/intention/impl/ConcatenationToMessageFormatAction.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2011 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,7 +25,6 @@ import com.intellij.pom.java.LanguageLevel; import com.intellij.psi.*; import com.intellij.psi.codeStyle.CodeStyleManager; import com.intellij.psi.codeStyle.JavaCodeStyleManager; -import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.util.PsiConcatenationUtil; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.util.PsiUtil; @@ -60,7 +59,7 @@ public class ConcatenationToMessageFormatAction implements IntentionAction { if (concatenation == null) return; StringBuilder formatString = new StringBuilder(); List<PsiExpression> args = new ArrayList<PsiExpression>(); - buildMessageFormatString(concatenation, formatString, args); + PsiConcatenationUtil.buildFormatString(concatenation, formatString, args, false); final PsiElementFactory factory = JavaPsiFacade.getElementFactory(project); PsiMethodCallExpression call = (PsiMethodCallExpression) @@ -87,47 +86,6 @@ public class ConcatenationToMessageFormatAction implements IntentionAction { concatenation.replace(call); } - public static void buildMessageFormatString(PsiExpression expression, - StringBuilder formatString, - List<PsiExpression> args) - throws IncorrectOperationException { - PsiConcatenationUtil.buildFormatString(expression, formatString, args, false); - - } - - private static void appendArgument(List<PsiExpression> args, PsiExpression argument, StringBuilder formatString) throws IncorrectOperationException { - formatString.append("{").append(args.size()).append("}"); - args.add(getBoxedArgument(argument)); - } - - private static PsiExpression getBoxedArgument(PsiExpression arg) throws IncorrectOperationException { - arg = PsiUtil.deparenthesizeExpression(arg); - assert arg != null; - if (PsiUtil.isLanguageLevel5OrHigher(arg)) { - return arg; - } - final PsiType type = arg.getType(); - if (!(type instanceof PsiPrimitiveType) || type.equals(PsiType.NULL)) { - return arg; - } - final PsiPrimitiveType primitiveType = (PsiPrimitiveType)type; - final String boxedQName = primitiveType.getBoxedTypeName(); - if (boxedQName == null) { - return arg; - } - final GlobalSearchScope resolveScope = arg.getResolveScope(); - final PsiElementFactory factory = JavaPsiFacade.getElementFactory(arg.getProject()); - final PsiJavaCodeReferenceElement ref = factory.createReferenceElementByFQClassName(boxedQName, resolveScope); - final PsiNewExpression newExpr = (PsiNewExpression)factory.createExpressionFromText("new A(b)", null); - final PsiElement classRef = newExpr.getClassReference(); - assert classRef != null; - classRef.replace(ref); - final PsiExpressionList argumentList = newExpr.getArgumentList(); - assert argumentList != null; - argumentList.getExpressions()[0].replace(arg); - return newExpr; - } - @Override public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) { if (PsiUtil.getLanguageLevel(file).compareTo(LanguageLevel.JDK_1_4) < 0) return false; diff --git a/java/java-impl/src/com/intellij/codeInsight/template/macro/MacroUtil.java b/java/java-impl/src/com/intellij/codeInsight/template/macro/MacroUtil.java index 059c0471eebb..6010a7a4b41f 100644 --- a/java/java-impl/src/com/intellij/codeInsight/template/macro/MacroUtil.java +++ b/java/java-impl/src/com/intellij/codeInsight/template/macro/MacroUtil.java @@ -27,11 +27,13 @@ import com.intellij.psi.scope.util.PsiScopesUtil; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.util.PsiUtil; import com.intellij.util.IncorrectOperationException; +import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.List; +import java.util.Set; public class MacroUtil { private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.template.macro.MacroUtil"); @@ -158,11 +160,15 @@ public class MacroUtil { return new PsiVariable[0]; } + final Set<String> usedNames = ContainerUtil.newHashSet(); final List<PsiVariable> list = new ArrayList<PsiVariable>(); VariablesProcessor varproc = new VariablesProcessor(prefix, true, list) { @Override public boolean execute(@NotNull PsiElement pe, ResolveState state) { if (pe instanceof PsiVariable) { + if (!usedNames.add(((PsiVariable)pe).getName())) { + return false; + } //exclude variables that are initialized in 'place' final PsiExpression initializer = ((PsiVariable)pe).getInitializer(); if (initializer != null && PsiTreeUtil.isAncestor(initializer, place, false)) return true; diff --git a/java/java-impl/src/com/intellij/codeInspection/RedundantSuppressInspection.java b/java/java-impl/src/com/intellij/codeInspection/RedundantSuppressInspection.java index f65d58051522..b2ce257425f5 100644 --- a/java/java-impl/src/com/intellij/codeInspection/RedundantSuppressInspection.java +++ b/java/java-impl/src/com/intellij/codeInspection/RedundantSuppressInspection.java @@ -141,7 +141,7 @@ public class RedundantSuppressInspection extends GlobalInspectionTool{ private void checkElement(final PsiElement owner) { String idsString = SuppressManager.getInstance().getSuppressedInspectionIdsIn(owner); - if (idsString != null && idsString.length() != 0) { + if (idsString != null && !idsString.isEmpty()) { List<String> ids = StringUtil.split(idsString, ","); if (IGNORE_ALL && (ids.contains(SuppressionUtil.ALL) || ids.contains(SuppressionUtil.ALL.toLowerCase()))) return; Collection<String> suppressed = suppressedScopes.get(owner); @@ -162,27 +162,29 @@ public class RedundantSuppressInspection extends GlobalInspectionTool{ if (suppressedScopes.values().isEmpty()) return null; // have to visit all file from scratch since inspections can be written in any perversive way including checkFile() overriding - Collection<InspectionTool> suppressedTools = new THashSet<InspectionTool>(); - InspectionTool[] tools = getInspectionTools(psiElement, manager); + Collection<InspectionToolWrapper> suppressedTools = new THashSet<InspectionToolWrapper>(); + InspectionToolWrapper[] toolWrappers = getInspectionTools(psiElement, manager); for (Collection<String> ids : suppressedScopes.values()) { for (Iterator<String> iterator = ids.iterator(); iterator.hasNext(); ) { final String shortName = iterator.next().trim(); - for (InspectionTool tool : tools) { - if (tool instanceof LocalInspectionToolWrapper && ((LocalInspectionToolWrapper)tool).getTool().getID().equals(shortName)) { - if (!((LocalInspectionToolWrapper)tool).isUnfair()) { - suppressedTools.add(tool); - } else { + for (InspectionToolWrapper toolWrapper : toolWrappers) { + if (toolWrapper instanceof LocalInspectionToolWrapper && ((LocalInspectionToolWrapper)toolWrapper).getTool().getID().equals(shortName)) { + if (((LocalInspectionToolWrapper)toolWrapper).isUnfair()) { iterator.remove(); break; } + else { + suppressedTools.add(toolWrapper); + } } - else if (tool.getShortName().equals(shortName)) { + else if (toolWrapper.getShortName().equals(shortName)) { //ignore global unused as it won't be checked anyway - if (!(tool instanceof LocalInspectionToolWrapper) && !(tool instanceof GlobalInspectionToolWrapper)) { + if (toolWrapper instanceof LocalInspectionToolWrapper || toolWrapper instanceof GlobalInspectionToolWrapper) { + suppressedTools.add(toolWrapper); + } + else { iterator.remove(); break; - } else { - suppressedTools.add(tool); } } } @@ -190,26 +192,26 @@ public class RedundantSuppressInspection extends GlobalInspectionTool{ } final AnalysisScope scope = new AnalysisScope(psiElement.getContainingFile()); - final InspectionManagerEx inspectionManagerEx = ((InspectionManagerEx)InspectionManager.getInstance(project)); + final InspectionManagerEx inspectionManagerEx = (InspectionManagerEx)InspectionManager.getInstance(project); GlobalInspectionContextImpl globalContext = inspectionManagerEx.createNewGlobalContext(false); globalContext.setCurrentScope(scope); - final RefManagerImpl refManager = ((RefManagerImpl)globalContext.getRefManager()); + final RefManagerImpl refManager = (RefManagerImpl)globalContext.getRefManager(); refManager.inspectionReadActionStarted(); final List<ProblemDescriptor> result; try { result = new ArrayList<ProblemDescriptor>(); - for (InspectionTool tool : suppressedTools) { - String toolId = tool instanceof LocalInspectionToolWrapper ? ((LocalInspectionToolWrapper)tool).getTool().getID() : tool.getShortName(); - tool.initialize(globalContext); + for (InspectionToolWrapper toolWrapper : suppressedTools) { + String toolId = toolWrapper instanceof LocalInspectionToolWrapper ? ((LocalInspectionToolWrapper)toolWrapper).getTool().getID() : toolWrapper.getShortName(); + toolWrapper.initialize(globalContext); Collection<CommonProblemDescriptor> descriptors; - if (tool instanceof LocalInspectionToolWrapper) { - LocalInspectionToolWrapper local = (LocalInspectionToolWrapper)tool; + if (toolWrapper instanceof LocalInspectionToolWrapper) { + LocalInspectionToolWrapper local = (LocalInspectionToolWrapper)toolWrapper; if (local.isUnfair()) continue; //cant't work with passes other than LocalInspectionPass local.processFile(psiElement.getContainingFile(), false, manager); descriptors = local.getProblemDescriptors(); } - else if (tool instanceof GlobalInspectionToolWrapper) { - GlobalInspectionToolWrapper global = (GlobalInspectionToolWrapper)tool; + else if (toolWrapper instanceof GlobalInspectionToolWrapper) { + GlobalInspectionToolWrapper global = (GlobalInspectionToolWrapper)toolWrapper; if (global.getTool().isGraphNeeded()) { refManager.findAllDeclarations(); } @@ -283,13 +285,12 @@ public class RedundantSuppressInspection extends GlobalInspectionTool{ return result.toArray(new ProblemDescriptor[result.size()]); } - protected InspectionTool[] getInspectionTools(PsiElement psiElement, InspectionManager manager) { - final ModifiableModel - model = InspectionProjectProfileManager.getInstance(manager.getProject()).getInspectionProfile().getModifiableModel(); + protected InspectionToolWrapper[] getInspectionTools(PsiElement psiElement, InspectionManager manager) { + ModifiableModel model = InspectionProjectProfileManager.getInstance(manager.getProject()).getInspectionProfile().getModifiableModel(); InspectionProfileWrapper profile = new InspectionProfileWrapper((InspectionProfile)model); profile.init(manager.getProject()); - return profile.getInspectionTools(psiElement); + return (InspectionToolWrapper[])profile.getInspectionTools(psiElement); } diff --git a/java/java-impl/src/com/intellij/codeInspection/dataFlow/DataFlowInspection.java b/java/java-impl/src/com/intellij/codeInspection/dataFlow/DataFlowInspection.java index 348d3dfc5fa5..c22571a65287 100644 --- a/java/java-impl/src/com/intellij/codeInspection/dataFlow/DataFlowInspection.java +++ b/java/java-impl/src/com/intellij/codeInspection/dataFlow/DataFlowInspection.java @@ -46,6 +46,7 @@ public class DataFlowInspection extends DataFlowInspectionBase { } private class OptionsPanel extends JPanel { + private final JCheckBox myIgnoreAssertions; private final JCheckBox mySuggestNullables; private final JCheckBox myDontReportTrueAsserts; @@ -77,6 +78,15 @@ public class DataFlowInspection extends DataFlowInspectionBase { DONT_REPORT_TRUE_ASSERT_STATEMENTS = myDontReportTrueAsserts.isSelected(); } }); + + myIgnoreAssertions = new JCheckBox("Ignore assert statements"); + myIgnoreAssertions.setSelected(IGNORE_ASSERT_STATEMENTS); + myIgnoreAssertions.getModel().addChangeListener(new ChangeListener() { + @Override + public void stateChanged(ChangeEvent e) { + IGNORE_ASSERT_STATEMENTS = myIgnoreAssertions.isSelected(); + } + }); gc.insets = new Insets(0, 0, 0, 0); gc.gridy = 0; @@ -121,6 +131,9 @@ public class DataFlowInspection extends DataFlowInspectionBase { gc.insets.left = 0; gc.gridy++; add(myDontReportTrueAsserts, gc); + + gc.gridy++; + add(myIgnoreAssertions, gc); } } diff --git a/java/java-impl/src/com/intellij/codeInspection/deadCode/UnusedDeclarationInspection.java b/java/java-impl/src/com/intellij/codeInspection/deadCode/UnusedDeclarationInspection.java index fa341a05bd20..633a6089d6e2 100644 --- a/java/java-impl/src/com/intellij/codeInspection/deadCode/UnusedDeclarationInspection.java +++ b/java/java-impl/src/com/intellij/codeInspection/deadCode/UnusedDeclarationInspection.java @@ -1100,8 +1100,9 @@ public class UnusedDeclarationInspection extends FilteringInspectionTool { super.updateContent(); } + @NotNull @Override - public InspectionNode createToolNode(@NotNull final InspectionRVContentProvider provider, final InspectionTreeNode parentNode, final boolean showStructure) { + public InspectionNode createToolNode(@NotNull final InspectionRVContentProvider provider, @NotNull final InspectionTreeNode parentNode, final boolean showStructure) { final InspectionNode toolNode = super.createToolNode(provider, parentNode, showStructure); final EntryPointsNode entryPointsNode = new EntryPointsNode(this); provider.appendToolNodeContent(entryPointsNode, toolNode, showStructure); diff --git a/java/java-impl/src/com/intellij/codeInspection/ex/GlobalJavaInspectionContextImpl.java b/java/java-impl/src/com/intellij/codeInspection/ex/GlobalJavaInspectionContextImpl.java index 86ff16ca9553..f3bdaf20aeea 100644 --- a/java/java-impl/src/com/intellij/codeInspection/ex/GlobalJavaInspectionContextImpl.java +++ b/java/java-impl/src/com/intellij/codeInspection/ex/GlobalJavaInspectionContextImpl.java @@ -23,7 +23,6 @@ package com.intellij.codeInspection.ex; import com.intellij.CommonBundle; import com.intellij.analysis.AnalysisScope; import com.intellij.codeInspection.*; -import com.intellij.codeInspection.deadCode.UnusedDeclarationInspection; import com.intellij.codeInspection.reference.*; import com.intellij.lang.StdLanguages; import com.intellij.openapi.application.ApplicationManager; @@ -413,32 +412,26 @@ public class GlobalJavaInspectionContextImpl extends GlobalJavaInspectionContext } @Override - public void performPreRunActivities(final List<Tools> globalTools, final List<Tools> localTools, - final GlobalInspectionContext context) { + public void performPreRunActivities(@NotNull final List<Tools> globalTools, + @NotNull final List<Tools> localTools, + @NotNull final GlobalInspectionContext context) { getEntryPointsManager(context.getRefManager()).resolveEntryPoints(context.getRefManager()); - for (int i = 0; i < globalTools.size(); i++) { - InspectionProfileEntry tool = globalTools.get(i).getTool(); - if (UnusedDeclarationInspection.SHORT_NAME.equals(tool.getShortName())) { - Collections.swap(globalTools, i, 0); - break; - } - } } @Override - public void performPostRunActivities(List<InspectionProfileEntry> needRepeatSearchRequest, final GlobalInspectionContext context) { + public void performPostRunActivities(@NotNull List<InspectionProfileEntry> needRepeatSearchRequest, @NotNull final GlobalInspectionContext context) { JobDescriptor progress = context.getStdJobDescriptors().FIND_EXTERNAL_USAGES; progress.setTotalAmount(getRequestCount()); do { processSearchRequests(context); - InspectionProfileEntry[] requestors = needRepeatSearchRequest.toArray(new InspectionProfileEntry[needRepeatSearchRequest.size()]); - for (InspectionProfileEntry requestor : requestors) { - if (requestor instanceof InspectionTool && - !((InspectionTool)requestor).queryExternalUsagesRequests(InspectionManager.getInstance(context.getProject()))) { - needRepeatSearchRequest.remove(requestor); + InspectionToolWrapper[] requestors = needRepeatSearchRequest.toArray(new InspectionToolWrapper[needRepeatSearchRequest.size()]); + for (InspectionToolWrapper wrapper : requestors) { + InspectionProfileEntry requestor = wrapper.getTool(); + if (requestor instanceof InspectionTool && !((InspectionTool)requestor).queryExternalUsagesRequests(InspectionManager.getInstance(context.getProject()))) { + needRepeatSearchRequest.remove(wrapper); } } int oldSearchRequestCount = progress.getTotalAmount(); diff --git a/java/java-impl/src/com/intellij/psi/formatter/java/JavaSpacePropertyProcessor.java b/java/java-impl/src/com/intellij/psi/formatter/java/JavaSpacePropertyProcessor.java index e81e167d3c45..1376f44c07ca 100644 --- a/java/java-impl/src/com/intellij/psi/formatter/java/JavaSpacePropertyProcessor.java +++ b/java/java-impl/src/com/intellij/psi/formatter/java/JavaSpacePropertyProcessor.java @@ -296,7 +296,12 @@ public class JavaSpacePropertyProcessor extends JavaElementVisitor { } else if (myRole1 == ChildRole.FIELD) { int lines = Math.max(getLinesAroundField(), getLinesAroundMethod()) + 1; - myResult = Spacing.createSpacing(0, mySettings.SPACE_BEFORE_CLASS_LBRACE ? 1 : 0, 0, true, mySettings.KEEP_BLANK_LINES_BEFORE_RBRACE, + // IJ has been keeping initialization block which starts at the same line as a field for a while. + // However, it's not convenient for a situation when particular code is created via PSI - it's easier to not bothering + // with whitespace elements when inserting, say, new initialization blocks. That's why we don't enforce new line + // only during explicit reformatting ('Reformat' action). + int minLineFeeds = FormatterUtil.isFormatterCalledExplicitly() ? 0 : 1; + myResult = Spacing.createSpacing(0, mySettings.SPACE_BEFORE_CLASS_LBRACE ? 1 : 0, 1, true, mySettings.KEEP_BLANK_LINES_BEFORE_RBRACE, lines); } else if (myRole1 == ChildRole.CLASS) { diff --git a/java/java-impl/src/com/intellij/psi/impl/PackagePrefixElementFinder.java b/java/java-impl/src/com/intellij/psi/impl/PackagePrefixElementFinder.java index 7f58413a051f..0f2df2db49ab 100644 --- a/java/java-impl/src/com/intellij/psi/impl/PackagePrefixElementFinder.java +++ b/java/java-impl/src/com/intellij/psi/impl/PackagePrefixElementFinder.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2011 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -68,7 +68,7 @@ public class PackagePrefixElementFinder extends PsiElementFinder implements Dumb final String qualifiedName = psiPackage.getQualifiedName(); for (final String prefix : myPackagePrefixIndex.getAllPackagePrefixes(scope)) { - if (StringUtil.isEmpty(qualifiedName) || StringUtil.startsWithConcatenationOf(prefix, qualifiedName, ".")) { + if (StringUtil.isEmpty(qualifiedName) || StringUtil.startsWithConcatenation(prefix, qualifiedName, ".")) { final int i = prefix.indexOf('.', qualifiedName.length() + 1); String childName = i >= 0 ? prefix.substring(0, i) : prefix; if (!packagesMap.containsKey(childName)) { @@ -83,7 +83,7 @@ public class PackagePrefixElementFinder extends PsiElementFinder implements Dumb public boolean packagePrefixExists(String packageQName) { for (final String prefix : myPackagePrefixIndex.getAllPackagePrefixes(null)) { - if (StringUtil.startsWithConcatenationOf(prefix, packageQName, ".") || prefix.equals(packageQName)) { + if (StringUtil.startsWithConcatenation(prefix, packageQName, ".") || prefix.equals(packageQName)) { return true; } } diff --git a/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/javadoc/JDMethodComment.java b/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/javadoc/JDMethodComment.java index 6fd664b1add7..67661e7c387b 100644 --- a/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/javadoc/JDMethodComment.java +++ b/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/javadoc/JDMethodComment.java @@ -25,19 +25,19 @@ import java.util.ArrayList; * @author Dmitry Skavish */ public class JDMethodComment extends JDParamListOwnerComment { - public JDMethodComment(CommentFormatter formatter) { - super(formatter); - } + + private static final @NonNls String THROWS_TAG = "@throws "; + private static final @NonNls String EXCEPTION_TAG = "@exception "; private String returnTag; private ArrayList<NameDesc> throwsList; - private static final @NonNls String THROWS_TAG = "@throws "; - private static final @NonNls String EXCEPTION_TAG = "@exception "; + public JDMethodComment(CommentFormatter formatter) { + super(formatter); + } @Override protected void generateSpecial(String prefix, @NonNls StringBuffer sb) { - super.generateSpecial(prefix, sb); if (returnTag != null) { @@ -56,27 +56,16 @@ public class JDMethodComment extends JDParamListOwnerComment { String tag = myFormatter.getSettings().JD_USE_THROWS_NOT_EXCEPTION ? THROWS_TAG : EXCEPTION_TAG; generateList(prefix, sb, throwsList, tag, myFormatter.getSettings().JD_ALIGN_EXCEPTION_COMMENTS, - myFormatter.getSettings().JD_MIN_EXCEPTION_NAME_LENGTH, - myFormatter.getSettings().JD_MAX_EXCEPTION_NAME_LENGTH, myFormatter.getSettings().JD_KEEP_EMPTY_EXCEPTION, myFormatter.getSettings().JD_PARAM_DESCRIPTION_ON_NEW_LINE ); } } - public String getReturnTag() { - return returnTag; - } - public void setReturnTag(String returnTag) { this.returnTag = returnTag; } - public void removeThrow(NameDesc nd) { - if (throwsList == null) return; - throwsList.remove(nd); - } - public ArrayList<NameDesc> getThrowsList() { return throwsList; } @@ -88,12 +77,4 @@ public class JDMethodComment extends JDParamListOwnerComment { throwsList.add(new NameDesc(className, description)); } - public NameDesc getThrow(String name) { - return getNameDesc(name, throwsList); - } - - public void setThrowsList(ArrayList<NameDesc> throwsList) { - this.throwsList = throwsList; - } - } diff --git a/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/javadoc/JDParamListOwnerComment.java b/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/javadoc/JDParamListOwnerComment.java index 64af28761b09..a063cf2935eb 100644 --- a/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/javadoc/JDParamListOwnerComment.java +++ b/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/javadoc/JDParamListOwnerComment.java @@ -22,6 +22,7 @@ package com.intellij.psi.impl.source.codeStyle.javadoc; import com.intellij.formatting.IndentInfo; import com.intellij.ide.highlighter.JavaFileType; +import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.codeStyle.CodeStyleSettings; import com.intellij.psi.codeStyle.CommonCodeStyleSettings; import org.jetbrains.annotations.NonNls; @@ -42,8 +43,6 @@ public class JDParamListOwnerComment extends JDComment{ int before = sb.length(); generateList(prefix, sb, parmsList, PARAM_TAG, myFormatter.getSettings().JD_ALIGN_PARAM_COMMENTS, - myFormatter.getSettings().JD_MIN_PARM_NAME_LENGTH, - myFormatter.getSettings().JD_MAX_PARM_NAME_LENGTH, myFormatter.getSettings().JD_KEEP_EMPTY_PARAMETER, myFormatter.getSettings().JD_PARAM_DESCRIPTION_ON_NEW_LINE ); @@ -60,15 +59,6 @@ public class JDParamListOwnerComment extends JDComment{ return getNameDesc(name, parmsList); } - public void removeParameter(NameDesc nd) { - if (parmsList == null) return; - parmsList.remove(nd); - } - - public ArrayList<NameDesc> getParmsList() { - return parmsList; - } - public void addParameter(String name, String description) { if (parmsList == null) { parmsList = new ArrayList<NameDesc>(); @@ -76,10 +66,6 @@ public class JDParamListOwnerComment extends JDComment{ parmsList.add(new NameDesc(name, description)); } - public void setParmsList(ArrayList<NameDesc> parmsList) { - this.parmsList = parmsList; - } - static NameDesc getNameDesc(String name, ArrayList<NameDesc> list) { if (list == null) return null; for (Object aList : list) { @@ -93,34 +79,37 @@ public class JDParamListOwnerComment extends JDComment{ * Generates parameters or exceptions * */ - protected void generateList(String prefix, StringBuffer sb, ArrayList<NameDesc> list, String tag, boolean align_comments, - int min_name_length, int max_name_length, boolean generate_empty_tags, boolean wrapDescription) + protected void generateList(String prefix, + StringBuffer sb, + ArrayList<NameDesc> list, + String tag, + boolean align_comments, + boolean generate_empty_tags, + boolean wrapDescription) { CodeStyleSettings settings = myFormatter.getSettings(); CommonCodeStyleSettings.IndentOptions indentOptions = settings.getIndentOptions(JavaFileType.INSTANCE); String continuationIndent = new IndentInfo(0, indentOptions.CONTINUATION_INDENT_SIZE, 0).generateNewWhiteSpace(indentOptions); + int max = 0; - if (align_comments && ! wrapDescription) { - for (Object aList : list) { - NameDesc nd = (NameDesc)aList; - int l = nd.name.length(); + + if (align_comments && !wrapDescription) { + for (NameDesc nd: list) { + int currentLength = nd.name.length(); if (isNull(nd.desc) && !generate_empty_tags) continue; - if (l > max && l <= max_name_length) max = l; + //finding longest parameter length + if (currentLength > max) { + max = currentLength; + } } } - max = Math.max(max, min_name_length); - - // create filler StringBuffer fill = new StringBuffer(prefix.length() + tag.length() + max + 1); fill.append(prefix); - int k = max + 1 + tag.length(); - for (int i = 0; i < k; i++) fill.append(' '); + StringUtil.repeatSymbol(fill, ' ', max + 1 + tag.length()); String wrapParametersPrefix = prefix + continuationIndent; - - for (Object aList1 : list) { - NameDesc nd = (NameDesc)aList1; + for (NameDesc nd : list) { if (isNull(nd.desc) && !generate_empty_tags) continue; if (wrapDescription && !isNull(nd.desc)) { sb.append(prefix).append(tag).append(nd.name).append("\n"); @@ -130,18 +119,9 @@ public class JDParamListOwnerComment extends JDComment{ sb.append(prefix); sb.append(tag); sb.append(nd.name); - - if (nd.name.length() > max_name_length) { - sb.append('\n'); - sb.append(myFormatter.getParser().splitIntoCLines(nd.desc, fill, true)); - } - else { - int len = max - nd.name.length() + 1; - for (int j = 0; j < len; j++) { - sb.append(' '); - } - sb.append(myFormatter.getParser().splitIntoCLines(nd.desc, fill, false)); - } + int spacesNumber = max + 1 - nd.name.length(); + StringUtil.repeatSymbol(sb, ' ', Math.max(0, spacesNumber)); + sb.append(myFormatter.getParser().splitIntoCLines(nd.desc, fill, false)); } else { sb.append(myFormatter.getParser().splitIntoCLines(tag + nd.name + " " + nd.desc, prefix, true)); diff --git a/java/java-impl/src/com/intellij/refactoring/changeSignature/JavaChangeSignatureDialog.java b/java/java-impl/src/com/intellij/refactoring/changeSignature/JavaChangeSignatureDialog.java index 647cd09f0806..d46fa203f7e0 100644 --- a/java/java-impl/src/com/intellij/refactoring/changeSignature/JavaChangeSignatureDialog.java +++ b/java/java-impl/src/com/intellij/refactoring/changeSignature/JavaChangeSignatureDialog.java @@ -30,7 +30,6 @@ import com.intellij.openapi.fileTypes.StdFileTypes; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.ui.ValidationInfo; -import com.intellij.openapi.ui.VerticalFlowLayout; import com.intellij.openapi.util.Computable; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.Ref; @@ -50,13 +49,13 @@ import com.intellij.refactoring.util.CanonicalTypes; import com.intellij.refactoring.util.RefactoringMessageUtil; import com.intellij.refactoring.util.RefactoringUtil; import com.intellij.ui.*; -import com.intellij.ui.components.JBLabel; import com.intellij.ui.table.JBTable; import com.intellij.ui.table.TableView; import com.intellij.ui.treeStructure.Tree; import com.intellij.util.*; import com.intellij.util.ui.DialogUtil; import com.intellij.util.ui.UIUtil; +import com.intellij.util.ui.table.JBListTable; import com.intellij.util.ui.table.JBTableRow; import com.intellij.util.ui.table.JBTableRowEditor; import org.jetbrains.annotations.NotNull; @@ -228,7 +227,6 @@ public class JavaChangeSignatureDialog extends ChangeSignatureDialogBase<Paramet @Override protected JComponent getRowPresentation(ParameterTableModelItemBase<ParameterInfoImpl> item, boolean selected, final boolean focused) { - final JPanel panel = new JPanel(new BorderLayout()); final String typeText = item.typeCodeFragment.getText(); final String separator = StringUtil.repeatSymbol(' ', getTypesMaxLength() - typeText.length() + 1); String text = typeText + separator + item.parameter.getName(); @@ -246,28 +244,7 @@ public class JavaChangeSignatureDialog extends ChangeSignatureDialogBase<Paramet if (!StringUtil.isEmpty(tail)) { text += " //" + tail; } - final EditorTextField field = new EditorTextField(" " + text, getProject(), getFileType()) { - @Override - protected boolean shouldHaveBorder() { - return false; - } - }; - - Font font = EditorColorsManager.getInstance().getGlobalScheme().getFont(EditorFontType.PLAIN); - font = new Font(font.getFontName(), font.getStyle(), 12); - field.setFont(font); - - if (selected && focused) { - panel.setBackground(UIUtil.getTableSelectionBackground()); - field.setAsRendererWithSelection(UIUtil.getTableSelectionBackground(), UIUtil.getTableSelectionForeground()); - } else { - panel.setBackground(UIUtil.getTableBackground()); - if (selected && !focused) { - panel.setBorder(new DottedBorder(UIUtil.getTableForeground())); - } - } - panel.add(field, BorderLayout.WEST); - return panel; + return JBListTable.createEditorTextFieldPresentation(getProject(), getFileType(), " " + text, selected, focused); } private int getTypesMaxLength() { @@ -311,43 +288,20 @@ public class JavaChangeSignatureDialog extends ChangeSignatureDialogBase<Paramet private EditorTextField myDefaultValueEditor; private JCheckBox myAnyVar; - class MyDocumentListener extends DocumentAdapter { - private int myColumn; - - private MyDocumentListener(int column) { - myColumn = column; - } - - @Override - public void documentChanged(DocumentEvent e) { - fireDocumentChanged(e, myColumn); - } - } - @Override public void prepareEditor(JTable table, int row) { setLayout(new BorderLayout()); - final JPanel typePanel = new JPanel(new VerticalFlowLayout(VerticalFlowLayout.TOP, 4, 2, true, false)); final Document document = PsiDocumentManager.getInstance(getProject()).getDocument(item.typeCodeFragment); myTypeEditor = new EditorTextField(document, getProject(), getFileType()); myTypeEditor.addDocumentListener(mySignatureUpdater); - final JBLabel typeLabel = new JBLabel("Type:", UIUtil.ComponentStyle.SMALL); - IJSwingUtilities.adjustComponentsOnMac(typeLabel, myTypeEditor); - typePanel.add(typeLabel); - typePanel.add(myTypeEditor); myTypeEditor.setPreferredWidth(t.getWidth() / 2); - myTypeEditor.addDocumentListener(new MyDocumentListener(0)); - add(typePanel, BorderLayout.WEST); + myTypeEditor.addDocumentListener(new RowEditorChangeListener(0)); + add(createLabeledPanel("Type:", myTypeEditor), BorderLayout.WEST); - final JPanel namePanel = new JPanel(new VerticalFlowLayout(VerticalFlowLayout.TOP, 4, 2, true, false)); myNameEditor = new EditorTextField(item.parameter.getName(), getProject(), getFileType()); myNameEditor.addDocumentListener(mySignatureUpdater); - myNameEditor.addDocumentListener(new MyDocumentListener(1)); - final JBLabel nameLabel = new JBLabel("Name:", UIUtil.ComponentStyle.SMALL); - IJSwingUtilities.adjustComponentsOnMac(nameLabel, myNameEditor); - namePanel.add(nameLabel); - namePanel.add(myNameEditor); - add(namePanel, BorderLayout.CENTER); + myNameEditor.addDocumentListener(new RowEditorChangeListener(1)); + add(createLabeledPanel("Name:", myNameEditor), BorderLayout.CENTER); new TextFieldCompletionProvider() { @Override @@ -377,17 +331,12 @@ public class JavaChangeSignatureDialog extends ChangeSignatureDialogBase<Paramet if (!item.isEllipsisType() && item.parameter.getOldIndex() == -1) { final JPanel additionalPanel = new JPanel(new BorderLayout()); - final JPanel defaultValuePanel = new JPanel(new VerticalFlowLayout(VerticalFlowLayout.TOP, 4, 2, true, false)); final Document doc = PsiDocumentManager.getInstance(getProject()).getDocument(item.defaultValueCodeFragment); myDefaultValueEditor = new EditorTextField(doc, getProject(), getFileType()); ((PsiExpressionCodeFragment)item.defaultValueCodeFragment).setExpectedType(getRowType(item)); - final JBLabel defaultValueLabel = new JBLabel("Default value:", UIUtil.ComponentStyle.SMALL); - IJSwingUtilities.adjustComponentsOnMac(defaultValueLabel, myDefaultValueEditor); - defaultValuePanel.add(defaultValueLabel); - defaultValuePanel.add(myDefaultValueEditor); myDefaultValueEditor.setPreferredWidth(t.getWidth() / 2); - myDefaultValueEditor.addDocumentListener(new MyDocumentListener(2)); - additionalPanel.add(defaultValuePanel, BorderLayout.WEST); + myDefaultValueEditor.addDocumentListener(new RowEditorChangeListener(2)); + additionalPanel.add(createLabeledPanel("Default value:", myDefaultValueEditor), BorderLayout.WEST); if (!isGenerateDelegate()) { myAnyVar = new JCheckBox("&Use Any Var"); diff --git a/java/java-impl/src/com/intellij/refactoring/copy/CopyClassesHandler.java b/java/java-impl/src/com/intellij/refactoring/copy/CopyClassesHandler.java index a081ff233ca6..b6e3be4b86bd 100644 --- a/java/java-impl/src/com/intellij/refactoring/copy/CopyClassesHandler.java +++ b/java/java-impl/src/com/intellij/refactoring/copy/CopyClassesHandler.java @@ -37,6 +37,7 @@ import com.intellij.refactoring.MoveDestination; import com.intellij.refactoring.RefactoringBundle; import com.intellij.refactoring.move.moveClassesOrPackages.MoveDirectoryWithClassesProcessor; import com.intellij.util.ArrayUtil; +import com.intellij.util.ArrayUtilRt; import com.intellij.util.IncorrectOperationException; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -183,14 +184,16 @@ public class CopyClassesHandler extends CopyHandlerDelegateBase { String className = null; boolean openInEditor = true; if (copyOneClass(classes)) { - final String commonPath = ArrayUtil.find(elements, classes.values().iterator().next()) == -1 ? normalizeRelativeMap(relativePathsMap) : null; + final String commonPath = + ArrayUtilRt.find(elements, classes.values().iterator().next()) == -1 ? normalizeRelativeMap(relativePathsMap) : null; CopyClassDialog dialog = new CopyClassDialog(classes.values().iterator().next()[0], defaultTargetDirectory, project, false){ @Override protected String getQualifiedName() { - if (commonPath != null && !commonPath.isEmpty()) { - return StringUtil.getQualifiedName(super.getQualifiedName(), commonPath.replaceAll("/", ".")); + final String qualifiedName = super.getQualifiedName(); + if (commonPath != null && !commonPath.isEmpty() && !qualifiedName.endsWith(commonPath)) { + return StringUtil.getQualifiedName(qualifiedName, commonPath.replaceAll("/", ".")); } - return super.getQualifiedName(); + return qualifiedName; } }; dialog.setTitle(RefactoringBundle.message("copy.handler.copy.class")); diff --git a/java/java-impl/src/com/intellij/refactoring/inline/InlineLocalHandler.java b/java/java-impl/src/com/intellij/refactoring/inline/InlineLocalHandler.java index 317117537ac7..3c90eecd11f9 100644 --- a/java/java-impl/src/com/intellij/refactoring/inline/InlineLocalHandler.java +++ b/java/java-impl/src/com/intellij/refactoring/inline/InlineLocalHandler.java @@ -195,7 +195,7 @@ public class InlineLocalHandler extends JavaInlineActionHandler { } } - final PsiElement writeAccess = checkRefsInAugmentedAssignmentOrUnaryModified(refsToInline); + final PsiElement writeAccess = checkRefsInAugmentedAssignmentOrUnaryModified(refsToInline, defToInline); if (writeAccess != null) { HighlightManager.getInstance(project).addOccurrenceHighlights(editor, new PsiElement[]{writeAccess}, writeAttributes, true, null); String message = RefactoringBundle.getCannotRefactorMessage(RefactoringBundle.message("variable.is.accessed.for.writing", localName)); @@ -273,12 +273,13 @@ public class InlineLocalHandler extends JavaInlineActionHandler { } @Nullable - public static PsiElement checkRefsInAugmentedAssignmentOrUnaryModified(final PsiElement[] refsToInline) { + public static PsiElement checkRefsInAugmentedAssignmentOrUnaryModified(final PsiElement[] refsToInline, PsiElement defToInline) { for (PsiElement element : refsToInline) { PsiElement parent = element.getParent(); if (parent instanceof PsiArrayAccessExpression) { if (((PsiArrayAccessExpression)parent).getIndexExpression() == element) continue; + if (defToInline instanceof PsiExpression && !(defToInline instanceof PsiNewExpression)) continue; element = parent; parent = parent.getParent(); } diff --git a/java/java-impl/src/com/intellij/refactoring/inline/InlineParameterHandler.java b/java/java-impl/src/com/intellij/refactoring/inline/InlineParameterHandler.java index e22f0b86e2cd..58d4d1eb282d 100644 --- a/java/java-impl/src/com/intellij/refactoring/inline/InlineParameterHandler.java +++ b/java/java-impl/src/com/intellij/refactoring/inline/InlineParameterHandler.java @@ -125,7 +125,7 @@ public class InlineParameterHandler extends JavaInlineActionHandler { if (rExpr != null) { final PsiElement[] refs = DefUseUtil.getRefs(codeBlock, psiParameter, refExpr); - if (InlineLocalHandler.checkRefsInAugmentedAssignmentOrUnaryModified(refs) == null) { + if (InlineLocalHandler.checkRefsInAugmentedAssignmentOrUnaryModified(refs, def) == null) { new WriteCommandAction(project) { @Override protected void run(Result result) throws Throwable { diff --git a/java/java-impl/src/com/intellij/refactoring/move/moveInner/MoveInnerImpl.java b/java/java-impl/src/com/intellij/refactoring/move/moveInner/MoveInnerImpl.java index fe37b7d3cf82..c33cc48b6864 100644 --- a/java/java-impl/src/com/intellij/refactoring/move/moveInner/MoveInnerImpl.java +++ b/java/java-impl/src/com/intellij/refactoring/move/moveInner/MoveInnerImpl.java @@ -34,14 +34,16 @@ public class MoveInnerImpl { public static final String REFACTORING_NAME = RefactoringBundle.message("move.inner.to.upper.level.title"); - public static void doMove(final Project project, PsiElement[] elements, final MoveCallback moveCallback) { + public static void doMove(final Project project, PsiElement[] elements, final MoveCallback moveCallback, @Nullable PsiElement targetContainer) { if (elements.length != 1) return; final PsiClass aClass = (PsiClass) elements[0]; boolean condition = aClass.getContainingClass() != null; LOG.assertTrue(condition); if (!CommonRefactoringUtil.checkReadOnlyStatus(project, aClass)) return; - final PsiElement targetContainer = getTargetContainer(aClass, true); + if (targetContainer == null) { + targetContainer = getTargetContainer(aClass, true); + } if (targetContainer == null) return; final MoveInnerDialog dialog = new MoveInnerDialog( diff --git a/java/java-impl/src/com/intellij/refactoring/move/moveInner/MoveInnerProcessor.java b/java/java-impl/src/com/intellij/refactoring/move/moveInner/MoveInnerProcessor.java index 35ca3e256ee2..ddff1f089669 100644 --- a/java/java-impl/src/com/intellij/refactoring/move/moveInner/MoveInnerProcessor.java +++ b/java/java-impl/src/com/intellij/refactoring/move/moveInner/MoveInnerProcessor.java @@ -164,7 +164,7 @@ public class MoveInnerProcessor extends BaseRefactoringProcessor { if (myParameterNameOuterClass != null) { // pass outer as a parameter field = factory.createField(myFieldNameOuterClass, factory.createType(myOuterClass)); - field = (PsiField)myInnerClass.add(field); + field = addOuterField(field); myInnerClass = field.getContainingClass(); addFieldInitializationToConstructors(myInnerClass, field, myParameterNameOuterClass); } @@ -296,6 +296,19 @@ public class MoveInnerProcessor extends BaseRefactoringProcessor { } } + private PsiField addOuterField(PsiField field) { + final PsiMember[] members = PsiTreeUtil.getChildrenOfType(myInnerClass, PsiMember.class); + if (members != null) { + for (PsiMember member : members) { + if (!member.hasModifierProperty(PsiModifier.STATIC)) { + return (PsiField)myInnerClass.addBefore(field, member); + } + } + } + + return (PsiField)myInnerClass.add(field); + } + protected void performPsiSpoilingRefactoring() { if (myNonCodeUsages != null) { RenameUtil.renameNonCodeUsages(myProject, myNonCodeUsages); diff --git a/java/java-impl/src/com/intellij/refactoring/move/moveInner/MoveInnerToUpperHandler.java b/java/java-impl/src/com/intellij/refactoring/move/moveInner/MoveInnerToUpperHandler.java index f807e89d4c64..706fc7954b27 100644 --- a/java/java-impl/src/com/intellij/refactoring/move/moveInner/MoveInnerToUpperHandler.java +++ b/java/java-impl/src/com/intellij/refactoring/move/moveInner/MoveInnerToUpperHandler.java @@ -17,6 +17,7 @@ package com.intellij.refactoring.move.moveInner; import com.intellij.featureStatistics.FeatureUsageTracker; import com.intellij.openapi.actionSystem.DataContext; +import com.intellij.openapi.actionSystem.LangDataKeys; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiClass; @@ -35,9 +36,7 @@ public class MoveInnerToUpperHandler extends MoveHandlerDelegate { public boolean canMove(final PsiElement[] elements, @Nullable final PsiElement targetContainer) { if (elements.length != 1) return false; PsiElement element = elements [0]; - return isNonStaticInnerClass(element) && - (targetContainer == null || targetContainer.equals(MoveInnerImpl.getTargetContainer((PsiClass)elements[0], false))); - + return isNonStaticInnerClass(element); } private static boolean isNonStaticInnerClass(final PsiElement element) { @@ -46,7 +45,7 @@ public class MoveInnerToUpperHandler extends MoveHandlerDelegate { } public void doMove(final Project project, final PsiElement[] elements, final PsiElement targetContainer, final MoveCallback callback) { - MoveInnerImpl.doMove(project, elements, callback); + MoveInnerImpl.doMove(project, elements, callback, targetContainer); } public boolean tryToMove(final PsiElement element, final Project project, final DataContext dataContext, final PsiReference reference, @@ -60,7 +59,7 @@ public class MoveInnerToUpperHandler extends MoveHandlerDelegate { RefactoringBundle.message("move.title"), null); return true; } - MoveInnerImpl.doMove(project, new PsiElement[]{aClass}, null); + MoveInnerImpl.doMove(project, new PsiElement[]{aClass}, null, LangDataKeys.TARGET_PSI_ELEMENT.getData(dataContext)); return true; } return false; diff --git a/java/java-impl/src/com/intellij/refactoring/move/moveInner/MoveInnerToUpperOrMembersHandler.java b/java/java-impl/src/com/intellij/refactoring/move/moveInner/MoveInnerToUpperOrMembersHandler.java index 823ee22a1687..1993c3c563f9 100644 --- a/java/java-impl/src/com/intellij/refactoring/move/moveInner/MoveInnerToUpperOrMembersHandler.java +++ b/java/java-impl/src/com/intellij/refactoring/move/moveInner/MoveInnerToUpperOrMembersHandler.java @@ -17,6 +17,7 @@ package com.intellij.refactoring.move.moveInner; import com.intellij.featureStatistics.FeatureUsageTracker; import com.intellij.openapi.actionSystem.DataContext; +import com.intellij.openapi.actionSystem.LangDataKeys; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.DialogWrapper; @@ -39,8 +40,7 @@ public class MoveInnerToUpperOrMembersHandler extends MoveHandlerDelegate { public boolean canMove(final PsiElement[] elements, @Nullable final PsiElement targetContainer) { if (elements.length != 1) return false; PsiElement element = elements [0]; - return isStaticInnerClass(element) && - (targetContainer == null || targetContainer.equals(MoveInnerImpl.getTargetContainer((PsiClass)elements[0], false))); + return isStaticInnerClass(element); } private static boolean isStaticInnerClass(final PsiElement element) { @@ -70,7 +70,7 @@ public class MoveInnerToUpperOrMembersHandler extends MoveHandlerDelegate { if (dialog.isOK()) { final MoveHandlerDelegate moveHandlerDelegate = dialog.getRefactoringHandler(); if (moveHandlerDelegate != null) { - moveHandlerDelegate.doMove(project, new PsiElement[] { aClass }, null, null); + moveHandlerDelegate.doMove(project, new PsiElement[] { aClass }, LangDataKeys.TARGET_PSI_ELEMENT.getData(dataContext), null); } } return true; diff --git a/java/java-impl/src/com/intellij/refactoring/move/moveMembers/MoveJavaMemberHandler.java b/java/java-impl/src/com/intellij/refactoring/move/moveMembers/MoveJavaMemberHandler.java index ea39904f5a1d..4dda4d75a304 100644 --- a/java/java-impl/src/com/intellij/refactoring/move/moveMembers/MoveJavaMemberHandler.java +++ b/java/java-impl/src/com/intellij/refactoring/move/moveMembers/MoveJavaMemberHandler.java @@ -193,7 +193,7 @@ public class MoveJavaMemberHandler implements MoveMemberHandler { } } else { // no qualifier - if (usage.qualifierClass != null && PsiTreeUtil.getParentOfType(refExpr, PsiSwitchLabelStatement.class) == null) { + if (usage.qualifierClass != null && (!usage.qualifierClass.isEnum() || PsiTreeUtil.getParentOfType(refExpr, PsiSwitchLabelStatement.class) == null)) { changeQualifier(refExpr, usage.qualifierClass, usage.member); } } diff --git a/java/java-indexing-impl/src/com/intellij/psi/impl/java/stubs/index/JavaAnonymousClassBaseRefOccurenceIndex.java b/java/java-indexing-impl/src/com/intellij/psi/impl/java/stubs/index/JavaAnonymousClassBaseRefOccurenceIndex.java index 2521522325c9..b2d61c4a9522 100644 --- a/java/java-indexing-impl/src/com/intellij/psi/impl/java/stubs/index/JavaAnonymousClassBaseRefOccurenceIndex.java +++ b/java/java-indexing-impl/src/com/intellij/psi/impl/java/stubs/index/JavaAnonymousClassBaseRefOccurenceIndex.java @@ -24,6 +24,7 @@ import com.intellij.psi.PsiAnonymousClass; import com.intellij.psi.impl.search.JavaSourceFilterScope; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.stubs.StringStubIndexExtension; +import com.intellij.psi.stubs.StubIndex; import com.intellij.psi.stubs.StubIndexKey; import org.jetbrains.annotations.NotNull; @@ -45,6 +46,6 @@ public class JavaAnonymousClassBaseRefOccurenceIndex extends StringStubIndexExte @Override public Collection<PsiAnonymousClass> get(final String s, final Project project, @NotNull final GlobalSearchScope scope) { - return super.get(s, project, new JavaSourceFilterScope(scope)); + return StubIndex.getInstance().safeGet(getKey(), s, project, new JavaSourceFilterScope(scope), PsiAnonymousClass.class); } }
\ No newline at end of file diff --git a/java/java-indexing-impl/src/com/intellij/psi/impl/java/stubs/index/JavaFieldNameIndex.java b/java/java-indexing-impl/src/com/intellij/psi/impl/java/stubs/index/JavaFieldNameIndex.java index 54eb0edf6a05..e00f2bf3ea9f 100644 --- a/java/java-indexing-impl/src/com/intellij/psi/impl/java/stubs/index/JavaFieldNameIndex.java +++ b/java/java-indexing-impl/src/com/intellij/psi/impl/java/stubs/index/JavaFieldNameIndex.java @@ -24,6 +24,7 @@ import com.intellij.psi.PsiField; import com.intellij.psi.impl.search.JavaSourceFilterScope; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.stubs.StringStubIndexExtension; +import com.intellij.psi.stubs.StubIndex; import com.intellij.psi.stubs.StubIndexKey; import org.jetbrains.annotations.NotNull; @@ -44,6 +45,6 @@ public class JavaFieldNameIndex extends StringStubIndexExtension<PsiField> { @Override public Collection<PsiField> get(final String s, final Project project, @NotNull final GlobalSearchScope scope) { - return super.get(s, project, new JavaSourceFilterScope(scope)); + return StubIndex.getInstance().safeGet(getKey(), s, project, new JavaSourceFilterScope(scope), PsiField.class); } }
\ No newline at end of file diff --git a/java/java-indexing-impl/src/com/intellij/psi/impl/java/stubs/index/JavaMethodNameIndex.java b/java/java-indexing-impl/src/com/intellij/psi/impl/java/stubs/index/JavaMethodNameIndex.java index a92856f2564c..51d28ad4ae93 100644 --- a/java/java-indexing-impl/src/com/intellij/psi/impl/java/stubs/index/JavaMethodNameIndex.java +++ b/java/java-indexing-impl/src/com/intellij/psi/impl/java/stubs/index/JavaMethodNameIndex.java @@ -24,6 +24,7 @@ import com.intellij.psi.PsiMethod; import com.intellij.psi.impl.search.JavaSourceFilterScope; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.stubs.StringStubIndexExtension; +import com.intellij.psi.stubs.StubIndex; import com.intellij.psi.stubs.StubIndexKey; import org.jetbrains.annotations.NotNull; @@ -44,6 +45,6 @@ public class JavaMethodNameIndex extends StringStubIndexExtension<PsiMethod> { @Override public Collection<PsiMethod> get(final String s, final Project project, @NotNull final GlobalSearchScope scope) { - return super.get(s, project, new JavaSourceFilterScope(scope)); + return StubIndex.getInstance().safeGet(getKey(), s, project, new JavaSourceFilterScope(scope), PsiMethod.class); } }
\ No newline at end of file diff --git a/java/java-indexing-impl/src/com/intellij/psi/impl/java/stubs/index/JavaSuperClassNameOccurenceIndex.java b/java/java-indexing-impl/src/com/intellij/psi/impl/java/stubs/index/JavaSuperClassNameOccurenceIndex.java index a70b7ea700d4..e1e88192809c 100644 --- a/java/java-indexing-impl/src/com/intellij/psi/impl/java/stubs/index/JavaSuperClassNameOccurenceIndex.java +++ b/java/java-indexing-impl/src/com/intellij/psi/impl/java/stubs/index/JavaSuperClassNameOccurenceIndex.java @@ -24,6 +24,7 @@ import com.intellij.psi.PsiReferenceList; import com.intellij.psi.impl.search.JavaSourceFilterScope; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.stubs.StringStubIndexExtension; +import com.intellij.psi.stubs.StubIndex; import com.intellij.psi.stubs.StubIndexKey; import org.jetbrains.annotations.NotNull; @@ -45,7 +46,7 @@ public class JavaSuperClassNameOccurenceIndex extends StringStubIndexExtension<P @Override public Collection<PsiReferenceList> get(final String s, final Project project, @NotNull final GlobalSearchScope scope) { - return super.get(s, project, new JavaSourceFilterScope(scope)); + return StubIndex.getInstance().safeGet(getKey(), s, project, new JavaSourceFilterScope(scope), PsiReferenceList.class); } @Override diff --git a/java/java-psi-api/src/com/intellij/psi/GenericsUtil.java b/java/java-psi-api/src/com/intellij/psi/GenericsUtil.java index 7c256977bd70..481f80981eed 100644 --- a/java/java-psi-api/src/com/intellij/psi/GenericsUtil.java +++ b/java/java-psi-api/src/com/intellij/psi/GenericsUtil.java @@ -23,7 +23,7 @@ import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.util.InheritanceUtil; import com.intellij.psi.util.PsiUtil; import com.intellij.psi.util.TypeConversionUtil; -import com.intellij.util.containers.*; +import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.HashMap; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -39,7 +39,8 @@ public class GenericsUtil { private GenericsUtil() {} - public static PsiType getGreatestLowerBound(PsiType type1, PsiType type2) { + public static PsiType getGreatestLowerBound(@Nullable PsiType type1, @Nullable PsiType type2) { + if (type1 == null || type2 == null) return null; return PsiIntersectionType.createIntersection(type1, type2); } @@ -185,18 +186,21 @@ public class GenericsUtil { public static PsiClass[] getLeastUpperClasses(PsiClass aClass, PsiClass bClass) { if (InheritanceUtil.isInheritorOrSelf(aClass, bClass, true)) return new PsiClass[]{bClass}; Set<PsiClass> supers = new LinkedHashSet<PsiClass>(); - getLeastUpperClassesInner(aClass, bClass, supers); + Set<PsiClass> visited = new HashSet<PsiClass>(); + getLeastUpperClassesInner(aClass, bClass, supers, visited); return supers.toArray(new PsiClass[supers.size()]); } - private static void getLeastUpperClassesInner(PsiClass aClass, PsiClass bClass, Set<PsiClass> supers) { + private static void getLeastUpperClassesInner(PsiClass aClass, PsiClass bClass, Set<PsiClass> supers, Set<PsiClass> visited) { if (bClass.isInheritor(aClass, true)) { addSuper(supers, aClass); } else { final PsiClass[] aSupers = aClass.getSupers(); for (PsiClass aSuper : aSupers) { - getLeastUpperClassesInner(aSuper, bClass, supers); + if (visited.add(aSuper)) { + getLeastUpperClassesInner(aSuper, bClass, supers, visited); + } } } } diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/PsiClassImplUtil.java b/java/java-psi-impl/src/com/intellij/psi/impl/PsiClassImplUtil.java index 71dff8a0704e..a0f3e9a3e045 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/PsiClassImplUtil.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/PsiClassImplUtil.java @@ -570,8 +570,8 @@ public class PsiClassImplUtil { if (!processor.execute(candidateMethod, state.put(PsiSubstitutor.KEY, finalSubstitutor))) { resolved = true; } - if (resolved) return false; } + if (resolved) return false; if (visited != null) { for (Pair<PsiMember, PsiSubstitutor> aList : list) { diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/PsiSubstitutorImpl.java b/java/java-psi-impl/src/com/intellij/psi/impl/PsiSubstitutorImpl.java index c7cd48afa8b7..917e5ead0d25 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/PsiSubstitutorImpl.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/PsiSubstitutorImpl.java @@ -291,7 +291,7 @@ public class PsiSubstitutorImpl implements PsiSubstitutor { return null; } PsiClassType result = JavaPsiFacade.getElementFactory(aClass.getProject()).createType(aClass, createSubstitutor(hashMap), classType.getLanguageLevel()); - assert result.isValid(); + PsiUtil.ensureValidType(result); return result; } diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/PsiJavaFileBaseImpl.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/PsiJavaFileBaseImpl.java index e71bf636fa02..47a1b8e3f159 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/source/PsiJavaFileBaseImpl.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/PsiJavaFileBaseImpl.java @@ -142,7 +142,9 @@ public abstract class PsiJavaFileBaseImpl extends PsiFileImpl implements PsiJava StubElement<?> stub = getStub(); if (stub != null) { PsiImportList[] nodes = stub.getChildrenByType(JavaStubElementTypes.IMPORT_LIST, PsiImportList.ARRAY_FACTORY); - assert nodes.length == 1 : stub + "; " + stub.getChildrenStubs(); + if (nodes.length != 1) { + reportStubAstMismatch(stub + "; " + stub.getChildrenStubs(), getStubTree(), PsiDocumentManager.getInstance(getProject()).getCachedDocument(this)); + } return nodes[0]; } diff --git a/java/java-psi-impl/src/com/intellij/refactoring/util/duplicates/DuplicatesFinder.java b/java/java-psi-impl/src/com/intellij/refactoring/util/duplicates/DuplicatesFinder.java index d44b9d840cdc..75403848cbe8 100644 --- a/java/java-psi-impl/src/com/intellij/refactoring/util/duplicates/DuplicatesFinder.java +++ b/java/java-psi-impl/src/com/intellij/refactoring/util/duplicates/DuplicatesFinder.java @@ -394,6 +394,12 @@ public class DuplicatesFinder { match.registerReturnValue(new ContinueReturnValue()); } else if (pattern instanceof PsiBreakStatement) { match.registerReturnValue(new BreakReturnValue()); + }else if (pattern instanceof PsiMethodCallExpression) { + final PsiMethod patternMethod = ((PsiMethodCallExpression)pattern).resolveMethod(); + final PsiMethod candidateMethod = ((PsiMethodCallExpression)candidate).resolveMethod(); + if (patternMethod != null && candidateMethod != null) { + if (!MethodSignatureUtil.areSignaturesEqual(patternMethod, candidateMethod)) return false; + } } else if (pattern instanceof PsiReferenceExpression) { final PsiReferenceExpression patternRefExpr = (PsiReferenceExpression)pattern; final PsiReferenceExpression candidateRefExpr = (PsiReferenceExpression)candidate; diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/SOEInLeastUpperClass.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/SOEInLeastUpperClass.java new file mode 100644 index 000000000000..70ad2666c619 --- /dev/null +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/SOEInLeastUpperClass.java @@ -0,0 +1,12 @@ +<error descr="Cyclic inheritance involving 'A'">interface A extends A</error> {} +interface B {} + +<error descr="Cyclic inheritance involving 'A'">class T implements A, B</error>{ + <T1> T1 foo(A a, B b) { + return null; + } + + void bar (boolean a, A a1, B b1){ + <error descr="Incompatible types. Found: 'java.lang.Object', required: 'T'">T t = a ? a1 : b1;</error> + } +} diff --git a/java/java-tests/testData/compileServer/incremental/markDirty/recompileTwinDependencies.log b/java/java-tests/testData/compileServer/incremental/markDirty/recompileTwinDependencies.log index 4badc88cf13a..1c40adc4f7fb 100644 --- a/java/java-tests/testData/compileServer/incremental/markDirty/recompileTwinDependencies.log +++ b/java/java-tests/testData/compileServer/incremental/markDirty/recompileTwinDependencies.log @@ -8,3 +8,9 @@ Compiling files: src/package2/A.java src/package2/C.java End of files +Cleaning output files: +out/production/RecompileTwinDependencies/com/B.class +End of files +Compiling files: +src/com/B.java +End of files diff --git a/java/java-tests/testData/inspection/dataFlow/fixture/IgnoreAssertions.java b/java/java-tests/testData/inspection/dataFlow/fixture/IgnoreAssertions.java new file mode 100644 index 000000000000..5fa6f05289e6 --- /dev/null +++ b/java/java-tests/testData/inspection/dataFlow/fixture/IgnoreAssertions.java @@ -0,0 +1,10 @@ +class Foo { + Object getObjectFromElsewhere() { return null; } + void foo() { + Object object = getObjectFromElsewhere(); + assert (object != null); + if (object != null) { + return; + } + } +}
\ No newline at end of file diff --git a/java/java-tests/testData/refactoring/extractMethod/OverloadedMethods.java b/java/java-tests/testData/refactoring/extractMethod/OverloadedMethods.java new file mode 100644 index 000000000000..a951ea0568bf --- /dev/null +++ b/java/java-tests/testData/refactoring/extractMethod/OverloadedMethods.java @@ -0,0 +1,21 @@ +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + + +public class Test { + public void myTest(List list, String s1, String s2) { + } + + public void myTest(Collection list, String s1, String s2) { + } + + public void usage() { + List list = new ArrayList(); + String aa = "AA"; + String bb = "bb"; + myTest(list, aa, bb); + Collection col = new ArrayList(); + <selection>myTest(col, aa, bb);</selection> + } +}
\ No newline at end of file diff --git a/java/java-tests/testData/refactoring/extractMethod/OverloadedMethods_after.java b/java/java-tests/testData/refactoring/extractMethod/OverloadedMethods_after.java new file mode 100644 index 000000000000..dd8e4c5ae446 --- /dev/null +++ b/java/java-tests/testData/refactoring/extractMethod/OverloadedMethods_after.java @@ -0,0 +1,25 @@ +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + + +public class Test { + public void myTest(List list, String s1, String s2) { + } + + public void myTest(Collection list, String s1, String s2) { + } + + public void usage() { + List list = new ArrayList(); + String aa = "AA"; + String bb = "bb"; + myTest(list, aa, bb); + Collection col = new ArrayList(); + newMethod(aa, bb, col); + } + + private void newMethod(String aa, String bb, Collection col) { + myTest(col, aa, bb); + } +}
\ No newline at end of file diff --git a/java/java-tests/testData/refactoring/inlineLocal/ArrayMethodCallInitialized.java b/java/java-tests/testData/refactoring/inlineLocal/ArrayMethodCallInitialized.java new file mode 100644 index 000000000000..aa7c17cf6fb1 --- /dev/null +++ b/java/java-tests/testData/refactoring/inlineLocal/ArrayMethodCallInitialized.java @@ -0,0 +1,11 @@ +public class A { + + public void testInlineRefactoring() { + int[] array = ar(); + arr<caret>ay[1] = 22; + } + + private int[] ar() { + return new int[0]; + } +}
\ No newline at end of file diff --git a/java/java-tests/testData/refactoring/inlineLocal/ArrayMethodCallInitialized.java.after b/java/java-tests/testData/refactoring/inlineLocal/ArrayMethodCallInitialized.java.after new file mode 100644 index 000000000000..72d6b9f2b18e --- /dev/null +++ b/java/java-tests/testData/refactoring/inlineLocal/ArrayMethodCallInitialized.java.after @@ -0,0 +1,10 @@ +public class A { + + public void testInlineRefactoring() { + ar()[1] = 22; + } + + private int[] ar() { + return new int[0]; + } +}
\ No newline at end of file diff --git a/java/java-tests/testData/refactoring/moveInner/scr30106/after/p/B.java b/java/java-tests/testData/refactoring/moveInner/scr30106/after/p/B.java index 6fa9162793ba..32301dba7aa1 100644 --- a/java/java-tests/testData/refactoring/moveInner/scr30106/after/p/B.java +++ b/java/java-tests/testData/refactoring/moveInner/scr30106/after/p/B.java @@ -1,12 +1,12 @@ package p; public class B extends X { + private A outer; + { method(); } - private A outer; - public B(A outer) { this.outer = outer; } diff --git a/java/java-tests/testData/refactoring/moveMembers/stringConstantFromCaseStatement/after/A.java b/java/java-tests/testData/refactoring/moveMembers/stringConstantFromCaseStatement/after/A.java new file mode 100644 index 000000000000..c77f0cda48d3 --- /dev/null +++ b/java/java-tests/testData/refactoring/moveMembers/stringConstantFromCaseStatement/after/A.java @@ -0,0 +1,3 @@ +public class A { + public static final String ONE = ""; +}
\ No newline at end of file diff --git a/java/java-tests/testData/refactoring/moveMembers/stringConstantFromCaseStatement/after/B.java b/java/java-tests/testData/refactoring/moveMembers/stringConstantFromCaseStatement/after/B.java new file mode 100644 index 000000000000..6ad677589b48 --- /dev/null +++ b/java/java-tests/testData/refactoring/moveMembers/stringConstantFromCaseStatement/after/B.java @@ -0,0 +1,8 @@ +public class B { + void foo(String s) { + switch (i) { + case A.ONE : + break; + } + } +}
\ No newline at end of file diff --git a/java/java-tests/testData/refactoring/moveMembers/stringConstantFromCaseStatement/before/A.java b/java/java-tests/testData/refactoring/moveMembers/stringConstantFromCaseStatement/before/A.java new file mode 100644 index 000000000000..61ff2abcc95e --- /dev/null +++ b/java/java-tests/testData/refactoring/moveMembers/stringConstantFromCaseStatement/before/A.java @@ -0,0 +1,2 @@ +public class A { +}
\ No newline at end of file diff --git a/java/java-tests/testData/refactoring/moveMembers/stringConstantFromCaseStatement/before/B.java b/java/java-tests/testData/refactoring/moveMembers/stringConstantFromCaseStatement/before/B.java new file mode 100644 index 000000000000..5ae2faed9bb6 --- /dev/null +++ b/java/java-tests/testData/refactoring/moveMembers/stringConstantFromCaseStatement/before/B.java @@ -0,0 +1,9 @@ +public class B { + public static final String ONE = ""; + void foo(String s) { + switch (i) { + case ONE : + break; + } + } +}
\ No newline at end of file diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/GenericsHighlightingTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/GenericsHighlightingTest.java index fca092470feb..2d42a723066e 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/GenericsHighlightingTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/GenericsHighlightingTest.java @@ -287,6 +287,7 @@ public class GenericsHighlightingTest extends LightDaemonAnalyzerTestCase { public void testIDEA104100() {doTest(LanguageLevel.JDK_1_7, JavaSdkVersion.JDK_1_7, false);} public void testIDEA104160() {doTest(LanguageLevel.JDK_1_7, JavaSdkVersion.JDK_1_7, false);} + public void testSOEInLeastUpperClass() {doTest(LanguageLevel.JDK_1_7, JavaSdkVersion.JDK_1_7, false);} public void testJavaUtilCollections_NoVerify() throws Exception { PsiClass collectionsClass = getJavaFacade().findClass("java.util.Collections", GlobalSearchScope.moduleWithLibrariesScope(getModule())); diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/RemoveRedundantUncheckedSuppressionTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/RemoveRedundantUncheckedSuppressionTest.java index f341e1d6363c..1101f6762ee9 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/RemoveRedundantUncheckedSuppressionTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/RemoveRedundantUncheckedSuppressionTest.java @@ -16,7 +16,7 @@ package com.intellij.codeInsight.daemon.quickFix; import com.intellij.codeInspection.*; -import com.intellij.codeInspection.ex.InspectionTool; +import com.intellij.codeInspection.ex.InspectionToolWrapper; import com.intellij.codeInspection.ex.LocalInspectionToolWrapper; import com.intellij.codeInspection.uncheckedWarnings.UncheckedWarningLocalInspection; import com.intellij.psi.*; @@ -32,8 +32,8 @@ public class RemoveRedundantUncheckedSuppressionTest extends LightQuickFixTestCa final UncheckedWarningLocalInspection warningLocalInspection = new UncheckedWarningLocalInspection(); final RedundantSuppressInspection inspection = new RedundantSuppressInspection(){ @Override - protected InspectionTool[] getInspectionTools(PsiElement psiElement, InspectionManager manager) { - return new InspectionTool[]{ + protected InspectionToolWrapper[] getInspectionTools(PsiElement psiElement, InspectionManager manager) { + return new InspectionToolWrapper[]{ new LocalInspectionToolWrapper(varargsInspection), new LocalInspectionToolWrapper(warningLocalInspection) }; diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/Suppress15InspectionsTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/Suppress15InspectionsTest.java index 13ebabffecf8..2ab3462a091e 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/Suppress15InspectionsTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/Suppress15InspectionsTest.java @@ -1,4 +1,3 @@ - /* * Copyright 2000-2012 JetBrains s.r.o. * @@ -19,7 +18,6 @@ package com.intellij.codeInsight.daemon.quickFix; import com.intellij.codeInspection.LocalInspectionTool; import com.intellij.codeInspection.accessStaticViaInstance.AccessStaticViaInstance; import com.intellij.codeInspection.deprecation.DeprecationInspection; -import com.intellij.codeInspection.ex.GlobalInspectionToolWrapper; import com.intellij.codeInspection.javaDoc.JavaDocReferenceInspection; import com.intellij.codeInspection.sillyAssignment.SillyAssignmentInspection; import com.intellij.codeInspection.uncheckedWarnings.UncheckedWarningLocalInspection; @@ -33,7 +31,7 @@ public class Suppress15InspectionsTest extends LightQuickFixTestCase { @Override protected void setUp() throws Exception { super.setUp(); - enableInspectionTool(new GlobalInspectionToolWrapper(new UnusedParametersInspection())); + enableInspectionTool(new UnusedParametersInspection()); } @NotNull diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/template/LiveTemplateTest.groovy b/java/java-tests/testSrc/com/intellij/codeInsight/template/LiveTemplateTest.groovy index d3a746668fcf..3ab71c0b61fa 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/template/LiveTemplateTest.groovy +++ b/java/java-tests/testSrc/com/intellij/codeInsight/template/LiveTemplateTest.groovy @@ -605,4 +605,15 @@ class Foo { assert myFixture.editor.document.text.contains('List<Map.Entry<String, Integer>> result;') } + public void "test name shadowing"() { + myFixture.configureByText "a.java", """class LiveTemplateVarSuggestion { + private Object value; + public void setValue(Object value, Object value1){ + inn<caret> + } +}""" + myFixture.type('\t') + assert myFixture.lookupElementStrings == ['value', 'value1'] + } + } diff --git a/java/java-tests/testSrc/com/intellij/codeInspection/ConcatenationToMessageFormatActionTest.java b/java/java-tests/testSrc/com/intellij/codeInspection/ConcatenationToMessageFormatActionTest.java index 412104c7beb4..11f426a67388 100644 --- a/java/java-tests/testSrc/com/intellij/codeInspection/ConcatenationToMessageFormatActionTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInspection/ConcatenationToMessageFormatActionTest.java @@ -3,36 +3,37 @@ */ package com.intellij.codeInspection; -import com.intellij.codeInsight.intention.impl.ConcatenationToMessageFormatAction; import com.intellij.psi.JavaPsiFacade; import com.intellij.psi.PsiExpression; +import com.intellij.psi.util.PsiConcatenationUtil; import com.intellij.testFramework.LightIdeaTestCase; import java.util.ArrayList; public class ConcatenationToMessageFormatActionTest extends LightIdeaTestCase { + + public void doTest(String expressionText, String messageFormatText, String... foundExpressionTexts) { + final PsiExpression expression = JavaPsiFacade.getElementFactory(getProject()).createExpressionFromText(expressionText, null); + final StringBuilder result = new StringBuilder(); + final ArrayList<PsiExpression> args = new ArrayList<PsiExpression>(); + PsiConcatenationUtil.buildFormatString(expression, result, args, false); + assertEquals(messageFormatText, result.toString()); + assertEquals(foundExpressionTexts.length, args.size()); + for (int i = 0; i < foundExpressionTexts.length; i++) { + final String foundExpressionText = foundExpressionTexts[i]; + assertEquals(foundExpressionText, args.get(i).getText()); + } + } public void test1() throws Exception{ - final String text = "\"aaa 'bbb' '\" + ((java.lang.String)ccc) + \"'\""; - final PsiExpression expression = JavaPsiFacade.getInstance(getProject()).getElementFactory().createExpressionFromText( - text, null - ); - final StringBuilder result = new StringBuilder(); - ConcatenationToMessageFormatAction.buildMessageFormatString(expression, - result, - new ArrayList<PsiExpression>()); - assertEquals("aaa ''bbb'' ''{0}''", result.toString()); + doTest("\"aaa 'bbb' '\" + ((java.lang.String)ccc) + \"'\"", "aaa ''bbb'' ''{0}''", "ccc"); } public void test2() throws Exception { - final String text = "1 + 2 + 3 + \"{}'\" + '\\n' + ((java.lang.String)ccc)"; - final PsiExpression expression = JavaPsiFacade.getElementFactory(getProject()).createExpressionFromText(text, null); - final StringBuilder result = new StringBuilder(); - final ArrayList<PsiExpression> args = new ArrayList<PsiExpression>(); - ConcatenationToMessageFormatAction.buildMessageFormatString(expression, result, args); - assertEquals("{0}'{'}''\\n{1}", result.toString()); - assertEquals(2, args.size()); - assertEquals("1 + 2 + 3", args.get(0).getText()); - assertEquals("ccc", args.get(1).getText()); + doTest("1 + 2 + 3 + \"{}'\" + '\\n' + ((java.lang.String)ccc)", "{0}'{}'''\\n{1}", "1 + 2 + 3", "ccc"); + } + + public void test3() throws Exception { + doTest("\"Test{A = \" + 1 + \", B = \" + 2 + \", C = \" + 3 + \"}\"", "Test'{'A = {0}, B = {1}, C = {2}'}'", "1", "2", "3"); } } diff --git a/java/java-tests/testSrc/com/intellij/codeInspection/DataFlowInspectionTest.java b/java/java-tests/testSrc/com/intellij/codeInspection/DataFlowInspectionTest.java index fc5824cd047f..63f946079a49 100644 --- a/java/java-tests/testSrc/com/intellij/codeInspection/DataFlowInspectionTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInspection/DataFlowInspectionTest.java @@ -228,4 +228,11 @@ public class DataFlowInspectionTest extends LightCodeInsightFixtureTestCase { assert psiMethod != null; return new ConditionChecker.FromPsiBuilder(psiMethod, psiMethod.getParameterList().getParameters()[0], type).build(); } + + public void testIgnoreAssertions() { + final DataFlowInspection inspection = new DataFlowInspection(); + inspection.IGNORE_ASSERT_STATEMENTS = true; + myFixture.enableInspections(inspection); + myFixture.testHighlighting(true, false, true, getTestName(false) + ".java"); + } } diff --git a/java/java-tests/testSrc/com/intellij/codeInspection/GlobalInspectionContextTest.java b/java/java-tests/testSrc/com/intellij/codeInspection/GlobalInspectionContextTest.java index 872ae1277119..803d325d8c3e 100644 --- a/java/java-tests/testSrc/com/intellij/codeInspection/GlobalInspectionContextTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInspection/GlobalInspectionContextTest.java @@ -56,11 +56,12 @@ public class GlobalInspectionContextTest extends CodeInsightTestCase { public void testRunInspectionContext() throws Exception { InspectionProfile profile = new InspectionProfileImpl("foo"); - InspectionProfileEntry[] tools = profile.getInspectionTools(null); - for (InspectionProfileEntry tool : tools) { - if (!tool.isEnabledByDefault()) { - GlobalInspectionContextImpl context = RunInspectionIntention.createContext(tool, (InspectionManagerEx)InspectionManager.getInstance(myProject), null); - context.initializeTools(new ArrayList<Tools>(), new ArrayList<Tools>(), new ArrayList<Tools>()); + InspectionToolWrapper[] tools = (InspectionToolWrapper[])profile.getInspectionTools(null); + for (InspectionToolWrapper toolWrapper : tools) { + if (!toolWrapper.isEnabledByDefault()) { + InspectionManagerEx instance = (InspectionManagerEx)InspectionManager.getInstance(myProject); + GlobalInspectionContextImpl context = RunInspectionIntention.createContext(toolWrapper, instance, null); + context.initializeTools(new ArrayList<Tools>(), new ArrayList<Tools>(), new ArrayList<Tools>(), new ArrayList<Tools>()); assertEquals(1, context.getTools().size()); return; } diff --git a/java/java-tests/testSrc/com/intellij/codeInspection/InspectionProfileTest.java b/java/java-tests/testSrc/com/intellij/codeInspection/InspectionProfileTest.java index b6f20b9efc19..a1630244c4d1 100644 --- a/java/java-tests/testSrc/com/intellij/codeInspection/InspectionProfileTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInspection/InspectionProfileTest.java @@ -267,7 +267,7 @@ public class InspectionProfileTest extends LightIdeaTestCase { GlobalInspectionContextImpl context = ((InspectionManagerEx)InspectionManager.getInstance(getProject())).createNewGlobalContext(false); context.setExternalProfile(profile); - context.initializeTools(new ArrayList<Tools>(), new ArrayList<Tools>(), new ArrayList<Tools>()); + context.initializeTools(new ArrayList<Tools>(), new ArrayList<Tools>(), new ArrayList<Tools>(), new ArrayList<Tools>()); } public void testInspectionsInitialization() throws Exception { @@ -299,11 +299,11 @@ public class InspectionProfileTest extends LightIdeaTestCase { InspectionProfileImpl profile = new InspectionProfileImpl("profile"); profile.setBaseProfile(InspectionProfileImpl.getDefaultProfile()); assertEquals(0, countInitializedTools(profile)); - InspectionProfileEntry[] tools = profile.getInspectionTools(null); - assertTrue(tools.length > 0); - InspectionProfileEntry tool = profile.getInspectionTool(new DataFlowInspection().getShortName()); - assertNotNull(tool); - String id = tool.getShortName(); + InspectionToolWrapper[] toolWrappers = profile.getInspectionTools(null); + assertTrue(toolWrappers.length > 0); + InspectionToolWrapper toolWrapper = profile.getInspectionTool(new DataFlowInspection().getShortName()); + assertNotNull(toolWrapper); + String id = toolWrapper.getShortName(); System.out.println(id); if (profile.isToolEnabled(HighlightDisplayKey.findById(id))) { profile.disableTool(id); @@ -313,9 +313,9 @@ public class InspectionProfileTest extends LightIdeaTestCase { } assertEquals(0, countInitializedTools(profile)); profile.writeExternal(new Element("profile")); - List<InspectionProfileEntry> initializedTools = getInitializedTools(profile); + List<InspectionToolWrapper> initializedTools = getInitializedTools(profile); if (initializedTools.size() != 1) { - for (InspectionProfileEntry initializedTool : initializedTools) { + for (InspectionToolWrapper initializedTool : initializedTools) { System.out.println(initializedTool.getShortName()); } fail(); @@ -340,14 +340,14 @@ public class InspectionProfileTest extends LightIdeaTestCase { return getInitializedTools(foo).size(); } - public static List<InspectionProfileEntry> getInitializedTools(Profile foo) { - List<InspectionProfileEntry> initialized = new ArrayList<InspectionProfileEntry>(); + @NotNull + public static List<InspectionToolWrapper> getInitializedTools(@NotNull Profile foo) { + List<InspectionToolWrapper> initialized = new ArrayList<InspectionToolWrapper>(); List<ScopeToolState> tools = ((InspectionProfileImpl)foo).getAllTools(); for (ScopeToolState tool : tools) { - InspectionProfileEntry entry = tool.getTool(); - assertTrue(entry instanceof InspectionToolWrapper); - if (entry.isInitialized()) { - initialized.add(entry); + InspectionToolWrapper toolWrapper = (InspectionToolWrapper)tool.getTool(); + if (toolWrapper.isInitialized()) { + initialized.add(toolWrapper); } } return initialized; diff --git a/java/java-tests/testSrc/com/intellij/codeInspection/RedundantSuppressTest.java b/java/java-tests/testSrc/com/intellij/codeInspection/RedundantSuppressTest.java index 9be168c9ff85..816eee99a47a 100644 --- a/java/java-tests/testSrc/com/intellij/codeInspection/RedundantSuppressTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInspection/RedundantSuppressTest.java @@ -8,19 +8,19 @@ import com.intellij.testFramework.InspectionTestCase; public class RedundantSuppressTest extends InspectionTestCase { private GlobalInspectionToolWrapper myWrapper; - private InspectionTool[] myInspectionTools; + private InspectionToolWrapper[] myInspectionToolWrappers; @Override protected void setUp() throws Exception { super.setUp(); InspectionToolRegistrar.getInstance().ensureInitialized(); - myInspectionTools = new InspectionTool[]{new LocalInspectionToolWrapper(new I18nInspection()), + myInspectionToolWrappers = new InspectionToolWrapper[]{new LocalInspectionToolWrapper(new I18nInspection()), new GlobalInspectionToolWrapper(new EmptyMethodInspection())}; myWrapper = new GlobalInspectionToolWrapper(new RedundantSuppressInspection() { @Override - protected InspectionTool[] getInspectionTools(PsiElement psiElement, InspectionManager manager) { - return myInspectionTools; + protected InspectionToolWrapper[] getInspectionTools(PsiElement psiElement, InspectionManager manager) { + return myInspectionToolWrappers; } }); } diff --git a/java/java-tests/testSrc/com/intellij/codeInspection/UnusedDeclarationTest.java b/java/java-tests/testSrc/com/intellij/codeInspection/UnusedDeclarationTest.java index a9a1e4e4b348..452083ed507f 100644 --- a/java/java-tests/testSrc/com/intellij/codeInspection/UnusedDeclarationTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInspection/UnusedDeclarationTest.java @@ -17,6 +17,7 @@ package com.intellij.codeInspection; import com.intellij.JavaTestUtil; import com.intellij.codeInspection.deadCode.UnusedDeclarationInspection; +import com.intellij.codeInspection.ex.CommonInspectionToolWrapper; import com.intellij.codeInspection.ex.EntryPointsManagerImpl; import com.intellij.openapi.roots.LanguageLevelProjectExtension; import com.intellij.pom.java.LanguageLevel; @@ -40,7 +41,7 @@ public class UnusedDeclarationTest extends InspectionTestCase { } private void doTest() { - doTest("deadCode/" + getTestName(true), myTool); + doTest("deadCode/" + getTestName(true), new CommonInspectionToolWrapper(myTool)); } public void testSCR6067() { @@ -151,7 +152,7 @@ public class UnusedDeclarationTest extends InspectionTestCase { public void testJunitAbstractClassWithoutInheritor() { doTest(); } - + public void testJunitEntryPointCustomRunWith() { doTest(); } diff --git a/java/java-tests/testSrc/com/intellij/projectView/ProjectViewUpdatingTest.java b/java/java-tests/testSrc/com/intellij/projectView/ProjectViewUpdatingTest.java new file mode 100644 index 000000000000..c23078e3a11a --- /dev/null +++ b/java/java-tests/testSrc/com/intellij/projectView/ProjectViewUpdatingTest.java @@ -0,0 +1,464 @@ +/* + * Copyright (c) 2004 JetBrains s.r.o. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * -Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * -Redistribution in binary form must reproduct the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the distribution. + * + * Neither the name of JetBrains or IntelliJ IDEA + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * This software is provided "AS IS," without a warranty of any kind. ALL + * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING + * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE + * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. JETBRAINS AND ITS LICENSORS SHALL NOT + * BE LIABLE FOR ANY DAMAGES OR LIABILITIES SUFFERED BY LICENSEE AS A RESULT + * OF OR RELATING TO USE, MODIFICATION OR DISTRIBUTION OF THE SOFTWARE OR ITS + * DERIVATIVES. IN NO EVENT WILL JETBRAINS OR ITS LICENSORS BE LIABLE FOR ANY LOST + * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, + * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY + * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE, EVEN + * IF JETBRAINS HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + * + */ +package com.intellij.projectView; + +import com.intellij.ide.projectView.PresentationData; +import com.intellij.ide.projectView.TreeStructureProvider; +import com.intellij.ide.projectView.ViewSettings; +import com.intellij.ide.projectView.impl.AbstractProjectViewPSIPane; +import com.intellij.ide.projectView.impl.ClassesTreeStructureProvider; +import com.intellij.ide.util.treeView.AbstractTreeNode; +import com.intellij.ide.util.treeView.NodeDescriptor; +import com.intellij.openapi.application.ApplicationManager; +import com.intellij.openapi.command.CommandProcessor; +import com.intellij.openapi.editor.Document; +import com.intellij.openapi.fileEditor.FileDocumentManager; +import com.intellij.openapi.project.Project; +import com.intellij.psi.*; +import com.intellij.refactoring.rename.RenameProcessor; +import com.intellij.testFramework.PlatformTestUtil; +import com.intellij.uiDesigner.projectView.FormMergerTreeStructureProvider; +import com.intellij.util.IncorrectOperationException; +import com.intellij.util.ui.tree.TreeUtil; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import javax.swing.*; +import java.awt.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Comparator; +import java.util.List; + +@SuppressWarnings({"HardCodedStringLiteral"}) +public class ProjectViewUpdatingTest extends BaseProjectViewTestCase { + public void testStandardProviders() throws Exception{ + PsiFile element = JavaDirectoryService.getInstance().getClasses(getPackageDirectory())[0].getContainingFile(); + final AbstractProjectViewPSIPane pane = myStructure.createPane(); + getProjectTreeStructure().setProviders(); + pane.select(element, element.getContainingFile().getVirtualFile(), true); + PlatformTestUtil.assertTreeEqual(pane.getTree(), "-Project\n" + + " -PsiDirectory: standardProviders\n" + + " -PsiDirectory: src\n" + + " -PsiDirectory: com\n" + + " -PsiDirectory: package1\n" + + " Class1.java\n" + + " Class2.java\n" + + " Class4.java\n" + + " Form1.form\n" + + " Form1.java\n" + + " Form2.form\n" + + getRootFiles() + + " +External Libraries\n" + ); + final PsiClass[] classes = JavaDirectoryService.getInstance() + .getPackage(getContentDirectory().findSubdirectory("src").findSubdirectory("com").findSubdirectory("package1")).getClasses(); + sortClassesByName(classes); + ApplicationManager.getApplication().runWriteAction(new Runnable() { + public void run() { + classes[0].delete(); + } + }); + + + PlatformTestUtil.waitForAlarm(600); + + PlatformTestUtil.assertTreeEqual(pane.getTree(), "-Project\n" + + " -PsiDirectory: standardProviders\n" + + " -PsiDirectory: src\n" + + " -PsiDirectory: com\n" + + " -PsiDirectory: package1\n" + + " Class2.java\n" + + " Class4.java\n" + + " Form1.form\n" + + " Form1.java\n" + + " Form2.form\n" + + getRootFiles() + + " +External Libraries\n"); + + } + + public void testUpdateProjectView() throws Exception { + getProjectTreeStructure().setProviders(new ClassesTreeStructureProvider(myProject), new FormMergerTreeStructureProvider(myProject)); + + final AbstractProjectViewPSIPane pane = myStructure.createPane(); + final JTree tree = pane.getTree(); + PlatformTestUtil.assertTreeEqual(tree, "-Project\n" + + " +PsiDirectory: updateProjectView\n" + + getRootFiles() + + " +External Libraries\n"); + + final PsiJavaFile classFile = (PsiJavaFile)getContentDirectory().findSubdirectory("src").findSubdirectory("com").findSubdirectory("package1").findFile("Form1.java"); + final PsiClass aClass = classFile.getClasses()[0]; + final PsiFile containingFile = aClass.getContainingFile(); + pane.select(aClass, containingFile.getVirtualFile(), true); + PlatformTestUtil.assertTreeEqual(pane.getTree(), "-Project\n" + + " -PsiDirectory: updateProjectView\n" + + " -PsiDirectory: src\n" + + " -PsiDirectory: com\n" + + " -PsiDirectory: package1\n" + + " Class1\n" + + " +Class2.java\n" + + " Class4.java\n" + + " Form2.form\n" + + " -Form:Form1\n" + + " [Form1]\n" + + " Form1.form\n" + + getRootFiles() + + " +External Libraries\n", true); + + CommandProcessor.getInstance().executeCommand(myProject, new Runnable() { + @Override + public void run() { + new RenameProcessor(myProject, aClass, "Form1_renamed", false, false).run(); + } + }, null, null); + + PlatformTestUtil.waitForAlarm(600); + PlatformTestUtil.assertTreeEqual(tree, "-Project\n" + + " -PsiDirectory: updateProjectView\n" + + " -PsiDirectory: src\n" + + " -PsiDirectory: com\n" + + " -PsiDirectory: package1\n" + + " Class1\n" + + " +Class2.java\n" + + " Class4.java\n" + + " Form2.form\n" + + " -Form:Form1_renamed\n" + + " Form1.form\n" + + " [Form1_renamed]\n" + + getRootFiles() + + " +External Libraries\n", true); + + TreeUtil.collapseAll(pane.getTree(), -1); + PlatformTestUtil.assertTreeEqual(tree, "-Project\n" + + " +PsiDirectory: updateProjectView\n" + + getRootFiles() + + " +External Libraries\n"); + + final PsiClass aClass2 = JavaDirectoryService.getInstance() + .createClass(getContentDirectory().findSubdirectory("src").findSubdirectory("com").findSubdirectory("package1"), "Class6"); + PlatformTestUtil.waitForAlarm(600); + final PsiFile containingFile2 = aClass2.getContainingFile(); + pane.select(aClass2, containingFile2.getVirtualFile(), true); + PlatformTestUtil.assertTreeEqual(pane.getTree(), "-Project\n" + + " -PsiDirectory: updateProjectView\n" + + " -PsiDirectory: src\n" + + " -PsiDirectory: com\n" + + " -PsiDirectory: package1\n" + + " Class1\n" + + " +Class2.java\n" + + " Class4.java\n" + + " [Class6]\n" + + " Form2.form\n" + + " +Form:Form1_renamed\n" + + getRootFiles() + + " +External Libraries\n", true); + } + + public void testShowClassMembers() throws Exception{ + + getProjectTreeStructure().setProviders(new ClassesTreeStructureProvider(myProject), new FormMergerTreeStructureProvider(myProject)); + + final AbstractProjectViewPSIPane pane = myStructure.createPane(); + final JTree tree = pane.getTree(); + PlatformTestUtil.assertTreeEqual(tree, "-Project\n" + + " +PsiDirectory: showClassMembers\n" + + getRootFiles() + + " +External Libraries\n"); + + myStructure.setShowMembers(true); + + PsiJavaFile classFile = (PsiJavaFile)getContentDirectory().findSubdirectory("src").findSubdirectory("com").findSubdirectory("package1").findFile("Class1.java"); + PsiClass aClass = classFile.getClasses()[0]; + PsiFile containingFile = aClass.getContainingFile(); + pane.select(aClass, containingFile.getVirtualFile(), true); + PlatformTestUtil.assertTreeEqual(pane.getTree(), "-Project\n" + + " -PsiDirectory: showClassMembers\n" + + " -PsiDirectory: src\n" + + " -PsiDirectory: com\n" + + " -PsiDirectory: package1\n" + + " -[Class1]\n" + + " +InnerClass\n" + + " getValue():int\n" + + " myField1:boolean\n" + + " myField2:boolean\n" + + " +Class2\n" + + getRootFiles() + + " +External Libraries\n", true); + + + final Document document = FileDocumentManager.getInstance().getDocument(containingFile.getVirtualFile()); + final int caretPosition = document.getText().indexOf("public class InnerClass") - 1; + + ApplicationManager.getApplication().runWriteAction(new Runnable() { + public void run() { + CommandProcessor.getInstance().executeCommand(myProject, + new Runnable() { + @Override + public void run() { + document.insertString(caretPosition, "\n"); + } + }, + "typing", + null); + } + }); + + + PsiDocumentManager.getInstance(myProject).commitDocument(document); + PlatformTestUtil.waitForAlarm(600); + + PlatformTestUtil.assertTreeEqual(pane.getTree(), "-Project\n" + + " -PsiDirectory: showClassMembers\n" + + " -PsiDirectory: src\n" + + " -PsiDirectory: com\n" + + " -PsiDirectory: package1\n" + + " -[Class1]\n" + + " +InnerClass\n" + + " getValue():int\n" + + " myField1:boolean\n" + + " myField2:boolean\n" + + " +Class2\n" + + getRootFiles() + + " +External Libraries\n", true); + + classFile = (PsiJavaFile)getContentDirectory().findSubdirectory("src").findSubdirectory("com").findSubdirectory("package1").findFile("Class1.java"); + aClass = classFile.getClasses()[0]; + final PsiField lastField = aClass.getFields()[1]; + pane.select(lastField, containingFile.getVirtualFile(), true); + + PlatformTestUtil.assertTreeEqual(pane.getTree(), "-Project\n" + + " -PsiDirectory: showClassMembers\n" + + " -PsiDirectory: src\n" + + " -PsiDirectory: com\n" + + " -PsiDirectory: package1\n" + + " -Class1\n" + + " +InnerClass\n" + + " getValue():int\n" + + " myField1:boolean\n" + + " [myField2:boolean]\n" + + " +Class2\n" + + getRootFiles() + + " +External Libraries\n", true); + + CommandProcessor.getInstance().executeCommand(myProject, new Runnable() { + @Override + public void run() { + ApplicationManager.getApplication().runWriteAction(new Runnable() { + @Override + public void run() { + try { + assertEquals("myField2", lastField.getName()); + lastField.setName("_firstField"); + } + catch (IncorrectOperationException e) { + fail(e.getMessage()); + } + } + }); + } + }, null, null); + + PlatformTestUtil.waitForAlarm(600); + + PlatformTestUtil.assertTreeEqual(pane.getTree(), "-Project\n" + + " -PsiDirectory: showClassMembers\n" + + " -PsiDirectory: src\n" + + " -PsiDirectory: com\n" + + " -PsiDirectory: package1\n" + + " -Class1\n" + + " +InnerClass\n" + + " getValue():int\n" + + " [_firstField:boolean]\n" + + " myField1:boolean\n" + + " +Class2\n" + + getRootFiles() + + " +External Libraries\n", true); + } + + public void testAnnoyingScrolling() throws Exception{ + + getProjectTreeStructure().setProviders(new ClassesTreeStructureProvider(myProject)); + + final AbstractProjectViewPSIPane pane = myStructure.createPane(); + final JTree tree = pane.getTree(); + + myStructure.setShowMembers(true); + + PsiJavaFile classFile = (PsiJavaFile)getContentDirectory().findSubdirectory("src").findSubdirectory("com").findSubdirectory("package1").findFile("Class1.java"); + PsiClass aClass = classFile.getClasses()[0]; + PsiFile containingFile = aClass.getContainingFile(); + PsiDirectory directory = containingFile.getContainingDirectory(); + pane.select(aClass, containingFile.getVirtualFile(), true); + Point viewPosition = ((JViewport)tree.getParent()).getViewPosition(); + for (int i=0;i<100;i++) { + JavaDirectoryService.getInstance().createClass(directory, "A" + i); + } + PlatformTestUtil.waitForAlarm(600); + Point viewPositionAfter = ((JViewport)tree.getParent()).getViewPosition(); + assertEquals(viewPosition, viewPositionAfter); + + } + + class NodeWrapper extends AbstractTreeNode<Object> { + String myName; + List<NodeWrapper> myChildren = new ArrayList<NodeWrapper>(); + + public NodeWrapper(final Project project, final String value) { + super(project, new Object()); + myName = value; + } + + @Override + @NotNull + public Collection<? extends AbstractTreeNode> getChildren() { + return myChildren; + } + + @Override + protected void update(final PresentationData presentation) { + presentation.setPresentableText(myName); + } + + public void addChild(final NodeWrapper nodeWrapper) { + myChildren.add(nodeWrapper); + } + + public void setName(final String s) { + myName = s; + } + } + + public void testUpdatingAfterRename() throws Exception{ + + final NodeWrapper rootWrapper = new NodeWrapper(myProject, "1"); + + final NodeWrapper wr11 = new NodeWrapper(myProject, "1.1"); + final NodeWrapper wr12 = new NodeWrapper(myProject, "1.2"); + final NodeWrapper wr13 = new NodeWrapper(myProject, "1.3"); + final NodeWrapper wr111 = new NodeWrapper(myProject, "1.1.1"); + final NodeWrapper wr112 = new NodeWrapper(myProject, "1.1.2"); + final NodeWrapper wr113 = new NodeWrapper(myProject, "1.1.3"); + final NodeWrapper wr121 = new NodeWrapper(myProject, "1.2.1"); + final NodeWrapper wr122 = new NodeWrapper(myProject, "1.2.2"); + final NodeWrapper wr123 = new NodeWrapper(myProject, "1.2.3"); + final NodeWrapper wr131 = new NodeWrapper(myProject, "1.3.1"); + final NodeWrapper wr132 = new NodeWrapper(myProject, "1.3.2"); + final NodeWrapper wr133 = new NodeWrapper(myProject, "1.3.3"); + + rootWrapper.addChild(wr11); + rootWrapper.addChild(wr12); + rootWrapper.addChild(wr13); + + wr11.addChild(wr111); + wr11.addChild(wr112); + wr11.addChild(wr113); + + wr12.addChild(wr121); + wr12.addChild(wr122); + wr12.addChild(wr123); + + wr13.addChild(wr131); + wr13.addChild(wr132); + wr13.addChild(wr133); + + + getProjectTreeStructure().setProviders(createWrapProvider(rootWrapper)); + + final AbstractProjectViewPSIPane pane = myStructure.createPane(); + + final JTree tree = pane.getTree(); + + pane.getTreeBuilder().setNodeDescriptorComparator(new Comparator<NodeDescriptor>() { + @Override + public int compare(final NodeDescriptor o1, final NodeDescriptor o2) { + if (o1 instanceof NodeWrapper && o2 instanceof NodeWrapper) { + return ((NodeWrapper)o1).getName().compareTo(((NodeWrapper)o2).getName()); + } + else { + return 0; + } + } + }); + + tree.expandRow(2); + TreeUtil.selectPath(tree, tree.getPathForRow(4)); + + PlatformTestUtil.assertTreeEqual(tree, "-Project\n" + + " -1\n" + + " +1.1\n" + + " -1.2\n" + + " 1.2.1\n" + + " [1.2.2]\n" + + " 1.2.3\n" + + " +1.3\n", true); + + wr12.setName("01.2"); + wr122.setName("01.2.2"); + + pane.getTreeBuilder().updateFromRoot(); + + PlatformTestUtil.assertTreeEqual(tree, "-Project\n" + + " -1\n" + + " -01.2\n" + + " [01.2.2]\n" + + " 1.2.1\n" + + " 1.2.3\n" + + " +1.1\n" + + " +1.3\n", true); + + + } + + private TreeStructureProvider createWrapProvider(final NodeWrapper rootWrapper) { + return new TreeStructureProvider() { + @Override + public Collection<AbstractTreeNode> modify(AbstractTreeNode parent, Collection<AbstractTreeNode> children, ViewSettings settings) { + + if (parent instanceof NodeWrapper) { + return children; + } + List<AbstractTreeNode> result = new ArrayList<AbstractTreeNode>(); + result.add(rootWrapper); + return result; + } + + @Override + @Nullable + public Object getData(Collection<AbstractTreeNode> selected, String dataName) { + return null; + } + }; + } + +} diff --git a/java/java-tests/testSrc/com/intellij/psi/StubAstSwitchTest.groovy b/java/java-tests/testSrc/com/intellij/psi/StubAstSwitchTest.groovy index b9a5732b83c6..da446c7a93b1 100644 --- a/java/java-tests/testSrc/com/intellij/psi/StubAstSwitchTest.groovy +++ b/java/java-tests/testSrc/com/intellij/psi/StubAstSwitchTest.groovy @@ -14,15 +14,16 @@ * limitations under the License. */ package com.intellij.psi - import com.intellij.openapi.application.ApplicationManager +import com.intellij.openapi.fileEditor.FileDocumentManager +import com.intellij.openapi.vfs.VfsUtil import com.intellij.psi.impl.source.PsiFileImpl +import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.util.PsiTreeUtil -import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase import com.intellij.reference.SoftReference +import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase import java.util.concurrent.CountDownLatch - /** * @author peter */ @@ -79,4 +80,21 @@ class StubAstSwitchTest extends LightCodeInsightFixtureTestCase { } latch.await() } + + public void "test external modification of a stubbed file with smart pointer switches the file to AST"() { + PsiFile file = myFixture.addFileToProject("A.java", "class A {}") + def oldClass = JavaPsiFacade.getInstance(project).findClass("A", GlobalSearchScope.allScope(project)) + def pointer = SmartPointerManager.getInstance(project).createSmartPsiElementPointer(oldClass) + + def document = FileDocumentManager.instance.getCachedDocument(file.virtualFile) + assert document + assert file == PsiDocumentManager.getInstance(project).getCachedPsiFile(document) + assert document == PsiDocumentManager.getInstance(project).getCachedDocument(file) + + assert ((PsiFileImpl)file).stub + + ApplicationManager.application.runWriteAction { VfsUtil.saveText(file.virtualFile, "import java.util.*; class A {}; class B {}") } + assert pointer.element == oldClass + assert ((PsiFileImpl)file).treeElement + } } diff --git a/java/java-tests/testSrc/com/intellij/psi/formatter/java/JavaFormatterIndentationTest.java b/java/java-tests/testSrc/com/intellij/psi/formatter/java/JavaFormatterIndentationTest.java index b61689b46a1d..be335471d355 100644 --- a/java/java-tests/testSrc/com/intellij/psi/formatter/java/JavaFormatterIndentationTest.java +++ b/java/java-tests/testSrc/com/intellij/psi/formatter/java/JavaFormatterIndentationTest.java @@ -40,7 +40,7 @@ public class JavaFormatterIndentationTest extends AbstractJavaFormatterTest { // Checking that closing curly brace of initialization block that is not the first block on a line is correctly indented. doTextTest("class Class {\n" + " private Type field; {\n" + " }\n" + "}", - "class Class {\n" + " private Type field; {\n" + " }\n" + "}"); + "class Class {\n" + " private Type field;\n\n {\n" + " }\n" + "}"); doTextTest( "class T {\n" + " private final DecimalFormat fmt = new DecimalFormat(); {\n" + @@ -49,7 +49,7 @@ public class JavaFormatterIndentationTest extends AbstractJavaFormatterTest { " }\n" + "}", "class T {\n" + - " private final DecimalFormat fmt = new DecimalFormat(); {\n" + + " private final DecimalFormat fmt = new DecimalFormat();\n\n {\n" + " fmt.setGroupingUsed(false);\n" + " fmt.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US));\n" + " }\n" + diff --git a/java/java-tests/testSrc/com/intellij/psi/formatter/java/JavadocFormatterTest.java b/java/java-tests/testSrc/com/intellij/psi/formatter/java/JavadocFormatterTest.java index d01f0f6a5ded..fb876ae3d8dd 100644 --- a/java/java-tests/testSrc/com/intellij/psi/formatter/java/JavadocFormatterTest.java +++ b/java/java-tests/testSrc/com/intellij/psi/formatter/java/JavadocFormatterTest.java @@ -122,7 +122,31 @@ public class JavadocFormatterTest extends AbstractJavaFormatterTest { "}" ); } - + + public void testParameterDescriptionNotOnNewLine() throws Exception { + // IDEA-107383 + getSettings().getRootSettings().ENABLE_JAVADOC_FORMATTING = true; + getSettings().getRootSettings().JD_ALIGN_PARAM_COMMENTS = true; + + doClassTest( + "/**\n" + + " @param protocolId protocol id\n" + + " @param connectedUserIdHandlerFromServer user id\n" + + " @return\n" + + + " */\n" + + "public void register(int protocolId, int connectedUserIdHandlerFromServer) {\n" + + "}", + + "/**\n" + + " * @param protocolId protocol id\n" + + " * @param connectedUserIdHandlerFromServer user id\n" + + " * @return\n" + + " */\n" + + "public void register(int protocolId, int connectedUserIdHandlerFromServer) {\n" + + "}"); + } + public void testWrappedParameterDescription() throws Exception { // Inspired by IDEA-13072 getSettings().getRootSettings().ENABLE_JAVADOC_FORMATTING = true; diff --git a/java/java-tests/testSrc/com/intellij/refactoring/ExtractMethodTest.java b/java/java-tests/testSrc/com/intellij/refactoring/ExtractMethodTest.java index 3639cbdfc78d..88537b77e8ea 100644 --- a/java/java-tests/testSrc/com/intellij/refactoring/ExtractMethodTest.java +++ b/java/java-tests/testSrc/com/intellij/refactoring/ExtractMethodTest.java @@ -583,6 +583,10 @@ public class ExtractMethodTest extends LightCodeInsightTestCase { doDuplicatesTest(); } + public void testOverloadedMethods() throws Exception { + doDuplicatesTest(); + } + public void testTargetAnonymous() throws Exception { doTest(); } diff --git a/java/java-tests/testSrc/com/intellij/refactoring/MoveMembersTest.java b/java/java-tests/testSrc/com/intellij/refactoring/MoveMembersTest.java index 596944b839d3..ca97d36cb650 100644 --- a/java/java-tests/testSrc/com/intellij/refactoring/MoveMembersTest.java +++ b/java/java-tests/testSrc/com/intellij/refactoring/MoveMembersTest.java @@ -107,6 +107,10 @@ public class MoveMembersTest extends MultiFileTestCase { doTest("B", "A", 0); } + public void testStringConstantFromCaseStatement() throws Exception { + doTest("B", "A", 0); + } + public void testDependantFields() throws Exception { doTest("B", "A", 0); } diff --git a/java/java-tests/testSrc/com/intellij/refactoring/inline/InlineLocalTest.java b/java/java-tests/testSrc/com/intellij/refactoring/inline/InlineLocalTest.java index 709db9911ea5..811d52f817c1 100644 --- a/java/java-tests/testSrc/com/intellij/refactoring/inline/InlineLocalTest.java +++ b/java/java-tests/testSrc/com/intellij/refactoring/inline/InlineLocalTest.java @@ -140,6 +140,10 @@ public class InlineLocalTest extends LightCodeInsightTestCase { "Variable 'arr' is accessed for writing."); } + public void testArrayMethodCallInitialized() throws Exception { + doTest(true); + } + public void testArrayIndex() throws Exception { doTest(true); } diff --git a/java/openapi/src/com/intellij/psi/util/PsiConcatenationUtil.java b/java/openapi/src/com/intellij/psi/util/PsiConcatenationUtil.java index 9b60456845ac..08e34433918b 100644 --- a/java/openapi/src/com/intellij/psi/util/PsiConcatenationUtil.java +++ b/java/openapi/src/com/intellij/psi/util/PsiConcatenationUtil.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2011 JetBrains s.r.o. + * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,65 +26,61 @@ import java.util.List; * User: cdr */ public class PsiConcatenationUtil { - public static void buildFormatString( - PsiExpression expression, StringBuilder formatString, - List<PsiExpression> formatParameters, boolean printfFormat) { - if (expression instanceof PsiLiteralExpression) { - final PsiLiteralExpression literalExpression = - (PsiLiteralExpression) expression; - final String text = String.valueOf(literalExpression.getValue()); - final String formatText; - if (printfFormat) { - formatText = StringUtil.escapeStringCharacters(text) - .replace("%", "%%").replace("\\'", "'"); - } - else { - formatText = StringUtil.escapeStringCharacters(text) - .replace("'", "''").replace("{", "'{").replace("}", "'}"); + + public static void buildFormatString(PsiExpression expression, StringBuilder formatString, + List<PsiExpression> formatParameters, boolean printfFormat) { + if (expression instanceof PsiLiteralExpression) { + final PsiLiteralExpression literalExpression = (PsiLiteralExpression) expression; + final String text = String.valueOf(literalExpression.getValue()); + final String formatText; + if (printfFormat) { + formatText = StringUtil.escapeStringCharacters(text).replace("%", "%%").replace("\\'", "'"); + } + else { + formatText = StringUtil.escapeStringCharacters(text).replace("'", "''").replaceAll("((\\{|})+)", "'$1'"); + } + formatString.append(formatText); + } else if (expression instanceof PsiPolyadicExpression) { + final PsiType type = expression.getType(); + if (type != null && type.equalsToText("java.lang.String")) { + final PsiPolyadicExpression binaryExpression = (PsiPolyadicExpression) expression; + PsiExpression[] operands = binaryExpression.getOperands(); + PsiType left = operands[0].getType(); + boolean stringStarted = left != null && left.equalsToText("java.lang.String"); + if (stringStarted) { + buildFormatString(operands[0], formatString, formatParameters, printfFormat); } - formatString.append(formatText); - } else if (expression instanceof PsiPolyadicExpression) { - final PsiType type = expression.getType(); - if (type != null && type.equalsToText("java.lang.String")) { - final PsiPolyadicExpression binaryExpression = - (PsiPolyadicExpression) expression; - PsiExpression[] operands = binaryExpression.getOperands(); - PsiType left = operands[0].getType(); - boolean stringStarted = left != null && left.equalsToText("java.lang.String"); - if (stringStarted) { - buildFormatString(operands[0], formatString, formatParameters, printfFormat); + for (int i = 1; i < operands.length; i++) { + PsiExpression op = operands[i]; + PsiType optype = op.getType(); + PsiType r = TypeConversionUtil.calcTypeForBinaryExpression(left, optype, binaryExpression.getOperationTokenType(), true); + if (r != null && r.equalsToText("java.lang.String") && !stringStarted) { + stringStarted = true; + PsiElement element = binaryExpression.getTokenBeforeOperand(op); + if (element.getPrevSibling() instanceof PsiWhiteSpace) element = element.getPrevSibling(); + String text = binaryExpression.getText().substring(0, element.getStartOffsetInParent()); + PsiExpression subExpression = JavaPsiFacade.getInstance(binaryExpression.getProject()).getElementFactory() + .createExpressionFromText(text, binaryExpression); + addFormatParameter(subExpression, formatString, formatParameters, printfFormat); + } + if (stringStarted) { + if (optype != null && (optype.equalsToText("java.lang.String") || optype == PsiType.CHAR)) { + buildFormatString(op, formatString, formatParameters, printfFormat); } - for (int i = 1; i < operands.length; i++) { - PsiExpression op = operands[i]; - PsiType optype = op.getType(); - PsiType r = TypeConversionUtil.calcTypeForBinaryExpression(left, optype, binaryExpression.getOperationTokenType(), true); - if (r != null && r.equalsToText("java.lang.String") && !stringStarted) { - stringStarted = true; - PsiElement element = binaryExpression.getTokenBeforeOperand(op); - if (element.getPrevSibling() instanceof PsiWhiteSpace) element = element.getPrevSibling(); - String text = binaryExpression.getText().substring(0, element.getStartOffsetInParent()); - PsiExpression subExpression = JavaPsiFacade.getInstance(binaryExpression.getProject()).getElementFactory() - .createExpressionFromText(text, binaryExpression); - addFormatParameter(subExpression, formatString, formatParameters, printfFormat); - } - if (stringStarted) { - if (optype != null && (optype.equalsToText("java.lang.String") || optype == PsiType.CHAR)) { - buildFormatString(op, formatString, formatParameters, printfFormat); - } - else { - addFormatParameter(op, formatString, formatParameters, printfFormat); - } - } - left = r; + else { + addFormatParameter(op, formatString, formatParameters, printfFormat); } } - else { - addFormatParameter(expression, formatString, formatParameters, printfFormat); - } + left = r; + } } else { addFormatParameter(expression, formatString, formatParameters, printfFormat); } + } + else { + addFormatParameter(expression, formatString, formatParameters, printfFormat); + } } private static void addFormatParameter(PsiExpression expression, @@ -92,13 +88,13 @@ public class PsiConcatenationUtil { List<PsiExpression> formatParameters, boolean printfFormat) { final PsiType type = expression.getType(); if (!printfFormat) { - formatString.append("{" + formatParameters.size() + "}"); + formatString.append("{").append(formatParameters.size()).append("}"); } else if (type != null && - (type.equalsToText("long") || - type.equalsToText("int") || - type.equalsToText("java.lang.Long") || - type.equalsToText("java.lang.Integer"))) { + (type.equalsToText("long") || + type.equalsToText("int") || + type.equalsToText("java.lang.Long") || + type.equalsToText("java.lang.Integer"))) { formatString.append("%d"); } else { diff --git a/java/testFramework/src/com/intellij/codeInsight/daemon/DaemonAnalyzerTestCase.java b/java/testFramework/src/com/intellij/codeInsight/daemon/DaemonAnalyzerTestCase.java index 6d40070c1d1d..ea893a18c4b0 100644 --- a/java/testFramework/src/com/intellij/codeInsight/daemon/DaemonAnalyzerTestCase.java +++ b/java/testFramework/src/com/intellij/codeInsight/daemon/DaemonAnalyzerTestCase.java @@ -119,16 +119,17 @@ public abstract class DaemonAnalyzerTestCase extends CodeInsightTestCase { @Override @NotNull - public InspectionTool[] getInspectionTools(PsiElement element) { + public InspectionToolWrapper[] getInspectionTools(PsiElement element) { Collection<InspectionToolWrapper> values = myAvailableTools.values(); - return values.toArray(new InspectionTool[values.size()]); + return values.toArray(new InspectionToolWrapper[values.size()]); } + @NotNull @Override - public List<ToolsImpl> getAllEnabledInspectionTools(Project project) { - List<ToolsImpl> result = new ArrayList<ToolsImpl>(); - for (InspectionProfileEntry entry : getInspectionTools(null)) { - result.add(new ToolsImpl(entry, entry.getDefaultLevel(), true)); + public List<Tools> getAllEnabledInspectionTools(Project project) { + List<Tools> result = new ArrayList<Tools>(); + for (InspectionToolWrapper toolWrapper : getInspectionTools(null)) { + result.add(new ToolsImpl(toolWrapper, toolWrapper.getDefaultLevel(), true)); } return result; } @@ -140,12 +141,12 @@ public abstract class DaemonAnalyzerTestCase extends CodeInsightTestCase { @Override public HighlightDisplayLevel getErrorLevel(@NotNull HighlightDisplayKey key, PsiElement element) { - final InspectionProfileEntry localInspectionTool = myAvailableTools.get(key.toString()); + final InspectionToolWrapper localInspectionTool = myAvailableTools.get(key.toString()); return localInspectionTool != null ? localInspectionTool.getDefaultLevel() : HighlightDisplayLevel.WARNING; } @Override - public InspectionTool getInspectionTool(@NotNull String shortName, @NotNull PsiElement element) { + public InspectionToolWrapper getInspectionTool(@NotNull String shortName, @NotNull PsiElement element) { return myAvailableTools.get(shortName); } }; @@ -192,7 +193,8 @@ public abstract class DaemonAnalyzerTestCase extends CodeInsightTestCase { //((VirtualFilePointerManagerImpl)VirtualFilePointerManager.getInstance()).assertPointersDisposed(); } - protected void enableInspectionTool(InspectionProfileEntry tool){ + protected void enableInspectionTool(@NotNull InspectionProfileEntry tool){ + assert !(tool instanceof InspectionToolWrapper) : tool; InspectionToolWrapper wrapper = InspectionToolRegistrar.wrapTool(tool); final String shortName = wrapper.getShortName(); final HighlightDisplayKey key = HighlightDisplayKey.find(shortName); diff --git a/java/testFramework/src/com/intellij/testFramework/InspectionTestCase.java b/java/testFramework/src/com/intellij/testFramework/InspectionTestCase.java index a93ea6bb718d..691dcba3520d 100644 --- a/java/testFramework/src/com/intellij/testFramework/InspectionTestCase.java +++ b/java/testFramework/src/com/intellij/testFramework/InspectionTestCase.java @@ -76,11 +76,11 @@ public abstract class InspectionTestCase extends PsiTestCase { doTest(folderName, new GlobalInspectionToolWrapper(tool), "java 1.4", checkRange, runDeadCodeFirst); } - public void doTest(@NonNls String folderName, InspectionTool tool) { + public void doTest(@NonNls String folderName, InspectionToolWrapper tool) { doTest(folderName, tool, "java 1.4"); } - public void doTest(@NonNls String folderName, InspectionTool tool, final boolean checkRange) { + public void doTest(@NonNls String folderName, InspectionToolWrapper tool, final boolean checkRange) { doTest(folderName, tool, "java 1.4", checkRange); } @@ -88,35 +88,35 @@ public abstract class InspectionTestCase extends PsiTestCase { doTest(folderName, new LocalInspectionToolWrapper(tool), jdkName); } - public void doTest(@NonNls String folderName, InspectionTool tool, @NonNls final String jdkName) { + public void doTest(@NonNls String folderName, InspectionToolWrapper tool, @NonNls final String jdkName) { doTest(folderName, tool, jdkName, false); } - public void doTest(@NonNls String folderName, InspectionTool tool, @NonNls final String jdkName, boolean checkRange) { + public void doTest(@NonNls String folderName, InspectionToolWrapper tool, @NonNls final String jdkName, boolean checkRange) { doTest(folderName, tool, jdkName, checkRange, false); } public void doTest(@NonNls String folderName, - InspectionTool tool, + InspectionToolWrapper toolWrapper, @NonNls final String jdkName, boolean checkRange, boolean runDeadCodeFirst, - InspectionTool... additional) { + InspectionToolWrapper... additional) { final String testDir = getTestDataPath() + "/" + folderName; - runTool(testDir, jdkName, runDeadCodeFirst, tool, additional); + runTool(testDir, jdkName, runDeadCodeFirst, toolWrapper, additional); - InspectionTestUtil.compareToolResults(tool, checkRange, testDir); + InspectionTestUtil.compareToolResults(toolWrapper, checkRange, testDir); } - protected void runTool(@NonNls final String testDir, @NonNls final String jdkName, final InspectionTool tool) { + protected void runTool(@NonNls final String testDir, @NonNls final String jdkName, final InspectionToolWrapper tool) { runTool(testDir, jdkName, false, tool); } protected void runTool(final String testDir, final String jdkName, boolean runDeadCodeFirst, - final InspectionTool tool, - InspectionTool... additional) { + final InspectionToolWrapper toolWrapper, + @NotNull InspectionToolWrapper... additional) { final VirtualFile[] sourceDir = new VirtualFile[1]; ApplicationManager.getApplication().runWriteAction(new Runnable() { @Override @@ -132,12 +132,12 @@ public abstract class InspectionTestCase extends PsiTestCase { AnalysisScope scope = createAnalysisScope(sourceDir[0].getParent()); InspectionManagerEx inspectionManager = (InspectionManagerEx)InspectionManager.getInstance(getProject()); - InspectionTool[] tools = runDeadCodeFirst ? new InspectionTool[]{new UnusedDeclarationInspection(), tool} : new InspectionTool[]{tool}; - tools = ArrayUtil.mergeArrays(tools, additional); + InspectionToolWrapper[] toolWrappers = runDeadCodeFirst ? new InspectionToolWrapper []{new CommonInspectionToolWrapper(new UnusedDeclarationInspection()), toolWrapper} : new InspectionToolWrapper []{toolWrapper}; + toolWrappers = ArrayUtil.mergeArrays(toolWrappers, additional); final GlobalInspectionContextImpl globalContext = - CodeInsightTestFixtureImpl.createGlobalContextForTool(scope, getProject(), inspectionManager, tools); + CodeInsightTestFixtureImpl.createGlobalContextForTool(scope, getProject(), inspectionManager, toolWrappers); - InspectionTestUtil.runTool(tool, scope, globalContext, inspectionManager); + InspectionTestUtil.runTool(toolWrapper, scope, globalContext, inspectionManager); } protected AnalysisScope createAnalysisScope(VirtualFile sourceDir) { |