diff --git a/.idea/artifacts/jps.xml b/.idea/artifacts/jps.xml deleted file mode 100644 index 1d3be3b3de76..000000000000 --- a/.idea/artifacts/jps.xml +++ /dev/null @@ -1,26 +0,0 @@ - - - $PROJECT_DIR$/out/artifacts/jps - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/.idea/inspectionProfiles/idea_default.xml b/.idea/inspectionProfiles/idea_default.xml index ceda65526e01..c56a697395e0 100644 --- a/.idea/inspectionProfiles/idea_default.xml +++ b/.idea/inspectionProfiles/idea_default.xml @@ -349,6 +349,9 @@ + + diff --git a/.idea/inspectionProfiles/idea_default_no_spellchecker.xml b/.idea/inspectionProfiles/idea_default_no_spellchecker.xml index a37e8d620b51..c2533ca21484 100644 --- a/.idea/inspectionProfiles/idea_default_no_spellchecker.xml +++ b/.idea/inspectionProfiles/idea_default_no_spellchecker.xml @@ -513,6 +513,9 @@ + + diff --git a/.idea/modules.xml b/.idea/modules.xml index abadb76c492f..ac849c617625 100644 --- a/.idea/modules.xml +++ b/.idea/modules.xml @@ -50,6 +50,8 @@ + + @@ -73,7 +75,6 @@ - diff --git a/bin/linux/fsnotifier b/bin/linux/fsnotifier index a69112111637..16677a1aa909 100755 Binary files a/bin/linux/fsnotifier and b/bin/linux/fsnotifier differ diff --git a/bin/linux/fsnotifier64 b/bin/linux/fsnotifier64 index 355776567d54..1335f1300ddb 100755 Binary files a/bin/linux/fsnotifier64 and b/bin/linux/fsnotifier64 differ diff --git a/build/scripts/layouts.gant b/build/scripts/layouts.gant index 5ed678e152f3..b999d8506f26 100644 --- a/build/scripts/layouts.gant +++ b/build/scripts/layouts.gant @@ -159,7 +159,6 @@ def layoutFull(String home, String targetDirectory, String patchedDescriptorDir jar("jps-server.jar") { module("jps-builders") - module("jps-model") } fileset(dir: "$home/jps/lib") { @@ -335,8 +334,17 @@ public def layoutCommunityPlugins(String home) { exclude(name: "standardDsls/**") } } - - jar("groovy_rt.jar") {module("groovy_rt")} + //layout of groovy jars must be consistent with GroovyBuilder.getGroovyRtRoot method + dir("jps") { + jar("groovy-jps-plugin.jar") { + module("groovy-jps-plugin") + module("groovy-rt-constants") + } + } + jar("groovy_rt.jar") { + module("groovy_rt") + module("groovy-rt-constants") + } dir("standardDsls") { fileset(dir: "$home/plugins/groovy/resources/standardDsls") } @@ -516,7 +524,6 @@ def layout_jps(String target) { module("util") } jar("jps-model.jar") { - module("jps-model") module("jps-model-api") module("jps-model-impl") module("jps-model-serialization") diff --git a/images/src/icons/ImagesIcons.java b/images/src/icons/ImagesIcons.java index 721de575a12f..8bba3a9663c7 100644 --- a/images/src/icons/ImagesIcons.java +++ b/images/src/icons/ImagesIcons.java @@ -14,7 +14,6 @@ public class ImagesIcons { } public static final Icon EditExternaly = load("/org/intellij/images/icons/EditExternaly.png"); // 16x16 - public static final Icon ImagesConfigurable = load("/org/intellij/images/icons/ImagesConfigurable.png"); // 32x32 public static final Icon ImagesFileType = load("/org/intellij/images/icons/ImagesFileType.png"); // 18x18 public static final Icon ThumbnailBlank = load("/org/intellij/images/icons/ThumbnailBlank.png"); // 75x86 public static final Icon ThumbnailDirectory = load("/org/intellij/images/icons/ThumbnailDirectory.png"); // 75x82 diff --git a/images/src/org/intellij/images/icons/ImagesConfigurable.png b/images/src/org/intellij/images/icons/ImagesConfigurable.png deleted file mode 100644 index c9b4e307e4c3..000000000000 Binary files a/images/src/org/intellij/images/icons/ImagesConfigurable.png and /dev/null differ diff --git a/java/compiler/impl/src/com/intellij/compiler/CompilerConfigurationImpl.java b/java/compiler/impl/src/com/intellij/compiler/CompilerConfigurationImpl.java index 81f9019d8619..5f5fa3af6813 100644 --- a/java/compiler/impl/src/com/intellij/compiler/CompilerConfigurationImpl.java +++ b/java/compiler/impl/src/com/intellij/compiler/CompilerConfigurationImpl.java @@ -56,6 +56,10 @@ import org.jdom.Element; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import org.jetbrains.jps.model.java.compiler.ProcessorConfigProfile; +import org.jetbrains.jps.model.java.impl.compiler.ProcessorConfigProfileImpl; +import org.jetbrains.jps.model.serialization.java.compiler.AnnotationProcessorProfileSerializer; +import org.jetbrains.jps.model.serialization.java.compiler.JpsJavaCompilerConfigurationSerializer; import java.io.File; import java.util.*; @@ -71,16 +75,6 @@ public class CompilerConfigurationImpl extends CompilerConfiguration implements private static final Logger LOG = Logger.getInstance("#com.intellij.compiler.CompilerConfiguration"); @NonNls public static final String TESTS_EXTERNAL_COMPILER_HOME_PROPERTY_NAME = "tests.external.compiler.home"; public static final int DEPENDENCY_FORMAT_VERSION = 55; - private static final Comparator ALPHA_COMPARATOR = new Comparator() { - @Override - public int compare(String o1, String o2) { - return o1.compareToIgnoreCase(o2); - } - }; - private static final String ENTRY = "entry"; - private static final String NAME = "name"; - private static final String ENABLED = "enabled"; - private static final String MODULE = "module"; @SuppressWarnings({"WeakerAccess"}) public String DEFAULT_COMPILER; @NotNull private BackendCompiler myDefaultJavaCompiler; @@ -104,7 +98,7 @@ public class CompilerConfigurationImpl extends CompilerConfiguration implements } private boolean myAddNotNullAssertions = true; - private final ProcessorConfigProfile myDefaultProcessorsProfile = new ProcessorConfigProfile("Default"); + private final ProcessorConfigProfile myDefaultProcessorsProfile = new ProcessorConfigProfileImpl("Default"); private final List myModuleProcessorProfiles = new ArrayList(); // the map is calculated by module processor profiles list for faster access to module settings @@ -597,35 +591,27 @@ public class CompilerConfigurationImpl extends CompilerConfiguration implements return true; } - // property names - private static final String EXCLUDE_FROM_COMPILE = "excludeFromCompile"; - private static final String RESOURCE_EXTENSIONS = "resourceExtensions"; - private static final String ANNOTATION_PROCESSING = "annotationProcessing"; - private static final String BYTECODE_TARGET_LEVEL = "bytecodeTargetLevel"; - private static final String WILDCARD_RESOURCE_PATTERNS = "wildcardResourcePatterns"; - private static final String ADD_NOTNULL_ASSERTIONS = "addNotNullAssertions"; - public void readExternal(Element parentNode) throws InvalidDataException { DefaultJDOMExternalizer.readExternal(this, parentNode); - final Element notNullAssertions = parentNode.getChild(ADD_NOTNULL_ASSERTIONS); + final Element notNullAssertions = parentNode.getChild(JpsJavaCompilerConfigurationSerializer.ADD_NOTNULL_ASSERTIONS); if (notNullAssertions != null) { - myAddNotNullAssertions = Boolean.valueOf(notNullAssertions.getAttributeValue(ENABLED, "true")); + myAddNotNullAssertions = Boolean.valueOf(notNullAssertions.getAttributeValue(JpsJavaCompilerConfigurationSerializer.ENABLED, "true")); } - Element node = parentNode.getChild(EXCLUDE_FROM_COMPILE); + Element node = parentNode.getChild(JpsJavaCompilerConfigurationSerializer.EXCLUDE_FROM_COMPILE); if (node != null) { myExcludedEntriesConfiguration.readExternal(node); } try { removeRegexpPatterns(); - node = parentNode.getChild(RESOURCE_EXTENSIONS); + node = parentNode.getChild(JpsJavaCompilerConfigurationSerializer.RESOURCE_EXTENSIONS); if (node != null) { - for (final Object o : node.getChildren(ENTRY)) { + for (final Object o : node.getChildren(JpsJavaCompilerConfigurationSerializer.ENTRY)) { Element element = (Element)o; - String pattern = element.getAttributeValue(NAME); + String pattern = element.getAttributeValue(JpsJavaCompilerConfigurationSerializer.NAME); if (!StringUtil.isEmpty(pattern)) { addRegexpPattern(pattern); } @@ -633,12 +619,12 @@ public class CompilerConfigurationImpl extends CompilerConfiguration implements } removeWildcardPatterns(); - node = parentNode.getChild(WILDCARD_RESOURCE_PATTERNS); + node = parentNode.getChild(JpsJavaCompilerConfigurationSerializer.WILDCARD_RESOURCE_PATTERNS); if (node != null) { myWildcardPatternsInitialized = true; - for (final Object o : node.getChildren(ENTRY)) { + for (final Object o : node.getChildren(JpsJavaCompilerConfigurationSerializer.ENTRY)) { final Element element = (Element)o; - String pattern = element.getAttributeValue(NAME); + String pattern = element.getAttributeValue(JpsJavaCompilerConfigurationSerializer.NAME); if (!StringUtil.isEmpty(pattern)) { addWildcardResourcePattern(pattern); } @@ -653,7 +639,7 @@ public class CompilerConfigurationImpl extends CompilerConfiguration implements myModuleProcessorProfiles.clear(); myProcessorsProfilesMap = null; - final Element annotationProcessingSettings = parentNode.getChild(ANNOTATION_PROCESSING); + final Element annotationProcessingSettings = parentNode.getChild(JpsJavaCompilerConfigurationSerializer.ANNOTATION_PROCESSING); if (annotationProcessingSettings != null) { final List profiles = annotationProcessingSettings.getChildren("profile"); if (!profiles.isEmpty()) { @@ -661,11 +647,11 @@ public class CompilerConfigurationImpl extends CompilerConfiguration implements final Element profileElement = (Element)elem; final boolean isDefault = "true".equals(profileElement.getAttributeValue("default")); if (isDefault) { - myDefaultProcessorsProfile.readExternal(profileElement); + AnnotationProcessorProfileSerializer.readExternal(myDefaultProcessorsProfile, profileElement); } else { - final ProcessorConfigProfile profile = new ProcessorConfigProfile(""); - profile.readExternal(profileElement); + final ProcessorConfigProfile profile = new ProcessorConfigProfileImpl(""); + AnnotationProcessorProfileSerializer.readExternal(profile, profileElement); myModuleProcessorProfiles.add(profile); } } @@ -678,15 +664,15 @@ public class CompilerConfigurationImpl extends CompilerConfiguration implements myBytecodeTargetLevel = null; myModuleBytecodeTarget.clear(); - final Element bytecodeTargetElement = parentNode.getChild(BYTECODE_TARGET_LEVEL); + final Element bytecodeTargetElement = parentNode.getChild(JpsJavaCompilerConfigurationSerializer.BYTECODE_TARGET_LEVEL); if (bytecodeTargetElement != null) { - myBytecodeTargetLevel = bytecodeTargetElement.getAttributeValue("target"); - for (Element elem : (Collection)bytecodeTargetElement.getChildren(MODULE)) { - final String name = elem.getAttributeValue(NAME); + myBytecodeTargetLevel = bytecodeTargetElement.getAttributeValue(JpsJavaCompilerConfigurationSerializer.TARGET_ATTRIBUTE); + for (Element elem : (Collection)bytecodeTargetElement.getChildren(JpsJavaCompilerConfigurationSerializer.MODULE)) { + final String name = elem.getAttributeValue(JpsJavaCompilerConfigurationSerializer.NAME); if (name == null) { continue; } - final String target = elem.getAttributeValue("target"); + final String target = elem.getAttributeValue(JpsJavaCompilerConfigurationSerializer.TARGET_ATTRIBUTE); if (target == null) { continue; } @@ -697,7 +683,7 @@ public class CompilerConfigurationImpl extends CompilerConfiguration implements private void loadProfilesFromOldFormat(Element processing) { // collect data - final boolean isEnabled = Boolean.parseBoolean(processing.getAttributeValue(ENABLED, "false")); + final boolean isEnabled = Boolean.parseBoolean(processing.getAttributeValue(JpsJavaCompilerConfigurationSerializer.ENABLED, "false")); final boolean isUseClasspath = Boolean.parseBoolean(processing.getAttributeValue("useClasspath", "true")); final StringBuilder processorPath = new StringBuilder(); final Set optionPairs = new HashSet(); @@ -717,7 +703,7 @@ public class CompilerConfigurationImpl extends CompilerConfiguration implements for (Object child : processing.getChildren("processor")) { final Element processorElement = (Element)child; - final String proc = processorElement.getAttributeValue(NAME, (String)null); + final String proc = processorElement.getAttributeValue(JpsJavaCompilerConfigurationSerializer.NAME, (String)null); if (proc != null) { processors.add(proc); } @@ -730,7 +716,7 @@ public class CompilerConfigurationImpl extends CompilerConfiguration implements for (Object child : processing.getChildren("processModule")) { final Element moduleElement = (Element)child; - final String name = moduleElement.getAttributeValue(NAME, (String)null); + final String name = moduleElement.getAttributeValue(JpsJavaCompilerConfigurationSerializer.NAME, (String)null); if (name == null) { continue; } @@ -769,7 +755,7 @@ public class CompilerConfigurationImpl extends CompilerConfiguration implements int profileIndex = 0; for (Map.Entry> entry : dirNameToModulesMap.entrySet()) { final String dirName = entry.getKey(); - final ProcessorConfigProfile profile = new ProcessorConfigProfile(myDefaultProcessorsProfile); + final ProcessorConfigProfile profile = new ProcessorConfigProfileImpl(myDefaultProcessorsProfile); profile.setName("Profile" + (++profileIndex)); profile.setEnabled(isEnabled); profile.setGeneratedSourcesDirectoryName(dirName); @@ -784,44 +770,47 @@ public class CompilerConfigurationImpl extends CompilerConfiguration implements DefaultJDOMExternalizer.writeExternal(this, parentNode); if (myAddNotNullAssertions != true) { - addChild(parentNode, ADD_NOTNULL_ASSERTIONS).setAttribute(ENABLED, String.valueOf(myAddNotNullAssertions)); + addChild(parentNode, JpsJavaCompilerConfigurationSerializer.ADD_NOTNULL_ASSERTIONS).setAttribute( + JpsJavaCompilerConfigurationSerializer.ENABLED, String.valueOf(myAddNotNullAssertions)); } if(myExcludedEntriesConfiguration.getExcludeEntryDescriptions().length > 0) { - myExcludedEntriesConfiguration.writeExternal(addChild(parentNode, EXCLUDE_FROM_COMPILE)); + myExcludedEntriesConfiguration.writeExternal(addChild(parentNode, JpsJavaCompilerConfigurationSerializer.EXCLUDE_FROM_COMPILE)); } - final Element newChild = addChild(parentNode, RESOURCE_EXTENSIONS); + final Element newChild = addChild(parentNode, JpsJavaCompilerConfigurationSerializer.RESOURCE_EXTENSIONS); for (final String pattern : getRegexpPatterns()) { - addChild(newChild, ENTRY).setAttribute(NAME, pattern); + addChild(newChild, JpsJavaCompilerConfigurationSerializer.ENTRY).setAttribute(JpsJavaCompilerConfigurationSerializer.NAME, pattern); } if (myWildcardPatternsInitialized || !myWildcardPatterns.isEmpty()) { - final Element wildcardPatterns = addChild(parentNode, WILDCARD_RESOURCE_PATTERNS); + final Element wildcardPatterns = addChild(parentNode, JpsJavaCompilerConfigurationSerializer.WILDCARD_RESOURCE_PATTERNS); for (final String wildcardPattern : myWildcardPatterns) { - addChild(wildcardPatterns, ENTRY).setAttribute(NAME, wildcardPattern); + addChild(wildcardPatterns, JpsJavaCompilerConfigurationSerializer.ENTRY).setAttribute(JpsJavaCompilerConfigurationSerializer.NAME, wildcardPattern); } } - final Element annotationProcessingSettings = addChild(parentNode, ANNOTATION_PROCESSING); - myDefaultProcessorsProfile.writeExternal(addChild(annotationProcessingSettings, "profile").setAttribute("default", "true")); + final Element annotationProcessingSettings = addChild(parentNode, JpsJavaCompilerConfigurationSerializer.ANNOTATION_PROCESSING); + AnnotationProcessorProfileSerializer + .writeExternal(myDefaultProcessorsProfile, addChild(annotationProcessingSettings, "profile").setAttribute("default", "true")); for (ProcessorConfigProfile profile : myModuleProcessorProfiles) { - profile.writeExternal(addChild(annotationProcessingSettings, "profile").setAttribute("default", "false")); + AnnotationProcessorProfileSerializer + .writeExternal(profile, addChild(annotationProcessingSettings, "profile").setAttribute("default", "false")); } if (!StringUtil.isEmpty(myBytecodeTargetLevel) || !myModuleBytecodeTarget.isEmpty()) { - final Element bytecodeTarget = addChild(parentNode, BYTECODE_TARGET_LEVEL); + final Element bytecodeTarget = addChild(parentNode, JpsJavaCompilerConfigurationSerializer.BYTECODE_TARGET_LEVEL); if (!StringUtil.isEmpty(myBytecodeTargetLevel)) { - bytecodeTarget.setAttribute("target", myBytecodeTargetLevel); + bytecodeTarget.setAttribute(JpsJavaCompilerConfigurationSerializer.TARGET_ATTRIBUTE, myBytecodeTargetLevel); } if (!myModuleBytecodeTarget.isEmpty()) { final List moduleNames = new ArrayList(myModuleBytecodeTarget.keySet()); - Collections.sort(moduleNames, ALPHA_COMPARATOR); + Collections.sort(moduleNames, String.CASE_INSENSITIVE_ORDER); for (String name : moduleNames) { - final Element moduleElement = addChild(bytecodeTarget, MODULE); - moduleElement.setAttribute(NAME, name); + final Element moduleElement = addChild(bytecodeTarget, JpsJavaCompilerConfigurationSerializer.MODULE); + moduleElement.setAttribute(JpsJavaCompilerConfigurationSerializer.NAME, name); final String value = myModuleBytecodeTarget.get(name); - moduleElement.setAttribute("target", value != null? value : ""); + moduleElement.setAttribute(JpsJavaCompilerConfigurationSerializer.TARGET_ATTRIBUTE, value != null? value : ""); } } } diff --git a/java/compiler/impl/src/com/intellij/compiler/actions/ProcessAnnotationsAction.java b/java/compiler/impl/src/com/intellij/compiler/actions/ProcessAnnotationsAction.java index 1b9c50e6ce2c..bb5970753e0c 100644 --- a/java/compiler/impl/src/com/intellij/compiler/actions/ProcessAnnotationsAction.java +++ b/java/compiler/impl/src/com/intellij/compiler/actions/ProcessAnnotationsAction.java @@ -15,7 +15,7 @@ */ package com.intellij.compiler.actions; -import com.intellij.compiler.AnnotationProcessingConfiguration; +import org.jetbrains.jps.model.java.compiler.AnnotationProcessingConfiguration; import com.intellij.compiler.CompilerConfiguration; import com.intellij.compiler.impl.FileSetCompileScope; import com.intellij.compiler.impl.ModuleCompileScope; diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/javac/JavacCompiler.java b/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/javac/JavacCompiler.java index 1a2a44ef74e7..7b3a9f5dd67d 100644 --- a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/javac/JavacCompiler.java +++ b/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/javac/JavacCompiler.java @@ -41,6 +41,7 @@ import com.intellij.rt.compiler.JavacRunner; import com.intellij.util.ArrayUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; +import org.jetbrains.jps.model.java.compiler.AnnotationProcessingConfiguration; import java.io.*; import java.util.*; diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/javac/JavacSettings.java b/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/javac/JavacSettings.java index 97106f0fe19b..f8dd14500237 100644 --- a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/javac/JavacSettings.java +++ b/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/javac/JavacSettings.java @@ -22,6 +22,7 @@ import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import com.intellij.util.Chunk; import org.jetbrains.annotations.TestOnly; +import org.jetbrains.jps.model.java.compiler.JpsJavaCompilerOptions; import java.nio.charset.Charset; import java.util.ArrayList; @@ -29,13 +30,7 @@ import java.util.Collection; import java.util.List; import java.util.StringTokenizer; -public class JavacSettings { - public boolean DEBUGGING_INFO = true; - public boolean GENERATE_NO_WARNINGS = false; - public boolean DEPRECATION = true; - public String ADDITIONAL_OPTIONS_STRING = ""; - public int MAXIMUM_HEAP_SIZE = 128; - +public class JavacSettings extends JpsJavaCompilerOptions { private boolean myTestsUseExternalCompiler = false; public Collection getOptions(Chunk chunk) { diff --git a/java/compiler/impl/src/com/intellij/compiler/options/AnnotationProcessorsConfigurable.java b/java/compiler/impl/src/com/intellij/compiler/options/AnnotationProcessorsConfigurable.java index ea1848d7dae8..1bf80911e040 100644 --- a/java/compiler/impl/src/com/intellij/compiler/options/AnnotationProcessorsConfigurable.java +++ b/java/compiler/impl/src/com/intellij/compiler/options/AnnotationProcessorsConfigurable.java @@ -17,13 +17,13 @@ package com.intellij.compiler.options; import com.intellij.compiler.CompilerConfiguration; import com.intellij.compiler.CompilerConfigurationImpl; -import com.intellij.compiler.ProcessorConfigProfile; import com.intellij.compiler.server.BuildManager; import com.intellij.openapi.options.Configurable; import com.intellij.openapi.options.ConfigurationException; import com.intellij.openapi.options.SearchableConfigurable; import com.intellij.openapi.project.Project; import org.jetbrains.annotations.NotNull; +import org.jetbrains.jps.model.java.compiler.ProcessorConfigProfile; import javax.swing.*; import java.util.List; diff --git a/java/compiler/impl/src/com/intellij/compiler/options/AnnotationProcessorsPanel.java b/java/compiler/impl/src/com/intellij/compiler/options/AnnotationProcessorsPanel.java index bd21e07f56b6..0eeadcab8c29 100644 --- a/java/compiler/impl/src/com/intellij/compiler/options/AnnotationProcessorsPanel.java +++ b/java/compiler/impl/src/com/intellij/compiler/options/AnnotationProcessorsPanel.java @@ -15,7 +15,7 @@ */ package com.intellij.compiler.options; -import com.intellij.compiler.ProcessorConfigProfile; +import org.jetbrains.jps.model.java.compiler.ProcessorConfigProfile; import com.intellij.icons.AllIcons; import com.intellij.openapi.actionSystem.ActionManager; import com.intellij.openapi.actionSystem.AnActionEvent; @@ -38,6 +38,7 @@ import com.intellij.ui.components.JBList; import com.intellij.ui.treeStructure.Tree; import com.intellij.util.ui.EditableTreeModel; import com.intellij.util.ui.tree.TreeUtil; +import org.jetbrains.jps.model.java.impl.compiler.ProcessorConfigProfileImpl; import javax.swing.*; import javax.swing.event.TreeSelectionEvent; @@ -55,7 +56,7 @@ import java.util.List; */ @SuppressWarnings({"unchecked", "UseOfObsoleteCollectionType"}) public class AnnotationProcessorsPanel extends JPanel { - private final ProcessorConfigProfile myDefaultProfile = new ProcessorConfigProfile(""); + private final ProcessorConfigProfile myDefaultProfile = new ProcessorConfigProfileImpl(""); private final List myModuleProfiles = new ArrayList(); private final Map myAllModulesMap = new HashMap(); private final Project myProject; @@ -170,7 +171,7 @@ public class AnnotationProcessorsPanel extends JPanel { myDefaultProfile.initFrom(defaultProfile); myModuleProfiles.clear(); for (ProcessorConfigProfile profile : moduleProfiles) { - ProcessorConfigProfile copy = new ProcessorConfigProfile(""); + ProcessorConfigProfile copy = new ProcessorConfigProfileImpl(""); copy.initFrom(profile); myModuleProfiles.add(copy); } @@ -252,7 +253,7 @@ public class AnnotationProcessorsPanel extends JPanel { } }); if (newProfileName != null) { - final ProcessorConfigProfile profile = new ProcessorConfigProfile(newProfileName); + final ProcessorConfigProfile profile = new ProcessorConfigProfileImpl(newProfileName); myModuleProfiles.add(profile); ((DataSynchronizable)getRoot()).sync(); final DefaultMutableTreeNode object = TreeUtil.findNodeWithObject((DefaultMutableTreeNode)getRoot(), profile); diff --git a/java/compiler/impl/src/com/intellij/compiler/options/ProcessorProfilePanel.java b/java/compiler/impl/src/com/intellij/compiler/options/ProcessorProfilePanel.java index 403e070b2657..e47cf402473a 100644 --- a/java/compiler/impl/src/com/intellij/compiler/options/ProcessorProfilePanel.java +++ b/java/compiler/impl/src/com/intellij/compiler/options/ProcessorProfilePanel.java @@ -15,7 +15,7 @@ */ package com.intellij.compiler.options; -import com.intellij.compiler.ProcessorConfigProfile; +import org.jetbrains.jps.model.java.compiler.ProcessorConfigProfile; import com.intellij.openapi.fileChooser.FileChooser; import com.intellij.openapi.fileChooser.FileChooserDescriptor; import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory; diff --git a/java/compiler/openapi/src/com/intellij/compiler/CompilerConfiguration.java b/java/compiler/openapi/src/com/intellij/compiler/CompilerConfiguration.java index 7bbba891ff29..76bb48a9f0ad 100644 --- a/java/compiler/openapi/src/com/intellij/compiler/CompilerConfiguration.java +++ b/java/compiler/openapi/src/com/intellij/compiler/CompilerConfiguration.java @@ -21,6 +21,7 @@ import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import org.jetbrains.jps.model.java.compiler.AnnotationProcessingConfiguration; public abstract class CompilerConfiguration { // need this flag for profiling purposes. In production code is always set to 'true' diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightVisitorImpl.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightVisitorImpl.java index 8bfcd3f2b0f0..a11968f67cbd 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightVisitorImpl.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightVisitorImpl.java @@ -268,7 +268,7 @@ public class HighlightVisitorImpl extends JavaElementVisitor implements Highligh final PsiClassType.ClassResolveResult resolveResult = PsiUtil.resolveGenericsClassInType(functionalInterfaceType); for (int i = 0; i < lambdaParameters.length; i++) { PsiParameter lambdaParameter = lambdaParameters[i]; - if (!TypeConversionUtil.isAssignable(resolveResult.getSubstitutor().substitute(parameters[i].getType()), lambdaParameter.getType())) { + if (!TypeConversionUtil.isAssignable(LambdaUtil.getSubstitutor(interfaceMethod, resolveResult).substitute(parameters[i].getType()), lambdaParameter.getType())) { myHolder.add(HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, lambdaParameter, incompatibleTypesMessage)); break; } diff --git a/java/java-impl/src/com/intellij/codeInspection/AnonymousCanBeLambdaInspection.java b/java/java-impl/src/com/intellij/codeInspection/AnonymousCanBeLambdaInspection.java index f9e873a5d891..99699e9a1a47 100644 --- a/java/java-impl/src/com/intellij/codeInspection/AnonymousCanBeLambdaInspection.java +++ b/java/java-impl/src/com/intellij/codeInspection/AnonymousCanBeLambdaInspection.java @@ -77,19 +77,29 @@ public class AnonymousCanBeLambdaInspection extends BaseJavaLocalInspectionTool if (methods.length == 1) { final PsiCodeBlock body = methods[0].getBody(); if (body != null) { - final boolean [] recursive = new boolean[1]; + final boolean [] bodyContainsForbiddenRefs = new boolean[1]; body.accept(new JavaRecursiveElementWalkingVisitor() { @Override public void visitMethodCallExpression(PsiMethodCallExpression methodCallExpression) { super.visitMethodCallExpression(methodCallExpression); if (methodCallExpression.resolveMethod() == methods[0]) { - recursive[0] = true; + bodyContainsForbiddenRefs[0] = true; } } + + @Override + public void visitThisExpression(PsiThisExpression expression) { + bodyContainsForbiddenRefs[0] = true; + } + + @Override + public void visitSuperExpression(PsiSuperExpression expression) { + bodyContainsForbiddenRefs[0] = true; + } }); - if (!recursive[0]) { + if (!bodyContainsForbiddenRefs[0]) { holder.registerProblem(aClass.getBaseClassReference(), "Anonymous #ref #loc can be replaced with lambda", - ProblemHighlightType.LIKE_UNUSED_SYMBOL, new ReplaceWithLambdaFix()); + ProblemHighlightType.GENERIC_ERROR_OR_WARNING, new ReplaceWithLambdaFix()); } } } 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 63f7af036750..64eaa91db3af 100644 --- a/java/java-impl/src/com/intellij/codeInspection/deadCode/UnusedDeclarationInspection.java +++ b/java/java-impl/src/com/intellij/codeInspection/deadCode/UnusedDeclarationInspection.java @@ -96,6 +96,7 @@ public class UnusedDeclarationInspection extends FilteringInspectionTool { private WeakUnreferencedFilter myFilter; private DeadHTMLComposer myComposer; @NonNls public static final String SHORT_NAME = "UnusedDeclaration"; + @NonNls private static final String ALTERNATIVE_ID = "unused"; private static final String COMMENT_OUT_QUICK_FIX = InspectionsBundle.message("inspection.dead.code.comment.quickfix"); private static final String DELETE_QUICK_FIX = InspectionsBundle.message("inspection.dead.code.safe.delete.quickfix"); @@ -351,7 +352,7 @@ public class UnusedDeclarationInspection extends FilteringInspectionTool { PsiFile file = refElement.getContainingFile(); if (file == null) return; - final boolean isSuppressed = refElement.isSuppressed(getShortName()); + final boolean isSuppressed = refElement.isSuppressed(getShortName(), ALTERNATIVE_ID); if (!getContext().isToCheckFile(file, UnusedDeclarationInspection.this) || isSuppressed) { if (isSuppressed || !scope.contains(file)) { getEntryPointsManager().addEntryPoint(refElement, false); diff --git a/java/java-impl/src/com/intellij/psi/codeStyle/arrangement/JavaArrangementVisitor.java b/java/java-impl/src/com/intellij/psi/codeStyle/arrangement/JavaArrangementVisitor.java index c14cb2f493df..2137a0c06318 100644 --- a/java/java-impl/src/com/intellij/psi/codeStyle/arrangement/JavaArrangementVisitor.java +++ b/java/java-impl/src/com/intellij/psi/codeStyle/arrangement/JavaArrangementVisitor.java @@ -45,14 +45,15 @@ public class JavaArrangementVisitor extends JavaElementVisitor { MODIFIERS.put(PsiModifier.ABSTRACT, ArrangementModifier.ABSTRACT); } - private final Stack myStack = new Stack(); + @NotNull private final Stack myStack = new Stack(); + @NotNull private final Map myEntries = new HashMap(); @NotNull private final List myRootEntries; - @NotNull private Document myDocument; @NotNull private Collection myRanges; + @Nullable private Document myDocument; public JavaArrangementVisitor(@NotNull List entries, - @NotNull Document document, + @Nullable Document document, @NotNull Collection ranges) { myRootEntries = entries; @@ -69,16 +70,16 @@ public class JavaArrangementVisitor extends JavaElementVisitor { else if (aClass.isInterface()) { type = ArrangementEntryType.INTERFACE; } - JavaElementArrangementEntry entry = createNewEntry(aClass.getTextRange(), type, aClass.getName(), true); + JavaElementArrangementEntry entry = createNewEntry(aClass, type, aClass.getName(), true); processEntry(entry, aClass, aClass); } @Override public void visitAnonymousClass(PsiAnonymousClass aClass) { - JavaElementArrangementEntry entry = createNewEntry(aClass.getTextRange(), ArrangementEntryType.CLASS, aClass.getName(), false); + JavaElementArrangementEntry entry = createNewEntry(aClass, ArrangementEntryType.CLASS, aClass.getName(), false); processEntry(entry, null, aClass); } - + @Override public void visitJavaFile(PsiJavaFile file) { for (PsiClass psiClass : file.getClasses()) { @@ -88,13 +89,43 @@ public class JavaArrangementVisitor extends JavaElementVisitor { @Override public void visitField(PsiField field) { - JavaElementArrangementEntry entry = createNewEntry(field.getTextRange(), ArrangementEntryType.FIELD, field.getName(), true); + JavaElementArrangementEntry entry = createNewEntry(field, ArrangementEntryType.FIELD, field.getName(), true); processEntry(entry, field, field.getInitializer()); } + @Override + public void visitClassInitializer(PsiClassInitializer initializer) { + JavaElementArrangementEntry entry = createNewEntry(initializer, ArrangementEntryType.FIELD, null, true); + if (entry == null) { + return; + } + + PsiElement classLBrace = null; + PsiClass clazz = initializer.getContainingClass(); + if (clazz != null) { + classLBrace = clazz.getLBrace(); + } + for (PsiElement e = initializer.getPrevSibling(); e != null; e = e.getPrevSibling()) { + JavaElementArrangementEntry prevEntry; + if (e == classLBrace) { + prevEntry = myEntries.get(clazz); + } + else { + prevEntry = myEntries.get(e); + } + if (prevEntry != null) { + entry.addDependency(prevEntry); + } + if (!(e instanceof PsiWhiteSpace)) { + break; + } + } + } + @Override public void visitMethod(PsiMethod method) { - JavaElementArrangementEntry entry = createNewEntry(method.getTextRange(), ArrangementEntryType.METHOD, method.getName(), true); + ArrangementEntryType type = method.isConstructor() ? ArrangementEntryType.CONSTRUCTOR : ArrangementEntryType.METHOD; + JavaElementArrangementEntry entry = createNewEntry(method, type, method.getName(), true); processEntry(entry, method, method.getBody()); } @@ -110,7 +141,7 @@ public class JavaArrangementVisitor extends JavaElementVisitor { return; } JavaElementArrangementEntry entry = - createNewEntry(anonymousClass.getTextRange(), ArrangementEntryType.CLASS, anonymousClass.getName(), false); + createNewEntry(anonymousClass, ArrangementEntryType.CLASS, anonymousClass.getName(), false); processEntry(entry, null, anonymousClass); } @@ -151,31 +182,33 @@ public class JavaArrangementVisitor extends JavaElementVisitor { } @Nullable - private JavaElementArrangementEntry createNewEntry(@NotNull TextRange range, + private JavaElementArrangementEntry createNewEntry(@NotNull PsiElement element, @NotNull ArrangementEntryType type, @Nullable String name, boolean canArrange) { + TextRange range = element.getTextRange(); if (!isWithinBounds(range)) { return null; } DefaultArrangementEntry current = getCurrent(); JavaElementArrangementEntry entry; if (canArrange) { - TextRange expandedRange = ArrangementUtil.expandToLine(range, myDocument.getCharsSequence()); + TextRange expandedRange = myDocument == null ? null : ArrangementUtil.expandToLine(range, myDocument.getCharsSequence()); TextRange rangeToUse = expandedRange == null ? range : expandedRange; - entry = new JavaElementArrangementEntry(current, rangeToUse, type, name, expandedRange != null); + entry = new JavaElementArrangementEntry(current, rangeToUse, type, name, myDocument == null || expandedRange != null); } else { entry = new JavaElementArrangementEntry(current, range, type, name, false); } + myEntries.put(element, entry); if (current == null) { myRootEntries.add(entry); } else { current.addChild(entry); } - + return entry; } diff --git a/java/java-impl/src/com/intellij/psi/codeStyle/arrangement/JavaElementArrangementEntry.java b/java/java-impl/src/com/intellij/psi/codeStyle/arrangement/JavaElementArrangementEntry.java index ebb29bf6868d..3e8499813fa3 100644 --- a/java/java-impl/src/com/intellij/psi/codeStyle/arrangement/JavaElementArrangementEntry.java +++ b/java/java-impl/src/com/intellij/psi/codeStyle/arrangement/JavaElementArrangementEntry.java @@ -26,6 +26,8 @@ import java.util.EnumSet; import java.util.Set; /** + * Not thread-safe. + * * @author Denis Zhdanov * @since 7/20/12 4:50 PM */ @@ -58,6 +60,9 @@ public class JavaElementArrangementEntry extends DefaultArrangementEntry super(parent, startOffset, endOffset, canBeArranged); myType = type; myTypes = EnumSet.of(type); + if (myType == ArrangementEntryType.CONSTRUCTOR) { + myTypes.add(ArrangementEntryType.METHOD); + } myName = name; } diff --git a/java/java-impl/src/com/intellij/psi/codeStyle/arrangement/JavaRearranger.java b/java/java-impl/src/com/intellij/psi/codeStyle/arrangement/JavaRearranger.java index f4b9a342257e..8cc7d3d1e8ec 100644 --- a/java/java-impl/src/com/intellij/psi/codeStyle/arrangement/JavaRearranger.java +++ b/java/java-impl/src/com/intellij/psi/codeStyle/arrangement/JavaRearranger.java @@ -45,7 +45,7 @@ public class JavaRearranger implements Rearranger, { // Type - @NotNull private static final Set SUPPORTED_TYPES = EnumSet.of(INTERFACE, CLASS, ENUM, FIELD, METHOD); + @NotNull private static final Set SUPPORTED_TYPES = EnumSet.of(INTERFACE, CLASS, ENUM, FIELD, METHOD, CONSTRUCTOR); // Modifier @NotNull private static final Set SUPPORTED_MODIFIERS = EnumSet.of( @@ -68,6 +68,7 @@ public class JavaRearranger implements Rearranger, MODIFIERS_BY_TYPE.put(INTERFACE, visibilityModifiers); MODIFIERS_BY_TYPE.put(CLASS, concat(commonModifiers, ABSTRACT)); MODIFIERS_BY_TYPE.put(METHOD, concat(commonModifiers, SYNCHRONIZED, ABSTRACT)); + MODIFIERS_BY_TYPE.put(CONSTRUCTOR, concat(commonModifiers, SYNCHRONIZED)); MODIFIERS_BY_TYPE.put(FIELD, concat(commonModifiers, TRANSIENT, VOLATILE)); } @@ -86,9 +87,12 @@ public class JavaRearranger implements Rearranger, for (ArrangementModifier modifier : visibility) { and(FIELD, modifier); } + and(CONSTRUCTOR); + and(METHOD, STATIC); and(METHOD); and(ENUM); and(INTERFACE); + and(CLASS, STATIC); and(CLASS); } @@ -114,11 +118,19 @@ public class JavaRearranger implements Rearranger, return result; } + @Nullable + @Override + public JavaElementArrangementEntry wrap(@NotNull PsiElement element) { + List result = new ArrayList(); + element.accept(new JavaArrangementVisitor(result, null, Collections.singleton(element.getTextRange()))); + return result.size() == 1 ? result.get(0) : null; + } + @NotNull @Override - public Collection parse(@NotNull PsiElement root, - @NotNull Document document, - @NotNull Collection ranges) + public List parse(@NotNull PsiElement root, + @Nullable Document document, + @NotNull Collection ranges) { // Following entries are subject to arrangement: class, interface, field, method. List result = new ArrayList(); diff --git a/java/java-impl/src/com/intellij/psi/impl/JavaPsiImplementationHelperImpl.java b/java/java-impl/src/com/intellij/psi/impl/JavaPsiImplementationHelperImpl.java index 5a1b11ae77f2..b50de94d8e6a 100644 --- a/java/java-impl/src/com/intellij/psi/impl/JavaPsiImplementationHelperImpl.java +++ b/java/java-impl/src/com/intellij/psi/impl/JavaPsiImplementationHelperImpl.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2011 JetBrains s.r.o. + * Copyright 2000-2012 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,6 +19,8 @@ import com.intellij.ide.fileTemplates.FileTemplate; import com.intellij.ide.fileTemplates.FileTemplateManager; import com.intellij.ide.fileTemplates.JavaTemplateUtil; import com.intellij.lang.ASTNode; +import com.intellij.lang.java.JavaLanguage; +import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileTypes.StdFileTypes; import com.intellij.openapi.module.Module; @@ -32,6 +34,7 @@ import com.intellij.pom.java.LanguageLevel; import com.intellij.psi.*; import com.intellij.psi.codeStyle.CodeStyleSettings; import com.intellij.psi.codeStyle.CodeStyleSettingsManager; +import com.intellij.psi.codeStyle.arrangement.MemberOrderService; import com.intellij.psi.impl.compiled.ClsClassImpl; import com.intellij.psi.impl.source.codeStyle.ImportHelper; import com.intellij.psi.search.GlobalSearchScope; @@ -174,43 +177,43 @@ public class JavaPsiImplementationHelperImpl extends JavaPsiImplementationHelper return importHelper.getDefaultAnchor(list, statement); } + @Nullable @Override - public PsiElement getDefaultMemberAnchor(PsiClass aClass, PsiMember member) { + public PsiElement getDefaultMemberAnchor(@NotNull PsiClass aClass, @NotNull PsiMember member) { CodeStyleSettings settings = CodeStyleSettingsManager.getSettings(aClass.getProject()); + MemberOrderService service = ServiceManager.getService(MemberOrderService.class); + PsiElement anchor = service.getAnchor(member, settings.getCommonSettings(JavaLanguage.INSTANCE), aClass); - int order = getMemberOrderWeight(member, settings); - if (order < 0) return null; - - PsiElement lastMember = null; - for (PsiElement child = aClass.getFirstChild(); child != null; child = child.getNextSibling()) { - int order1 = getMemberOrderWeight(child, settings); - if (order1 < 0) continue; - if (order1 > order) { - if (lastMember != null) { - PsiElement nextSibling = lastMember.getNextSibling(); - while (nextSibling instanceof PsiJavaToken && (nextSibling.getText().equals(",") || nextSibling.getText().equals(";"))) { - nextSibling = nextSibling.getNextSibling(); - } - return nextSibling == null ? aClass.getLBrace().getNextSibling() : nextSibling; - } - else { - // The main idea is to avoid to anchor to 'white space' element because that causes reformatting algorithm - // to perform incorrectly. The algorithm is encapsulated at PostprocessReformattingAspect.doPostponedFormattingInner(). - final PsiElement lBrace = aClass.getLBrace(); - if (lBrace != null) { - PsiElement result = lBrace.getNextSibling(); - while (result instanceof PsiWhiteSpace) { - result = result.getNextSibling(); - } - return result; - } - } - } - lastMember = child; + if (anchor != null && anchor.getNextSibling() == aClass.getRBrace()) { + // Given member should be inserted as the last child. + return aClass.getRBrace(); } + + if (anchor != null && anchor != aClass) { + anchor = anchor.getNextSibling(); + while (anchor instanceof PsiJavaToken && (anchor.getText().equals(",") || anchor.getText().equals(";"))) { + anchor = anchor.getNextSibling(); + } + if (anchor != null) { + return anchor; + } + } + + // The main idea is to avoid to anchor to 'white space' element because that causes reformatting algorithm + // to perform incorrectly. The algorithm is encapsulated at the PostprocessReformattingAspect.doPostponedFormattingInner(). + final PsiElement lBrace = aClass.getLBrace(); + if (lBrace != null) { + PsiElement result = lBrace.getNextSibling(); + while (result instanceof PsiWhiteSpace) { + result = result.getNextSibling(); + } + return result; + } + return aClass.getRBrace(); } - + + // TODO remove as soon as an arrangement sub-system is provided for groovy. public static int getMemberOrderWeight(PsiElement member, CodeStyleSettings settings) { if (member instanceof PsiField) { if (member instanceof PsiEnumConstant) { diff --git a/java/java-indexing-impl/src/com/intellij/psi/impl/search/AnnotatedElementsSearcher.java b/java/java-indexing-impl/src/com/intellij/psi/impl/search/AnnotatedElementsSearcher.java index bd34343787ee..1ceaaa9295dd 100644 --- a/java/java-indexing-impl/src/com/intellij/psi/impl/search/AnnotatedElementsSearcher.java +++ b/java/java-indexing-impl/src/com/intellij/psi/impl/search/AnnotatedElementsSearcher.java @@ -1,8 +1,6 @@ package com.intellij.psi.impl.search; -import com.intellij.openapi.application.AccessToken; import com.intellij.openapi.application.ApplicationManager; -import com.intellij.openapi.application.ReadAction; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.Computable; import com.intellij.openapi.vfs.VirtualFile; @@ -13,7 +11,7 @@ import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.LocalSearchScope; import com.intellij.psi.search.SearchScope; import com.intellij.psi.search.searches.AnnotatedElementsSearch; -import com.intellij.psi.util.PsiUtil; +import com.intellij.psi.util.PsiUtilCore; import com.intellij.util.Processor; import com.intellij.util.QueryExecutor; import com.intellij.util.indexing.FileBasedIndex; @@ -21,6 +19,7 @@ import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.Collection; +import java.util.List; /** * @author max @@ -71,11 +70,8 @@ public class AnnotatedElementsSearcher implements QueryExecutor getAnnotationCandidates(final PsiClass annClass, SearchScope useScope) { - AccessToken token = ReadAction.start(); - try { - if (useScope instanceof GlobalSearchScope) { - return JavaAnnotationIndex.getInstance().get(annClass.getName(), annClass.getProject(), (GlobalSearchScope)useScope); - } - final ArrayList result = new ArrayList(); - for (PsiElement element : ((LocalSearchScope)useScope).getScope()) { - element.accept(new PsiRecursiveElementWalkingVisitor() { - @Override - public void visitElement(PsiElement element) { - if (element instanceof PsiAnnotation) { - result.add((PsiAnnotation)element); + private static Collection getAnnotationCandidates(final PsiClass annClass, final SearchScope useScope) { + return ApplicationManager.getApplication().runReadAction(new Computable>() { + @Override + public Collection compute() { + if (useScope instanceof GlobalSearchScope) { + return JavaAnnotationIndex.getInstance().get(annClass.getName(), annClass.getProject(), (GlobalSearchScope)useScope); + } + final List result = new ArrayList(); + for (PsiElement element : ((LocalSearchScope)useScope).getScope()) { + element.accept(new PsiRecursiveElementWalkingVisitor() { + @Override + public void visitElement(PsiElement element) { + if (element instanceof PsiAnnotation) { + result.add(element); + } } - } - }); + }); + } + return result; } - return result; - } - finally { - token.finish(); - } + }); } public static boolean isInstanceof(PsiElement owner, Class[] types) { @@ -123,7 +118,7 @@ public class AnnotatedElementsSearcher implements QueryExecutor() { + @Override + public Boolean compute() { + return !p.isCheckInheritance() || candidate.isInheritor(aClass, false); + } + }); } private static boolean processSameNamedClasses(Processor consumer, PsiClass aClass, List sameNamedClasses) { 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 9ace49ef2003..18a71e4c5944 100644 --- a/java/java-psi-api/src/com/intellij/psi/GenericsUtil.java +++ b/java/java-psi-api/src/com/intellij/psi/GenericsUtil.java @@ -340,10 +340,10 @@ public class GenericsUtil { } public static PsiType eliminateWildcards(PsiType type) { - return eliminateWildcardsInner(type, true); + return eliminateWildcards(type, true); } - static PsiType eliminateWildcardsInner(PsiType type, final boolean eliminateInTypeArguments) { + public static PsiType eliminateWildcards(PsiType type, final boolean eliminateInTypeArguments) { if (eliminateInTypeArguments && type instanceof PsiClassType) { PsiClassType classType = ((PsiClassType)type); JavaResolveResult resolveResult = classType.resolveGenerics(); @@ -367,7 +367,7 @@ public class GenericsUtil { } } else if (type instanceof PsiArrayType) { - return eliminateWildcardsInner(((PsiArrayType)type).getComponentType(), false).createArrayType(); + return eliminateWildcards(((PsiArrayType)type).getComponentType(), false).createArrayType(); } else if (type instanceof PsiWildcardType) { final PsiType bound = ((PsiWildcardType)type).getBound(); diff --git a/java/java-psi-api/src/com/intellij/psi/LambdaUtil.java b/java/java-psi-api/src/com/intellij/psi/LambdaUtil.java index 859ffea05220..d27d77536a2e 100644 --- a/java/java-psi-api/src/com/intellij/psi/LambdaUtil.java +++ b/java/java-psi-api/src/com/intellij/psi/LambdaUtil.java @@ -30,6 +30,7 @@ import java.util.*; */ public class LambdaUtil { private static final Logger LOG = Logger.getInstance("#" + LambdaUtil.class.getName()); + public static ThreadLocal> ourParams = new ThreadLocal>(); @Nullable public static PsiType getFunctionalInterfaceReturnType(PsiLambdaExpression expr) { @@ -52,8 +53,12 @@ public class LambdaUtil { @Nullable public static PsiMethod getFunctionalInterfaceMethod(PsiType functionalInterfaceType) { - final PsiClassType.ClassResolveResult resolveResult = PsiUtil.resolveGenericsClassInType(functionalInterfaceType); - final PsiClass psiClass = resolveResult.getElement(); + return getFunctionalInterfaceMethod(PsiUtil.resolveGenericsClassInType(functionalInterfaceType)); + } + + @Nullable + public static PsiMethod getFunctionalInterfaceMethod(PsiClassType.ClassResolveResult result) { + final PsiClass psiClass = result.getElement(); if (psiClass != null) { final MethodSignature methodSignature = getFunction(psiClass); if (methodSignature != null) { @@ -63,6 +68,15 @@ public class LambdaUtil { return null; } + public static PsiSubstitutor getSubstitutor(@NotNull PsiMethod method, @NotNull PsiClassType.ClassResolveResult resolveResult) { + final PsiClass derivedClass = resolveResult.getElement(); + LOG.assertTrue(derivedClass != null); + + final PsiClass methodContainingClass = method.getContainingClass(); + LOG.assertTrue(methodContainingClass != null); + return TypeConversionUtil.getSuperClassSubstitutor(methodContainingClass, derivedClass, resolveResult.getSubstitutor()); + } + public static boolean isValidLambdaContext(PsiElement context) { return context instanceof PsiTypeCastExpression || context instanceof PsiAssignmentExpression || @@ -75,9 +89,10 @@ public class LambdaUtil { } public static boolean isLambdaFullyInferred(PsiLambdaExpression expression, PsiType functionalInterfaceType) { - if (expression.getParameterList().getParametersCount() > 0 || getFunctionalInterfaceReturnType(functionalInterfaceType) != PsiType.VOID) { //todo check that void lambdas without params check + if (expression.getParameterList().getParametersCount() > 0 || + getFunctionalInterfaceReturnType(functionalInterfaceType) != PsiType.VOID) { //todo check that void lambdas without params check if (functionalInterfaceType instanceof PsiClassType && ((PsiClassType)functionalInterfaceType).isRaw()) return false; - return !dependsOnTypeParams(functionalInterfaceType, expression); + return !dependsOnTypeParams(functionalInterfaceType, functionalInterfaceType, expression, null); } return true; } @@ -126,11 +141,11 @@ public class LambdaUtil { return null; } - public static boolean isAcceptable(PsiLambdaExpression lambdaExpression, final PsiType leftType) { + public static boolean isAcceptable(PsiLambdaExpression lambdaExpression, final PsiType leftType, boolean checkReturnType) { final PsiClassType.ClassResolveResult resolveResult = PsiUtil.resolveGenericsClassInType(leftType); final PsiClass psiClass = resolveResult.getElement(); if (psiClass instanceof PsiAnonymousClass) { - return isAcceptable(lambdaExpression, ((PsiAnonymousClass)psiClass).getBaseClassType()); + return isAcceptable(lambdaExpression, ((PsiAnonymousClass)psiClass).getBaseClassType(), checkReturnType); } final MethodSignature methodSignature = getFunction(psiClass); if (methodSignature == null) return false; @@ -149,16 +164,19 @@ public class LambdaUtil { } if (!TypeConversionUtil.erasure(lambdaFormalType) - .isAssignableFrom(TypeConversionUtil.erasure(GenericsUtil.eliminateWildcards(resolveResult.getSubstitutor().substitute(methodSignature.getSubstitutor().substitute(methodParameterType)))))) { + .isAssignableFrom(TypeConversionUtil.erasure(GenericsUtil.eliminateWildcards( + resolveResult.getSubstitutor().substitute(methodSignature.getSubstitutor().substitute(methodParameterType)))))) { return false; } } } - LOG.assertTrue(psiClass != null); - PsiType methodReturnType = getReturnType(psiClass, methodSignature); - if (methodReturnType != null) { - methodReturnType = resolveResult.getSubstitutor().substitute(methodSignature.getSubstitutor().substitute(methodReturnType)); - return checkReturnTypeCompatible(lambdaExpression, methodReturnType) == null; + if (checkReturnType) { + LOG.assertTrue(psiClass != null); + PsiType methodReturnType = getReturnType(psiClass, methodSignature); + if (methodReturnType != null) { + methodReturnType = resolveResult.getSubstitutor().substitute(methodSignature.getSubstitutor().substitute(methodReturnType)); + return checkReturnTypeCompatible(lambdaExpression, methodReturnType) == null; + } } return true; } @@ -274,6 +292,14 @@ public class LambdaUtil { return depends(type, param2Check, new TypeParamsChecker(expr)); } + public static boolean dependsOnTypeParams(PsiType type, + PsiType functionalInterfaceType, + PsiLambdaExpression lambdaExpression, + PsiTypeParameter param2Check) { + return depends(type, param2Check, new TypeParamsChecker(lambdaExpression, + PsiUtil.resolveClassInType(functionalInterfaceType))); + } + public static boolean dependsOnTypeParams(PsiType type, PsiClass aClass, PsiMethod aMethod) { @@ -291,7 +317,10 @@ public class LambdaUtil { public static boolean isFreeFromTypeInferenceArgs(final PsiParameter[] methodParameters, final PsiLambdaExpression lambdaExpression, - final PsiExpression expression) { + final PsiExpression expression, + final PsiSubstitutor subst, + final PsiType functionalInterfaceType, + final PsiTypeParameter typeParam) { if (expression instanceof PsiCallExpression && ((PsiCallExpression)expression).getTypeArguments().length > 0) return true; if (expression instanceof PsiNewExpression) { final PsiJavaCodeReferenceElement classReference = ((PsiNewExpression)expression).getClassOrAnonymousClassReference(); @@ -300,16 +329,16 @@ public class LambdaUtil { if (parameterList != null) { final PsiTypeElement[] typeParameterElements = parameterList.getTypeParameterElements(); if (typeParameterElements.length > 0) { - if (!(typeParameterElements[0].getType() instanceof PsiDiamondType)){ + if (!(typeParameterElements[0].getType() instanceof PsiDiamondType)) { return true; } } } } } - final PsiParameter[] lambdaParams = lambdaExpression.getParameterList().getParameters(); + final PsiParameter[] lambdaParams = lambdaExpression.getParameterList().getParameters(); if (lambdaParams.length != methodParameters.length) return false; - final boolean [] independent = new boolean[]{true}; + final boolean[] independent = new boolean[]{true}; expression.accept(new JavaRecursiveElementWalkingVisitor() { @Override public void visitConditionalExpression(PsiConditionalExpression expression) { @@ -335,7 +364,7 @@ public class LambdaUtil { } } - if (usedParamIdx > -1 && dependsOnTypeParams(methodParameters[usedParamIdx].getType(), lambdaExpression)) { + if (usedParamIdx > -1 && dependsOnTypeParams(subst.substitute(methodParameters[usedParamIdx].getType()), functionalInterfaceType, lambdaExpression, typeParam)) { independent[0] = false; } } @@ -386,22 +415,21 @@ public class LambdaUtil { final PsiElement gParent = expressionList.getParent(); if (gParent instanceof PsiCallExpression) { final PsiCallExpression contextCall = (PsiCallExpression)gParent; - final JavaResolveResult resolveResult = contextCall.resolveMethodGenerics(); - final PsiElement resolve = resolveResult.getElement(); - if (resolve instanceof PsiMethod) { - final PsiParameter[] parameters = ((PsiMethod)resolve).getParameterList().getParameters(); - if (lambdaIdx < parameters.length) { - if (!tryToSubstitute) { - return parameters[lambdaIdx].getType(); - } - return PsiResolveHelper.ourGuard.doPreventingRecursion(expression, true, new Computable() { - @Override - public PsiType compute() { + return PsiResolveHelper.ourGuard.doPreventingRecursion(expression, true, new Computable() { + @Override + public PsiType compute() { + final JavaResolveResult resolveResult = contextCall.resolveMethodGenerics(); + final PsiElement resolve = resolveResult.getElement(); + if (resolve instanceof PsiMethod) { + final PsiParameter[] parameters = ((PsiMethod)resolve).getParameterList().getParameters(); + if (lambdaIdx < parameters.length) { + if (!tryToSubstitute) return parameters[lambdaIdx].getType(); return resolveResult.getSubstitutor().substitute(parameters[lambdaIdx].getType()); } - }); + } + return null; } - } + }); } } } @@ -426,28 +454,38 @@ public class LambdaUtil { final int parameterIndex = ((PsiParameterList)paramParent).getParameterIndex(param); if (parameterIndex > -1) { final PsiLambdaExpression lambdaExpression = PsiTreeUtil.getParentOfType(param, PsiLambdaExpression.class); - PsiType type = getFunctionalInterfaceType(lambdaExpression, true); - if (type == null) { - type = getFunctionalInterfaceType(lambdaExpression, false); - } - final PsiClassType.ClassResolveResult resolveResult = PsiUtil.resolveGenericsClassInType(type); - if (resolveResult != null) { - final PsiMethod method = getFunctionalInterfaceMethod(type); - if (method != null) { - final PsiParameter[] parameters = method.getParameterList().getParameters(); - if (parameterIndex < parameters.length) { - final PsiType psiType = resolveResult.getSubstitutor().substitute(parameters[parameterIndex].getType()); - if (!dependsOnTypeParams(psiType, lambdaExpression)) { - if (psiType instanceof PsiWildcardType) { - final PsiType bound = ((PsiWildcardType)psiType).getBound(); - if (bound != null) { - return bound; + if (lambdaExpression != null) { + + Set currentStack = ourParams.get(); + if (currentStack == null) { + currentStack = new HashSet(); + ourParams.set(currentStack); + } + + final PsiParameterList parameterList = lambdaExpression.getParameterList(); + try { + currentStack.add(parameterList); + PsiType type = getFunctionalInterfaceType(lambdaExpression, true); + if (type == null) { + type = getFunctionalInterfaceType(lambdaExpression, false); + } + final PsiClassType.ClassResolveResult resolveResult = PsiUtil.resolveGenericsClassInType(type); + if (resolveResult != null) { + final PsiMethod method = getFunctionalInterfaceMethod(type); + if (method != null) { + final PsiParameter[] parameters = method.getParameterList().getParameters(); + if (parameterIndex < parameters.length) { + final PsiType psiType = getSubstitutor(method, resolveResult).substitute(parameters[parameterIndex].getType()); + if (!dependsOnTypeParams(psiType, type, lambdaExpression, null)) { + return GenericsUtil.eliminateWildcards(psiType); } } - return psiType; } } } + finally { + currentStack.remove(parameterList); + } } } } @@ -457,7 +495,7 @@ public class LambdaUtil { private static class TypeParamsChecker extends PsiTypeVisitor { private PsiMethod myMethod; private final PsiClass myClass; - private final Set myUsedTypeParams = new HashSet(); + private final Set myUsedTypeParams = new HashSet(); private TypeParamsChecker(PsiMethod method, PsiClass aClass) { myMethod = method; @@ -465,7 +503,11 @@ public class LambdaUtil { } public TypeParamsChecker(PsiLambdaExpression expression) { - myClass = PsiUtil.resolveGenericsClassInType(getFunctionalInterfaceType(expression, false)).getElement(); + this(expression, PsiUtil.resolveGenericsClassInType(getFunctionalInterfaceType(expression, false)).getElement()); + } + + public TypeParamsChecker(PsiLambdaExpression expression, PsiClass aClass) { + myClass = aClass; PsiElement parent = expression.getParent(); while (parent instanceof PsiParenthesizedExpression) { parent = parent.getParent(); diff --git a/java/java-psi-api/src/com/intellij/psi/infos/MethodCandidateInfo.java b/java/java-psi-api/src/com/intellij/psi/infos/MethodCandidateInfo.java index 02085303e9d8..019dc845efcd 100644 --- a/java/java-psi-api/src/com/intellij/psi/infos/MethodCandidateInfo.java +++ b/java/java-psi-api/src/com/intellij/psi/infos/MethodCandidateInfo.java @@ -15,19 +15,17 @@ */ package com.intellij.psi.infos; -import com.intellij.openapi.util.Key; import com.intellij.pom.java.LanguageLevel; import com.intellij.psi.*; import com.intellij.psi.impl.source.resolve.DefaultParameterTypeInferencePolicy; import com.intellij.psi.impl.source.resolve.ParameterTypeInferencePolicy; import com.intellij.psi.util.PsiUtil; -import com.intellij.util.containers.ConcurrentHashMap; import com.intellij.util.containers.ConcurrentWeakHashMap; import org.intellij.lang.annotations.MagicConstant; import org.jetbrains.annotations.Nullable; -import java.util.HashMap; import java.util.Map; +import java.util.Set; /** * @author ik, dsl @@ -108,6 +106,12 @@ public class MethodCandidateInfo extends CandidateInfo{ } map.put(myArgumentList, getElement()); try { + + final Set lists = LambdaUtil.ourParams.get(); + if (lists != null && !lists.isEmpty()) { + return inferTypeArguments(DefaultParameterTypeInferencePolicy.INSTANCE); + } + myCalcedSubstitutor = inferTypeArguments(DefaultParameterTypeInferencePolicy.INSTANCE); } finally { diff --git a/java/java-psi-api/src/com/intellij/psi/util/TypeConversionUtil.java b/java/java-psi-api/src/com/intellij/psi/util/TypeConversionUtil.java index 06c0bcad82ee..d3f9c17ce7e3 100644 --- a/java/java-psi-api/src/com/intellij/psi/util/TypeConversionUtil.java +++ b/java/java-psi-api/src/com/intellij/psi/util/TypeConversionUtil.java @@ -648,7 +648,7 @@ public class TypeConversionUtil { if (right instanceof PsiLambdaExpressionType) { final PsiLambdaExpression rLambdaExpression = ((PsiLambdaExpressionType)right).getExpression(); if (left instanceof PsiClassType) { - return LambdaUtil.isAcceptable(rLambdaExpression, left); + return LambdaUtil.isAcceptable(rLambdaExpression, left, false); } if (left instanceof PsiLambdaExpressionType) { final PsiLambdaExpression lLambdaExpression = ((PsiLambdaExpressionType)left).getExpression(); diff --git a/java/java-psi-impl/src/com/intellij/core/CoreJavaPsiImplementationHelper.java b/java/java-psi-impl/src/com/intellij/core/CoreJavaPsiImplementationHelper.java index 0407bc285e35..e78527248038 100644 --- a/java/java-psi-impl/src/com/intellij/core/CoreJavaPsiImplementationHelper.java +++ b/java/java-psi-impl/src/com/intellij/core/CoreJavaPsiImplementationHelper.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2011 JetBrains s.r.o. + * Copyright 2000-2012 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,6 +20,7 @@ import com.intellij.openapi.vfs.VirtualFile; import com.intellij.pom.java.LanguageLevel; import com.intellij.psi.*; import com.intellij.psi.impl.JavaPsiImplementationHelper; +import org.jetbrains.annotations.NotNull; /** * @author yole @@ -46,7 +47,7 @@ public class CoreJavaPsiImplementationHelper extends JavaPsiImplementationHelper } @Override - public PsiElement getDefaultMemberAnchor(PsiClass psiClass, PsiMember firstPsi) { + public PsiElement getDefaultMemberAnchor(@NotNull PsiClass psiClass, @NotNull PsiMember firstPsi) { throw new UnsupportedOperationException("TODO"); } diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/JavaPsiImplementationHelper.java b/java/java-psi-impl/src/com/intellij/psi/impl/JavaPsiImplementationHelper.java index 89030a88f5fb..77b0675b6dde 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/JavaPsiImplementationHelper.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/JavaPsiImplementationHelper.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2011 JetBrains s.r.o. + * Copyright 2000-2012 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,6 +21,7 @@ import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.pom.java.LanguageLevel; import com.intellij.psi.*; +import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** @@ -46,7 +47,8 @@ public abstract class JavaPsiImplementationHelper { public abstract ASTNode getDefaultImportAnchor(PsiImportList list, PsiImportStatementBase statement); - public abstract PsiElement getDefaultMemberAnchor(PsiClass psiClass, PsiMember firstPsi); + @Nullable + public abstract PsiElement getDefaultMemberAnchor(@NotNull PsiClass psiClass, @NotNull PsiMember firstPsi); public abstract void setupCatchBlock(String exceptionName, PsiElement context, PsiCatchSection element); } diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/compiled/ClsTypeParametersListImpl.java b/java/java-psi-impl/src/com/intellij/psi/impl/compiled/ClsTypeParametersListImpl.java index 05b9cc608287..48ba55cc57e2 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/compiled/ClsTypeParametersListImpl.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/compiled/ClsTypeParametersListImpl.java @@ -16,15 +16,13 @@ package com.intellij.psi.impl.compiled; import com.intellij.openapi.diagnostic.Logger; -import com.intellij.psi.JavaElementVisitor; -import com.intellij.psi.PsiElementVisitor; -import com.intellij.psi.PsiTypeParameter; -import com.intellij.psi.PsiTypeParameterList; +import com.intellij.psi.*; import com.intellij.psi.impl.PsiImplUtil; import com.intellij.psi.impl.java.stubs.JavaStubElementTypes; import com.intellij.psi.impl.java.stubs.PsiTypeParameterListStub; import com.intellij.psi.impl.source.SourceTreeToPsiMap; import com.intellij.psi.impl.source.tree.TreeElement; +import com.intellij.psi.scope.PsiScopeProcessor; import org.jetbrains.annotations.NotNull; /** @@ -90,4 +88,16 @@ public class ClsTypeParametersListImpl extends ClsRepositoryPsiElement RAW_INFERENCE = new Pair(null, ConstraintType.EQUALS); private final PsiManager myManager; public PsiResolveHelperImpl(PsiManager manager) { @@ -206,7 +208,10 @@ public class PsiResolveHelperImpl implements PsiResolveHelper { final Pair currentSubstitution; if (argumentType instanceof PsiLambdaExpressionType) { currentSubstitution = inferSubstitutionFromLambda(typeParameter, (PsiLambdaExpressionType)argumentType, lowerBound); - if (rawType && currentSubstitution == FAILED_INFERENCE || nullPassed && currentSubstitution == null) return new Pair(null, ConstraintType.EQUALS); + if (rawType) { + if (currentSubstitution == FAILED_INFERENCE || (currentSubstitution == null && lowerBound == PsiType.NULL)) return RAW_INFERENCE; + } + if (nullPassed && currentSubstitution == null) return RAW_INFERENCE; } else { currentSubstitution = getSubstitutionForTypeParameterConstraint(typeParameter, parameterType, argumentType, true, PsiUtil.getLanguageLevel(typeParameter)); @@ -218,7 +223,7 @@ public class PsiResolveHelperImpl implements PsiResolveHelper { final ConstraintType constraintType = currentSubstitution.getSecond(); final PsiType type = currentSubstitution.getFirst(); - if (type == null) return new Pair(null, ConstraintType.EQUALS); + if (type == null) return RAW_INFERENCE; switch(constraintType) { case EQUALS: if (!(type instanceof PsiWildcardType)) return currentSubstitution; @@ -590,27 +595,31 @@ public class PsiResolveHelperImpl implements PsiResolveHelper { final PsiType functionalInterfaceType, PsiType lowerBound) { final PsiClassType.ClassResolveResult resolveResult = PsiUtil.resolveGenericsClassInType(functionalInterfaceType); - final PsiMethod method = LambdaUtil.getFunctionalInterfaceMethod(functionalInterfaceType); + final PsiMethod method = LambdaUtil.getFunctionalInterfaceMethod(resolveResult); if (method != null) { - final Pair constraintFromFormalParams = inferConstraintFromLambdaFormalParams(typeParam, resolveResult, method, lambdaExpression); + final PsiSubstitutor subst = LambdaUtil.getSubstitutor(method, resolveResult); + final Pair constraintFromFormalParams = inferConstraintFromLambdaFormalParams(typeParam, subst, method, lambdaExpression); if (constraintFromFormalParams != null) return constraintFromFormalParams; final PsiParameter[] methodParameters = method.getParameterList().getParameters(); - final PsiSubstitutor subst = - TypeConversionUtil.getSuperClassSubstitutor(method.getContainingClass(), resolveResult.getElement(), resolveResult.getSubstitutor()); - final boolean methodParamsDependOnTypeParams = methodParamsDependOnTypeParams(lambdaExpression, methodParameters, subst, typeParam); + if (methodParamsDependOn(typeParam, lambdaExpression, functionalInterfaceType, methodParameters, subst)) { + if (lowerBound != PsiType.NULL) { + return null; + } + return getFailedInferenceConstraint(typeParam); + } + + final Set lists = LambdaUtil.ourParams.get(); + if (lists != null && lists.contains(lambdaExpression.getParameterList())){ + return null; + } + final PsiType returnType = subst.substitute(method.getReturnType()); if (returnType != null && returnType != PsiType.VOID) { Pair constraint = null; final List expressions = lambdaExpression.getReturnExpressions(); for (final PsiExpression expression : expressions) { - final boolean independent = LambdaUtil.isFreeFromTypeInferenceArgs(methodParameters, lambdaExpression, expression); - if (independent && methodParamsDependOnTypeParams ) { - if (lowerBound != PsiType.NULL) { - return null; - } - return FAILED_INFERENCE; - } + final boolean independent = LambdaUtil.isFreeFromTypeInferenceArgs(methodParameters, lambdaExpression, expression, subst, functionalInterfaceType, typeParam); if (!independent) { if (lowerBound != PsiType.NULL) { return null; @@ -634,7 +643,7 @@ public class PsiResolveHelperImpl implements PsiResolveHelper { } final Pair returnExprConstraint = - getSubstitutionForTypeParameterConstraint(typeParam, returnType, exprType, true, PsiUtil.getLanguageLevel(method)); + getSubstitutionForTypeParameterConstraint(typeParam, GenericsUtil.eliminateWildcards(returnType), exprType, true, PsiUtil.getLanguageLevel(method)); if (returnExprConstraint != null) { if (returnExprConstraint == FAILED_INFERENCE) return returnExprConstraint; if (constraint != null) { @@ -647,17 +656,16 @@ public class PsiResolveHelperImpl implements PsiResolveHelper { } if (constraint != null) return constraint; } - if (methodParamsDependOnTypeParams) return getFailedInferenceConstraint(typeParam); } return null; } - private static boolean methodParamsDependOnTypeParams(PsiLambdaExpression lambdaExpression, - PsiParameter[] methodParameters, - PsiSubstitutor subst, - PsiTypeParameter typeParam) { + private static boolean methodParamsDependOn(PsiTypeParameter typeParam, PsiLambdaExpression lambdaExpression, + PsiType functionalInterfaceType, + PsiParameter[] methodParameters, + PsiSubstitutor subst) { for (PsiParameter parameter : methodParameters) { - if (LambdaUtil.dependsOnTypeParams(subst.substitute(parameter.getType()), lambdaExpression, typeParam)) { + if (LambdaUtil.dependsOnTypeParams(subst.substitute(parameter.getType()), functionalInterfaceType, lambdaExpression, typeParam)) { return true; } } @@ -666,7 +674,7 @@ public class PsiResolveHelperImpl implements PsiResolveHelper { @Nullable private static Pair inferConstraintFromLambdaFormalParams(PsiTypeParameter typeParam, - PsiClassType.ClassResolveResult resolveResult, + PsiSubstitutor subst, PsiMethod method, PsiLambdaExpression lambdaExpression) { final PsiParameter[] parameters = lambdaExpression.getParameterList().getParameters(); if (parameters.length == 0) return null; @@ -679,13 +687,12 @@ public class PsiResolveHelperImpl implements PsiResolveHelper { lambdaArgs[i] = parameter.getType(); } - final PsiSubstitutor subst = resolveResult.getSubstitutor(); final PsiParameter[] methodParameters = method.getParameterList().getParameters(); PsiType[] methodParamTypes = new PsiType[methodParameters.length]; for (int i = 0; i < methodParameters.length; i++) { methodParamTypes[i] = subst.substitute(methodParameters[i].getType()); } - return inferTypeForMethodTypeParameterInner(typeParam, methodParamTypes, lambdaArgs, subst, null, DefaultParameterTypeInferencePolicy.INSTANCE); + return inferTypeForMethodTypeParameterInner(typeParam, methodParamTypes, lambdaArgs, subst, null, DefaultParameterTypeInferencePolicy.INSTANCE); } private static PsiType intersectAllExtends(PsiTypeParameter typeParam, PsiType arg) { @@ -903,8 +910,9 @@ public class PsiResolveHelperImpl implements PsiResolveHelper { final PsiMethod method = LambdaUtil.getFunctionalInterfaceMethod(functionalInterfaceType); final PsiClassType.ClassResolveResult resolveResult = PsiUtil.resolveGenericsClassInType(functionalInterfaceType); - if (method == null || methodParamsDependOnTypeParams((PsiLambdaExpression)expression, method.getParameterList().getParameters(), - TypeConversionUtil.getSuperClassSubstitutor(method.getContainingClass(), resolveResult.getElement(), resolveResult.getSubstitutor()), typeParameter)) { + if (method == null || methodParamsDependOn(typeParameter, (PsiLambdaExpression)expression, + functionalInterfaceType, method.getParameterList().getParameters(), + LambdaUtil.getSubstitutor(method, resolveResult))) { return getFailedInferenceConstraint(typeParameter); } } diff --git a/java/java-psi-impl/src/com/intellij/psi/presentation/java/VariablePresentationProvider.java b/java/java-psi-impl/src/com/intellij/psi/presentation/java/VariablePresentationProvider.java index 90c2e440a55f..c94ee9f79548 100644 --- a/java/java-psi-impl/src/com/intellij/psi/presentation/java/VariablePresentationProvider.java +++ b/java/java-psi-impl/src/com/intellij/psi/presentation/java/VariablePresentationProvider.java @@ -18,10 +18,7 @@ package com.intellij.psi.presentation.java; import com.intellij.navigation.ItemPresentation; import com.intellij.navigation.ItemPresentationProvider; import com.intellij.navigation.NavigationItem; -import com.intellij.psi.PsiSubstitutor; import com.intellij.psi.PsiVariable; -import com.intellij.psi.util.PsiFormatUtil; -import com.intellij.psi.util.PsiFormatUtilBase; import javax.swing.*; @@ -34,7 +31,8 @@ public class VariablePresentationProvider { + interface BinaryOperator { + + public T eval(T left, T right); + } + + interface Mapper { + U map(T t); + } + + public static LambdaTest map(final Iterable iterable, final Mapper mapper) { + return null; + } + + TT reduce(TT base, BinaryOperator reducer) { + return null; + } + + public void test() { + final List aStrings = Arrays.asList("1", "2", "3"); + map(aStrings, s -> s.length()).reduce(0, (l, r) -> l + r); + } +} + +class LambdaTest2 { + interface BinaryOperator { + public T eval(T left, T right); + } + + interface Mapper { + U map(T t); + } + + public LambdaTest map(final Mapper mapper) { + return null; + } + + TypeParam reduce(TypeParam base, BinaryOperator reducer) { + return null; + } + + public void test() { + final LambdaTest2 lt = new LambdaTest2<>(); + lt.map(s -> s.length()).reduce(0, (l, r) -> l + r); + } +} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/highlighting/LambdaRawOrNot.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/highlighting/LambdaRawOrNot.java index f4dfd65eed29..cfece56e219b 100644 --- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/highlighting/LambdaRawOrNot.java +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/highlighting/LambdaRawOrNot.java @@ -34,3 +34,27 @@ class Test3 { bar(x->{}, new ArrayList()); } } + + +class Test4 { + protected U exerciseOps(TestData data, TerminalOp1 terminal, IntermediateOp1... ops) { + return exerciseOps(data, (u, v) -> u.equals(v), terminal, ops); + } + + protected static U exerciseOps(TestData data, + BiPredicate1 equalator, + TerminalOp1 terminalOp, + IntermediateOp1[] ops) { + return null; + } + + public interface IntermediateOp1 { + + } + public interface BiPredicate1 extends IntermediateOp1{ + boolean _(T t, U u); + } + + public interface TerminalOp1 extends IntermediateOp1 {} + +} diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/anonymous2lambda/beforeThisRefInside.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/anonymous2lambda/beforeThisRefInside.java new file mode 100644 index 000000000000..9bfb884a7be1 --- /dev/null +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/anonymous2lambda/beforeThisRefInside.java @@ -0,0 +1,11 @@ +// "Replace with lambda" "false" +class Test { + { + Runnable x = new Runnable() { + public void run() { + this.toString(); + } + }; + + } +} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/bindFieldsFromParameters/afterSimple.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/bindFieldsFromParameters/afterSimple.java index 829746789fed..673c1773b046 100644 --- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/bindFieldsFromParameters/afterSimple.java +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/bindFieldsFromParameters/afterSimple.java @@ -2,11 +2,11 @@ class Bar { - private int myi1; - private int myi2; private final int myI1; private final int myI2; private final String myI3; + private int myi1; + private int myi2; Bar(int i1, int i2, String i3) { myI1 = i1; diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/bindFieldsFromParameters/beforeSimple.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/bindFieldsFromParameters/beforeSimple.java index 6f64007a938f..608d6064f84d 100644 --- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/bindFieldsFromParameters/beforeSimple.java +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/bindFieldsFromParameters/beforeSimple.java @@ -2,9 +2,9 @@ class Bar { - private int myi1; - private int myi2; + private int myi1; + private int myi2; - Bar(int i1, int i2, String i3) { - } + Bar(int i1, int i2, String i3) { + } } \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/changeParameterClass/before6.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/changeParameterClass/before6.java index cc6d7029a28e..3aa784d6b1ef 100644 --- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/changeParameterClass/before6.java +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/changeParameterClass/before6.java @@ -3,7 +3,6 @@ class a { void f(b r) { r.g(this); } - } interface b { void g(b t); diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/createInnerClassFromNew/after6.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/createInnerClassFromNew/after6.java index 6a2efa6d4be0..9d3259784c3f 100644 --- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/createInnerClassFromNew/after6.java +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/createInnerClassFromNew/after6.java @@ -3,7 +3,7 @@ public class Test { public static void main() { Collection[] cc = new MyCollection[10]; } - + private static class MyCollection { } } \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/createInnerClassFromNew/after8.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/createInnerClassFromNew/after8.java index cc29ef3e9228..edc5d2214de0 100644 --- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/createInnerClassFromNew/after8.java +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/createInnerClassFromNew/after8.java @@ -6,7 +6,7 @@ public class Test { public static void main() { JTable table = new JTable(new MyTableModel()); } - + private static class MyTableModel implements TableModel { } } \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/createInnerClassFromNew/afterGenerics.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/createInnerClassFromNew/afterGenerics.java index b6b899b61d22..4461f899b52b 100644 --- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/createInnerClassFromNew/afterGenerics.java +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/createInnerClassFromNew/afterGenerics.java @@ -3,7 +3,7 @@ class Test { void foo () { new Generic (); } - + private class Generic { } } \ No newline at end of file diff --git a/java/java-tests/testData/refactoring/extractMethodObject/WithPrivateMethodUsed1.java b/java/java-tests/testData/refactoring/extractMethodObject/WithPrivateMethodUsed1.java index c5fbbd81e4c1..e2c3ea2bb64b 100644 --- a/java/java-tests/testData/refactoring/extractMethodObject/WithPrivateMethodUsed1.java +++ b/java/java-tests/testData/refactoring/extractMethodObject/WithPrivateMethodUsed1.java @@ -43,12 +43,10 @@ public class TestClass { return yearsTo( expiry ); } return 0.0; - } private double yearsTo( final Date endDate ) { Date beginDate = ( today == null ? start : today ); return ( ( endDate.getTime() - beginDate.getTime() )); } - } \ No newline at end of file diff --git a/java/java-tests/testData/refactoring/extractMethodObject/WithPrivateMethodUsed1.java.after b/java/java-tests/testData/refactoring/extractMethodObject/WithPrivateMethodUsed1.java.after index b19b72b035ae..c4543e3e663e 100644 --- a/java/java-tests/testData/refactoring/extractMethodObject/WithPrivateMethodUsed1.java.after +++ b/java/java-tests/testData/refactoring/extractMethodObject/WithPrivateMethodUsed1.java.after @@ -41,7 +41,6 @@ public class TestClass { return yearsTo( expiry ); } return 0.0; - } private double riskFactor() { diff --git a/java/java-tests/testData/refactoring/extractMethodObject/multipleExitPoints/MultilineDeclarations.java b/java/java-tests/testData/refactoring/extractMethodObject/multipleExitPoints/MultilineDeclarations.java index c180b6d990c0..89619d3152a2 100644 --- a/java/java-tests/testData/refactoring/extractMethodObject/multipleExitPoints/MultilineDeclarations.java +++ b/java/java-tests/testData/refactoring/extractMethodObject/multipleExitPoints/MultilineDeclarations.java @@ -6,5 +6,4 @@ class Test { System.out.println(MessageFormat.format("i: {0}", i)); System.out.println(MessageFormat.format("k: {0}", j)); } - } \ No newline at end of file diff --git a/java/java-tests/testData/refactoring/extractMethodObject/multipleExitPoints/OutputVarsReferences.java b/java/java-tests/testData/refactoring/extractMethodObject/multipleExitPoints/OutputVarsReferences.java index 8f488e8ef028..e0028c433982 100644 --- a/java/java-tests/testData/refactoring/extractMethodObject/multipleExitPoints/OutputVarsReferences.java +++ b/java/java-tests/testData/refactoring/extractMethodObject/multipleExitPoints/OutputVarsReferences.java @@ -7,5 +7,4 @@ class Test { System.out.println(MessageFormat.format("i: {0}", i)); System.out.println(MessageFormat.format("k: {0}", k)); } - } \ No newline at end of file diff --git a/java/java-tests/testData/refactoring/extractMethodObject/multipleExitPoints/WithInnerClasses.java b/java/java-tests/testData/refactoring/extractMethodObject/multipleExitPoints/WithInnerClasses.java index fba58852f134..880283dfb940 100644 --- a/java/java-tests/testData/refactoring/extractMethodObject/multipleExitPoints/WithInnerClasses.java +++ b/java/java-tests/testData/refactoring/extractMethodObject/multipleExitPoints/WithInnerClasses.java @@ -48,7 +48,6 @@ public class Demo { this.content = content; } } - } diff --git a/java/java-tests/testData/refactoring/inheritanceToDelegation/hierarchy/after/X.java b/java/java-tests/testData/refactoring/inheritanceToDelegation/hierarchy/after/X.java index 2e2966015be7..de17c5c88db9 100644 --- a/java/java-tests/testData/refactoring/inheritanceToDelegation/hierarchy/after/X.java +++ b/java/java-tests/testData/refactoring/inheritanceToDelegation/hierarchy/after/X.java @@ -1,7 +1,6 @@ public class X { - A myField; private final Base myDelegate = new Base(); - + A myField; public void method(Test t) { myField = t.getA(); myField.methodFromA(); diff --git a/java/java-tests/testData/refactoring/inheritanceToDelegation/overridenMethods/after/A.java b/java/java-tests/testData/refactoring/inheritanceToDelegation/overridenMethods/after/A.java index f9de8b45ae26..3eae87f94120 100644 --- a/java/java-tests/testData/refactoring/inheritanceToDelegation/overridenMethods/after/A.java +++ b/java/java-tests/testData/refactoring/inheritanceToDelegation/overridenMethods/after/A.java @@ -1,6 +1,6 @@ class A { - int fieldFromA; private final MyBase myDelegate = new MyBase(); + int fieldFromA; public void firstMethodFromBase() { myDelegate.firstMethodFromBase(); diff --git a/java/java-tests/testData/refactoring/inplaceIntroduceField/beforeAssignmentReplaceAllCall_after.java b/java/java-tests/testData/refactoring/inplaceIntroduceField/beforeAssignmentReplaceAllCall_after.java index f7d817a812a8..ed252a20d1d1 100644 --- a/java/java-tests/testData/refactoring/inplaceIntroduceField/beforeAssignmentReplaceAllCall_after.java +++ b/java/java-tests/testData/refactoring/inplaceIntroduceField/beforeAssignmentReplaceAllCall_after.java @@ -1,6 +1,6 @@ class Test { - private Foo myFoo; private final Foo foo; + private Foo myFoo; Test() { foo = new Foo(); diff --git a/java/java-tests/testData/refactoring/inplaceIntroduceField/beforeAssignmentReplaceAll_after.java b/java/java-tests/testData/refactoring/inplaceIntroduceField/beforeAssignmentReplaceAll_after.java index 3e61dd57c8de..356bd37129fd 100644 --- a/java/java-tests/testData/refactoring/inplaceIntroduceField/beforeAssignmentReplaceAll_after.java +++ b/java/java-tests/testData/refactoring/inplaceIntroduceField/beforeAssignmentReplaceAll_after.java @@ -1,6 +1,6 @@ class Test { - private String myTimer; private final String string; + private String myTimer; Test() { string = ""; diff --git a/java/java-tests/testData/refactoring/inplaceIntroduceField/beforeAssignment_after.java b/java/java-tests/testData/refactoring/inplaceIntroduceField/beforeAssignment_after.java index affd5251fc65..8c1a737d6311 100644 --- a/java/java-tests/testData/refactoring/inplaceIntroduceField/beforeAssignment_after.java +++ b/java/java-tests/testData/refactoring/inplaceIntroduceField/beforeAssignment_after.java @@ -1,6 +1,6 @@ class Test { - private String myTimer; private final String string; + private String myTimer; Test() { string = ""; diff --git a/java/java-tests/testData/refactoring/moveInstanceMethod/PolyadicExpr.java b/java/java-tests/testData/refactoring/moveInstanceMethod/PolyadicExpr.java index d9ecff9098e5..387ed5dd9347 100644 --- a/java/java-tests/testData/refactoring/moveInstanceMethod/PolyadicExpr.java +++ b/java/java-tests/testData/refactoring/moveInstanceMethod/PolyadicExpr.java @@ -20,5 +20,4 @@ class B { public int getI() { return i; } - } \ No newline at end of file diff --git a/java/java-tests/testData/refactoring/wrapReturnValue/staticMethodInnerClass/before/Test.java b/java/java-tests/testData/refactoring/wrapReturnValue/staticMethodInnerClass/before/Test.java index b48e2eb88e18..d406379d1e43 100644 --- a/java/java-tests/testData/refactoring/wrapReturnValue/staticMethodInnerClass/before/Test.java +++ b/java/java-tests/testData/refactoring/wrapReturnValue/staticMethodInnerClass/before/Test.java @@ -6,5 +6,4 @@ class Test { void bar() { String s = foo(); } - } \ No newline at end of file diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/LambdaHighlightingTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/LambdaHighlightingTest.java index 1ba880774e42..7dcec9c186b5 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/LambdaHighlightingTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/LambdaHighlightingTest.java @@ -125,6 +125,10 @@ public class LambdaHighlightingTest extends LightDaemonAnalyzerTestCase { doTest(); } + public void testIncompleteSubst() throws Exception { + doTest(); + } + private void doTest() throws Exception { doTest(BASE_PATH + "/" + getTestName(false) + ".java", false, false); } diff --git a/java/java-tests/testSrc/com/intellij/psi/codeStyle/arrangement/JavaRearrangerByTypeAndModifierTest.groovy b/java/java-tests/testSrc/com/intellij/psi/codeStyle/arrangement/JavaRearrangerByTypeAndModifierTest.groovy index 2d2fa4e39634..eec789d00f25 100644 --- a/java/java-tests/testSrc/com/intellij/psi/codeStyle/arrangement/JavaRearrangerByTypeAndModifierTest.groovy +++ b/java/java-tests/testSrc/com/intellij/psi/codeStyle/arrangement/JavaRearrangerByTypeAndModifierTest.groovy @@ -69,4 +69,38 @@ class Test { rule(CLASS)] ) } + + void testInstanceInitializationBlockBoundToField() { + doTest('''\ +class Test { + private int i; + public int j; + { j = 1; } + protected int k; +}''', '''\ +class Test { + public int j; + { j = 1; } + protected int k; + private int i; +}''', + [rule(FIELD, PUBLIC), rule(FIELD, PROTECTED), rule(FIELD, PRIVATE)]) + } + + void testInstanceInitializationBlockAsFirstChild() { + doTest('''\ +class Test { + { j = 1; } + private int i; + public int j; + protected int k; +}''', '''\ +class Test { + { j = 1; } + public int j; + protected int k; + private int i; +}''', + [rule(FIELD, PUBLIC), rule(FIELD, PROTECTED), rule(FIELD, PRIVATE)]) + } } diff --git a/java/java-tests/testSrc/com/intellij/psi/codeStyle/arrangement/JavaRearrangerByTypeTest.groovy b/java/java-tests/testSrc/com/intellij/psi/codeStyle/arrangement/JavaRearrangerByTypeTest.groovy index 29a24c4f2773..4397ffcd2cd3 100644 --- a/java/java-tests/testSrc/com/intellij/psi/codeStyle/arrangement/JavaRearrangerByTypeTest.groovy +++ b/java/java-tests/testSrc/com/intellij/psi/codeStyle/arrangement/JavaRearrangerByTypeTest.groovy @@ -18,6 +18,7 @@ package com.intellij.psi.codeStyle.arrangement import org.junit.Before import static com.intellij.psi.codeStyle.arrangement.match.ArrangementEntryType.* +import static com.intellij.psi.codeStyle.arrangement.match.ArrangementModifier.PUBLIC /** * @author Denis Zhdanov * @since 7/20/12 2:45 PM @@ -198,4 +199,36 @@ class Test { [rule(FIELD)] ) } + + void testMethodsAndConstructors() { + doTest('''\ +class Test { + abstract void method1(); + Test() {} + abstract void method2(); +}''', + '''\ +class Test { + Test() {} + abstract void method1(); + abstract void method2(); +}''', + [rule(CONSTRUCTOR), rule(METHOD)]) + } + + void testConstructorAsMethod() { + doTest('''\ +class Test { + private int i; + Test() {} + public int j; +}''', + '''\ +class Test { + public int j; + Test() {} + private int i; +}''', + [rule(FIELD, PUBLIC), rule(METHOD), rule(FIELD)]) + } } diff --git a/jps/jps-builders/jps-builders.iml b/jps/jps-builders/jps-builders.iml index 663db3cccfe0..52b7313e1d64 100644 --- a/jps/jps-builders/jps-builders.iml +++ b/jps/jps-builders/jps-builders.iml @@ -8,7 +8,6 @@ - @@ -37,6 +36,7 @@ + diff --git a/jps/model/src/org/jetbrains/ether/dependencyView/Callbacks.java b/jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/Callbacks.java similarity index 96% rename from jps/model/src/org/jetbrains/ether/dependencyView/Callbacks.java rename to jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/Callbacks.java index 2b3e499a2493..750297cab978 100644 --- a/jps/model/src/org/jetbrains/ether/dependencyView/Callbacks.java +++ b/jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/Callbacks.java @@ -1,4 +1,4 @@ -package org.jetbrains.ether.dependencyView; +package org.jetbrains.jps.builders.java.dependencyView; import org.jetbrains.asm4.ClassReader; diff --git a/jps/model/src/org/jetbrains/ether/dependencyView/ClassRepr.java b/jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/ClassRepr.java similarity index 99% rename from jps/model/src/org/jetbrains/ether/dependencyView/ClassRepr.java rename to jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/ClassRepr.java index 0a8f41e27766..a6a1db871f5a 100644 --- a/jps/model/src/org/jetbrains/ether/dependencyView/ClassRepr.java +++ b/jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/ClassRepr.java @@ -1,10 +1,9 @@ -package org.jetbrains.ether.dependencyView; +package org.jetbrains.jps.builders.java.dependencyView; import com.intellij.util.io.DataExternalizer; -import groovyjarjarasm.asm.Opcodes; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.jetbrains.ether.RW; +import org.jetbrains.asm4.Opcodes; import java.io.*; import java.lang.annotation.RetentionPolicy; diff --git a/jps/model/src/org/jetbrains/ether/dependencyView/ClassfileAnalyzer.java b/jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/ClassfileAnalyzer.java similarity index 99% rename from jps/model/src/org/jetbrains/ether/dependencyView/ClassfileAnalyzer.java rename to jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/ClassfileAnalyzer.java index af8622107a5a..2a999cfe49b0 100644 --- a/jps/model/src/org/jetbrains/ether/dependencyView/ClassfileAnalyzer.java +++ b/jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/ClassfileAnalyzer.java @@ -1,4 +1,4 @@ -package org.jetbrains.ether.dependencyView; +package org.jetbrains.jps.builders.java.dependencyView; import com.intellij.openapi.util.Pair; import gnu.trove.TIntHashSet; diff --git a/jps/model/src/org/jetbrains/ether/dependencyView/CollectionFactory.java b/jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/CollectionFactory.java similarity index 73% rename from jps/model/src/org/jetbrains/ether/dependencyView/CollectionFactory.java rename to jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/CollectionFactory.java index dc0f4a0b8952..879507f76e81 100644 --- a/jps/model/src/org/jetbrains/ether/dependencyView/CollectionFactory.java +++ b/jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/CollectionFactory.java @@ -1,4 +1,4 @@ -package org.jetbrains.ether.dependencyView; +package org.jetbrains.jps.builders.java.dependencyView; import java.util.Collection; diff --git a/jps/model/src/org/jetbrains/ether/dependencyView/DependencyContext.java b/jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/DependencyContext.java similarity index 94% rename from jps/model/src/org/jetbrains/ether/dependencyView/DependencyContext.java rename to jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/DependencyContext.java index bebf0d5ecfed..dac4794f6484 100644 --- a/jps/model/src/org/jetbrains/ether/dependencyView/DependencyContext.java +++ b/jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/DependencyContext.java @@ -1,122 +1,122 @@ -package org.jetbrains.ether.dependencyView; - -import com.intellij.openapi.util.io.FileUtil; -import com.intellij.util.io.PersistentStringEnumerator; - -import java.io.File; -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - -/** - * Created by IntelliJ IDEA. - * User: db - * Date: 14.02.11 - * Time: 2:03 - * To change this template use File | Settings | File Templates. - */ -class DependencyContext { - private final static String STRING_TABLE_NAME = "strings.tab"; - private final PersistentStringEnumerator myEnumerator; - - private final Map myTypeMap = new HashMap(); - private final Map myUsageMap = new HashMap(); - - UsageRepr.Usage getUsage(final UsageRepr.Usage u) { - final UsageRepr.Usage r = myUsageMap.get(u); - - if (r == null) { - myUsageMap.put(u, u); - return u; - } - - return r; - } - - TypeRepr.AbstractType getType(final TypeRepr.AbstractType t) { - final TypeRepr.AbstractType r = myTypeMap.get(t); - - if (r != null) { - return r; - } - - myTypeMap.put(t, t); - - return t; - } - - void clearMemoryCaches() { - myTypeMap.clear(); - myUsageMap.clear(); - } - - static File getTableFile (final File rootDir, final String name) { - final File file = new File(FileUtil.toSystemIndependentName(rootDir.getAbsoluteFile() + File.separator + name)); - FileUtil.createIfDoesntExist(file); - return file; - } - - DependencyContext(final File rootDir) throws IOException { - final File file = getTableFile(rootDir, STRING_TABLE_NAME); - - myEnumerator = new PersistentStringEnumerator(file, true); - } - - public String getValue(final int s) { - try { - return myEnumerator.valueOf(s); - } - catch (IOException e) { - throw new RuntimeException(e); - } - } - - public int get(final String s) { - try { - final int i = s == null ? myEnumerator.enumerate("") : myEnumerator.enumerate(s); - - return i; - } - catch (IOException e) { - throw new RuntimeException(e); - } - } - - public void close() { - try { - myEnumerator.close(); - } - catch (IOException e) { - throw new RuntimeException(e); - } - } - - public void flush() { - myEnumerator.force(); - } - - public Logger getLogger(final com.intellij.openapi.diagnostic.Logger log) { - return new Logger() { - @Override - public void debug(String comment, Integer s) { - if (log.isDebugEnabled()) { - log.debug(comment + getValue(s)); - } - } - - @Override - public void debug(String comment, String t) { - if (log.isDebugEnabled()){ - log.debug(comment + t); - } - } - - @Override - public void debug(String comment, boolean t) { - if (log.isDebugEnabled()) { - log.debug(comment + Boolean.toString(t)); - } - } - }; - } -} +package org.jetbrains.jps.builders.java.dependencyView; + +import com.intellij.openapi.util.io.FileUtil; +import com.intellij.util.io.PersistentStringEnumerator; + +import java.io.File; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +/** + * Created by IntelliJ IDEA. + * User: db + * Date: 14.02.11 + * Time: 2:03 + * To change this template use File | Settings | File Templates. + */ +class DependencyContext { + private final static String STRING_TABLE_NAME = "strings.tab"; + private final PersistentStringEnumerator myEnumerator; + + private final Map myTypeMap = new HashMap(); + private final Map myUsageMap = new HashMap(); + + UsageRepr.Usage getUsage(final UsageRepr.Usage u) { + final UsageRepr.Usage r = myUsageMap.get(u); + + if (r == null) { + myUsageMap.put(u, u); + return u; + } + + return r; + } + + TypeRepr.AbstractType getType(final TypeRepr.AbstractType t) { + final TypeRepr.AbstractType r = myTypeMap.get(t); + + if (r != null) { + return r; + } + + myTypeMap.put(t, t); + + return t; + } + + void clearMemoryCaches() { + myTypeMap.clear(); + myUsageMap.clear(); + } + + static File getTableFile (final File rootDir, final String name) { + final File file = new File(FileUtil.toSystemIndependentName(rootDir.getAbsoluteFile() + File.separator + name)); + FileUtil.createIfDoesntExist(file); + return file; + } + + DependencyContext(final File rootDir) throws IOException { + final File file = getTableFile(rootDir, STRING_TABLE_NAME); + + myEnumerator = new PersistentStringEnumerator(file, true); + } + + public String getValue(final int s) { + try { + return myEnumerator.valueOf(s); + } + catch (IOException e) { + throw new RuntimeException(e); + } + } + + public int get(final String s) { + try { + final int i = s == null ? myEnumerator.enumerate("") : myEnumerator.enumerate(s); + + return i; + } + catch (IOException e) { + throw new RuntimeException(e); + } + } + + public void close() { + try { + myEnumerator.close(); + } + catch (IOException e) { + throw new RuntimeException(e); + } + } + + public void flush() { + myEnumerator.force(); + } + + public Logger getLogger(final com.intellij.openapi.diagnostic.Logger log) { + return new Logger() { + @Override + public void debug(String comment, Integer s) { + if (log.isDebugEnabled()) { + log.debug(comment + getValue(s)); + } + } + + @Override + public void debug(String comment, String t) { + if (log.isDebugEnabled()){ + log.debug(comment + t); + } + } + + @Override + public void debug(String comment, boolean t) { + if (log.isDebugEnabled()) { + log.debug(comment + Boolean.toString(t)); + } + } + }; + } +} diff --git a/jps/model/src/org/jetbrains/ether/dependencyView/Difference.java b/jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/Difference.java similarity index 94% rename from jps/model/src/org/jetbrains/ether/dependencyView/Difference.java rename to jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/Difference.java index c7e5027c576d..cc16299e7d7a 100644 --- a/jps/model/src/org/jetbrains/ether/dependencyView/Difference.java +++ b/jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/Difference.java @@ -1,132 +1,132 @@ -package org.jetbrains.ether.dependencyView; - -import com.intellij.openapi.util.Pair; -import org.jetbrains.asm4.Opcodes; - -import java.util.*; - -/** - * Created by IntelliJ IDEA. - * User: db - * Date: 01.03.11 - * Time: 17:39 - * To change this template use File | Settings | File Templates. - */ -abstract class Difference { - public static boolean isPackageLocal(final int access) { - return (access & (Opcodes.ACC_PRIVATE | Opcodes.ACC_PROTECTED | Opcodes.ACC_PUBLIC)) == 0; - } - - public static boolean weakerAccess(final int me, final int then) { - return ((me & Opcodes.ACC_PRIVATE) > 0 && (then & Opcodes.ACC_PRIVATE) == 0) || - ((me & Opcodes.ACC_PROTECTED) > 0 && (then & Opcodes.ACC_PUBLIC) > 0) || - (isPackageLocal(me) && (then & Opcodes.ACC_PROTECTED) > 0); - } - - public static final int NONE = 0; - public static final int ACCESS = 1; - public static final int TYPE = 2; - public static final int VALUE = 4; - public static final int SIGNATURE = 8; - public static final int SUPERCLASS = 16; - public static final int USAGES = 32; - - public interface Specifier { - Collection added(); - - Collection removed(); - - Collection> changed(); - - boolean unchanged(); - } - - public static Specifier make(final Set past, final Set now) { - if (past == null) { - final Collection _now = Collections.unmodifiableCollection(now); - return new Specifier() { - public Collection added() { - return _now; - } - - public Collection removed() { - return Collections.emptyList(); - } - - public Collection> changed() { - return Collections.emptyList(); - } - - public boolean unchanged() { - return false; - } - }; - } - - final Set added = new HashSet(now); - - added.removeAll(past); - - final Set removed = new HashSet(past); - - removed.removeAll(now); - - final Set> changed = new HashSet>(); - final Set intersect = new HashSet(past); - final Map nowMap = new HashMap(); - - for (T s : now) { - if (intersect.contains(s)) { - nowMap.put(s, s); - } - } - - intersect.retainAll(now); - - for (T x : intersect) { - final T y = nowMap.get(x); - - if (x instanceof Proto) { - final Proto px = (Proto)x; - final Proto py = (Proto)y; - final Difference diff = py.difference(px); - - if (!diff.no()) { - changed.add(new Pair(x, diff)); - } - } - } - - return new Specifier() { - public Collection added() { - return added; - } - - public Collection removed() { - return removed; - } - - public Collection> changed() { - return changed; - } - - public boolean unchanged() { - return changed.isEmpty() && added.isEmpty() && removed.isEmpty(); - } - }; - } - - public abstract int base(); - - public abstract boolean no(); - - public abstract boolean weakedAccess(); - - public abstract int addedModifiers(); - - public abstract int removedModifiers(); - - public abstract boolean packageLocalOn(); - - public abstract boolean hadValue(); -} +package org.jetbrains.jps.builders.java.dependencyView; + +import com.intellij.openapi.util.Pair; +import org.jetbrains.asm4.Opcodes; + +import java.util.*; + +/** + * Created by IntelliJ IDEA. + * User: db + * Date: 01.03.11 + * Time: 17:39 + * To change this template use File | Settings | File Templates. + */ +abstract class Difference { + public static boolean isPackageLocal(final int access) { + return (access & (Opcodes.ACC_PRIVATE | Opcodes.ACC_PROTECTED | Opcodes.ACC_PUBLIC)) == 0; + } + + public static boolean weakerAccess(final int me, final int then) { + return ((me & Opcodes.ACC_PRIVATE) > 0 && (then & Opcodes.ACC_PRIVATE) == 0) || + ((me & Opcodes.ACC_PROTECTED) > 0 && (then & Opcodes.ACC_PUBLIC) > 0) || + (isPackageLocal(me) && (then & Opcodes.ACC_PROTECTED) > 0); + } + + public static final int NONE = 0; + public static final int ACCESS = 1; + public static final int TYPE = 2; + public static final int VALUE = 4; + public static final int SIGNATURE = 8; + public static final int SUPERCLASS = 16; + public static final int USAGES = 32; + + public interface Specifier { + Collection added(); + + Collection removed(); + + Collection> changed(); + + boolean unchanged(); + } + + public static Specifier make(final Set past, final Set now) { + if (past == null) { + final Collection _now = Collections.unmodifiableCollection(now); + return new Specifier() { + public Collection added() { + return _now; + } + + public Collection removed() { + return Collections.emptyList(); + } + + public Collection> changed() { + return Collections.emptyList(); + } + + public boolean unchanged() { + return false; + } + }; + } + + final Set added = new HashSet(now); + + added.removeAll(past); + + final Set removed = new HashSet(past); + + removed.removeAll(now); + + final Set> changed = new HashSet>(); + final Set intersect = new HashSet(past); + final Map nowMap = new HashMap(); + + for (T s : now) { + if (intersect.contains(s)) { + nowMap.put(s, s); + } + } + + intersect.retainAll(now); + + for (T x : intersect) { + final T y = nowMap.get(x); + + if (x instanceof Proto) { + final Proto px = (Proto)x; + final Proto py = (Proto)y; + final Difference diff = py.difference(px); + + if (!diff.no()) { + changed.add(new Pair(x, diff)); + } + } + } + + return new Specifier() { + public Collection added() { + return added; + } + + public Collection removed() { + return removed; + } + + public Collection> changed() { + return changed; + } + + public boolean unchanged() { + return changed.isEmpty() && added.isEmpty() && removed.isEmpty(); + } + }; + } + + public abstract int base(); + + public abstract boolean no(); + + public abstract boolean weakedAccess(); + + public abstract int addedModifiers(); + + public abstract int removedModifiers(); + + public abstract boolean packageLocalOn(); + + public abstract boolean hadValue(); +} diff --git a/jps/model/src/org/jetbrains/ether/dependencyView/ElemType.java b/jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/ElemType.java similarity index 89% rename from jps/model/src/org/jetbrains/ether/dependencyView/ElemType.java rename to jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/ElemType.java index 038cbe4e6b83..b38c1ad15eb2 100644 --- a/jps/model/src/org/jetbrains/ether/dependencyView/ElemType.java +++ b/jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/ElemType.java @@ -1,4 +1,4 @@ -package org.jetbrains.ether.dependencyView; +package org.jetbrains.jps.builders.java.dependencyView; public enum ElemType { /** Class, interface (including annotation type), or enum declaration */ diff --git a/jps/model/src/org/jetbrains/ether/dependencyView/FieldRepr.java b/jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/FieldRepr.java similarity index 94% rename from jps/model/src/org/jetbrains/ether/dependencyView/FieldRepr.java rename to jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/FieldRepr.java index 55f65321b969..4e88c31c20c9 100644 --- a/jps/model/src/org/jetbrains/ether/dependencyView/FieldRepr.java +++ b/jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/FieldRepr.java @@ -1,66 +1,66 @@ -package org.jetbrains.ether.dependencyView; - -import com.intellij.util.io.DataExternalizer; - -import java.io.DataInput; -import java.io.DataOutput; -import java.io.IOException; -import java.util.Set; - -/** - * Created by IntelliJ IDEA. - * User: db - * Date: 01.02.11 - * Time: 4:56 - * To change this template use File | Settings | File Templates. - */ -class FieldRepr extends ProtoMember { - public void updateClassUsages(final DependencyContext context, final int owner, final Set s) { - myType.updateClassUsages(context, owner, s); - } - - public FieldRepr(final DependencyContext context, final int a, final int n, final int d, final int s, final Object v) { - super(a, s, n, TypeRepr.getType(context, d), v); - } - - public FieldRepr(final DependencyContext context, final DataInput in) { - super(context, in); - } - - @Override - public boolean equals(final Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - final FieldRepr fieldRepr = (FieldRepr)o; - - return name == fieldRepr.name; - } - - @Override - public int hashCode() { - return 31 * name; - } - - public static DataExternalizer externalizer(final DependencyContext context) { - return new DataExternalizer() { - @Override - public void save(final DataOutput out, final FieldRepr value) throws IOException { - value.save(out); - } - - @Override - public FieldRepr read(final DataInput in) throws IOException { - return new FieldRepr(context, in); - } - }; - } - - public UsageRepr.Usage createUsage(final DependencyContext context, final int owner) { - return UsageRepr.createFieldUsage(context, name, owner, context.get(myType.getDescr(context))); - } - - public UsageRepr.Usage createAssignUsage(final DependencyContext context, final int owner) { - return UsageRepr.createFieldAssignUsage(context, name, owner, context.get(myType.getDescr(context))); - } -} +package org.jetbrains.jps.builders.java.dependencyView; + +import com.intellij.util.io.DataExternalizer; + +import java.io.DataInput; +import java.io.DataOutput; +import java.io.IOException; +import java.util.Set; + +/** + * Created by IntelliJ IDEA. + * User: db + * Date: 01.02.11 + * Time: 4:56 + * To change this template use File | Settings | File Templates. + */ +class FieldRepr extends ProtoMember { + public void updateClassUsages(final DependencyContext context, final int owner, final Set s) { + myType.updateClassUsages(context, owner, s); + } + + public FieldRepr(final DependencyContext context, final int a, final int n, final int d, final int s, final Object v) { + super(a, s, n, TypeRepr.getType(context, d), v); + } + + public FieldRepr(final DependencyContext context, final DataInput in) { + super(context, in); + } + + @Override + public boolean equals(final Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + final FieldRepr fieldRepr = (FieldRepr)o; + + return name == fieldRepr.name; + } + + @Override + public int hashCode() { + return 31 * name; + } + + public static DataExternalizer externalizer(final DependencyContext context) { + return new DataExternalizer() { + @Override + public void save(final DataOutput out, final FieldRepr value) throws IOException { + value.save(out); + } + + @Override + public FieldRepr read(final DataInput in) throws IOException { + return new FieldRepr(context, in); + } + }; + } + + public UsageRepr.Usage createUsage(final DependencyContext context, final int owner) { + return UsageRepr.createFieldUsage(context, name, owner, context.get(myType.getDescr(context))); + } + + public UsageRepr.Usage createAssignUsage(final DependencyContext context, final int owner) { + return UsageRepr.createFieldAssignUsage(context, name, owner, context.get(myType.getDescr(context))); + } +} diff --git a/jps/model/src/org/jetbrains/ether/dependencyView/IntIntMaplet.java b/jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/IntIntMaplet.java similarity index 96% rename from jps/model/src/org/jetbrains/ether/dependencyView/IntIntMaplet.java rename to jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/IntIntMaplet.java index 5f41a26c090d..fd6267389dd1 100644 --- a/jps/model/src/org/jetbrains/ether/dependencyView/IntIntMaplet.java +++ b/jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/IntIntMaplet.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.jetbrains.ether.dependencyView; +package org.jetbrains.jps.builders.java.dependencyView; import gnu.trove.TIntIntProcedure; diff --git a/jps/model/src/org/jetbrains/ether/dependencyView/IntIntMultiMaplet.java b/jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/IntIntMultiMaplet.java similarity index 94% rename from jps/model/src/org/jetbrains/ether/dependencyView/IntIntMultiMaplet.java rename to jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/IntIntMultiMaplet.java index a3fcd178aba3..e57356909a82 100644 --- a/jps/model/src/org/jetbrains/ether/dependencyView/IntIntMultiMaplet.java +++ b/jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/IntIntMultiMaplet.java @@ -1,101 +1,101 @@ -/* - * Copyright 2000-2011 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.jetbrains.ether.dependencyView; - -import gnu.trove.TIntHashSet; -import gnu.trove.TIntObjectProcedure; -import gnu.trove.TIntProcedure; - -import java.io.PrintStream; -import java.util.Collections; -import java.util.LinkedList; -import java.util.List; - -/** - * Created by IntelliJ IDEA. - * User: db - * Date: 03.11.11 - * Time: 21:01 - * To change this template use File | Settings | File Templates. - */ -abstract class IntIntMultiMaplet implements Streamable { - abstract boolean containsKey(final int key); - - abstract TIntHashSet get(final int key); - - abstract void put(final int key, final int value); - - abstract void put(final int key, final TIntHashSet value); - - abstract void replace(final int key, final TIntHashSet value); - - abstract void putAll(IntIntMultiMaplet m); - - abstract void replaceAll(IntIntMultiMaplet m); - - abstract void remove(final int key); - - abstract void removeFrom(final int key, final int value); - - abstract void removeAll(final int key, final TIntHashSet values); - - abstract void close(); - - abstract void forEachEntry(TIntObjectProcedure proc); - - abstract void flush(boolean memoryCachesOnly); - - public void toStream(final DependencyContext context, final PrintStream stream) { - final OrderProvider op = new OrderProvider(context); - - forEachEntry(new TIntObjectProcedure() { - @Override - public boolean execute(final int a, final TIntHashSet b) { - op.register(a); - return true; - } - }); - - final int[] keys = op.get(); - - for (final int a : keys) { - final TIntHashSet b = get(a); - - stream.print(" Key: "); - stream.println(context.getValue(a)); - stream.println(" Values:"); - - final List list = new LinkedList(); - - b.forEach(new TIntProcedure() { - @Override - public boolean execute(final int value) { - list.add(context.getValue(value)); - return true; - } - }); - - Collections.sort(list); - - for (final String l : list) { - stream.print(" "); - stream.println(l); - } - - stream.println(" End Of Values"); - } - } -} +/* + * Copyright 2000-2011 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.jps.builders.java.dependencyView; + +import gnu.trove.TIntHashSet; +import gnu.trove.TIntObjectProcedure; +import gnu.trove.TIntProcedure; + +import java.io.PrintStream; +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; + +/** + * Created by IntelliJ IDEA. + * User: db + * Date: 03.11.11 + * Time: 21:01 + * To change this template use File | Settings | File Templates. + */ +abstract class IntIntMultiMaplet implements Streamable { + abstract boolean containsKey(final int key); + + abstract TIntHashSet get(final int key); + + abstract void put(final int key, final int value); + + abstract void put(final int key, final TIntHashSet value); + + abstract void replace(final int key, final TIntHashSet value); + + abstract void putAll(IntIntMultiMaplet m); + + abstract void replaceAll(IntIntMultiMaplet m); + + abstract void remove(final int key); + + abstract void removeFrom(final int key, final int value); + + abstract void removeAll(final int key, final TIntHashSet values); + + abstract void close(); + + abstract void forEachEntry(TIntObjectProcedure proc); + + abstract void flush(boolean memoryCachesOnly); + + public void toStream(final DependencyContext context, final PrintStream stream) { + final OrderProvider op = new OrderProvider(context); + + forEachEntry(new TIntObjectProcedure() { + @Override + public boolean execute(final int a, final TIntHashSet b) { + op.register(a); + return true; + } + }); + + final int[] keys = op.get(); + + for (final int a : keys) { + final TIntHashSet b = get(a); + + stream.print(" Key: "); + stream.println(context.getValue(a)); + stream.println(" Values:"); + + final List list = new LinkedList(); + + b.forEach(new TIntProcedure() { + @Override + public boolean execute(final int value) { + list.add(context.getValue(value)); + return true; + } + }); + + Collections.sort(list); + + for (final String l : list) { + stream.print(" "); + stream.println(l); + } + + stream.println(" End Of Values"); + } + } +} diff --git a/jps/model/src/org/jetbrains/ether/dependencyView/IntIntPersistentMaplet.java b/jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/IntIntPersistentMaplet.java similarity index 98% rename from jps/model/src/org/jetbrains/ether/dependencyView/IntIntPersistentMaplet.java rename to jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/IntIntPersistentMaplet.java index 6a814bfde0ca..86c774faad47 100644 --- a/jps/model/src/org/jetbrains/ether/dependencyView/IntIntPersistentMaplet.java +++ b/jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/IntIntPersistentMaplet.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.jetbrains.ether.dependencyView; +package org.jetbrains.jps.builders.java.dependencyView; import com.intellij.util.Processor; import com.intellij.util.containers.SLRUCache; diff --git a/jps/model/src/org/jetbrains/ether/dependencyView/IntIntPersistentMultiMaplet.java b/jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/IntIntPersistentMultiMaplet.java similarity index 95% rename from jps/model/src/org/jetbrains/ether/dependencyView/IntIntPersistentMultiMaplet.java rename to jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/IntIntPersistentMultiMaplet.java index e46676091852..4c4b089b314a 100644 --- a/jps/model/src/org/jetbrains/ether/dependencyView/IntIntPersistentMultiMaplet.java +++ b/jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/IntIntPersistentMultiMaplet.java @@ -1,291 +1,291 @@ -/* - * Copyright 2000-2011 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.jetbrains.ether.dependencyView; - -import com.intellij.openapi.util.Ref; -import com.intellij.util.Processor; -import com.intellij.util.containers.SLRUCache; -import com.intellij.util.io.DataExternalizer; -import com.intellij.util.io.KeyDescriptor; -import com.intellij.util.io.PersistentHashMap; -import gnu.trove.TIntHashSet; -import gnu.trove.TIntObjectProcedure; -import gnu.trove.TIntProcedure; -import org.jetbrains.annotations.NotNull; - -import java.io.*; - -/** - * Created by IntelliJ IDEA. - * User: db - * Date: 08.03.11 - * Time: 15:38 - * To change this template use File | Settings | File Templates. - */ -class IntIntPersistentMultiMaplet extends IntIntMultiMaplet { - private static final TIntHashSet NULL_COLLECTION = new TIntHashSet(); - private static final int CACHE_SIZE = 128; - private final PersistentHashMap myMap; - private final SLRUCache myCache; - - public IntIntPersistentMultiMaplet(final File file, final KeyDescriptor keyExternalizer) throws IOException { - myMap = new PersistentHashMap(file, keyExternalizer, new IntSetExternalizer()); - myCache = new SLRUCache(CACHE_SIZE, CACHE_SIZE) { - @NotNull - @Override - public TIntHashSet createValue(Integer key) { - try { - final TIntHashSet collection = myMap.get(key); - return collection == null? NULL_COLLECTION : collection; - } - catch (IOException e) { - throw new RuntimeException(e); - } - } - }; - } - - @Override - public boolean containsKey(final int key) { - try { - return myMap.containsMapping(key); - } - catch (IOException e) { - throw new RuntimeException(e); - } - } - - @Override - public TIntHashSet get(final int key) { - final TIntHashSet collection = myCache.get(key); - return collection == NULL_COLLECTION? null : collection; - } - - @Override - public void replace(int key, TIntHashSet value) { - try { - myCache.remove(key); - if (value == null || value.isEmpty()) { - myMap.remove(key); - } - else { - myMap.put(key, value); - } - } - catch (IOException e) { - throw new RuntimeException(e); - } - } - - @Override - public void put(final int key, final TIntHashSet value) { - try { - myCache.remove(key); - myMap.appendData(key, new PersistentHashMap.ValueDataAppender() { - public void append(final DataOutput out) throws IOException { - final Ref exRef = new Ref(); - value.forEach(new TIntProcedure() { - @Override - public boolean execute(int value) { - try { - out.writeInt(value); - } - catch (IOException e) { - exRef.set(e); - return false; - } - return true; - } - }); - final IOException exception = exRef.get(); - if (exception != null) { - throw exception; - } - } - }); - } - catch (IOException e) { - throw new RuntimeException(e); - } - } - - @Override - public void put(final int key, final int value) { - try { - myCache.remove(key); - myMap.appendData(key, new PersistentHashMap.ValueDataAppender() { - public void append(final DataOutput out) throws IOException { - out.writeInt(value); - } - }); - } - catch (IOException e) { - throw new RuntimeException(e); - } - } - - @Override - public void removeAll(int key, TIntHashSet values) { - try { - final TIntHashSet collection = myCache.get(key); - - if (collection != NULL_COLLECTION) { - if (collection.removeAll(values.toArray())) { - myCache.remove(key); - if (collection.isEmpty()) { - myMap.remove(key); - } - else { - myMap.put(key, collection); - } - } - } - } - catch (IOException e) { - throw new RuntimeException(e); - } - } - - @Override - public void removeFrom(final int key, final int value) { - try { - final TIntHashSet collection = myCache.get(key); - if (collection != NULL_COLLECTION) { - if (collection.remove(value)) { - myCache.remove(key); - if (collection.isEmpty()) { - myMap.remove(key); - } - else { - myMap.put(key, collection); - } - } - } - } - catch (IOException e) { - throw new RuntimeException(e); - } - } - - @Override - public void remove(final int key) { - try { - myCache.remove(key); - myMap.remove(key); - } - catch (IOException e) { - throw new RuntimeException(e); - } - } - - @Override - public void putAll(IntIntMultiMaplet m) { - m.forEachEntry(new TIntObjectProcedure() { - @Override - public boolean execute(int key, TIntHashSet value) { - put(key, value); - return true; - } - }); - } - - @Override - public void replaceAll(IntIntMultiMaplet m) { - m.forEachEntry(new TIntObjectProcedure() { - @Override - public boolean execute(int key, TIntHashSet value) { - replace(key, value); - return true; - } - }); - } - - @Override - public void close() { - try { - myCache.clear(); - myMap.close(); - } - catch (IOException e) { - throw new RuntimeException(e); - } - } - - public void flush(boolean memoryCachesOnly) { - if (memoryCachesOnly) { - if (myMap.isDirty()) { - myMap.dropMemoryCaches(); - } - } - else { - myMap.force(); - } - } - - @Override - public void forEachEntry(final TIntObjectProcedure procedure) { - try { - myMap.processKeysWithExistingMapping(new Processor() { - @Override - public boolean process(Integer key) { - try { - return procedure.execute(key, myMap.get(key)); - } - catch (IOException e) { - throw new RuntimeException(e); - } - } - }); - } - catch (IOException e) { - throw new RuntimeException(e); - } - } - - private static class IntSetExternalizer implements DataExternalizer { - @Override - public void save(final DataOutput out, final TIntHashSet value) throws IOException { - final Ref exRef = new Ref(null); - value.forEach(new TIntProcedure() { - @Override - public boolean execute(int elem) { - try { - out.writeInt(elem); - } - catch (IOException e) { - exRef.set(e); - return false; - } - return true; - } - }); - final IOException exception = exRef.get(); - if (exception != null) { - throw exception; - } - } - - @Override - public TIntHashSet read(final DataInput in) throws IOException { - final TIntHashSet result = new TIntHashSet(); - final DataInputStream stream = (DataInputStream)in; - while (stream.available() > 0) { - result.add(in.readInt()); - } - return result; - } - } -} +/* + * Copyright 2000-2011 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.jps.builders.java.dependencyView; + +import com.intellij.openapi.util.Ref; +import com.intellij.util.Processor; +import com.intellij.util.containers.SLRUCache; +import com.intellij.util.io.DataExternalizer; +import com.intellij.util.io.KeyDescriptor; +import com.intellij.util.io.PersistentHashMap; +import gnu.trove.TIntHashSet; +import gnu.trove.TIntObjectProcedure; +import gnu.trove.TIntProcedure; +import org.jetbrains.annotations.NotNull; + +import java.io.*; + +/** + * Created by IntelliJ IDEA. + * User: db + * Date: 08.03.11 + * Time: 15:38 + * To change this template use File | Settings | File Templates. + */ +class IntIntPersistentMultiMaplet extends IntIntMultiMaplet { + private static final TIntHashSet NULL_COLLECTION = new TIntHashSet(); + private static final int CACHE_SIZE = 128; + private final PersistentHashMap myMap; + private final SLRUCache myCache; + + public IntIntPersistentMultiMaplet(final File file, final KeyDescriptor keyExternalizer) throws IOException { + myMap = new PersistentHashMap(file, keyExternalizer, new IntSetExternalizer()); + myCache = new SLRUCache(CACHE_SIZE, CACHE_SIZE) { + @NotNull + @Override + public TIntHashSet createValue(Integer key) { + try { + final TIntHashSet collection = myMap.get(key); + return collection == null? NULL_COLLECTION : collection; + } + catch (IOException e) { + throw new RuntimeException(e); + } + } + }; + } + + @Override + public boolean containsKey(final int key) { + try { + return myMap.containsMapping(key); + } + catch (IOException e) { + throw new RuntimeException(e); + } + } + + @Override + public TIntHashSet get(final int key) { + final TIntHashSet collection = myCache.get(key); + return collection == NULL_COLLECTION? null : collection; + } + + @Override + public void replace(int key, TIntHashSet value) { + try { + myCache.remove(key); + if (value == null || value.isEmpty()) { + myMap.remove(key); + } + else { + myMap.put(key, value); + } + } + catch (IOException e) { + throw new RuntimeException(e); + } + } + + @Override + public void put(final int key, final TIntHashSet value) { + try { + myCache.remove(key); + myMap.appendData(key, new PersistentHashMap.ValueDataAppender() { + public void append(final DataOutput out) throws IOException { + final Ref exRef = new Ref(); + value.forEach(new TIntProcedure() { + @Override + public boolean execute(int value) { + try { + out.writeInt(value); + } + catch (IOException e) { + exRef.set(e); + return false; + } + return true; + } + }); + final IOException exception = exRef.get(); + if (exception != null) { + throw exception; + } + } + }); + } + catch (IOException e) { + throw new RuntimeException(e); + } + } + + @Override + public void put(final int key, final int value) { + try { + myCache.remove(key); + myMap.appendData(key, new PersistentHashMap.ValueDataAppender() { + public void append(final DataOutput out) throws IOException { + out.writeInt(value); + } + }); + } + catch (IOException e) { + throw new RuntimeException(e); + } + } + + @Override + public void removeAll(int key, TIntHashSet values) { + try { + final TIntHashSet collection = myCache.get(key); + + if (collection != NULL_COLLECTION) { + if (collection.removeAll(values.toArray())) { + myCache.remove(key); + if (collection.isEmpty()) { + myMap.remove(key); + } + else { + myMap.put(key, collection); + } + } + } + } + catch (IOException e) { + throw new RuntimeException(e); + } + } + + @Override + public void removeFrom(final int key, final int value) { + try { + final TIntHashSet collection = myCache.get(key); + if (collection != NULL_COLLECTION) { + if (collection.remove(value)) { + myCache.remove(key); + if (collection.isEmpty()) { + myMap.remove(key); + } + else { + myMap.put(key, collection); + } + } + } + } + catch (IOException e) { + throw new RuntimeException(e); + } + } + + @Override + public void remove(final int key) { + try { + myCache.remove(key); + myMap.remove(key); + } + catch (IOException e) { + throw new RuntimeException(e); + } + } + + @Override + public void putAll(IntIntMultiMaplet m) { + m.forEachEntry(new TIntObjectProcedure() { + @Override + public boolean execute(int key, TIntHashSet value) { + put(key, value); + return true; + } + }); + } + + @Override + public void replaceAll(IntIntMultiMaplet m) { + m.forEachEntry(new TIntObjectProcedure() { + @Override + public boolean execute(int key, TIntHashSet value) { + replace(key, value); + return true; + } + }); + } + + @Override + public void close() { + try { + myCache.clear(); + myMap.close(); + } + catch (IOException e) { + throw new RuntimeException(e); + } + } + + public void flush(boolean memoryCachesOnly) { + if (memoryCachesOnly) { + if (myMap.isDirty()) { + myMap.dropMemoryCaches(); + } + } + else { + myMap.force(); + } + } + + @Override + public void forEachEntry(final TIntObjectProcedure procedure) { + try { + myMap.processKeysWithExistingMapping(new Processor() { + @Override + public boolean process(Integer key) { + try { + return procedure.execute(key, myMap.get(key)); + } + catch (IOException e) { + throw new RuntimeException(e); + } + } + }); + } + catch (IOException e) { + throw new RuntimeException(e); + } + } + + private static class IntSetExternalizer implements DataExternalizer { + @Override + public void save(final DataOutput out, final TIntHashSet value) throws IOException { + final Ref exRef = new Ref(null); + value.forEach(new TIntProcedure() { + @Override + public boolean execute(int elem) { + try { + out.writeInt(elem); + } + catch (IOException e) { + exRef.set(e); + return false; + } + return true; + } + }); + final IOException exception = exRef.get(); + if (exception != null) { + throw exception; + } + } + + @Override + public TIntHashSet read(final DataInput in) throws IOException { + final TIntHashSet result = new TIntHashSet(); + final DataInputStream stream = (DataInputStream)in; + while (stream.available() > 0) { + result.add(in.readInt()); + } + return result; + } + } +} diff --git a/jps/model/src/org/jetbrains/ether/dependencyView/IntIntTransientMaplet.java b/jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/IntIntTransientMaplet.java similarity index 96% rename from jps/model/src/org/jetbrains/ether/dependencyView/IntIntTransientMaplet.java rename to jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/IntIntTransientMaplet.java index 68d53a193846..b5485f12458e 100644 --- a/jps/model/src/org/jetbrains/ether/dependencyView/IntIntTransientMaplet.java +++ b/jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/IntIntTransientMaplet.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.jetbrains.ether.dependencyView; +package org.jetbrains.jps.builders.java.dependencyView; import gnu.trove.TIntIntHashMap; import gnu.trove.TIntIntProcedure; diff --git a/jps/model/src/org/jetbrains/ether/dependencyView/IntIntTransientMultiMaplet.java b/jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/IntIntTransientMultiMaplet.java similarity index 94% rename from jps/model/src/org/jetbrains/ether/dependencyView/IntIntTransientMultiMaplet.java rename to jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/IntIntTransientMultiMaplet.java index 5a7ea477fd9e..71e2abf6bc0f 100644 --- a/jps/model/src/org/jetbrains/ether/dependencyView/IntIntTransientMultiMaplet.java +++ b/jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/IntIntTransientMultiMaplet.java @@ -1,137 +1,137 @@ -package org.jetbrains.ether.dependencyView; - -import gnu.trove.TIntHashSet; -import gnu.trove.TIntObjectHashMap; -import gnu.trove.TIntObjectProcedure; -import gnu.trove.TIntProcedure; - -/** - * Created by IntelliJ IDEA. - * User: db - * Date: 08.03.11 - * Time: 15:38 - * To change this template use File | Settings | File Templates. - */ -class IntIntTransientMultiMaplet extends IntIntMultiMaplet { - private final TIntObjectHashMap myMap = new TIntObjectHashMap(); - - - @Override - public boolean containsKey(final int key) { - return myMap.containsKey(key); - } - - @Override - public TIntHashSet get(final int key) { - return myMap.get(key); - } - - @Override - public void putAll(IntIntMultiMaplet m) { - m.forEachEntry(new TIntObjectProcedure() { - @Override - public boolean execute(int key, TIntHashSet values) { - put(key, values); - return true; - } - }); - } - - @Override - public void put(final int key, final TIntHashSet value) { - final TIntHashSet x = myMap.get(key); - if (x == null) { - myMap.put(key, value); - } - else { - value.forEach(new TIntProcedure() { - @Override - public boolean execute(int value) { - x.add(value); - return true; - } - }); - } - } - - @Override - public void replace(int key, TIntHashSet value) { - if (value == null || value.isEmpty()) { - myMap.remove(key); - } - else { - myMap.put(key, value); - } - } - - @Override - public void put(final int key, final int value) { - final TIntHashSet collection = myMap.get(key); - if (collection == null) { - final TIntHashSet x = new TIntHashSet(); - x.add(value); - myMap.put(key, x); - } - else { - collection.add(value); - } - } - - @Override - public void removeFrom(final int key, final int value) { - final TIntHashSet collection = myMap.get(key); - if (collection != null) { - if (collection.remove(value)) { - if (collection.isEmpty()) { - myMap.remove(key); - } - } - } - } - - @Override - public void removeAll(int key, TIntHashSet values) { - final TIntHashSet collection = myMap.get(key); - if (collection != null) { - values.forEach(new TIntProcedure() { - @Override - public boolean execute(int value) { - collection.remove(value); - return true; - } - }); - if (collection.isEmpty()) { - myMap.remove(key); - } - } - } - - @Override - public void remove(final int key) { - myMap.remove(key); - } - - @Override - public void replaceAll(IntIntMultiMaplet m) { - m.forEachEntry(new TIntObjectProcedure() { - @Override - public boolean execute(int key, TIntHashSet value) { - replace(key, value); - return true; - } - }); - } - - @Override - public void forEachEntry(TIntObjectProcedure procedure) { - myMap.forEachEntry(procedure); - } - - @Override - public void close(){ - myMap.clear(); // free memory - } - - public void flush(boolean memoryCachesOnly) { - } -} +package org.jetbrains.jps.builders.java.dependencyView; + +import gnu.trove.TIntHashSet; +import gnu.trove.TIntObjectHashMap; +import gnu.trove.TIntObjectProcedure; +import gnu.trove.TIntProcedure; + +/** + * Created by IntelliJ IDEA. + * User: db + * Date: 08.03.11 + * Time: 15:38 + * To change this template use File | Settings | File Templates. + */ +class IntIntTransientMultiMaplet extends IntIntMultiMaplet { + private final TIntObjectHashMap myMap = new TIntObjectHashMap(); + + + @Override + public boolean containsKey(final int key) { + return myMap.containsKey(key); + } + + @Override + public TIntHashSet get(final int key) { + return myMap.get(key); + } + + @Override + public void putAll(IntIntMultiMaplet m) { + m.forEachEntry(new TIntObjectProcedure() { + @Override + public boolean execute(int key, TIntHashSet values) { + put(key, values); + return true; + } + }); + } + + @Override + public void put(final int key, final TIntHashSet value) { + final TIntHashSet x = myMap.get(key); + if (x == null) { + myMap.put(key, value); + } + else { + value.forEach(new TIntProcedure() { + @Override + public boolean execute(int value) { + x.add(value); + return true; + } + }); + } + } + + @Override + public void replace(int key, TIntHashSet value) { + if (value == null || value.isEmpty()) { + myMap.remove(key); + } + else { + myMap.put(key, value); + } + } + + @Override + public void put(final int key, final int value) { + final TIntHashSet collection = myMap.get(key); + if (collection == null) { + final TIntHashSet x = new TIntHashSet(); + x.add(value); + myMap.put(key, x); + } + else { + collection.add(value); + } + } + + @Override + public void removeFrom(final int key, final int value) { + final TIntHashSet collection = myMap.get(key); + if (collection != null) { + if (collection.remove(value)) { + if (collection.isEmpty()) { + myMap.remove(key); + } + } + } + } + + @Override + public void removeAll(int key, TIntHashSet values) { + final TIntHashSet collection = myMap.get(key); + if (collection != null) { + values.forEach(new TIntProcedure() { + @Override + public boolean execute(int value) { + collection.remove(value); + return true; + } + }); + if (collection.isEmpty()) { + myMap.remove(key); + } + } + } + + @Override + public void remove(final int key) { + myMap.remove(key); + } + + @Override + public void replaceAll(IntIntMultiMaplet m) { + m.forEachEntry(new TIntObjectProcedure() { + @Override + public boolean execute(int key, TIntHashSet value) { + replace(key, value); + return true; + } + }); + } + + @Override + public void forEachEntry(TIntObjectProcedure procedure) { + myMap.forEachEntry(procedure); + } + + @Override + public void close(){ + myMap.clear(); // free memory + } + + public void flush(boolean memoryCachesOnly) { + } +} diff --git a/jps/model/src/org/jetbrains/ether/dependencyView/IntObjectMultiMaplet.java b/jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/IntObjectMultiMaplet.java similarity index 95% rename from jps/model/src/org/jetbrains/ether/dependencyView/IntObjectMultiMaplet.java rename to jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/IntObjectMultiMaplet.java index d0d6f71c0ca1..a6d5d8b395d5 100644 --- a/jps/model/src/org/jetbrains/ether/dependencyView/IntObjectMultiMaplet.java +++ b/jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/IntObjectMultiMaplet.java @@ -1,101 +1,101 @@ -/* - * Copyright 2000-2011 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.jetbrains.ether.dependencyView; - -import gnu.trove.TIntObjectProcedure; - -import java.io.ByteArrayOutputStream; -import java.io.PrintStream; -import java.util.Collection; -import java.util.Collections; -import java.util.LinkedList; -import java.util.List; - -/** - * Created by IntelliJ IDEA. - * User: db - * Date: 03.11.11 - * Time: 21:01 - * To change this template use File | Settings | File Templates. - */ -abstract class IntObjectMultiMaplet implements Streamable { - abstract boolean containsKey(final int key); - - abstract Collection get(final int key); - - abstract void put(final int key, final V value); - - abstract void put(final int key, final Collection value); - - abstract void replace(final int key, final Collection value); - - abstract void putAll(IntObjectMultiMaplet m); - - abstract void replaceAll(IntObjectMultiMaplet m); - - abstract void remove(final int key); - - abstract void removeFrom(final int key, final V value); - - abstract void removeAll(final int key, final Collection value); - - abstract void close(); - - abstract void forEachEntry(TIntObjectProcedure> procedure); - - abstract void flush(boolean memoryCachesOnly); - - public void toStream(final DependencyContext context, final PrintStream stream) { - final OrderProvider op = new OrderProvider(context); - - forEachEntry(new TIntObjectProcedure>() { - @Override - public boolean execute(final int a, final Collection b) { - op.register(a); - return true; - } - }); - - final int[] keys = op.get(); - - for (final int a : keys) { - final Collection b = get(a); - - stream.print(" Key: "); - stream.println(context.getValue(a)); - stream.println(" Values:"); - - final List list = new LinkedList(); - - for (final V value : b) { - final ByteArrayOutputStream baos = new ByteArrayOutputStream(); - final PrintStream s = new PrintStream(baos); - - value.toStream(context, s); - - list.add(baos.toString()); - } - - Collections.sort(list); - - for (final String l : list) { - stream.print(l); - } - - stream.println(" End Of Values"); - } - } -} +/* + * Copyright 2000-2011 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.jps.builders.java.dependencyView; + +import gnu.trove.TIntObjectProcedure; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.util.Collection; +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; + +/** + * Created by IntelliJ IDEA. + * User: db + * Date: 03.11.11 + * Time: 21:01 + * To change this template use File | Settings | File Templates. + */ +abstract class IntObjectMultiMaplet implements Streamable { + abstract boolean containsKey(final int key); + + abstract Collection get(final int key); + + abstract void put(final int key, final V value); + + abstract void put(final int key, final Collection value); + + abstract void replace(final int key, final Collection value); + + abstract void putAll(IntObjectMultiMaplet m); + + abstract void replaceAll(IntObjectMultiMaplet m); + + abstract void remove(final int key); + + abstract void removeFrom(final int key, final V value); + + abstract void removeAll(final int key, final Collection value); + + abstract void close(); + + abstract void forEachEntry(TIntObjectProcedure> procedure); + + abstract void flush(boolean memoryCachesOnly); + + public void toStream(final DependencyContext context, final PrintStream stream) { + final OrderProvider op = new OrderProvider(context); + + forEachEntry(new TIntObjectProcedure>() { + @Override + public boolean execute(final int a, final Collection b) { + op.register(a); + return true; + } + }); + + final int[] keys = op.get(); + + for (final int a : keys) { + final Collection b = get(a); + + stream.print(" Key: "); + stream.println(context.getValue(a)); + stream.println(" Values:"); + + final List list = new LinkedList(); + + for (final V value : b) { + final ByteArrayOutputStream baos = new ByteArrayOutputStream(); + final PrintStream s = new PrintStream(baos); + + value.toStream(context, s); + + list.add(baos.toString()); + } + + Collections.sort(list); + + for (final String l : list) { + stream.print(l); + } + + stream.println(" End Of Values"); + } + } +} diff --git a/jps/model/src/org/jetbrains/ether/dependencyView/IntObjectPersistentMultiMaplet.java b/jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/IntObjectPersistentMultiMaplet.java similarity index 95% rename from jps/model/src/org/jetbrains/ether/dependencyView/IntObjectPersistentMultiMaplet.java rename to jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/IntObjectPersistentMultiMaplet.java index 683b3aca4cfb..eebf074dd817 100644 --- a/jps/model/src/org/jetbrains/ether/dependencyView/IntObjectPersistentMultiMaplet.java +++ b/jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/IntObjectPersistentMultiMaplet.java @@ -1,266 +1,266 @@ -/* - * Copyright 2000-2011 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.jetbrains.ether.dependencyView; - -import com.intellij.util.Processor; -import com.intellij.util.containers.SLRUCache; -import com.intellij.util.io.DataExternalizer; -import com.intellij.util.io.KeyDescriptor; -import com.intellij.util.io.PersistentHashMap; -import gnu.trove.TIntObjectProcedure; -import org.jetbrains.annotations.NotNull; - -import java.io.*; -import java.util.Collection; -import java.util.Collections; - -/** - * Created by IntelliJ IDEA. - * User: db - * Date: 08.03.11 - * Time: 15:38 - * To change this template use File | Settings | File Templates. - */ -class IntObjectPersistentMultiMaplet extends IntObjectMultiMaplet { - private static final Collection NULL_COLLECTION = Collections.emptySet(); - private static final int CACHE_SIZE = 128; - private final PersistentHashMap> myMap; - private final DataExternalizer myValueExternalizer; - private final SLRUCache myCache; - - public IntObjectPersistentMultiMaplet(final File file, - final KeyDescriptor keyExternalizer, - final DataExternalizer valueExternalizer, - final CollectionFactory collectionFactory) throws IOException { - myValueExternalizer = valueExternalizer; - myMap = new PersistentHashMap>(file, keyExternalizer, new CollectionDataExternalizer(valueExternalizer, collectionFactory)); - myCache = new SLRUCache(CACHE_SIZE, CACHE_SIZE) { - @NotNull - @Override - public Collection createValue(Integer key) { - try { - final Collection collection = myMap.get(key); - return collection == null? NULL_COLLECTION : collection; - } - catch (IOException e) { - throw new RuntimeException(e); - } - } - }; - } - - - @Override - public boolean containsKey(final int key) { - try { - return myMap.containsMapping(key); - } - catch (IOException e) { - throw new RuntimeException(e); - } - } - - @Override - public Collection get(final int key) { - final Collection collection = myCache.get(key); - return collection == NULL_COLLECTION? null : collection; - } - - @Override - public void replace(int key, Collection value) { - try { - myCache.remove(key); - if (value == null || value.isEmpty()) { - myMap.remove(key); - } - else { - myMap.put(key, value); - } - } - catch (IOException e) { - throw new RuntimeException(e); - } - } - - @Override - public void put(final int key, final Collection value) { - try { - myCache.remove(key); - myMap.appendData(key, new PersistentHashMap.ValueDataAppender() { - public void append(DataOutput out) throws IOException { - for (V v : value) { - myValueExternalizer.save(out, v); - } - } - }); - } - catch (IOException e) { - throw new RuntimeException(e); - } - } - - @Override - public void put(final int key, final V value) { - put(key, Collections.singleton(value)); - } - - @Override - public void removeAll(int key, Collection values) { - try { - final Collection collection = myCache.get(key); - - if (collection != NULL_COLLECTION) { - if (collection.removeAll(values)) { - myCache.remove(key); - if (collection.isEmpty()) { - myMap.remove(key); - } - else { - myMap.put(key, (Collection)collection); - } - } - } - } - catch (IOException e) { - throw new RuntimeException(e); - } - } - - @Override - public void removeFrom(final int key, final V value) { - try { - final Collection collection = myCache.get(key); - - if (collection != NULL_COLLECTION) { - if (collection.remove(value)) { - myCache.remove(key); - if (collection.isEmpty()) { - myMap.remove(key); - } - else { - myMap.put(key, (Collection)collection); - } - } - } - } - catch (IOException e) { - throw new RuntimeException(e); - } - } - - @Override - public void remove(final int key) { - try { - myCache.remove(key); - myMap.remove(key); - } - catch (IOException e) { - throw new RuntimeException(e); - } - } - - @Override - public void putAll(IntObjectMultiMaplet m) { - m.forEachEntry(new TIntObjectProcedure>() { - @Override - public boolean execute(int key, Collection value) { - put(key, value); - return true; - } - }); - } - - @Override - public void replaceAll(IntObjectMultiMaplet m) { - m.forEachEntry(new TIntObjectProcedure>() { - @Override - public boolean execute(int key, Collection value) { - replace(key, value); - return true; - } - }); - } - - @Override - public void close() { - try { - myCache.clear(); - myMap.close(); - } - catch (IOException e) { - throw new RuntimeException(e); - } - } - - public void flush(boolean memoryCachesOnly) { - if (memoryCachesOnly) { - if (myMap.isDirty()) { - myMap.dropMemoryCaches(); - } - } - else { - myMap.force(); - } - } - - @Override - public void forEachEntry(final TIntObjectProcedure> procedure) { - try { - myMap.processKeysWithExistingMapping(new Processor() { - @Override - public boolean process(Integer key) { - try { - return procedure.execute(key, myMap.get(key)); - } - catch (IOException e) { - throw new RuntimeException(e); - } - } - }); - } - catch (IOException e) { - throw new RuntimeException(e); - } - } - - private static class CollectionDataExternalizer implements DataExternalizer> { - private final DataExternalizer myElementExternalizer; - private final CollectionFactory myCollectionFactory; - - public CollectionDataExternalizer(DataExternalizer elementExternalizer, - CollectionFactory collectionFactory) { - myElementExternalizer = elementExternalizer; - myCollectionFactory = collectionFactory; - } - - @Override - public void save(final DataOutput out, final Collection value) throws IOException { - for (V x : value) { - myElementExternalizer.save(out, x); - } - } - - @Override - public Collection read(final DataInput in) throws IOException { - final Collection result = myCollectionFactory.create(); - final DataInputStream stream = (DataInputStream)in; - while (stream.available() > 0) { - result.add(myElementExternalizer.read(in)); - } - return result; - } - } -} +/* + * Copyright 2000-2011 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.jps.builders.java.dependencyView; + +import com.intellij.util.Processor; +import com.intellij.util.containers.SLRUCache; +import com.intellij.util.io.DataExternalizer; +import com.intellij.util.io.KeyDescriptor; +import com.intellij.util.io.PersistentHashMap; +import gnu.trove.TIntObjectProcedure; +import org.jetbrains.annotations.NotNull; + +import java.io.*; +import java.util.Collection; +import java.util.Collections; + +/** + * Created by IntelliJ IDEA. + * User: db + * Date: 08.03.11 + * Time: 15:38 + * To change this template use File | Settings | File Templates. + */ +class IntObjectPersistentMultiMaplet extends IntObjectMultiMaplet { + private static final Collection NULL_COLLECTION = Collections.emptySet(); + private static final int CACHE_SIZE = 128; + private final PersistentHashMap> myMap; + private final DataExternalizer myValueExternalizer; + private final SLRUCache myCache; + + public IntObjectPersistentMultiMaplet(final File file, + final KeyDescriptor keyExternalizer, + final DataExternalizer valueExternalizer, + final CollectionFactory collectionFactory) throws IOException { + myValueExternalizer = valueExternalizer; + myMap = new PersistentHashMap>(file, keyExternalizer, new CollectionDataExternalizer(valueExternalizer, collectionFactory)); + myCache = new SLRUCache(CACHE_SIZE, CACHE_SIZE) { + @NotNull + @Override + public Collection createValue(Integer key) { + try { + final Collection collection = myMap.get(key); + return collection == null? NULL_COLLECTION : collection; + } + catch (IOException e) { + throw new RuntimeException(e); + } + } + }; + } + + + @Override + public boolean containsKey(final int key) { + try { + return myMap.containsMapping(key); + } + catch (IOException e) { + throw new RuntimeException(e); + } + } + + @Override + public Collection get(final int key) { + final Collection collection = myCache.get(key); + return collection == NULL_COLLECTION? null : collection; + } + + @Override + public void replace(int key, Collection value) { + try { + myCache.remove(key); + if (value == null || value.isEmpty()) { + myMap.remove(key); + } + else { + myMap.put(key, value); + } + } + catch (IOException e) { + throw new RuntimeException(e); + } + } + + @Override + public void put(final int key, final Collection value) { + try { + myCache.remove(key); + myMap.appendData(key, new PersistentHashMap.ValueDataAppender() { + public void append(DataOutput out) throws IOException { + for (V v : value) { + myValueExternalizer.save(out, v); + } + } + }); + } + catch (IOException e) { + throw new RuntimeException(e); + } + } + + @Override + public void put(final int key, final V value) { + put(key, Collections.singleton(value)); + } + + @Override + public void removeAll(int key, Collection values) { + try { + final Collection collection = myCache.get(key); + + if (collection != NULL_COLLECTION) { + if (collection.removeAll(values)) { + myCache.remove(key); + if (collection.isEmpty()) { + myMap.remove(key); + } + else { + myMap.put(key, (Collection)collection); + } + } + } + } + catch (IOException e) { + throw new RuntimeException(e); + } + } + + @Override + public void removeFrom(final int key, final V value) { + try { + final Collection collection = myCache.get(key); + + if (collection != NULL_COLLECTION) { + if (collection.remove(value)) { + myCache.remove(key); + if (collection.isEmpty()) { + myMap.remove(key); + } + else { + myMap.put(key, (Collection)collection); + } + } + } + } + catch (IOException e) { + throw new RuntimeException(e); + } + } + + @Override + public void remove(final int key) { + try { + myCache.remove(key); + myMap.remove(key); + } + catch (IOException e) { + throw new RuntimeException(e); + } + } + + @Override + public void putAll(IntObjectMultiMaplet m) { + m.forEachEntry(new TIntObjectProcedure>() { + @Override + public boolean execute(int key, Collection value) { + put(key, value); + return true; + } + }); + } + + @Override + public void replaceAll(IntObjectMultiMaplet m) { + m.forEachEntry(new TIntObjectProcedure>() { + @Override + public boolean execute(int key, Collection value) { + replace(key, value); + return true; + } + }); + } + + @Override + public void close() { + try { + myCache.clear(); + myMap.close(); + } + catch (IOException e) { + throw new RuntimeException(e); + } + } + + public void flush(boolean memoryCachesOnly) { + if (memoryCachesOnly) { + if (myMap.isDirty()) { + myMap.dropMemoryCaches(); + } + } + else { + myMap.force(); + } + } + + @Override + public void forEachEntry(final TIntObjectProcedure> procedure) { + try { + myMap.processKeysWithExistingMapping(new Processor() { + @Override + public boolean process(Integer key) { + try { + return procedure.execute(key, myMap.get(key)); + } + catch (IOException e) { + throw new RuntimeException(e); + } + } + }); + } + catch (IOException e) { + throw new RuntimeException(e); + } + } + + private static class CollectionDataExternalizer implements DataExternalizer> { + private final DataExternalizer myElementExternalizer; + private final CollectionFactory myCollectionFactory; + + public CollectionDataExternalizer(DataExternalizer elementExternalizer, + CollectionFactory collectionFactory) { + myElementExternalizer = elementExternalizer; + myCollectionFactory = collectionFactory; + } + + @Override + public void save(final DataOutput out, final Collection value) throws IOException { + for (V x : value) { + myElementExternalizer.save(out, x); + } + } + + @Override + public Collection read(final DataInput in) throws IOException { + final Collection result = myCollectionFactory.create(); + final DataInputStream stream = (DataInputStream)in; + while (stream.available() > 0) { + result.add(myElementExternalizer.read(in)); + } + return result; + } + } +} diff --git a/jps/model/src/org/jetbrains/ether/dependencyView/IntObjectTransientMultiMaplet.java b/jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/IntObjectTransientMultiMaplet.java similarity index 94% rename from jps/model/src/org/jetbrains/ether/dependencyView/IntObjectTransientMultiMaplet.java rename to jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/IntObjectTransientMultiMaplet.java index 35e9ed2cbd9e..aa7ac1e3dd3c 100644 --- a/jps/model/src/org/jetbrains/ether/dependencyView/IntObjectTransientMultiMaplet.java +++ b/jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/IntObjectTransientMultiMaplet.java @@ -1,131 +1,131 @@ -package org.jetbrains.ether.dependencyView; - -import gnu.trove.TIntObjectHashMap; -import gnu.trove.TIntObjectProcedure; - -import java.util.Collection; - -/** - * Created by IntelliJ IDEA. - * User: db - * Date: 08.03.11 - * Time: 15:38 - * To change this template use File | Settings | File Templates. - */ -class IntObjectTransientMultiMaplet extends IntObjectMultiMaplet { - - private final TIntObjectHashMap> myMap = new TIntObjectHashMap>(); - private final CollectionFactory myCollectionFactory; - - public IntObjectTransientMultiMaplet(CollectionFactory collectionFactory) { - myCollectionFactory = collectionFactory; - } - - @Override - public boolean containsKey(final int key) { - return myMap.containsKey(key); - } - - @Override - public Collection get(final int key) { - return myMap.get(key); - } - - @Override - public void putAll(IntObjectMultiMaplet m) { - m.forEachEntry(new TIntObjectProcedure>() { - @Override - public boolean execute(int key, Collection value) { - put(key, value); - return true; - } - }); - } - - @Override - public void put(final int key, final Collection value) { - final Collection x = myMap.get(key); - if (x == null) { - myMap.put(key, value); - } - else { - x.addAll(value); - } - } - - @Override - public void replace(int key, Collection value) { - if (value == null || value.isEmpty()) { - myMap.remove(key); - } - else { - myMap.put(key, value); - } - } - - @Override - public void put(final int key, final V value) { - final Collection collection = myMap.get(key); - if (collection == null) { - final Collection x = myCollectionFactory.create(); - x.add(value); - myMap.put(key, x); - } - else { - collection.add(value); - } - } - - @Override - public void removeFrom(final int key, final V value) { - final Collection collection = myMap.get(key); - if (collection != null) { - if (collection.remove(value)) { - if (collection.isEmpty()) { - myMap.remove(key); - } - } - } - } - - @Override - public void removeAll(int key, Collection values) { - final Collection collection = myMap.get(key); - if (collection != null) { - if (collection.removeAll(values)) { - if (collection.isEmpty()) { - myMap.remove(key); - } - } - } - } - - @Override - public void remove(final int key) { - myMap.remove(key); - } - - @Override - public void replaceAll(IntObjectMultiMaplet m) { - m.forEachEntry(new TIntObjectProcedure>() { - @Override - public boolean execute(int key, Collection value) { - replace(key, value); - return true; - } - }); - } - - @Override - public void forEachEntry(TIntObjectProcedure> procedure) { - myMap.forEachEntry(procedure); - } - - @Override - public void close(){ - myMap.clear(); // free memory - } - - public void flush(boolean memoryCachesOnly) { - } -} +package org.jetbrains.jps.builders.java.dependencyView; + +import gnu.trove.TIntObjectHashMap; +import gnu.trove.TIntObjectProcedure; + +import java.util.Collection; + +/** + * Created by IntelliJ IDEA. + * User: db + * Date: 08.03.11 + * Time: 15:38 + * To change this template use File | Settings | File Templates. + */ +class IntObjectTransientMultiMaplet extends IntObjectMultiMaplet { + + private final TIntObjectHashMap> myMap = new TIntObjectHashMap>(); + private final CollectionFactory myCollectionFactory; + + public IntObjectTransientMultiMaplet(CollectionFactory collectionFactory) { + myCollectionFactory = collectionFactory; + } + + @Override + public boolean containsKey(final int key) { + return myMap.containsKey(key); + } + + @Override + public Collection get(final int key) { + return myMap.get(key); + } + + @Override + public void putAll(IntObjectMultiMaplet m) { + m.forEachEntry(new TIntObjectProcedure>() { + @Override + public boolean execute(int key, Collection value) { + put(key, value); + return true; + } + }); + } + + @Override + public void put(final int key, final Collection value) { + final Collection x = myMap.get(key); + if (x == null) { + myMap.put(key, value); + } + else { + x.addAll(value); + } + } + + @Override + public void replace(int key, Collection value) { + if (value == null || value.isEmpty()) { + myMap.remove(key); + } + else { + myMap.put(key, value); + } + } + + @Override + public void put(final int key, final V value) { + final Collection collection = myMap.get(key); + if (collection == null) { + final Collection x = myCollectionFactory.create(); + x.add(value); + myMap.put(key, x); + } + else { + collection.add(value); + } + } + + @Override + public void removeFrom(final int key, final V value) { + final Collection collection = myMap.get(key); + if (collection != null) { + if (collection.remove(value)) { + if (collection.isEmpty()) { + myMap.remove(key); + } + } + } + } + + @Override + public void removeAll(int key, Collection values) { + final Collection collection = myMap.get(key); + if (collection != null) { + if (collection.removeAll(values)) { + if (collection.isEmpty()) { + myMap.remove(key); + } + } + } + } + + @Override + public void remove(final int key) { + myMap.remove(key); + } + + @Override + public void replaceAll(IntObjectMultiMaplet m) { + m.forEachEntry(new TIntObjectProcedure>() { + @Override + public boolean execute(int key, Collection value) { + replace(key, value); + return true; + } + }); + } + + @Override + public void forEachEntry(TIntObjectProcedure> procedure) { + myMap.forEachEntry(procedure); + } + + @Override + public void close(){ + myMap.clear(); // free memory + } + + public void flush(boolean memoryCachesOnly) { + } +} diff --git a/jps/model/src/org/jetbrains/ether/dependencyView/Logger.java b/jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/Logger.java similarity index 94% rename from jps/model/src/org/jetbrains/ether/dependencyView/Logger.java rename to jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/Logger.java index a409a4c9ec6f..840ccf63fb80 100644 --- a/jps/model/src/org/jetbrains/ether/dependencyView/Logger.java +++ b/jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/Logger.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.jetbrains.ether.dependencyView; +package org.jetbrains.jps.builders.java.dependencyView; /** * Created by IntelliJ IDEA. diff --git a/jps/model/src/org/jetbrains/ether/dependencyView/Mappings.java b/jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/Mappings.java similarity index 99% rename from jps/model/src/org/jetbrains/ether/dependencyView/Mappings.java rename to jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/Mappings.java index 12751d34af88..917fe4cc4d90 100644 --- a/jps/model/src/org/jetbrains/ether/dependencyView/Mappings.java +++ b/jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/Mappings.java @@ -1,4 +1,4 @@ -package org.jetbrains.ether.dependencyView; +package org.jetbrains.jps.builders.java.dependencyView; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.Pair; @@ -62,7 +62,7 @@ public class Mappings { private DependencyContext myContext; private final int myInitName; private final int myEmptyName; - private org.jetbrains.ether.dependencyView.Logger myDebugS; + private org.jetbrains.jps.builders.java.dependencyView.Logger myDebugS; private IntIntMultiMaplet myClassToSubclasses; private IntIntMultiMaplet myClassToClassDependency; diff --git a/jps/model/src/org/jetbrains/ether/dependencyView/MethodRepr.java b/jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/MethodRepr.java similarity index 95% rename from jps/model/src/org/jetbrains/ether/dependencyView/MethodRepr.java rename to jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/MethodRepr.java index 6f899f9b2ad0..a37dc53c7421 100644 --- a/jps/model/src/org/jetbrains/ether/dependencyView/MethodRepr.java +++ b/jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/MethodRepr.java @@ -1,229 +1,228 @@ -package org.jetbrains.ether.dependencyView; - -import com.intellij.util.io.DataExternalizer; -import org.jetbrains.asm4.Type; -import org.jetbrains.ether.RW; - -import java.io.DataInput; -import java.io.DataOutput; -import java.io.IOException; -import java.io.PrintStream; -import java.util.Arrays; -import java.util.Comparator; -import java.util.HashSet; -import java.util.Set; - -/** - * Created by IntelliJ IDEA. - * User: db - * Date: 01.02.11 - * Time: 5:03 - * To change this template use File | Settings | File Templates. - */ -class MethodRepr extends ProtoMember { - interface Predicate { - boolean satisfy(MethodRepr m); - } - - public final TypeRepr.AbstractType[] myArgumentTypes; - public final Set myExceptions; - - public abstract class Diff extends Difference { - public abstract Specifier exceptions(); - - public abstract boolean defaultAdded(); - - public abstract boolean defaultRemoved(); - } - - @Override - public Difference difference(final Proto past) { - final Difference diff = super.difference(past); - final Difference.Specifier excs = Difference.make(((MethodRepr)past).myExceptions, myExceptions); - - return new Diff() { - @Override - public int addedModifiers() { - return diff.addedModifiers(); - } - - @Override - public int removedModifiers() { - return diff.removedModifiers(); - } - - @Override - public boolean no() { - return base() == NONE && !defaultAdded() && !defaultRemoved() && excs.unchanged(); - } - - @Override - public boolean defaultAdded() { - return hasValue() && !((MethodRepr)past).hasValue(); - } - - @Override - public boolean defaultRemoved() { - return !hasValue() && ((MethodRepr)past).hasValue(); - } - - @Override - public Specifier exceptions() { - return excs; - } - - @Override - public int base() { - return diff.base(); - } - - @Override - public boolean packageLocalOn() { - return diff.packageLocalOn(); - } - - @Override - public boolean hadValue() { - return ((MethodRepr)past).hasValue(); - } - - @Override - public boolean weakedAccess() { - return diff.weakedAccess(); - } - }; - } - - public void updateClassUsages(final DependencyContext context, final int owner, final Set s) { - myType.updateClassUsages(context, owner, s); - - for (int i = 0; i < myArgumentTypes.length; i++) { - myArgumentTypes[i].updateClassUsages(context, owner, s); - } - - if (myExceptions != null) { - for (TypeRepr.AbstractType typ : myExceptions) { - typ.updateClassUsages(context, owner, s); - } - } - } - - public MethodRepr(final DependencyContext context, - final int a, - final int n, - final int s, - final String d, - final String[] e, - final Object value) { - super(a, s, n, TypeRepr.getType(context, Type.getReturnType(d)), value); - myExceptions = (Set)TypeRepr.createClassType(context, e, new HashSet()); - myArgumentTypes = TypeRepr.getType(context, Type.getArgumentTypes(d)); - } - - public MethodRepr(final DependencyContext context, final DataInput in) { - super(context, in); - try { - final DataExternalizer externalizer = TypeRepr.externalizer(context); - final int size = in.readInt(); - myArgumentTypes = RW.read(externalizer, in, new TypeRepr.AbstractType[size]); - myExceptions = (Set)RW.read(externalizer, new HashSet(), in); - } - catch (IOException e) { - throw new RuntimeException(e); - } - } - - @Override - public void save(final DataOutput out) { - super.save(out); - RW.save(myArgumentTypes, out); - RW.save(myExceptions, out); - } - - public static DataExternalizer externalizer(final DependencyContext context) { - return new DataExternalizer() { - @Override - public void save(final DataOutput out, final MethodRepr value) throws IOException { - value.save(out); - } - - @Override - public MethodRepr read(DataInput in) throws IOException { - return new MethodRepr(context, in); - } - }; - } - - static Predicate equalByJavaRules(final MethodRepr me) { - return new Predicate() { - @Override - public boolean satisfy(MethodRepr that) { - if (me == that) return true; - return me.name == that.name && Arrays.equals(me.myArgumentTypes, that.myArgumentTypes); - } - }; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - final MethodRepr that = (MethodRepr)o; - - return name == that.name && myType.equals(that.myType) && Arrays.equals(myArgumentTypes, that.myArgumentTypes); - } - - @Override - public int hashCode() { - return 31 * (31 * Arrays.hashCode(myArgumentTypes) + myType.hashCode()) + name; - } - - private String getDescr(final DependencyContext context) { - final StringBuilder buf = new StringBuilder(); - - buf.append("("); - - for (TypeRepr.AbstractType t : myArgumentTypes) { - buf.append(t.getDescr(context)); - } - - buf.append(")"); - buf.append(myType.getDescr(context)); - - return buf.toString(); - } - - public UsageRepr.Usage createUsage(final DependencyContext context, final int owner) { - return UsageRepr.createMethodUsage(context, name, owner, getDescr(context)); - } - - public UsageRepr.Usage createMetaUsage(final DependencyContext context, final int owner) { - return UsageRepr.createMetaMethodUsage(context, name, owner, getDescr(context)); - } - - @Override - public void toStream(final DependencyContext context, final PrintStream stream) { - super.toStream(context, stream); - stream.print(" Arguments : "); - for (TypeRepr.AbstractType t : myArgumentTypes) { - stream.print(t.getDescr(context)); - stream.print("; "); - } - stream.println(); - - final TypeRepr.AbstractType[] es = myExceptions.toArray(new TypeRepr.AbstractType[myExceptions.size()]); - Arrays.sort(es, new Comparator() { - @Override - public int compare(final TypeRepr.AbstractType o1, final TypeRepr.AbstractType o2) { - return o1.getDescr(context).compareTo(o2.getDescr(context)); - } - }); - stream.print(" Exceptions : "); - for (final TypeRepr.AbstractType e : es) { - stream.print(e.getDescr(context)); - stream.print("; "); - } - stream.println(); - } -} +package org.jetbrains.jps.builders.java.dependencyView; + +import com.intellij.util.io.DataExternalizer; +import org.jetbrains.asm4.Type; + +import java.io.DataInput; +import java.io.DataOutput; +import java.io.IOException; +import java.io.PrintStream; +import java.util.Arrays; +import java.util.Comparator; +import java.util.HashSet; +import java.util.Set; + +/** + * Created by IntelliJ IDEA. + * User: db + * Date: 01.02.11 + * Time: 5:03 + * To change this template use File | Settings | File Templates. + */ +class MethodRepr extends ProtoMember { + interface Predicate { + boolean satisfy(MethodRepr m); + } + + public final TypeRepr.AbstractType[] myArgumentTypes; + public final Set myExceptions; + + public abstract class Diff extends Difference { + public abstract Specifier exceptions(); + + public abstract boolean defaultAdded(); + + public abstract boolean defaultRemoved(); + } + + @Override + public Difference difference(final Proto past) { + final Difference diff = super.difference(past); + final Difference.Specifier excs = Difference.make(((MethodRepr)past).myExceptions, myExceptions); + + return new Diff() { + @Override + public int addedModifiers() { + return diff.addedModifiers(); + } + + @Override + public int removedModifiers() { + return diff.removedModifiers(); + } + + @Override + public boolean no() { + return base() == NONE && !defaultAdded() && !defaultRemoved() && excs.unchanged(); + } + + @Override + public boolean defaultAdded() { + return hasValue() && !((MethodRepr)past).hasValue(); + } + + @Override + public boolean defaultRemoved() { + return !hasValue() && ((MethodRepr)past).hasValue(); + } + + @Override + public Specifier exceptions() { + return excs; + } + + @Override + public int base() { + return diff.base(); + } + + @Override + public boolean packageLocalOn() { + return diff.packageLocalOn(); + } + + @Override + public boolean hadValue() { + return ((MethodRepr)past).hasValue(); + } + + @Override + public boolean weakedAccess() { + return diff.weakedAccess(); + } + }; + } + + public void updateClassUsages(final DependencyContext context, final int owner, final Set s) { + myType.updateClassUsages(context, owner, s); + + for (int i = 0; i < myArgumentTypes.length; i++) { + myArgumentTypes[i].updateClassUsages(context, owner, s); + } + + if (myExceptions != null) { + for (TypeRepr.AbstractType typ : myExceptions) { + typ.updateClassUsages(context, owner, s); + } + } + } + + public MethodRepr(final DependencyContext context, + final int a, + final int n, + final int s, + final String d, + final String[] e, + final Object value) { + super(a, s, n, TypeRepr.getType(context, Type.getReturnType(d)), value); + myExceptions = (Set)TypeRepr.createClassType(context, e, new HashSet()); + myArgumentTypes = TypeRepr.getType(context, Type.getArgumentTypes(d)); + } + + public MethodRepr(final DependencyContext context, final DataInput in) { + super(context, in); + try { + final DataExternalizer externalizer = TypeRepr.externalizer(context); + final int size = in.readInt(); + myArgumentTypes = RW.read(externalizer, in, new TypeRepr.AbstractType[size]); + myExceptions = (Set)RW.read(externalizer, new HashSet(), in); + } + catch (IOException e) { + throw new RuntimeException(e); + } + } + + @Override + public void save(final DataOutput out) { + super.save(out); + RW.save(myArgumentTypes, out); + RW.save(myExceptions, out); + } + + public static DataExternalizer externalizer(final DependencyContext context) { + return new DataExternalizer() { + @Override + public void save(final DataOutput out, final MethodRepr value) throws IOException { + value.save(out); + } + + @Override + public MethodRepr read(DataInput in) throws IOException { + return new MethodRepr(context, in); + } + }; + } + + static Predicate equalByJavaRules(final MethodRepr me) { + return new Predicate() { + @Override + public boolean satisfy(MethodRepr that) { + if (me == that) return true; + return me.name == that.name && Arrays.equals(me.myArgumentTypes, that.myArgumentTypes); + } + }; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + final MethodRepr that = (MethodRepr)o; + + return name == that.name && myType.equals(that.myType) && Arrays.equals(myArgumentTypes, that.myArgumentTypes); + } + + @Override + public int hashCode() { + return 31 * (31 * Arrays.hashCode(myArgumentTypes) + myType.hashCode()) + name; + } + + private String getDescr(final DependencyContext context) { + final StringBuilder buf = new StringBuilder(); + + buf.append("("); + + for (TypeRepr.AbstractType t : myArgumentTypes) { + buf.append(t.getDescr(context)); + } + + buf.append(")"); + buf.append(myType.getDescr(context)); + + return buf.toString(); + } + + public UsageRepr.Usage createUsage(final DependencyContext context, final int owner) { + return UsageRepr.createMethodUsage(context, name, owner, getDescr(context)); + } + + public UsageRepr.Usage createMetaUsage(final DependencyContext context, final int owner) { + return UsageRepr.createMetaMethodUsage(context, name, owner, getDescr(context)); + } + + @Override + public void toStream(final DependencyContext context, final PrintStream stream) { + super.toStream(context, stream); + stream.print(" Arguments : "); + for (TypeRepr.AbstractType t : myArgumentTypes) { + stream.print(t.getDescr(context)); + stream.print("; "); + } + stream.println(); + + final TypeRepr.AbstractType[] es = myExceptions.toArray(new TypeRepr.AbstractType[myExceptions.size()]); + Arrays.sort(es, new Comparator() { + @Override + public int compare(final TypeRepr.AbstractType o1, final TypeRepr.AbstractType o2) { + return o1.getDescr(context).compareTo(o2.getDescr(context)); + } + }); + stream.print(" Exceptions : "); + for (final TypeRepr.AbstractType e : es) { + stream.print(e.getDescr(context)); + stream.print("; "); + } + stream.println(); + } +} diff --git a/jps/model/src/org/jetbrains/ether/dependencyView/OrderProvider.java b/jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/OrderProvider.java similarity index 91% rename from jps/model/src/org/jetbrains/ether/dependencyView/OrderProvider.java rename to jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/OrderProvider.java index 76a01f35b693..bde1f84a11b8 100644 --- a/jps/model/src/org/jetbrains/ether/dependencyView/OrderProvider.java +++ b/jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/OrderProvider.java @@ -1,6 +1,4 @@ -package org.jetbrains.ether.dependencyView; - -import org.intellij.lang.annotations.JdkConstants; +package org.jetbrains.jps.builders.java.dependencyView; import java.util.Collections; import java.util.LinkedList; diff --git a/jps/model/src/org/jetbrains/ether/dependencyView/Proto.java b/jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/Proto.java similarity index 93% rename from jps/model/src/org/jetbrains/ether/dependencyView/Proto.java rename to jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/Proto.java index 16349c15bb77..55640fc90c5b 100644 --- a/jps/model/src/org/jetbrains/ether/dependencyView/Proto.java +++ b/jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/Proto.java @@ -1,132 +1,131 @@ -package org.jetbrains.ether.dependencyView; - -import org.jetbrains.asm4.Opcodes; -import org.jetbrains.ether.RW; - -import java.io.DataInput; -import java.io.DataOutput; -import java.io.IOException; -import java.io.PrintStream; - -/** - * Created by IntelliJ IDEA. - * User: db - * Date: 01.03.11 - * Time: 17:57 - * To change this template use File | Settings | File Templates. - */ -class Proto implements RW.Savable, Streamable { - public final int access; - public final int signature; - public final int name; - - protected Proto(final int access, final int signature, final int name) { - this.access = access; - this.signature = signature; - this.name = name; - } - - protected Proto(final DataInput in) { - try { - access = in.readInt(); - signature = in.readInt(); - name = in.readInt(); - } - catch (IOException e) { - throw new RuntimeException(e); - } - } - - @Override - public void save(final DataOutput out) { - try { - out.writeInt(access); - out.writeInt(signature); - out.writeInt(name); - } - catch (IOException e) { - throw new RuntimeException(e); - } - } - - public Difference difference(final Proto past) { - int diff = Difference.NONE; - - if (past.access != access) { - diff |= Difference.ACCESS; - } - - if (past.signature != signature) { - diff |= Difference.SIGNATURE; - } - - final int base = diff; - - return new Difference() { - @Override - public int base() { - return base; - } - - @Override - public boolean no() { - return base == NONE; - } - - @Override - public int addedModifiers() { - return ~past.access & access; - } - - @Override - public int removedModifiers() { - return ~access & past.access; - } - - @Override - public boolean packageLocalOn() { - return ((past.access & Opcodes.ACC_PRIVATE) != 0 || - (past.access & Opcodes.ACC_PUBLIC) != 0 || - (past.access & Opcodes.ACC_PROTECTED) != 0) && - Difference.isPackageLocal(access); - } - - @Override - public boolean hadValue() { - return false; - } - - @Override - public boolean weakedAccess() { - return Difference.weakerAccess(past.access, access); - } - }; - } - - public void toStream(final DependencyContext context, final PrintStream stream) { - final String d = this instanceof ClassRepr ? " " : " "; - - if (this instanceof ClassRepr) { - stream.print(" Class "); - stream.println(context.getValue(name)); - } - - if (this instanceof MethodRepr) { - stream.print(" Method "); - stream.println(context.getValue(name)); - } - - if (this instanceof FieldRepr) { - stream.print(" Field "); - stream.println(context.getValue(name)); - } - - stream.print(d); - stream.print("Access : "); - stream.println(access); - - stream.print(d); - stream.print("Signature : "); - stream.println(context.getValue(signature)); - } -} +package org.jetbrains.jps.builders.java.dependencyView; + +import org.jetbrains.asm4.Opcodes; + +import java.io.DataInput; +import java.io.DataOutput; +import java.io.IOException; +import java.io.PrintStream; + +/** + * Created by IntelliJ IDEA. + * User: db + * Date: 01.03.11 + * Time: 17:57 + * To change this template use File | Settings | File Templates. + */ +class Proto implements RW.Savable, Streamable { + public final int access; + public final int signature; + public final int name; + + protected Proto(final int access, final int signature, final int name) { + this.access = access; + this.signature = signature; + this.name = name; + } + + protected Proto(final DataInput in) { + try { + access = in.readInt(); + signature = in.readInt(); + name = in.readInt(); + } + catch (IOException e) { + throw new RuntimeException(e); + } + } + + @Override + public void save(final DataOutput out) { + try { + out.writeInt(access); + out.writeInt(signature); + out.writeInt(name); + } + catch (IOException e) { + throw new RuntimeException(e); + } + } + + public Difference difference(final Proto past) { + int diff = Difference.NONE; + + if (past.access != access) { + diff |= Difference.ACCESS; + } + + if (past.signature != signature) { + diff |= Difference.SIGNATURE; + } + + final int base = diff; + + return new Difference() { + @Override + public int base() { + return base; + } + + @Override + public boolean no() { + return base == NONE; + } + + @Override + public int addedModifiers() { + return ~past.access & access; + } + + @Override + public int removedModifiers() { + return ~access & past.access; + } + + @Override + public boolean packageLocalOn() { + return ((past.access & Opcodes.ACC_PRIVATE) != 0 || + (past.access & Opcodes.ACC_PUBLIC) != 0 || + (past.access & Opcodes.ACC_PROTECTED) != 0) && + Difference.isPackageLocal(access); + } + + @Override + public boolean hadValue() { + return false; + } + + @Override + public boolean weakedAccess() { + return Difference.weakerAccess(past.access, access); + } + }; + } + + public void toStream(final DependencyContext context, final PrintStream stream) { + final String d = this instanceof ClassRepr ? " " : " "; + + if (this instanceof ClassRepr) { + stream.print(" Class "); + stream.println(context.getValue(name)); + } + + if (this instanceof MethodRepr) { + stream.print(" Method "); + stream.println(context.getValue(name)); + } + + if (this instanceof FieldRepr) { + stream.print(" Field "); + stream.println(context.getValue(name)); + } + + stream.print(d); + stream.print("Access : "); + stream.println(access); + + stream.print(d); + stream.print("Signature : "); + stream.println(context.getValue(signature)); + } +} diff --git a/jps/model/src/org/jetbrains/ether/dependencyView/ProtoMember.java b/jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/ProtoMember.java similarity index 95% rename from jps/model/src/org/jetbrains/ether/dependencyView/ProtoMember.java rename to jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/ProtoMember.java index c181667b0dea..54e361742827 100644 --- a/jps/model/src/org/jetbrains/ether/dependencyView/ProtoMember.java +++ b/jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/ProtoMember.java @@ -1,192 +1,192 @@ -package org.jetbrains.ether.dependencyView; - -import org.jetbrains.asm4.Type; - -import java.io.DataInput; -import java.io.DataOutput; -import java.io.IOException; -import java.io.PrintStream; - -/** - * Created by IntelliJ IDEA. - * User: db - * Date: 07.03.11 - * Time: 19:54 - * To change this template use File | Settings | File Templates. - */ -abstract class ProtoMember extends Proto { - private final static byte STRING = 0; - private final static byte NONE = 1; - private final static byte INTEGER = 2; - private final static byte LONG = 3; - private final static byte FLOAT = 4; - private final static byte DOUBLE = 5; - private final static byte TYPE = 6; - - public final TypeRepr.AbstractType myType; - public final Object myValue; - - public boolean hasValue() { - return myValue != null; - } - - protected ProtoMember(final int access, final int signature, final int name, final TypeRepr.AbstractType t, final Object value) { - super(access, signature, name); - this.myType = t; - this.myValue = value; - } - - private static Object loadTyped(final DataInput in) { - try { - switch (in.readByte()) { - case STRING: - return in.readUTF(); - case NONE: - return null; - case INTEGER: - return in.readInt(); - case LONG: - return in.readLong(); - case FLOAT: - return in.readFloat(); - case DOUBLE: - return in.readDouble(); - case TYPE : - return Type.getType(in.readUTF()); - } - } - catch (IOException e) { - throw new RuntimeException(e); - } - - assert (false); - - return null; - } - - protected ProtoMember(final DependencyContext context, final DataInput in) { - super(in); - try { - myType = TypeRepr.externalizer(context).read(in); - myValue = loadTyped(in); - } - catch (IOException e) { - throw new RuntimeException(e); - } - } - - public void save(final DataOutput out) { - super.save(out); - myType.save(out); - - try { - if (myValue instanceof String) { - out.writeByte(STRING); - out.writeUTF((String)myValue); - } - else if (myValue instanceof Integer) { - out.writeByte(INTEGER); - out.writeInt(((Integer)myValue).intValue()); - } - else if (myValue instanceof Long) { - out.writeByte(LONG); - out.writeLong(((Long)myValue).longValue()); - } - else if (myValue instanceof Float) { - out.writeByte(FLOAT); - out.writeFloat(((Float)myValue).floatValue()); - } - else if (myValue instanceof Double) { - out.writeByte(DOUBLE); - out.writeDouble(((Double)myValue).doubleValue()); - } - else if (myValue instanceof Type) { - out.writeByte(TYPE); - out.writeUTF(((Type)myValue).getDescriptor()); - } - else { - out.writeByte(NONE); - } - } - catch (IOException e) { - throw new RuntimeException(e); - } - } - - public Difference difference(final Proto past) { - final ProtoMember m = (ProtoMember)past; - final Difference diff = super.difference(past); - int base = diff.base(); - - if (!m.myType.equals(myType)) { - base |= Difference.TYPE; - } - - switch ((myValue == null ? 0 : 1) + (m.myValue == null ? 0 : 2)) { - case 3: - if (!myValue.equals(m.myValue)) { - base |= Difference.VALUE; - } - break; - - case 2: - base |= Difference.VALUE; - break; - - case 1: - base |= Difference.VALUE; - break; - - case 0: - break; - } - - final int newBase = base; - - return new Difference() { - @Override - public int base() { - return newBase; - } - - @Override - public boolean no() { - return newBase == NONE && diff.no(); - } - - @Override - public int addedModifiers() { - return diff.addedModifiers(); - } - - @Override - public int removedModifiers() { - return diff.removedModifiers(); - } - - @Override - public boolean packageLocalOn() { - return diff.packageLocalOn(); - } - - @Override - public boolean hadValue() { - return ((ProtoMember)past).hasValue(); - } - - @Override - public boolean weakedAccess() { - return diff.weakedAccess(); - } - }; - } - - public void toStream(final DependencyContext context, final PrintStream stream) { - super.toStream(context, stream); - stream.print(" Type : "); - stream.println(myType.getDescr(context)); - - stream.print(" Value : "); - stream.println(myValue == null ? "" : myValue.toString()); - } -} +package org.jetbrains.jps.builders.java.dependencyView; + +import org.jetbrains.asm4.Type; + +import java.io.DataInput; +import java.io.DataOutput; +import java.io.IOException; +import java.io.PrintStream; + +/** + * Created by IntelliJ IDEA. + * User: db + * Date: 07.03.11 + * Time: 19:54 + * To change this template use File | Settings | File Templates. + */ +abstract class ProtoMember extends Proto { + private final static byte STRING = 0; + private final static byte NONE = 1; + private final static byte INTEGER = 2; + private final static byte LONG = 3; + private final static byte FLOAT = 4; + private final static byte DOUBLE = 5; + private final static byte TYPE = 6; + + public final TypeRepr.AbstractType myType; + public final Object myValue; + + public boolean hasValue() { + return myValue != null; + } + + protected ProtoMember(final int access, final int signature, final int name, final TypeRepr.AbstractType t, final Object value) { + super(access, signature, name); + this.myType = t; + this.myValue = value; + } + + private static Object loadTyped(final DataInput in) { + try { + switch (in.readByte()) { + case STRING: + return in.readUTF(); + case NONE: + return null; + case INTEGER: + return in.readInt(); + case LONG: + return in.readLong(); + case FLOAT: + return in.readFloat(); + case DOUBLE: + return in.readDouble(); + case TYPE : + return Type.getType(in.readUTF()); + } + } + catch (IOException e) { + throw new RuntimeException(e); + } + + assert (false); + + return null; + } + + protected ProtoMember(final DependencyContext context, final DataInput in) { + super(in); + try { + myType = TypeRepr.externalizer(context).read(in); + myValue = loadTyped(in); + } + catch (IOException e) { + throw new RuntimeException(e); + } + } + + public void save(final DataOutput out) { + super.save(out); + myType.save(out); + + try { + if (myValue instanceof String) { + out.writeByte(STRING); + out.writeUTF((String)myValue); + } + else if (myValue instanceof Integer) { + out.writeByte(INTEGER); + out.writeInt(((Integer)myValue).intValue()); + } + else if (myValue instanceof Long) { + out.writeByte(LONG); + out.writeLong(((Long)myValue).longValue()); + } + else if (myValue instanceof Float) { + out.writeByte(FLOAT); + out.writeFloat(((Float)myValue).floatValue()); + } + else if (myValue instanceof Double) { + out.writeByte(DOUBLE); + out.writeDouble(((Double)myValue).doubleValue()); + } + else if (myValue instanceof Type) { + out.writeByte(TYPE); + out.writeUTF(((Type)myValue).getDescriptor()); + } + else { + out.writeByte(NONE); + } + } + catch (IOException e) { + throw new RuntimeException(e); + } + } + + public Difference difference(final Proto past) { + final ProtoMember m = (ProtoMember)past; + final Difference diff = super.difference(past); + int base = diff.base(); + + if (!m.myType.equals(myType)) { + base |= Difference.TYPE; + } + + switch ((myValue == null ? 0 : 1) + (m.myValue == null ? 0 : 2)) { + case 3: + if (!myValue.equals(m.myValue)) { + base |= Difference.VALUE; + } + break; + + case 2: + base |= Difference.VALUE; + break; + + case 1: + base |= Difference.VALUE; + break; + + case 0: + break; + } + + final int newBase = base; + + return new Difference() { + @Override + public int base() { + return newBase; + } + + @Override + public boolean no() { + return newBase == NONE && diff.no(); + } + + @Override + public int addedModifiers() { + return diff.addedModifiers(); + } + + @Override + public int removedModifiers() { + return diff.removedModifiers(); + } + + @Override + public boolean packageLocalOn() { + return diff.packageLocalOn(); + } + + @Override + public boolean hadValue() { + return ((ProtoMember)past).hasValue(); + } + + @Override + public boolean weakedAccess() { + return diff.weakedAccess(); + } + }; + } + + public void toStream(final DependencyContext context, final PrintStream stream) { + super.toStream(context, stream); + stream.print(" Type : "); + stream.println(myType.getDescr(context)); + + stream.print(" Value : "); + stream.println(myValue == null ? "" : myValue.toString()); + } +} diff --git a/jps/model/src/org/jetbrains/ether/RW.java b/jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/RW.java similarity index 99% rename from jps/model/src/org/jetbrains/ether/RW.java rename to jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/RW.java index 6764ada467aa..482e57d41d2a 100644 --- a/jps/model/src/org/jetbrains/ether/RW.java +++ b/jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/RW.java @@ -1,4 +1,4 @@ -package org.jetbrains.ether; +package org.jetbrains.jps.builders.java.dependencyView; import com.intellij.util.io.DataExternalizer; import gnu.trove.TIntHashSet; diff --git a/jps/model/src/org/jetbrains/ether/dependencyView/Streamable.java b/jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/Streamable.java similarity index 82% rename from jps/model/src/org/jetbrains/ether/dependencyView/Streamable.java rename to jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/Streamable.java index 2f074a7cfdc2..c74db331378e 100644 --- a/jps/model/src/org/jetbrains/ether/dependencyView/Streamable.java +++ b/jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/Streamable.java @@ -1,4 +1,4 @@ -package org.jetbrains.ether.dependencyView; +package org.jetbrains.jps.builders.java.dependencyView; import java.io.PrintStream; diff --git a/jps/model/src/org/jetbrains/ether/dependencyView/TypeRepr.java b/jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/TypeRepr.java similarity index 99% rename from jps/model/src/org/jetbrains/ether/dependencyView/TypeRepr.java rename to jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/TypeRepr.java index 92696a105510..9eee4544fafe 100644 --- a/jps/model/src/org/jetbrains/ether/dependencyView/TypeRepr.java +++ b/jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/TypeRepr.java @@ -1,9 +1,8 @@ -package org.jetbrains.ether.dependencyView; +package org.jetbrains.jps.builders.java.dependencyView; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.io.DataExternalizer; import org.jetbrains.asm4.Type; -import org.jetbrains.ether.RW; import java.io.DataInput; import java.io.DataOutput; diff --git a/jps/model/src/org/jetbrains/ether/dependencyView/UsageRepr.java b/jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/UsageRepr.java similarity index 99% rename from jps/model/src/org/jetbrains/ether/dependencyView/UsageRepr.java rename to jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/UsageRepr.java index 995ebfc85232..1100e7d16c12 100644 --- a/jps/model/src/org/jetbrains/ether/dependencyView/UsageRepr.java +++ b/jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/UsageRepr.java @@ -1,10 +1,9 @@ -package org.jetbrains.ether.dependencyView; +package org.jetbrains.jps.builders.java.dependencyView; import com.intellij.util.io.DataExternalizer; import gnu.trove.TIntHashSet; import gnu.trove.TIntProcedure; import org.jetbrains.asm4.Type; -import org.jetbrains.ether.RW; import java.io.*; import java.util.*; diff --git a/jps/jps-builders/src/org/jetbrains/jps/cmdline/BuildRunner.java b/jps/jps-builders/src/org/jetbrains/jps/cmdline/BuildRunner.java index d2ec39615d0f..db8e7c8d603d 100644 --- a/jps/jps-builders/src/org/jetbrains/jps/cmdline/BuildRunner.java +++ b/jps/jps-builders/src/org/jetbrains/jps/cmdline/BuildRunner.java @@ -4,8 +4,7 @@ import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import org.jetbrains.annotations.Nullable; -import org.jetbrains.ether.dependencyView.Callbacks; -import org.jetbrains.jps.Project; +import org.jetbrains.jps.builders.java.dependencyView.Callbacks; import org.jetbrains.jps.api.BuildType; import org.jetbrains.jps.api.CanceledStatus; import org.jetbrains.jps.api.GlobalOptions; @@ -80,8 +79,7 @@ public class BuildRunner { } final JpsModel jpsModel = myModelLoader.loadModel(); - final Project project = myModelLoader.loadOldProject(); - return new ProjectDescriptor(project, jpsModel, fsState, projectTimestamps, dataManager, BuildLoggingManager.DEFAULT); + return new ProjectDescriptor(jpsModel, fsState, projectTimestamps, dataManager, BuildLoggingManager.DEFAULT); } public void runBuild(ProjectDescriptor pd, CanceledStatus cs, @Nullable Callbacks.ConstantAffectionResolver constantSearch, @@ -143,7 +141,7 @@ public class BuildRunner { final CompileScope compileScope; if (buildType == BuildType.PROJECT_REBUILD || (modules.isEmpty() && paths.isEmpty())) { - compileScope = new AllProjectScope(pd.project, pd.jpsProject, artifacts, buildType != BuildType.MAKE); + compileScope = new AllProjectScope(pd.jpsProject, artifacts, buildType != BuildType.MAKE); } else { final Set forcedModules; @@ -183,10 +181,10 @@ public class BuildRunner { } if (filesToCompile.isEmpty()) { - compileScope = new ModulesScope(pd.project, pd.jpsProject, forcedModules, artifacts, buildType != BuildType.MAKE, includeTests); + compileScope = new ModulesScope(pd.jpsProject, forcedModules, artifacts, buildType != BuildType.MAKE, includeTests); } else { - compileScope = new ModulesAndFilesScope(pd.project, pd.jpsProject, forcedModules, filesToCompile, artifacts, buildType != BuildType.MAKE, includeTests); + compileScope = new ModulesAndFilesScope(pd.jpsProject, forcedModules, filesToCompile, artifacts, buildType != BuildType.MAKE, includeTests); } } return compileScope; diff --git a/jps/jps-builders/src/org/jetbrains/jps/cmdline/BuildSession.java b/jps/jps-builders/src/org/jetbrains/jps/cmdline/BuildSession.java index e9d6b5e2d0b7..42c0118cbed4 100644 --- a/jps/jps-builders/src/org/jetbrains/jps/cmdline/BuildSession.java +++ b/jps/jps-builders/src/org/jetbrains/jps/cmdline/BuildSession.java @@ -10,7 +10,7 @@ import com.intellij.util.io.DataOutputStream; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.Channels; import org.jetbrains.annotations.Nullable; -import org.jetbrains.ether.dependencyView.Callbacks; +import org.jetbrains.jps.builders.java.dependencyView.Callbacks; import org.jetbrains.jps.api.*; import org.jetbrains.jps.builders.java.JavaModuleBuildTargetType; import org.jetbrains.jps.incremental.MessageHandler; diff --git a/jps/jps-builders/src/org/jetbrains/jps/cmdline/ClasspathBootstrap.java b/jps/jps-builders/src/org/jetbrains/jps/cmdline/ClasspathBootstrap.java index 3110b39878ba..a5baaec58453 100644 --- a/jps/jps-builders/src/org/jetbrains/jps/cmdline/ClasspathBootstrap.java +++ b/jps/jps-builders/src/org/jetbrains/jps/cmdline/ClasspathBootstrap.java @@ -25,12 +25,10 @@ import com.intellij.uiDesigner.core.GridConstraints; import com.intellij.util.SystemProperties; import com.jgoodies.forms.layout.CellConstraints; import net.n3.nanoxml.IXMLBuilder; -import org.codehaus.groovy.GroovyException; import org.jboss.netty.util.Version; import org.jetbrains.annotations.Nullable; import org.jetbrains.asm4.ClassVisitor; import org.jetbrains.asm4.ClassWriter; -import org.jetbrains.jps.MacroExpander; import org.jetbrains.jps.javac.JavacServer; import org.jetbrains.jps.model.JpsModel; import org.jetbrains.jps.model.impl.JpsModelImpl; @@ -96,12 +94,10 @@ public class ClasspathBootstrap { cp.add(getResourcePath(Version.class)); // netty cp.add(getResourcePath(ClassWriter.class)); // asm cp.add(getResourcePath(ClassVisitor.class)); // asm-commons - cp.add(getResourcePath(MacroExpander.class)); // jps-model - cp.add(getResourcePath(JpsModel.class)); // jps-project-model - cp.add(getResourcePath(JpsModelImpl.class)); // jps-project-model + cp.add(getResourcePath(JpsModel.class)); // jps-model-api + cp.add(getResourcePath(JpsModelImpl.class)); // jps-model-impl cp.add(getResourcePath(JpsProjectLoader.class)); // jps-model-serialization cp.add(getResourcePath(AlienFormFileException.class)); // forms-compiler - cp.add(getResourcePath(GroovyException.class)); // groovy cp.add(getResourcePath(GridConstraints.class)); // forms-rt cp.add(getResourcePath(CellConstraints.class)); // jgoodies-forms cp.add(getResourcePath(NotNullVerifyingInstrumenter.class)); // not-null diff --git a/jps/jps-builders/src/org/jetbrains/jps/cmdline/JpsModelLoader.java b/jps/jps-builders/src/org/jetbrains/jps/cmdline/JpsModelLoader.java index fed3536d5051..7e4ba8a7f2fe 100644 --- a/jps/jps-builders/src/org/jetbrains/jps/cmdline/JpsModelLoader.java +++ b/jps/jps-builders/src/org/jetbrains/jps/cmdline/JpsModelLoader.java @@ -1,6 +1,5 @@ package org.jetbrains.jps.cmdline; -import org.jetbrains.jps.Project; import org.jetbrains.jps.model.JpsModel; /** @@ -8,6 +7,4 @@ import org.jetbrains.jps.model.JpsModel; */ public interface JpsModelLoader { JpsModel loadModel(); - - Project loadOldProject(); } diff --git a/jps/jps-builders/src/org/jetbrains/jps/cmdline/JpsModelLoaderImpl.java b/jps/jps-builders/src/org/jetbrains/jps/cmdline/JpsModelLoaderImpl.java index 7d864c45af7d..6c670a05b825 100644 --- a/jps/jps-builders/src/org/jetbrains/jps/cmdline/JpsModelLoaderImpl.java +++ b/jps/jps-builders/src/org/jetbrains/jps/cmdline/JpsModelLoaderImpl.java @@ -2,9 +2,6 @@ package org.jetbrains.jps.cmdline; import com.intellij.openapi.diagnostic.Logger; import com.intellij.util.ParameterizedRunnable; -import org.jetbrains.jps.Project; -import org.jetbrains.jps.idea.IdeaProjectLoader; -import org.jetbrains.jps.idea.SystemOutErrorReporter; import org.jetbrains.jps.model.JpsElementFactory; import org.jetbrains.jps.model.JpsModel; import org.jetbrains.jps.model.serialization.JpsGlobalLoader; @@ -59,24 +56,6 @@ public class JpsModelLoaderImpl implements JpsModelLoader { } } - @Override - public Project loadOldProject() { - final long start = System.currentTimeMillis(); - try { - final Project project = new Project(); - - final File projectFile = new File(myProjectPath); - - final String loadPath = isDirectoryBased(projectFile) ? new File(projectFile, IDEA_PROJECT_DIRNAME).getPath() : myProjectPath; - IdeaProjectLoader.loadFromPath(project, loadPath, myPathVars, null, new SystemOutErrorReporter(false)); - return project; - } - finally { - final long loadTime = System.currentTimeMillis() - start; - LOG.info("Project " + myProjectPath + " loaded in " + loadTime + " ms"); - } - } - private static boolean isDirectoryBased(File projectFile) { return !(projectFile.isFile() && projectFile.getName().endsWith(".ipr")); } diff --git a/jps/jps-builders/src/org/jetbrains/jps/cmdline/ProjectDescriptor.java b/jps/jps-builders/src/org/jetbrains/jps/cmdline/ProjectDescriptor.java index 1afe34ca08c2..b1e4123caa50 100644 --- a/jps/jps-builders/src/org/jetbrains/jps/cmdline/ProjectDescriptor.java +++ b/jps/jps-builders/src/org/jetbrains/jps/cmdline/ProjectDescriptor.java @@ -1,6 +1,5 @@ package org.jetbrains.jps.cmdline; -import org.jetbrains.jps.Project; import org.jetbrains.jps.incremental.BuildLoggingManager; import org.jetbrains.jps.incremental.CompilerEncodingConfiguration; import org.jetbrains.jps.incremental.ModuleRootsIndex; @@ -23,7 +22,6 @@ import java.util.Set; * Date: 1/8/12 */ public final class ProjectDescriptor { - public final Project project; public final JpsProject jpsProject; public final JpsModel jpsModel; public final BuildFSState fsState; @@ -36,13 +34,11 @@ public final class ProjectDescriptor { private Set> myProjectJavaSdks; private CompilerEncodingConfiguration myEncodingConfiguration; - public ProjectDescriptor(Project project, - JpsModel jpsModel, + public ProjectDescriptor(JpsModel jpsModel, BuildFSState fsState, ProjectTimestamps timestamps, BuildDataManager dataManager, BuildLoggingManager loggingManager) { - this.project = project; this.jpsModel = jpsModel; this.jpsProject = jpsModel.getProject(); this.fsState = fsState; @@ -50,7 +46,7 @@ public final class ProjectDescriptor { this.dataManager = dataManager; myLoggingManager = loggingManager; rootsIndex = new ModuleRootsIndex(jpsModel, dataManager); - myArtifactRootsIndex = new ArtifactRootsIndex(jpsModel, project, dataManager, rootsIndex); + myArtifactRootsIndex = new ArtifactRootsIndex(jpsModel, dataManager, rootsIndex); myProjectJavaSdks = new HashSet>(); myEncodingConfiguration = new CompilerEncodingConfiguration(jpsModel, rootsIndex); for (JpsModule module : jpsProject.getModules()) { diff --git a/jps/jps-builders/src/org/jetbrains/jps/incremental/AllProjectScope.java b/jps/jps-builders/src/org/jetbrains/jps/incremental/AllProjectScope.java index db0590eb43f5..55157e1af503 100644 --- a/jps/jps-builders/src/org/jetbrains/jps/incremental/AllProjectScope.java +++ b/jps/jps-builders/src/org/jetbrains/jps/incremental/AllProjectScope.java @@ -1,7 +1,6 @@ package org.jetbrains.jps.incremental; import org.jetbrains.annotations.NotNull; -import org.jetbrains.jps.Project; import org.jetbrains.jps.builders.BuildTarget; import org.jetbrains.jps.model.JpsProject; import org.jetbrains.jps.model.artifact.JpsArtifact; @@ -14,8 +13,8 @@ import java.util.Set; * Date: 9/17/11 */ public class AllProjectScope extends CompileScope { - public AllProjectScope(Project project, JpsProject jpsProject, Set artifacts, boolean forcedCompilation) { - super(project, jpsProject, artifacts, forcedCompilation); + public AllProjectScope(JpsProject jpsProject, Set artifacts, boolean forcedCompilation) { + super(jpsProject, artifacts, forcedCompilation); } public boolean isRecompilationForced(@NotNull BuildTarget target) { diff --git a/jps/jps-builders/src/org/jetbrains/jps/incremental/CompileContext.java b/jps/jps-builders/src/org/jetbrains/jps/incremental/CompileContext.java index 1cd175b697cf..f99b8f3d74db 100644 --- a/jps/jps-builders/src/org/jetbrains/jps/incremental/CompileContext.java +++ b/jps/jps-builders/src/org/jetbrains/jps/incremental/CompileContext.java @@ -3,12 +3,12 @@ package org.jetbrains.jps.incremental; import com.intellij.openapi.util.UserDataHolder; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.jetbrains.jps.AnnotationProcessingProfile; import org.jetbrains.jps.ModuleChunk; import org.jetbrains.jps.ProjectChunks; import org.jetbrains.jps.ProjectPaths; import org.jetbrains.jps.api.CanceledStatus; import org.jetbrains.jps.cmdline.ProjectDescriptor; +import org.jetbrains.jps.model.java.compiler.ProcessorConfigProfile; import org.jetbrains.jps.model.module.JpsModule; /** @@ -34,7 +34,7 @@ public interface CompileContext extends UserDataHolder, MessageHandler { void removeBuildListener(BuildListener listener); @NotNull - AnnotationProcessingProfile getAnnotationProcessingProfile(JpsModule module); + ProcessorConfigProfile getAnnotationProcessingProfile(JpsModule module); boolean shouldDifferentiate(ModuleChunk chunk); diff --git a/jps/jps-builders/src/org/jetbrains/jps/incremental/CompileContextImpl.java b/jps/jps-builders/src/org/jetbrains/jps/incremental/CompileContextImpl.java index 6001b2aeee9c..23acf15f3167 100644 --- a/jps/jps-builders/src/org/jetbrains/jps/incremental/CompileContextImpl.java +++ b/jps/jps-builders/src/org/jetbrains/jps/incremental/CompileContextImpl.java @@ -13,6 +13,9 @@ import org.jetbrains.jps.incremental.messages.BuildMessage; import org.jetbrains.jps.incremental.messages.FileDeletedEvent; import org.jetbrains.jps.incremental.messages.FileGeneratedEvent; import org.jetbrains.jps.incremental.messages.ProgressMessage; +import org.jetbrains.jps.model.java.JpsJavaExtensionService; +import org.jetbrains.jps.model.java.compiler.JpsJavaCompilerConfiguration; +import org.jetbrains.jps.model.java.compiler.ProcessorConfigProfile; import org.jetbrains.jps.model.module.JpsModule; import java.util.*; @@ -37,7 +40,7 @@ public class CompileContextImpl extends UserDataHolderBase implements CompileCon private final CanceledStatus myCancelStatus; private volatile float myDone = -1.0f; private EventDispatcher myListeners = EventDispatcher.create(BuildListener.class); - private Map myAnnotationProcessingProfileMap; + private Map myAnnotationProcessingProfileMap; public CompileContextImpl(CompileScope scope, ProjectDescriptor pd, boolean isMake, @@ -105,18 +108,18 @@ public class CompileContextImpl extends UserDataHolderBase implements CompileCon @Override @NotNull - public AnnotationProcessingProfile getAnnotationProcessingProfile(JpsModule module) { - final CompilerConfiguration compilerConfig = getProjectDescriptor().project.getCompilerConfiguration(); - Map map = myAnnotationProcessingProfileMap; + public ProcessorConfigProfile getAnnotationProcessingProfile(JpsModule module) { + final JpsJavaCompilerConfiguration compilerConfig = JpsJavaExtensionService.getInstance().getOrCreateCompilerConfiguration(getProjectDescriptor().jpsProject); + Map map = myAnnotationProcessingProfileMap; if (map == null) { - map = new HashMap(); + map = new HashMap(); final Map namesMap = new HashMap(); for (JpsModule m : getProjectDescriptor().jpsProject.getModules()) { namesMap.put(m.getName(), m); } if (!namesMap.isEmpty()) { - for (AnnotationProcessingProfile profile : compilerConfig.getModuleAnnotationProcessingProfiles()) { - for (String name : profile.getProcessModule()) { + for (ProcessorConfigProfile profile : compilerConfig.getAnnotationProcessingConfigurations()) { + for (String name : profile.getModuleNames()) { final JpsModule mod = namesMap.get(name); if (mod != null) { map.put(mod, profile); @@ -126,8 +129,8 @@ public class CompileContextImpl extends UserDataHolderBase implements CompileCon } myAnnotationProcessingProfileMap = map; } - final AnnotationProcessingProfile profile = map.get(module); - return profile != null? profile : compilerConfig.getDefaultAnnotationProcessingProfile(); + final ProcessorConfigProfile profile = map.get(module); + return profile != null? profile : compilerConfig.getDefaultAnnotationProcessingConfiguration(); } @Override diff --git a/jps/jps-builders/src/org/jetbrains/jps/incremental/CompileScope.java b/jps/jps-builders/src/org/jetbrains/jps/incremental/CompileScope.java index 768990d3c2ad..8c02526cdeb9 100644 --- a/jps/jps-builders/src/org/jetbrains/jps/incremental/CompileScope.java +++ b/jps/jps-builders/src/org/jetbrains/jps/incremental/CompileScope.java @@ -2,7 +2,6 @@ package org.jetbrains.jps.incremental; import org.jetbrains.annotations.NotNull; import org.jetbrains.jps.ModuleChunk; -import org.jetbrains.jps.Project; import org.jetbrains.jps.builders.BuildTarget; import org.jetbrains.jps.model.JpsProject; import org.jetbrains.jps.model.artifact.JpsArtifact; @@ -15,17 +14,13 @@ import java.util.Set; * Date: 1/15/12 */ public abstract class CompileScope { - @NotNull - private final Project myProject; private final JpsProject myJpsProject; private final Set myArtifacts; protected final boolean myForcedCompilation; - protected CompileScope(@NotNull Project project, - JpsProject jpsProject, + protected CompileScope(JpsProject jpsProject, Set artifacts, boolean forcedCompilation) { - myProject = project; myJpsProject = jpsProject; myArtifacts = artifacts; myForcedCompilation = forcedCompilation; @@ -58,11 +53,6 @@ public abstract class CompileScope { return myArtifacts; } - @NotNull - public final Project getProject() { - return myProject; - } - public JpsProject getJpsProject() { return myJpsProject; } diff --git a/jps/jps-builders/src/org/jetbrains/jps/incremental/IncProjectBuilder.java b/jps/jps-builders/src/org/jetbrains/jps/incremental/IncProjectBuilder.java index a1e46f18c939..8c745e0813c4 100644 --- a/jps/jps-builders/src/org/jetbrains/jps/incremental/IncProjectBuilder.java +++ b/jps/jps-builders/src/org/jetbrains/jps/incremental/IncProjectBuilder.java @@ -13,7 +13,7 @@ import com.intellij.util.io.MappingFailedException; import com.intellij.util.io.PersistentEnumerator; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.jetbrains.ether.dependencyView.Callbacks; +import org.jetbrains.jps.builders.java.dependencyView.Callbacks; import org.jetbrains.jps.*; import org.jetbrains.jps.api.CanceledStatus; import org.jetbrains.jps.api.GlobalOptions; @@ -28,6 +28,7 @@ import org.jetbrains.jps.incremental.java.JavaBuilderLogger; import org.jetbrains.jps.incremental.messages.*; import org.jetbrains.jps.incremental.storage.*; import org.jetbrains.jps.model.java.JpsJavaExtensionService; +import org.jetbrains.jps.model.java.compiler.ProcessorConfigProfile; import org.jetbrains.jps.model.module.JpsModule; import org.jetbrains.jps.service.SharedThreadPool; @@ -265,7 +266,8 @@ public class IncProjectBuilder { private void cleanOutputRoots(CompileContext context) throws ProjectBuildException { // whole project is affected - final boolean shouldClear = context.getProjectDescriptor().project.getCompilerConfiguration().isClearOutputDirectoryOnRebuild(); + final boolean shouldClear = JpsJavaExtensionService.getInstance().getOrCreateCompilerConfiguration( + context.getProjectDescriptor().jpsProject).isClearOutputDirectoryOnRebuild(); try { if (shouldClear) { clearOutputs(context); @@ -321,10 +323,10 @@ public class IncProjectBuilder { rootsToDelete.putValue(out, target); } - final AnnotationProcessingProfile profile = context.getAnnotationProcessingProfile(target.getModule()); + final ProcessorConfigProfile profile = context.getAnnotationProcessingProfile(target.getModule()); if (profile.isEnabled()) { File annotationOut = - paths.getAnnotationProcessorGeneratedSourcesOutputDir(target.getModule(), target.isTests(), profile.getGeneratedSourcesDirName()); + paths.getAnnotationProcessorGeneratedSourcesOutputDir(target.getModule(), target.isTests(), profile.getGeneratedSourcesDirectoryName()); if (annotationOut != null) { annotationOutputs.add(annotationOut); } diff --git a/jps/jps-builders/src/org/jetbrains/jps/incremental/ModuleLevelBuilder.java b/jps/jps-builders/src/org/jetbrains/jps/incremental/ModuleLevelBuilder.java index a5f688f837d1..818692023eac 100644 --- a/jps/jps-builders/src/org/jetbrains/jps/incremental/ModuleLevelBuilder.java +++ b/jps/jps-builders/src/org/jetbrains/jps/incremental/ModuleLevelBuilder.java @@ -3,8 +3,8 @@ package org.jetbrains.jps.incremental; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.Pair; -import org.jetbrains.ether.dependencyView.Callbacks; -import org.jetbrains.ether.dependencyView.Mappings; +import org.jetbrains.jps.builders.java.dependencyView.Callbacks; +import org.jetbrains.jps.builders.java.dependencyView.Mappings; import org.jetbrains.jps.ModuleChunk; import org.jetbrains.jps.ProjectPaths; import org.jetbrains.jps.incremental.fs.RootDescriptor; diff --git a/jps/jps-builders/src/org/jetbrains/jps/incremental/ModulesAndFilesScope.java b/jps/jps-builders/src/org/jetbrains/jps/incremental/ModulesAndFilesScope.java index 6f4a696c4c07..3cd2b772db00 100644 --- a/jps/jps-builders/src/org/jetbrains/jps/incremental/ModulesAndFilesScope.java +++ b/jps/jps-builders/src/org/jetbrains/jps/incremental/ModulesAndFilesScope.java @@ -1,7 +1,6 @@ package org.jetbrains.jps.incremental; import org.jetbrains.annotations.NotNull; -import org.jetbrains.jps.Project; import org.jetbrains.jps.builders.BuildTarget; import org.jetbrains.jps.builders.java.JavaModuleBuildTargetType; import org.jetbrains.jps.model.JpsProject; @@ -22,9 +21,9 @@ public class ModulesAndFilesScope extends CompileScope { private final Set myTargets; private final Map> myFiles; - public ModulesAndFilesScope(Project project, JpsProject jpsProject, Collection targets, Map> files, + public ModulesAndFilesScope(JpsProject jpsProject, Collection targets, Map> files, Set artifacts, boolean isForcedCompilation, boolean includeTests) { - super(project, jpsProject, artifacts, isForcedCompilation); + super(jpsProject, artifacts, isForcedCompilation); myFiles = files; myTargets = new HashSet(); for (JpsModule module : targets) { diff --git a/jps/jps-builders/src/org/jetbrains/jps/incremental/ModulesScope.java b/jps/jps-builders/src/org/jetbrains/jps/incremental/ModulesScope.java index 30e9bdf58945..4bc1873fb384 100644 --- a/jps/jps-builders/src/org/jetbrains/jps/incremental/ModulesScope.java +++ b/jps/jps-builders/src/org/jetbrains/jps/incremental/ModulesScope.java @@ -1,7 +1,6 @@ package org.jetbrains.jps.incremental; import org.jetbrains.annotations.NotNull; -import org.jetbrains.jps.Project; import org.jetbrains.jps.builders.BuildTarget; import org.jetbrains.jps.builders.java.JavaModuleBuildTargetType; import org.jetbrains.jps.model.JpsProject; @@ -19,13 +18,12 @@ import java.util.Set; public class ModulesScope extends CompileScope { private final Set myTargets; - public ModulesScope(Project project, - JpsProject jpsProject, + public ModulesScope(JpsProject jpsProject, Set modules, Set artifacts, boolean isForcedCompilation, boolean includeTests) { - super(project, jpsProject, artifacts, isForcedCompilation); + super(jpsProject, artifacts, isForcedCompilation); myTargets = new HashSet(); for (JpsModule module : modules) { myTargets.add(new ModuleBuildTarget(module, JavaModuleBuildTargetType.PRODUCTION)); diff --git a/jps/jps-builders/src/org/jetbrains/jps/incremental/ResourcePatterns.java b/jps/jps-builders/src/org/jetbrains/jps/incremental/ResourcePatterns.java index c08dd504a7e7..229e1e0b76d7 100644 --- a/jps/jps-builders/src/org/jetbrains/jps/incremental/ResourcePatterns.java +++ b/jps/jps-builders/src/org/jetbrains/jps/incremental/ResourcePatterns.java @@ -8,7 +8,9 @@ import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; -import org.jetbrains.jps.Project; +import org.jetbrains.jps.model.JpsProject; +import org.jetbrains.jps.model.java.JpsJavaExtensionService; +import org.jetbrains.jps.model.java.compiler.JpsJavaCompilerConfiguration; import java.io.File; import java.util.ArrayList; @@ -27,8 +29,9 @@ public class ResourcePatterns { private final List> myCompiledPatterns = new ArrayList>(); private final List> myNegatedCompiledPatterns = new ArrayList>(); - public ResourcePatterns(Project project) { - final List patterns = project.getCompilerConfiguration().getResourcePatterns(); + public ResourcePatterns(JpsProject project) { + JpsJavaCompilerConfiguration configuration = JpsJavaExtensionService.getInstance().getOrCreateCompilerConfiguration(project); + final List patterns = configuration.getResourcePatterns(); for (String pattern : patterns) { final Pair regexp = convertToRegexp(pattern); if (isPatternNegated(pattern)) { diff --git a/jps/jps-builders/src/org/jetbrains/jps/incremental/artifacts/ArtifactRootsIndex.java b/jps/jps-builders/src/org/jetbrains/jps/incremental/artifacts/ArtifactRootsIndex.java index aa6f4ff95a19..054e6914c0bc 100644 --- a/jps/jps-builders/src/org/jetbrains/jps/incremental/artifacts/ArtifactRootsIndex.java +++ b/jps/jps-builders/src/org/jetbrains/jps/incremental/artifacts/ArtifactRootsIndex.java @@ -5,7 +5,6 @@ import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.containers.MultiMap; import org.jetbrains.annotations.NotNull; -import org.jetbrains.jps.Project; import org.jetbrains.jps.ProjectPaths; import org.jetbrains.jps.incremental.ModuleRootsIndex; import org.jetbrains.jps.incremental.artifacts.builders.LayoutElementBuildersRegistry; @@ -25,7 +24,7 @@ public class ArtifactRootsIndex { private MultiMap myRootToDescriptorMap; private Map myInstructions; - public ArtifactRootsIndex(JpsModel model, Project project, BuildDataManager manager, ModuleRootsIndex rootsIndex) { + public ArtifactRootsIndex(JpsModel model, BuildDataManager manager, ModuleRootsIndex rootsIndex) { myRootToDescriptorMap = new MultiMap(); myInstructions = new HashMap(); ArtifactsBuildData data = manager.getArtifactsBuildData(); diff --git a/jps/jps-builders/src/org/jetbrains/jps/incremental/fs/BuildFSState.java b/jps/jps-builders/src/org/jetbrains/jps/incremental/fs/BuildFSState.java index 3b61bd5e8174..3827e9cfdbbd 100644 --- a/jps/jps-builders/src/org/jetbrains/jps/incremental/fs/BuildFSState.java +++ b/jps/jps-builders/src/org/jetbrains/jps/incremental/fs/BuildFSState.java @@ -6,13 +6,15 @@ import com.intellij.openapi.util.io.FileSystemUtil; import com.intellij.openapi.util.io.FileUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.jetbrains.jps.CompilerExcludes; import org.jetbrains.jps.ModuleChunk; import org.jetbrains.jps.incremental.*; import org.jetbrains.jps.incremental.artifacts.ArtifactFilesDelta; import org.jetbrains.jps.incremental.artifacts.ArtifactSourceTimestampStorage; import org.jetbrains.jps.incremental.artifacts.instructions.ArtifactRootDescriptor; import org.jetbrains.jps.incremental.storage.Timestamps; +import org.jetbrains.jps.model.JpsProject; +import org.jetbrains.jps.model.java.JpsJavaExtensionService; +import org.jetbrains.jps.model.java.compiler.JpsCompilerExcludes; import java.io.File; import java.io.IOException; @@ -119,7 +121,8 @@ public class BuildFSState extends FSState { public boolean processFilesToRecompile(CompileContext context, final ModuleBuildTarget target, final FileProcessor processor) throws IOException { final Map> data = getSourcesToRecompile(context, target); - final CompilerExcludes excludes = context.getProjectDescriptor().project.getCompilerConfiguration().getExcludes(); + JpsProject project = context.getProjectDescriptor().jpsProject; + final JpsCompilerExcludes excludes = JpsJavaExtensionService.getInstance().getOrCreateCompilerConfiguration(project).getCompilerExcludes(); final CompileScope scope = context.getScope(); synchronized (data) { for (Map.Entry> entry : data.entrySet()) { @@ -148,7 +151,7 @@ public class BuildFSState extends FSState { final FilesDelta delta = getDelta(rd.target); final Set files = delta.clearRecompile(rd.root); if (files != null) { - final CompilerExcludes excludes = scope.getProject().getCompilerConfiguration().getExcludes(); + final JpsCompilerExcludes excludes = JpsJavaExtensionService.getInstance().getOrCreateCompilerConfiguration(scope.getJpsProject()).getCompilerExcludes(); for (File file : files) { if (!excludes.isExcluded(file)) { if (scope.isAffected(rd.target, file)) { diff --git a/jps/jps-builders/src/org/jetbrains/jps/incremental/java/JavaBuilder.java b/jps/jps-builders/src/org/jetbrains/jps/incremental/java/JavaBuilder.java index 0bafdad4cbb9..a0a665a2f17d 100644 --- a/jps/jps-builders/src/org/jetbrains/jps/incremental/java/JavaBuilder.java +++ b/jps/jps-builders/src/org/jetbrains/jps/incremental/java/JavaBuilder.java @@ -25,8 +25,8 @@ import org.jetbrains.asm4.ClassReader; import org.jetbrains.asm4.ClassVisitor; import org.jetbrains.asm4.ClassWriter; import org.jetbrains.asm4.Opcodes; -import org.jetbrains.ether.dependencyView.Callbacks; -import org.jetbrains.ether.dependencyView.Mappings; +import org.jetbrains.jps.builders.java.dependencyView.Callbacks; +import org.jetbrains.jps.builders.java.dependencyView.Mappings; import org.jetbrains.jps.*; import org.jetbrains.jps.api.GlobalOptions; import org.jetbrains.jps.api.RequestFuture; @@ -40,9 +40,14 @@ import org.jetbrains.jps.incremental.storage.BuildDataManager; import org.jetbrains.jps.incremental.storage.SourceToFormMapping; import org.jetbrains.jps.javac.*; import org.jetbrains.jps.model.JpsDummyElement; +import org.jetbrains.jps.model.JpsProject; import org.jetbrains.jps.model.java.JpsJavaExtensionService; import org.jetbrains.jps.model.java.JpsJavaSdkType; import org.jetbrains.jps.model.java.LanguageLevel; +import org.jetbrains.jps.model.java.compiler.JpsCompilerExcludes; +import org.jetbrains.jps.model.java.compiler.JpsJavaCompilerConfiguration; +import org.jetbrains.jps.model.java.compiler.JpsJavaCompilerOptions; +import org.jetbrains.jps.model.java.compiler.ProcessorConfigProfile; import org.jetbrains.jps.model.library.sdk.JpsSdk; import org.jetbrains.jps.model.module.JpsModule; import org.jetbrains.jps.uiDesigner.model.JpsUiDesignerConfiguration; @@ -163,7 +168,7 @@ public class JavaBuilder extends ModuleLevelBuilder { }); // force compilation of bound source file if the form is dirty - final CompilerExcludes excludes = context.getProjectDescriptor().project.getCompilerConfiguration().getExcludes(); + final JpsCompilerExcludes excludes = JpsJavaExtensionService.getInstance().getOrCreateCompilerConfiguration(context.getProjectDescriptor().jpsProject).getCompilerExcludes(); if (!context.isProjectRebuild()) { for (Iterator formsIterator = formsToCompile.iterator(); formsIterator.hasNext(); ) { final File form = formsIterator.next(); @@ -283,7 +288,8 @@ public class JavaBuilder extends ModuleLevelBuilder { final ProjectPaths paths = context.getProjectPaths(); final ProjectDescriptor pd = context.getProjectDescriptor(); - final boolean addNotNullAssertions = pd.project.getCompilerConfiguration().isAddNotNullAssertions(); + final boolean addNotNullAssertions = JpsJavaExtensionService.getInstance().getOrCreateCompilerConfiguration( + pd.jpsProject).isAddNotNullAssertions(); final Collection classpath = paths.getCompilationClasspath(chunk, false/*context.isProjectRebuild()*/); @@ -432,14 +438,14 @@ public class JavaBuilder extends ModuleLevelBuilder { COUNTER_KEY.set(context, counter); final Set modules = chunk.getModules(); - AnnotationProcessingProfile profile = null; + ProcessorConfigProfile profile = null; if (modules.size() == 1) { profile = context.getAnnotationProcessingProfile(modules.iterator().next()); } else { // check that all chunk modules are excluded from annotation processing for (JpsModule module : modules) { - final AnnotationProcessingProfile prof = context.getAnnotationProcessingProfile(module); + final ProcessorConfigProfile prof = context.getAnnotationProcessingProfile(module); if (prof.isEnabled()) { String message = "Annotation processing is not supported for module cycles. Please ensure that all modules from cycle [" + getChunkPresentableName(chunk) + "] are excluded from annotation processing"; context.processMessage(new CompilerMessage(BUILDER_NAME, BuildMessage.Kind.ERROR, message)); @@ -479,7 +485,8 @@ public class JavaBuilder extends ModuleLevelBuilder { } private static boolean useEclipseCompiler(CompileContext context) { - return USE_EMBEDDED_JAVAC && "Eclipse".equalsIgnoreCase( context.getProjectDescriptor().project.getCompilerConfiguration().getOptions().get("DEFAULT_COMPILER")); + JpsProject project = context.getProjectDescriptor().jpsProject; + return USE_EMBEDDED_JAVAC && "Eclipse".equalsIgnoreCase(JpsJavaExtensionService.getInstance().getOrCreateCompilerConfiguration(project).getJavaCompilerId()); } private void submitAsyncTask(CompileContext context, final Runnable taskRunnable) { @@ -586,19 +593,11 @@ public class JavaBuilder extends ModuleLevelBuilder { } private static int getJavacServerHeapSize(CompileContext context) { - int heapSize = 512; - final Project project = context.getProjectDescriptor().project; - final CompilerConfiguration config = project.getCompilerConfiguration(); - final Map opts = useEclipseCompiler(context)? config.getEclipseOptions() : config.getJavacOptions(); - final String hSize = opts.get("MAXIMUM_HEAP_SIZE"); - if (hSize != null) { - try { - heapSize = Integer.parseInt(hSize); - } - catch (NumberFormatException ignored) { - } - } - return heapSize; + final JpsProject project = context.getProjectDescriptor().jpsProject; + final JpsJavaCompilerConfiguration config = JpsJavaExtensionService.getInstance().getOrCreateCompilerConfiguration(project); + final JpsJavaCompilerOptions options = config.getCurrentCompilerOptions(); + return options.MAXIMUM_HEAP_SIZE; + //return 512;//todo[jeka] default value was 128 in IDEA, do we really need to set it to 512 for javac server? } private static InstrumentationClassFinder createInstrumentationClassFinder(Collection platformCp, @@ -643,7 +642,7 @@ public class JavaBuilder extends ModuleLevelBuilder { return cached; } - private static List getCompilationOptions(CompileContext context, ModuleChunk chunk, AnnotationProcessingProfile profile) { + private static List getCompilationOptions(CompileContext context, ModuleChunk chunk, ProcessorConfigProfile profile) { List cached = JAVAC_OPTIONS.get(context); if (cached == null) { loadCommonJavacOptions(context); @@ -662,7 +661,7 @@ public class JavaBuilder extends ModuleLevelBuilder { } context.processMessage(new CompilerMessage(BUILDER_NAME, BuildMessage.Kind.INFO, msgBuilder.toString())); } - if (encoding != null) { + if (!StringUtil.isEmpty(encoding)) { options.add("-encoding"); options.add(encoding); } @@ -674,7 +673,8 @@ public class JavaBuilder extends ModuleLevelBuilder { options.add(langLevel); } - final BytecodeTargetConfiguration targetConfig = context.getProjectDescriptor().project.getCompilerConfiguration().getBytecodeTarget(); + JpsJavaCompilerConfiguration compilerConfiguration = JpsJavaExtensionService.getInstance().getOrCreateCompilerConfiguration( + context.getProjectDescriptor().jpsProject); String bytecodeTarget = null; int chunkSdkVersion = -1; for (JpsModule module : chunk.getModules()) { @@ -686,7 +686,7 @@ public class JavaBuilder extends ModuleLevelBuilder { } } - final String moduleTarget = getModuleTarget(targetConfig, module); + final String moduleTarget = compilerConfiguration.getByteCodeTargetLevel(module.getName()); if (moduleTarget == null) { continue; } @@ -713,8 +713,8 @@ public class JavaBuilder extends ModuleLevelBuilder { if (profile != null && profile.isEnabled()) { // configuring annotation processing - if (!profile.getObtainProcessorsFromClasspath()) { - final String processorsPath = profile.getProcessorsPath(); + if (!profile.isObtainProcessorsFromClasspath()) { + final String processorsPath = profile.getProcessorPath(); options.add("-processorpath"); options.add(processorsPath == null? "" : FileUtil.toSystemDependentName(processorsPath.trim())); } @@ -724,13 +724,13 @@ public class JavaBuilder extends ModuleLevelBuilder { options.add(procFQName); } - for (Map.Entry optionEntry : profile.getProcessorsOptions().entrySet()) { + for (Map.Entry optionEntry : profile.getProcessorOptions().entrySet()) { options.add("-A" + optionEntry.getKey() + "=" + optionEntry.getValue()); } final File srcOutput = context.getProjectPaths() .getAnnotationProcessorGeneratedSourcesOutputDir(chunk.getModules().iterator().next(), chunk.isTests(), - profile.getGeneratedSourcesDirName()); + profile.getGeneratedSourcesDirectoryName()); if (srcOutput != null) { srcOutput.mkdirs(); options.add("-s"); @@ -788,37 +788,25 @@ public class JavaBuilder extends ModuleLevelBuilder { return javaVersion; } - @Nullable - private static String getModuleTarget(BytecodeTargetConfiguration config, JpsModule module) { - final String level = config.getModulesBytecodeTarget().get(module.getName()); - if (level != null) { - return level.isEmpty()? null : level; - } - return config.getProjectBytecodeTarget(); - } - private static void loadCommonJavacOptions(CompileContext context) { final List options = new ArrayList(); final List vmOptions = new ArrayList(); - final Project project = context.getProjectDescriptor().project; - final CompilerConfiguration compilerConfig = project.getCompilerConfiguration(); + final JpsProject project = context.getProjectDescriptor().jpsProject; + final JpsJavaCompilerConfiguration compilerConfig = JpsJavaExtensionService.getInstance().getOrCreateCompilerConfiguration(project); final boolean useEclipseCompiler = useEclipseCompiler(context); - final Map opts = useEclipseCompiler ? compilerConfig.getEclipseOptions() : compilerConfig.getJavacOptions(); - final boolean debugInfo = !"false".equals(opts.get("DEBUGGING_INFO")); - final boolean nowarn = "true".equals(opts.get("GENERATE_NO_WARNINGS")); - final boolean deprecation = !"false".equals(opts.get("DEPRECATION")); - if (debugInfo) { + final JpsJavaCompilerOptions compilerOptions = compilerConfig.getCurrentCompilerOptions(); + if (compilerOptions.DEBUGGING_INFO) { options.add("-g"); } - if (deprecation) { + if (compilerOptions.DEPRECATION) { options.add("-deprecation"); } - if (nowarn) { + if (compilerOptions.GENERATE_NO_WARNINGS) { options.add("-nowarn"); } - final String customArgs = opts.get("ADDITIONAL_OPTIONS_STRING"); + final String customArgs = compilerOptions.ADDITIONAL_OPTIONS_STRING; if (customArgs != null) { final StringTokenizer customOptsTokenizer = new StringTokenizer(customArgs, " \t\r\n"); boolean skip = false; diff --git a/jps/jps-builders/src/org/jetbrains/jps/incremental/resources/ResourcesBuilder.java b/jps/jps-builders/src/org/jetbrains/jps/incremental/resources/ResourcesBuilder.java index e1dd4f048278..a948e126da90 100644 --- a/jps/jps-builders/src/org/jetbrains/jps/incremental/resources/ResourcesBuilder.java +++ b/jps/jps-builders/src/org/jetbrains/jps/incremental/resources/ResourcesBuilder.java @@ -40,7 +40,7 @@ public class ResourcesBuilder extends ModuleLevelBuilder { // init patterns ResourcePatterns patterns = ResourcePatterns.KEY.get(context); if (patterns == null) { - ResourcePatterns.KEY.set(context, new ResourcePatterns(context.getProjectDescriptor().project)); + ResourcePatterns.KEY.set(context, new ResourcePatterns(context.getProjectDescriptor().jpsProject)); } } diff --git a/jps/jps-builders/src/org/jetbrains/jps/incremental/storage/BuildDataManager.java b/jps/jps-builders/src/org/jetbrains/jps/incremental/storage/BuildDataManager.java index 6f768610da0c..52022255c210 100644 --- a/jps/jps-builders/src/org/jetbrains/jps/incremental/storage/BuildDataManager.java +++ b/jps/jps-builders/src/org/jetbrains/jps/incremental/storage/BuildDataManager.java @@ -3,7 +3,7 @@ package org.jetbrains.jps.incremental.storage; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.io.FileUtil; import org.jetbrains.annotations.Nullable; -import org.jetbrains.ether.dependencyView.Mappings; +import org.jetbrains.jps.builders.java.dependencyView.Mappings; import org.jetbrains.jps.ModuleChunk; import org.jetbrains.jps.builders.BuildTarget; import org.jetbrains.jps.incremental.ModuleBuildTarget; diff --git a/jps/jps-builders/testSrc/org/jetbrains/ether/IncrementalTestCase.java b/jps/jps-builders/testSrc/org/jetbrains/ether/IncrementalTestCase.java index d29afbeb7baf..dd8c8a4c1317 100644 --- a/jps/jps-builders/testSrc/org/jetbrains/ether/IncrementalTestCase.java +++ b/jps/jps-builders/testSrc/org/jetbrains/ether/IncrementalTestCase.java @@ -144,7 +144,7 @@ public abstract class IncrementalTestCase extends JpsBuildTestCase { final ProjectDescriptor projectDescriptor = createProjectDescriptor(new BuildLoggingManager(new ArtifactBuilderLoggerImpl(), javaBuilderLogger)); try { - doBuild(projectDescriptor, new AllProjectScope(myProject, myJpsProject, Collections.emptySet(), true), false, + doBuild(projectDescriptor, new AllProjectScope(myJpsProject, Collections.emptySet(), true), false, true, false).assertSuccessful(); modify(); @@ -153,7 +153,7 @@ public abstract class IncrementalTestCase extends JpsBuildTestCase { } - BuildResult result = doBuild(projectDescriptor, new AllProjectScope(myProject, myJpsProject, Collections.emptySet(), false), true, false, false); + BuildResult result = doBuild(projectDescriptor, new AllProjectScope(myJpsProject, Collections.emptySet(), false), true, false, false); final ByteArrayOutputStream makeDump = new ByteArrayOutputStream(); @@ -173,7 +173,7 @@ public abstract class IncrementalTestCase extends JpsBuildTestCase { assertEquals(expected, actual); if (result.isSuccessful()) { - doBuild(projectDescriptor, new AllProjectScope(myProject, myJpsProject, Collections.emptySet(), true), false, + doBuild(projectDescriptor, new AllProjectScope(myJpsProject, Collections.emptySet(), true), false, true, false).assertSuccessful(); final ByteArrayOutputStream rebuildDump = new ByteArrayOutputStream(); diff --git a/jps/jps-builders/testSrc/org/jetbrains/ether/StorageDumper.java b/jps/jps-builders/testSrc/org/jetbrains/ether/StorageDumper.java index 66c561774f1c..771fffb5633c 100644 --- a/jps/jps-builders/testSrc/org/jetbrains/ether/StorageDumper.java +++ b/jps/jps-builders/testSrc/org/jetbrains/ether/StorageDumper.java @@ -1,6 +1,6 @@ package org.jetbrains.ether; -import org.jetbrains.ether.dependencyView.Mappings; +import org.jetbrains.jps.builders.java.dependencyView.Mappings; import java.io.File; diff --git a/jps/jps-builders/testSrc/org/jetbrains/jps/builders/CompilerConfigurationTest.groovy b/jps/jps-builders/testSrc/org/jetbrains/jps/builders/CompilerConfigurationTest.groovy deleted file mode 100644 index 25b040bdd06d..000000000000 --- a/jps/jps-builders/testSrc/org/jetbrains/jps/builders/CompilerConfigurationTest.groovy +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright 2000-2011 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.jetbrains.jps.builders - -import com.intellij.openapi.util.io.FileUtil -import org.jetbrains.jps.CompilerConfiguration -import org.jetbrains.jps.builders.rebuild.JpsRebuildTestCase -/** - * @author nik - */ -class CompilerConfigurationTest extends JpsRebuildTestCase { - public void testLoadFromIpr() { - doTest("compilerConfiguration/compilerConfiguration.ipr") - } - - public void testLoadFromDirectory() { - doTest("compilerConfigurationDir/.idea") - } - - private def doTest(final String path) { - loadProject(path, [:]) - CompilerConfiguration configuration = myProject.compilerConfiguration - String basePath = FileUtil.toSystemIndependentName(getTestDataRootPath()) + "/" + path.substring(0, path.indexOf('/')) - assertFalse(configuration.clearOutputDirectoryOnRebuild) - assertFalse(configuration.addNotNullAssertions) - assertTrue(configuration.defaultAnnotationProcessingProfile.enabled) - assertFalse(configuration.defaultAnnotationProcessingProfile.obtainProcessorsFromClasspath) - assertEquals("$basePath/src", configuration.defaultAnnotationProcessingProfile.processorsPath) - assertEquals("b", configuration.defaultAnnotationProcessingProfile.processorsOptions["a"]) - assertEquals("d", configuration.defaultAnnotationProcessingProfile.processorsOptions["c"]) - assertEquals("gen", configuration.defaultAnnotationProcessingProfile.generatedSourcesDirName) - assertFalse(configuration.excludes.isExcluded(new File("$basePath/src/nonrec/x/Y.java"))) - assertTrue(configuration.excludes.isExcluded(new File("$basePath/src/nonrec/Y.java"))) - assertTrue(configuration.excludes.isExcluded(new File("$basePath/src/rec/x/Y.java"))) - assertTrue(configuration.excludes.isExcluded(new File("$basePath/src/rec/Y.java"))) - assertTrue(configuration.excludes.isExcluded(new File("$basePath/src/A.java"))) - assertFalse(configuration.excludes.isExcluded(new File("$basePath/src/B.java"))) - } - - public void testLoadJavacSettings() { - loadProject("resourceCopying/resourceCopying.ipr", [:]); - Map options = myProject.compilerConfiguration.javacOptions - assertNotNull(options) - assertEquals("512", options["MAXIMUM_HEAP_SIZE"]) - assertEquals("false", options["DEBUGGING_INFO"]) - assertEquals("true", options["GENERATE_NO_WARNINGS"]) - } -} diff --git a/jps/jps-builders/testSrc/org/jetbrains/jps/builders/JavacFileEncodingTest.groovy b/jps/jps-builders/testSrc/org/jetbrains/jps/builders/JavacFileEncodingTest.groovy index a46cf60fb7e8..8815a69af372 100644 --- a/jps/jps-builders/testSrc/org/jetbrains/jps/builders/JavacFileEncodingTest.groovy +++ b/jps/jps-builders/testSrc/org/jetbrains/jps/builders/JavacFileEncodingTest.groovy @@ -7,7 +7,7 @@ import org.jetbrains.jps.builders.rebuild.JpsRebuildTestCase */ class JavacFileEncodingTest extends JpsRebuildTestCase { public void test() { - doTest("javacFileEncoding/javacFileEncoding.ipr", null, { + doTest("javacFileEncoding/javacFileEncoding.ipr", { dir("production") { dir("javacFileEncoding") { file("MyClass.class") diff --git a/jps/jps-builders/testSrc/org/jetbrains/jps/builders/JpsBuildTestCase.java b/jps/jps-builders/testSrc/org/jetbrains/jps/builders/JpsBuildTestCase.java index fbc024fc2b15..e93e6320fa06 100644 --- a/jps/jps-builders/testSrc/org/jetbrains/jps/builders/JpsBuildTestCase.java +++ b/jps/jps-builders/testSrc/org/jetbrains/jps/builders/JpsBuildTestCase.java @@ -6,11 +6,9 @@ import com.intellij.testFramework.UsefulTestCase; import junit.framework.Assert; import org.jetbrains.annotations.Nullable; import org.jetbrains.jps.JpsPathUtil; -import org.jetbrains.jps.Project; import org.jetbrains.jps.api.CanceledStatus; import org.jetbrains.jps.cmdline.ClasspathBootstrap; import org.jetbrains.jps.cmdline.ProjectDescriptor; -import org.jetbrains.jps.idea.IdeaProjectLoader; import org.jetbrains.jps.incremental.*; import org.jetbrains.jps.incremental.fs.BuildFSState; import org.jetbrains.jps.incremental.storage.BuildDataManager; @@ -37,13 +35,11 @@ import java.util.Map; public abstract class JpsBuildTestCase extends UsefulTestCase { protected JpsProject myJpsProject; protected JpsModel myModel; - protected Project myProject; private File myDataStorageRoot; @Override protected void setUp() throws Exception { super.setUp(); - myProject = new Project(); myModel = JpsElementFactory.getInstance().createModel(); myJpsProject = myModel.getProject(); myDataStorageRoot = FileUtil.createTempDirectory("compile-server-" + getProjectName(), null); @@ -74,7 +70,7 @@ public abstract class JpsBuildTestCase extends UsefulTestCase { try { ProjectTimestamps timestamps = new ProjectTimestamps(myDataStorageRoot); BuildDataManager dataManager = new BuildDataManager(myDataStorageRoot, true); - return new ProjectDescriptor(myProject, myModel, new BuildFSState(true), timestamps, dataManager, buildLoggingManager); + return new ProjectDescriptor(myModel, new BuildFSState(true), timestamps, dataManager, buildLoggingManager); } catch (IOException e) { throw new RuntimeException(e); @@ -91,7 +87,6 @@ public abstract class JpsBuildTestCase extends UsefulTestCase { String testDataRootPath = getTestDataRootPath(); String fullProjectPath = FileUtil.toSystemDependentName(testDataRootPath != null ? testDataRootPath + "/" + projectPath : projectPath); pathVariables = addPathVariables(pathVariables); - IdeaProjectLoader.loadFromPath(myProject, fullProjectPath, pathVariables); JpsProjectLoader.loadProject(myJpsProject, pathVariables, fullProjectPath); } catch (IOException e) { diff --git a/jps/jps-builders/testSrc/org/jetbrains/jps/builders/rebuild/ArtifactRebuildTest.groovy b/jps/jps-builders/testSrc/org/jetbrains/jps/builders/rebuild/ArtifactRebuildTest.groovy index fbf198df974d..3847c1bafa63 100644 --- a/jps/jps-builders/testSrc/org/jetbrains/jps/builders/rebuild/ArtifactRebuildTest.groovy +++ b/jps/jps-builders/testSrc/org/jetbrains/jps/builders/rebuild/ArtifactRebuildTest.groovy @@ -12,7 +12,7 @@ class ArtifactRebuildTest extends JpsRebuildTestCase { public void testArtifactIncludesArchiveArtifact() { def name = "artifactIncludesArchiveArtifact" try { - doTest("$name/${name}.ipr", null) { + doTest("$name/${name}.ipr", { dir("artifacts") { dir("data") { archive("a.jar") { @@ -20,7 +20,7 @@ class ArtifactRebuildTest extends JpsRebuildTestCase { } } } - } + }) } finally { FileUtil.delete(new File(FileUtil.toSystemDependentName(getTestDataRootPath() + "/$name/data/a.jar"))) @@ -43,7 +43,7 @@ class ArtifactRebuildTest extends JpsRebuildTestCase { } public void testExtractDir() { - doTest("extractDirTest/extractDirTest.ipr", null, { + doTest("extractDirTest/extractDirTest.ipr", { dir("artifacts") { dir("extractDir") { file("b.txt", "b") @@ -74,7 +74,7 @@ class ArtifactRebuildTest extends JpsRebuildTestCase { } public void testManifestInArtifact() { - loadAndRebuild("manifestInArtifact/manifest.ipr", [:], null) + loadAndRebuild("manifestInArtifact/manifest.ipr", [:]) File jarFile = new File(myOutputDirectory, "artifacts/simple/simple.jar") junit.framework.Assert.assertTrue(jarFile.exists()) File extracted = FileUtil.createTempDirectory("build-manifest", "") @@ -86,7 +86,7 @@ class ArtifactRebuildTest extends JpsRebuildTestCase { } public void testOverwriteArtifacts() { - doTest("overwriteTest/overwriteTest.ipr", null, { + doTest("overwriteTest/overwriteTest.ipr", { dir("artifacts") { dir("classes") { file("a.xml", "") @@ -115,7 +115,7 @@ class ArtifactRebuildTest extends JpsRebuildTestCase { public void testPathVariablesInArtifact() { String externalDir = "${getTestDataRootPath()}/pathVariables/external" - doTest("pathVariables/pathVariables.ipr", ["EXTERNAL_DIR": externalDir], null, { + doTest("pathVariables/pathVariables.ipr", ["EXTERNAL_DIR": externalDir], { dir("artifacts") { dir("fileCopy") { dir("dir") { @@ -127,7 +127,7 @@ class ArtifactRebuildTest extends JpsRebuildTestCase { } public void testModuleTestOutputElement() { - doTest("moduleTestOutput/moduleTestOutput.ipr", null, { + doTest("moduleTestOutput/moduleTestOutput.ipr", { dir("artifacts") { dir("tests") { file("MyTest.class") diff --git a/jps/jps-builders/testSrc/org/jetbrains/jps/builders/rebuild/JpsRebuildTestCase.groovy b/jps/jps-builders/testSrc/org/jetbrains/jps/builders/rebuild/JpsRebuildTestCase.groovy index 7b3a1807c0fc..fa8db0a9f5a7 100644 --- a/jps/jps-builders/testSrc/org/jetbrains/jps/builders/rebuild/JpsRebuildTestCase.groovy +++ b/jps/jps-builders/testSrc/org/jetbrains/jps/builders/rebuild/JpsRebuildTestCase.groovy @@ -24,12 +24,12 @@ abstract class JpsRebuildTestCase extends JpsBuildTestCase { addJdk("1.6") } - def doTest(String projectPath, Closure initProject, Closure expectedOutput) { - doTest(projectPath, [:], initProject, expectedOutput) + def doTest(String projectPath, Closure expectedOutput) { + doTest(projectPath, [:], expectedOutput) } - def doTest(String projectPath, Map pathVariables, Closure initProject, Closure expectedOutput) { - loadAndRebuild(projectPath, pathVariables, initProject) + def doTest(String projectPath, Map pathVariables, Closure expectedOutput) { + loadAndRebuild(projectPath, pathVariables) assertOutput(getOrCreateOutputDirectory().getAbsolutePath(), expectedOutput); } @@ -39,11 +39,8 @@ abstract class JpsRebuildTestCase extends JpsBuildTestCase { root.build().assertDirectoryEqual(new File(FileUtil.toSystemDependentName(targetFolder))) } - protected void loadAndRebuild(String projectPath, Map pathVariables, Closure initProject) { + protected void loadAndRebuild(String projectPath, Map pathVariables) { loadProject(projectPath, pathVariables) - if (initProject != null) { - initProject(myProject, null) - } rebuild() } @@ -51,7 +48,7 @@ abstract class JpsRebuildTestCase extends JpsBuildTestCase { JpsJavaExtensionService.getInstance().getOrCreateProjectExtension(myJpsProject).outputUrl = JpsPathUtil.pathToUrl(FileUtil.toSystemIndependentName(getOrCreateOutputDirectory().getAbsolutePath())) def descriptor = createProjectDescriptor(new BuildLoggingManager(new ArtifactBuilderLoggerImpl(), new JavaBuilderLoggerImpl())) try { - def scope = new AllProjectScope(myProject, myJpsProject, new HashSet(JpsArtifactService.getInstance().getArtifacts(myJpsProject)), true) + def scope = new AllProjectScope(myJpsProject, new HashSet(JpsArtifactService.getInstance().getArtifacts(myJpsProject)), true) doBuild(descriptor, scope, false, true, false).assertSuccessful() } finally { @@ -78,11 +75,6 @@ abstract class JpsRebuildTestCase extends JpsBuildTestCase { return PathManagerEx.getCommunityHomePath() + "/jps/jps-builders/testData/output" } - protected void loadProject(String projectPath, Map pathVariables, Closure initGlobal) { - initGlobal(myProject) - loadProject(projectPath, pathVariables) - } - def initFileSystemItem(TestFileSystemBuilder item, Closure initializer) { def meta = new Expando() meta.dir = {String name, Closure content -> @@ -100,10 +92,6 @@ abstract class JpsRebuildTestCase extends JpsBuildTestCase { initializer() } - def File createTempDir() { - return FileUtil.createTempDirectory("jps-build", ""); - } - def File createTempFile() { return FileUtil.createTempFile("jps-build-file", ""); } diff --git a/jps/jps-builders/testSrc/org/jetbrains/jps/builders/rebuild/ModuleRebuildTest.groovy b/jps/jps-builders/testSrc/org/jetbrains/jps/builders/rebuild/ModuleRebuildTest.groovy index 4e223ded0321..0824e15cc22e 100644 --- a/jps/jps-builders/testSrc/org/jetbrains/jps/builders/rebuild/ModuleRebuildTest.groovy +++ b/jps/jps-builders/testSrc/org/jetbrains/jps/builders/rebuild/ModuleRebuildTest.groovy @@ -4,7 +4,7 @@ package org.jetbrains.jps.builders.rebuild */ public class ModuleRebuildTest extends JpsRebuildTestCase { public void testModuleCycle() { - doTest("moduleCycle/moduleCycle.ipr", null, { + doTest("moduleCycle/moduleCycle.ipr", { dir("production") { dir("module1") { file("Bar1.class") @@ -20,7 +20,7 @@ public class ModuleRebuildTest extends JpsRebuildTestCase { } public void testOverlappingSourceRoots() { - doTest("overlappingSourceRoots/overlappingSourceRoots.ipr", null, { + doTest("overlappingSourceRoots/overlappingSourceRoots.ipr", { dir("production") { dir("inner") { dir("y") { @@ -38,7 +38,7 @@ public class ModuleRebuildTest extends JpsRebuildTestCase { } public void testResourceCopying() { - doTest("resourceCopying/resourceCopying.ipr", null, { + doTest("resourceCopying/resourceCopying.ipr", { dir("production") { dir("resourceCopying") { dir("copy") { diff --git a/jps/jps-builders/testSrc/org/jetbrains/jps/incremental/artifacts/ArtifactBuilderTestCase.java b/jps/jps-builders/testSrc/org/jetbrains/jps/incremental/artifacts/ArtifactBuilderTestCase.java index 18cb9c8f07c1..21c3ab2f8d77 100644 --- a/jps/jps-builders/testSrc/org/jetbrains/jps/incremental/artifacts/ArtifactBuilderTestCase.java +++ b/jps/jps-builders/testSrc/org/jetbrains/jps/incremental/artifacts/ArtifactBuilderTestCase.java @@ -155,7 +155,7 @@ public abstract class ArtifactBuilderTestCase extends JpsBuildTestCase { myDescriptor.incUsageCounter(); } myArtifactBuilderLogger.clear(); - final CompileScope scope = new AllProjectScope(myDescriptor.project, myDescriptor.jpsProject, + final CompileScope scope = new AllProjectScope(myDescriptor.jpsProject, new HashSet(Arrays.asList(artifacts)), force); return doBuild(myDescriptor, scope, !force, false, false); } diff --git a/jps/jps.iml b/jps/jps.iml index da2dc806611e..54910c7b6733 100644 --- a/jps/jps.iml +++ b/jps/jps.iml @@ -11,7 +11,6 @@ - diff --git a/jps/model-api/src/org/jetbrains/jps/model/java/JpsJavaExtensionService.java b/jps/model-api/src/org/jetbrains/jps/model/java/JpsJavaExtensionService.java index 280f96e4a293..c2fe89391d79 100644 --- a/jps/model-api/src/org/jetbrains/jps/model/java/JpsJavaExtensionService.java +++ b/jps/model-api/src/org/jetbrains/jps/model/java/JpsJavaExtensionService.java @@ -5,6 +5,7 @@ import org.jetbrains.annotations.Nullable; import org.jetbrains.jps.model.JpsDummyElement; import org.jetbrains.jps.model.JpsGlobal; import org.jetbrains.jps.model.JpsProject; +import org.jetbrains.jps.model.java.compiler.JpsJavaCompilerConfiguration; import org.jetbrains.jps.model.library.JpsTypedLibrary; import org.jetbrains.jps.model.library.sdk.JpsSdk; import org.jetbrains.jps.model.module.JpsDependencyElement; @@ -20,12 +21,6 @@ import java.util.List; * @author nik */ public abstract class JpsJavaExtensionService { - @NotNull - public abstract JpsProductionModuleOutputPackagingElement createProductionModuleOutput(@NotNull JpsModuleReference moduleReference); - - @NotNull - public abstract JpsTestModuleOutputPackagingElement createTestModuleOutput(@NotNull JpsModuleReference moduleReference); - public static JpsJavaExtensionService getInstance() { return JpsServiceManager.getInstance().getService(JpsJavaExtensionService.class); } @@ -38,6 +33,12 @@ public abstract class JpsJavaExtensionService { return getInstance().enumerateDependencies(project); } + @NotNull + public abstract JpsProductionModuleOutputPackagingElement createProductionModuleOutput(@NotNull JpsModuleReference moduleReference); + + @NotNull + public abstract JpsTestModuleOutputPackagingElement createTestModuleOutput(@NotNull JpsModuleReference moduleReference); + public abstract JpsJavaDependenciesEnumerator enumerateDependencies(Collection modules); protected abstract JpsJavaDependenciesEnumerator enumerateDependencies(JpsProject project); @@ -86,4 +87,10 @@ public abstract class JpsJavaExtensionService { public abstract JpsTypedLibrary> addJavaSdk(@NotNull JpsGlobal global, @NotNull String name, @NotNull String homePath); + + @Nullable + public abstract JpsJavaCompilerConfiguration getCompilerConfiguration(@NotNull JpsProject project); + + @NotNull + public abstract JpsJavaCompilerConfiguration getOrCreateCompilerConfiguration(@NotNull JpsProject project); } diff --git a/java/compiler/openapi/src/com/intellij/compiler/AnnotationProcessingConfiguration.java b/jps/model-api/src/org/jetbrains/jps/model/java/compiler/AnnotationProcessingConfiguration.java similarity index 95% rename from java/compiler/openapi/src/com/intellij/compiler/AnnotationProcessingConfiguration.java rename to jps/model-api/src/org/jetbrains/jps/model/java/compiler/AnnotationProcessingConfiguration.java index bd5a9b0cf4de..8546dd5537a7 100644 --- a/java/compiler/openapi/src/com/intellij/compiler/AnnotationProcessingConfiguration.java +++ b/jps/model-api/src/org/jetbrains/jps/model/java/compiler/AnnotationProcessingConfiguration.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.intellij.compiler; +package org.jetbrains.jps.model.java.compiler; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; diff --git a/jps/model-api/src/org/jetbrains/jps/model/java/compiler/JpsCompilerExcludes.java b/jps/model-api/src/org/jetbrains/jps/model/java/compiler/JpsCompilerExcludes.java new file mode 100644 index 000000000000..6ac293bb6fda --- /dev/null +++ b/jps/model-api/src/org/jetbrains/jps/model/java/compiler/JpsCompilerExcludes.java @@ -0,0 +1,14 @@ +package org.jetbrains.jps.model.java.compiler; + +import java.io.File; + +/** + * @author nik + */ +public interface JpsCompilerExcludes { + void addExcludedFile(String url); + + void addExcludedDirectory(String url, boolean recursively); + + boolean isExcluded(File file); +} diff --git a/jps/model-api/src/org/jetbrains/jps/model/java/compiler/JpsJavaCompilerConfiguration.java b/jps/model-api/src/org/jetbrains/jps/model/java/compiler/JpsJavaCompilerConfiguration.java new file mode 100644 index 000000000000..73fbedbe976a --- /dev/null +++ b/jps/model-api/src/org/jetbrains/jps/model/java/compiler/JpsJavaCompilerConfiguration.java @@ -0,0 +1,50 @@ +package org.jetbrains.jps.model.java.compiler; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.jetbrains.jps.model.JpsElement; + +import java.util.Collection; +import java.util.List; + +/** + * @author nik + */ +public interface JpsJavaCompilerConfiguration extends JpsElement { + boolean isAddNotNullAssertions(); + void setAddNotNullAssertions(boolean addNotNullAssertions); + + boolean isClearOutputDirectoryOnRebuild(); + void setClearOutputDirectoryOnRebuild(boolean clearOutputDirectoryOnRebuild); + + @NotNull + JpsCompilerExcludes getCompilerExcludes(); + + @NotNull + ProcessorConfigProfile getDefaultAnnotationProcessingConfiguration(); + ProcessorConfigProfile addAnnotationProcessingProfile(); + @NotNull + Collection getAnnotationProcessingConfigurations(); + + void addResourcePattern(String pattern); + List getResourcePatterns(); + + + @Nullable + String getByteCodeTargetLevel(String moduleName); + + void setProjectByteCodeTargetLevel(String level); + void setModuleByteCodeTargetLevel(String moduleName, String level); + + @NotNull + String getJavaCompilerId(); + void setJavaCompilerId(@NotNull String compiler); + + @NotNull + JpsJavaCompilerOptions getCompilerOptions(@NotNull String compilerId); + void setCompilerOptions(@NotNull String compilerId, @NotNull JpsJavaCompilerOptions options); + + @NotNull + JpsJavaCompilerOptions getCurrentCompilerOptions(); + +} diff --git a/jps/model-api/src/org/jetbrains/jps/model/java/compiler/JpsJavaCompilerOptions.java b/jps/model-api/src/org/jetbrains/jps/model/java/compiler/JpsJavaCompilerOptions.java new file mode 100644 index 000000000000..945ed6406554 --- /dev/null +++ b/jps/model-api/src/org/jetbrains/jps/model/java/compiler/JpsJavaCompilerOptions.java @@ -0,0 +1,12 @@ +package org.jetbrains.jps.model.java.compiler; + +/** + * @author nik + */ +public class JpsJavaCompilerOptions { + public boolean DEBUGGING_INFO = true; + public boolean GENERATE_NO_WARNINGS = false; + public boolean DEPRECATION = true; + public String ADDITIONAL_OPTIONS_STRING = ""; + public int MAXIMUM_HEAP_SIZE = 128; +} diff --git a/jps/model-api/src/org/jetbrains/jps/model/java/compiler/ProcessorConfigProfile.java b/jps/model-api/src/org/jetbrains/jps/model/java/compiler/ProcessorConfigProfile.java new file mode 100644 index 000000000000..007651801d39 --- /dev/null +++ b/jps/model-api/src/org/jetbrains/jps/model/java/compiler/ProcessorConfigProfile.java @@ -0,0 +1,52 @@ +package org.jetbrains.jps.model.java.compiler; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.Collection; +import java.util.Set; + +/** + * @author nik + */ +public interface ProcessorConfigProfile extends AnnotationProcessingConfiguration { + void initFrom(ProcessorConfigProfile other); + + String getName(); + + void setName(String name); + + void setEnabled(boolean enabled); + + void setProcessorPath(@Nullable String processorPath); + + void setObtainProcessorsFromClasspath(boolean value); + + void setGeneratedSourcesDirectoryName(@Nullable String generatedSourcesDirectoryName); + + @NotNull + Set getModuleNames(); + + boolean addModuleName(String name); + + boolean addModuleNames(Collection names); + + boolean removeModuleName(String name); + + boolean removeModuleNames(Collection names); + + void clearModuleNames(); + + void clearProcessors(); + + boolean addProcessor(String processor); + + boolean removeProcessor(String processor); + + String setOption(String key, String value); + + @Nullable + String getOption(String key); + + void clearProcessorOptions(); +} diff --git a/jps/model-impl/src/org/jetbrains/jps/model/impl/JpsElementContainerImpl.java b/jps/model-impl/src/org/jetbrains/jps/model/impl/JpsElementContainerImpl.java index dded7a68f9ff..7ec7fa39a150 100644 --- a/jps/model-impl/src/org/jetbrains/jps/model/impl/JpsElementContainerImpl.java +++ b/jps/model-impl/src/org/jetbrains/jps/model/impl/JpsElementContainerImpl.java @@ -74,6 +74,7 @@ public class JpsElementContainerImpl implements JpsElementContainer { public void removeChild(@NotNull JpsElementChildRole role) { //noinspection unchecked final T removed = (T)myElements.remove(role); + if (removed == null) return; final JpsEventDispatcher eventDispatcher = getEventDispatcher(); if (eventDispatcher != null) { eventDispatcher.fireElementRemoved(removed, role); diff --git a/jps/model-impl/src/org/jetbrains/jps/model/impl/JpsEncodingConfigurationServiceImpl.java b/jps/model-impl/src/org/jetbrains/jps/model/impl/JpsEncodingConfigurationServiceImpl.java index fca1efc90d24..407c292c52db 100644 --- a/jps/model-impl/src/org/jetbrains/jps/model/impl/JpsEncodingConfigurationServiceImpl.java +++ b/jps/model-impl/src/org/jetbrains/jps/model/impl/JpsEncodingConfigurationServiceImpl.java @@ -21,7 +21,12 @@ public class JpsEncodingConfigurationServiceImpl extends JpsEncodingConfiguratio @Override public void setGlobalEncoding(@NotNull JpsGlobal global, @Nullable String encoding) { - global.getContainer().setChild(ENCODING_ROLE, JpsElementFactory.getInstance().createSimpleElement(encoding)); + if (encoding != null) { + global.getContainer().setChild(ENCODING_ROLE, JpsElementFactory.getInstance().createSimpleElement(encoding)); + } + else { + global.getContainer().removeChild(ENCODING_ROLE); + } } @Nullable diff --git a/jps/model-impl/src/org/jetbrains/jps/model/java/impl/JpsJavaExtensionServiceImpl.java b/jps/model-impl/src/org/jetbrains/jps/model/java/impl/JpsJavaExtensionServiceImpl.java index 2678d7c0dce3..86018efbb23d 100644 --- a/jps/model-impl/src/org/jetbrains/jps/model/java/impl/JpsJavaExtensionServiceImpl.java +++ b/jps/model-impl/src/org/jetbrains/jps/model/java/impl/JpsJavaExtensionServiceImpl.java @@ -9,6 +9,8 @@ import org.jetbrains.jps.model.JpsGlobal; import org.jetbrains.jps.model.JpsProject; import org.jetbrains.jps.model.JpsSimpleElement; import org.jetbrains.jps.model.java.*; +import org.jetbrains.jps.model.java.compiler.JpsJavaCompilerConfiguration; +import org.jetbrains.jps.model.java.impl.compiler.JpsJavaCompilerConfigurationImpl; import org.jetbrains.jps.model.library.JpsOrderRootType; import org.jetbrains.jps.model.library.JpsTypedLibrary; import org.jetbrains.jps.model.library.sdk.JpsSdk; @@ -143,6 +145,22 @@ public class JpsJavaExtensionServiceImpl extends JpsJavaExtensionService { return sdk; } + @Nullable + @Override + public JpsJavaCompilerConfiguration getCompilerConfiguration(@NotNull JpsProject project) { + return project.getContainer().getChild(JpsJavaCompilerConfigurationImpl.ROLE); + } + + @NotNull + @Override + public JpsJavaCompilerConfiguration getOrCreateCompilerConfiguration(@NotNull JpsProject project) { + JpsJavaCompilerConfiguration configuration = getCompilerConfiguration(project); + if (configuration == null) { + configuration = project.getContainer().setChild(JpsJavaCompilerConfigurationImpl.ROLE, new JpsJavaCompilerConfigurationImpl()); + } + return configuration; + } + @Override @NotNull public JpsProductionModuleOutputPackagingElement createProductionModuleOutput(@NotNull JpsModuleReference moduleReference) { diff --git a/jps/model/src/org/jetbrains/jps/CompilerExcludes.java b/jps/model-impl/src/org/jetbrains/jps/model/java/impl/compiler/JpsCompilerExcludesImpl.java similarity index 68% rename from jps/model/src/org/jetbrains/jps/CompilerExcludes.java rename to jps/model-impl/src/org/jetbrains/jps/model/java/impl/compiler/JpsCompilerExcludesImpl.java index b0fe02dc8d7b..ee29135f7ea5 100644 --- a/jps/model/src/org/jetbrains/jps/CompilerExcludes.java +++ b/jps/model-impl/src/org/jetbrains/jps/model/java/impl/compiler/JpsCompilerExcludesImpl.java @@ -1,6 +1,8 @@ -package org.jetbrains.jps; +package org.jetbrains.jps.model.java.impl.compiler; import com.intellij.openapi.util.io.FileUtil; +import org.jetbrains.jps.JpsPathUtil; +import org.jetbrains.jps.model.java.compiler.JpsCompilerExcludes; import java.io.File; import java.util.HashSet; @@ -9,11 +11,21 @@ import java.util.Set; /** * @author nik */ -public class CompilerExcludes { +public class JpsCompilerExcludesImpl implements JpsCompilerExcludes { private final Set myFiles = new HashSet(); private final Set myDirectories = new HashSet(); private final Set myRecursivelyExcludedDirectories = new HashSet(); + @Override + public void addExcludedFile(String url) { + addExcludedFile(JpsPathUtil.urlToFile(url)); + } + + @Override + public void addExcludedDirectory(String url, boolean recursively) { + addExcludedDirectory(JpsPathUtil.urlToFile(url), recursively); + } + public void addExcludedFile(File file) { myFiles.add(file); } @@ -22,6 +34,7 @@ public class CompilerExcludes { (recursively ? myRecursivelyExcludedDirectories : myDirectories).add(dir); } + @Override public boolean isExcluded(File file) { if (myFiles.contains(file)) { return true; diff --git a/jps/model-impl/src/org/jetbrains/jps/model/java/impl/compiler/JpsJavaCompilerConfigurationImpl.java b/jps/model-impl/src/org/jetbrains/jps/model/java/impl/compiler/JpsJavaCompilerConfigurationImpl.java new file mode 100644 index 000000000000..a2d5a6ad9a32 --- /dev/null +++ b/jps/model-impl/src/org/jetbrains/jps/model/java/impl/compiler/JpsJavaCompilerConfigurationImpl.java @@ -0,0 +1,151 @@ +package org.jetbrains.jps.model.java.impl.compiler; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.jetbrains.jps.model.JpsElementChildRole; +import org.jetbrains.jps.model.impl.JpsCompositeElementBase; +import org.jetbrains.jps.model.impl.JpsElementChildRoleBase; +import org.jetbrains.jps.model.java.compiler.JpsCompilerExcludes; +import org.jetbrains.jps.model.java.compiler.JpsJavaCompilerConfiguration; +import org.jetbrains.jps.model.java.compiler.JpsJavaCompilerOptions; +import org.jetbrains.jps.model.java.compiler.ProcessorConfigProfile; + +import java.util.*; + +/** + * @author nik + */ +public class JpsJavaCompilerConfigurationImpl extends JpsCompositeElementBase implements JpsJavaCompilerConfiguration { + public static final JpsElementChildRole ROLE = JpsElementChildRoleBase.create("compiler configuration"); + private boolean myAddNotNullAssertions = true; + private boolean myClearOutputDirectoryOnRebuild; + private JpsCompilerExcludes myCompilerExcludes = new JpsCompilerExcludesImpl(); + private List myResourcePatterns = new ArrayList(); + private List myAnnotationProcessingProfiles = new ArrayList(); + private ProcessorConfigProfileImpl myDefaultAnnotationProcessingProfile = new ProcessorConfigProfileImpl("Default"); + private String myProjectByteCodeTargetLevel; + private Map myModulesByteCodeTargetLevels = new HashMap(); + private Map myCompilerOptions = new HashMap(); + private String myJavaCompilerId = "Javac"; + + public JpsJavaCompilerConfigurationImpl() { + } + + private JpsJavaCompilerConfigurationImpl(JpsJavaCompilerConfigurationImpl original) { + super(original); + } + + @NotNull + @Override + public JpsJavaCompilerConfigurationImpl createCopy() { + return new JpsJavaCompilerConfigurationImpl(this); + } + + @Override + public boolean isAddNotNullAssertions() { + return myAddNotNullAssertions; + } + + @Override + public boolean isClearOutputDirectoryOnRebuild() { + return myClearOutputDirectoryOnRebuild; + } + + @Override + public void setAddNotNullAssertions(boolean addNotNullAssertions) { + myAddNotNullAssertions = addNotNullAssertions; + } + + @Override + public void setClearOutputDirectoryOnRebuild(boolean clearOutputDirectoryOnRebuild) { + myClearOutputDirectoryOnRebuild = clearOutputDirectoryOnRebuild; + } + + @NotNull + @Override + public JpsCompilerExcludes getCompilerExcludes() { + return myCompilerExcludes; + } + + @NotNull + @Override + public ProcessorConfigProfile getDefaultAnnotationProcessingConfiguration() { + return myDefaultAnnotationProcessingProfile; + } + + @NotNull + @Override + public Collection getAnnotationProcessingConfigurations() { + return myAnnotationProcessingProfiles; + } + + @Override + public void addResourcePattern(String pattern) { + myResourcePatterns.add(pattern); + } + + @Override + public List getResourcePatterns() { + return myResourcePatterns; + } + + @Override + @Nullable + public String getByteCodeTargetLevel(String moduleName) { + String level = myModulesByteCodeTargetLevels.get(moduleName); + if (level != null) { + return level.isEmpty() ? null : level; + } + return myProjectByteCodeTargetLevel; + } + + @Override + public void setModuleByteCodeTargetLevel(String moduleName, String level) { + myModulesByteCodeTargetLevels.put(moduleName, level); + } + + @NotNull + @Override + public String getJavaCompilerId() { + return myJavaCompilerId; + } + + @Override + public void setJavaCompilerId(@NotNull String compiler) { + myJavaCompilerId = compiler; + } + + @NotNull + @Override + public JpsJavaCompilerOptions getCompilerOptions(@NotNull String compilerId) { + JpsJavaCompilerOptions options = myCompilerOptions.get(compilerId); + if (options == null) { + options = new JpsJavaCompilerOptions(); + myCompilerOptions.put(compilerId, options); + } + return options; + } + + @Override + public void setCompilerOptions(@NotNull String compilerId, @NotNull JpsJavaCompilerOptions options) { + myCompilerOptions.put(compilerId, options); + } + + @NotNull + @Override + public JpsJavaCompilerOptions getCurrentCompilerOptions() { + return getCompilerOptions(getJavaCompilerId()); + } + + @Override + public void setProjectByteCodeTargetLevel(String level) { + myProjectByteCodeTargetLevel = level; + } + + @Override + public ProcessorConfigProfile addAnnotationProcessingProfile() { + ProcessorConfigProfileImpl profile = new ProcessorConfigProfileImpl(""); + myAnnotationProcessingProfiles.add(profile); + return profile; + } +} diff --git a/java/compiler/impl/src/com/intellij/compiler/ProcessorConfigProfile.java b/jps/model-impl/src/org/jetbrains/jps/model/java/impl/compiler/ProcessorConfigProfileImpl.java similarity index 50% rename from java/compiler/impl/src/com/intellij/compiler/ProcessorConfigProfile.java rename to jps/model-impl/src/org/jetbrains/jps/model/java/impl/compiler/ProcessorConfigProfileImpl.java index ce6f7e5127b1..60d4bbf1544e 100644 --- a/java/compiler/impl/src/com/intellij/compiler/ProcessorConfigProfile.java +++ b/jps/model-impl/src/org/jetbrains/jps/model/java/impl/compiler/ProcessorConfigProfileImpl.java @@ -13,35 +13,19 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.intellij.compiler; +package org.jetbrains.jps.model.java.impl.compiler; -import com.intellij.openapi.util.io.FileUtil; -import com.intellij.openapi.util.text.StringUtil; -import org.jdom.Element; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import org.jetbrains.jps.model.java.compiler.ProcessorConfigProfile; -import java.io.File; import java.util.*; /** * @author Eugene Zhuravlev * Date: 5/25/12 */ -public final class ProcessorConfigProfile implements AnnotationProcessingConfiguration { - private static final Comparator ALPHA_COMPARATOR = new Comparator() { - @Override - public int compare(String o1, String o2) { - return o1.compareToIgnoreCase(o2); - } - }; - private static final String ENTRY = "entry"; - private static final String NAME = "name"; - private static final String VALUE = "value"; - private static final String ENABLED = "enabled"; - private static final String OPTION = "option"; - private static final String MODULE = "module"; - +public final class ProcessorConfigProfileImpl implements ProcessorConfigProfile { private String myName = ""; private boolean myEnabled = false; private boolean myObtainProcessorsFromClasspath = true; @@ -52,129 +36,35 @@ public final class ProcessorConfigProfile implements AnnotationProcessingConfigu private String myGeneratedSourcesDirectoryName = null; // null means 'auto' private final Set myModuleNames = new HashSet(); - public ProcessorConfigProfile(String name) { + public ProcessorConfigProfileImpl(String name) { myName = name; } - public ProcessorConfigProfile(ProcessorConfigProfile profile) { + public ProcessorConfigProfileImpl(ProcessorConfigProfile profile) { initFrom(profile); } - public void readExternal(Element element) { - setName(element.getAttributeValue(NAME, "")); - setEnabled(Boolean.valueOf(element.getAttributeValue(ENABLED, "false"))); - - final Element srcOutput = element.getChild("sourceOutputDir"); - setGeneratedSourcesDirectoryName(srcOutput != null ? srcOutput.getAttributeValue(NAME) : null); - - clearProcessorOptions(); - for (Object optionElement : element.getChildren(OPTION)) { - final Element elem = (Element)optionElement; - final String key = elem.getAttributeValue(NAME); - final String value = elem.getAttributeValue(VALUE); - if (!StringUtil.isEmptyOrSpaces(key) && value != null) { - setOption(key, value); - } - } - - clearProcessors(); - for (Object procElement : element.getChildren("processor")) { - final String name = ((Element)procElement).getAttributeValue(NAME); - if (StringUtil.isEmptyOrSpaces(name)) { - addProcessor(name); - } - } - - final Element pathElement = element.getChild("processorPath"); - if (pathElement != null) { - setObtainProcessorsFromClasspath(Boolean.parseBoolean(pathElement.getAttributeValue("useClasspath", "true"))); - final StringBuilder pathBuilder = new StringBuilder(); - for (Object entry : pathElement.getChildren(ENTRY)) { - final String path = ((Element)entry).getAttributeValue(NAME); - if (!StringUtil.isEmptyOrSpaces(path)) { - if (pathBuilder.length() > 0) { - pathBuilder.append(File.pathSeparator); - } - pathBuilder.append(FileUtil.toSystemDependentName(path)); - } - } - setProcessorPath(pathBuilder.toString()); - } - - clearModuleNames(); - for (Object moduleElement : element.getChildren(MODULE)) { - final String name = ((Element)moduleElement).getAttributeValue(NAME); - if (!StringUtil.isEmptyOrSpaces(name)) { - addModuleName(name); - } - } - } - - public void writeExternal(final Element element) { - element.setAttribute(NAME, getName()); - element.setAttribute(ENABLED, Boolean.toString(isEnabled())); - - final String srcDirName = getGeneratedSourcesDirectoryName(); - if (srcDirName != null) { - addChild(element, "sourceOutputDir").setAttribute(NAME, srcDirName); - } - - final Map options = getProcessorOptions(); - if (!options.isEmpty()) { - final List keys = new ArrayList(options.keySet()); - Collections.sort(keys, ALPHA_COMPARATOR); - for (String key : keys) { - addChild(element, OPTION).setAttribute(NAME, key).setAttribute(VALUE, options.get(key)); - } - } - - final Set processors = getProcessors(); - if (!processors.isEmpty()) { - final List processorList = new ArrayList(processors); - Collections.sort(processorList, ALPHA_COMPARATOR); - for (String proc : processorList) { - addChild(element, "processor").setAttribute(NAME, proc); - } - } - - final Element pathElement = addChild(element, "processorPath").setAttribute("useClasspath", Boolean.toString(isObtainProcessorsFromClasspath())); - final String path = getProcessorPath(); - if (!StringUtil.isEmpty(path)) { - final StringTokenizer tokenizer = new StringTokenizer(path, File.pathSeparator, false); - while (tokenizer.hasMoreTokens()) { - final String token = tokenizer.nextToken(); - addChild(pathElement, ENTRY).setAttribute(NAME, FileUtil.toSystemIndependentName(token)); - } - } - - final Set moduleNames = getModuleNames(); - if (!moduleNames.isEmpty()) { - final List names = new ArrayList(moduleNames); - Collections.sort(names, ALPHA_COMPARATOR); - for (String name : names) { - addChild(element, MODULE).setAttribute(NAME, name); - } - } - } - + @Override public final void initFrom(ProcessorConfigProfile other) { - myName = other.myName; - myEnabled = other.myEnabled; - myObtainProcessorsFromClasspath = other.myObtainProcessorsFromClasspath; - myProcessorPath = other.myProcessorPath; + myName = other.getName(); + myEnabled = other.isEnabled(); + myObtainProcessorsFromClasspath = other.isObtainProcessorsFromClasspath(); + myProcessorPath = other.getProcessorPath(); myProcessors.clear(); - myProcessors.addAll(other.myProcessors); + myProcessors.addAll(other.getProcessors()); myProcessorOptions.clear(); - myProcessorOptions.putAll(other.myProcessorOptions); - myGeneratedSourcesDirectoryName = other.myGeneratedSourcesDirectoryName; + myProcessorOptions.putAll(other.getProcessorOptions()); + myGeneratedSourcesDirectoryName = other.getGeneratedSourcesDirectoryName(); myModuleNames.clear(); - myModuleNames.addAll(other.myModuleNames); + myModuleNames.addAll(other.getModuleNames()); } + @Override public String getName() { return myName; } + @Override public void setName(String name) { myName = name; } @@ -184,6 +74,7 @@ public final class ProcessorConfigProfile implements AnnotationProcessingConfigu return myEnabled; } + @Override public void setEnabled(boolean enabled) { myEnabled = enabled; } @@ -194,6 +85,7 @@ public final class ProcessorConfigProfile implements AnnotationProcessingConfigu return myProcessorPath; } + @Override public void setProcessorPath(@Nullable String processorPath) { myProcessorPath = processorPath != null? processorPath : ""; } @@ -203,6 +95,7 @@ public final class ProcessorConfigProfile implements AnnotationProcessingConfigu return myObtainProcessorsFromClasspath; } + @Override public void setObtainProcessorsFromClasspath(boolean value) { myObtainProcessorsFromClasspath = value; } @@ -213,43 +106,53 @@ public final class ProcessorConfigProfile implements AnnotationProcessingConfigu return myGeneratedSourcesDirectoryName; } + @Override public void setGeneratedSourcesDirectoryName(@Nullable String generatedSourcesDirectoryName) { myGeneratedSourcesDirectoryName = generatedSourcesDirectoryName; } + @Override @NotNull public Set getModuleNames() { return myModuleNames; } + @Override public boolean addModuleName(String name) { return myModuleNames.add(name); } + @Override public boolean addModuleNames(Collection names) { return myModuleNames.addAll(names); } + @Override public boolean removeModuleName(String name) { return myModuleNames.remove(name); } + @Override public boolean removeModuleNames(Collection names) { return myModuleNames.removeAll(names); } + @Override public void clearModuleNames() { myModuleNames.clear(); } + @Override public void clearProcessors() { myProcessors.clear(); } + @Override public boolean addProcessor(String processor) { return myProcessors.add(processor); } + @Override public boolean removeProcessor(String processor) { return myProcessors.remove(processor); } @@ -266,15 +169,18 @@ public final class ProcessorConfigProfile implements AnnotationProcessingConfigu return Collections.unmodifiableMap(myProcessorOptions); } + @Override public String setOption(String key, String value) { return myProcessorOptions.put(key, value); } + @Override @Nullable public String getOption(String key) { return myProcessorOptions.get(key); } + @Override public void clearProcessorOptions() { myProcessorOptions.clear(); } @@ -284,7 +190,7 @@ public final class ProcessorConfigProfile implements AnnotationProcessingConfigu if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; - ProcessorConfigProfile profile = (ProcessorConfigProfile)o; + ProcessorConfigProfileImpl profile = (ProcessorConfigProfileImpl)o; if (myEnabled != profile.myEnabled) return false; if (myObtainProcessorsFromClasspath != profile.myObtainProcessorsFromClasspath) return false; @@ -319,11 +225,5 @@ public final class ProcessorConfigProfile implements AnnotationProcessingConfigu public String toString() { return myName; } - - private static Element addChild(Element parent, final String childName) { - final Element child = new Element(childName); - parent.addContent(child); - return child; - } } diff --git a/jps/model-serialization/src/org/jetbrains/jps/model/serialization/JpsEncodingModelSerializerExtension.java b/jps/model-serialization/src/org/jetbrains/jps/model/serialization/JpsEncodingModelSerializerExtension.java index 9612e942e678..0302f596813a 100644 --- a/jps/model-serialization/src/org/jetbrains/jps/model/serialization/JpsEncodingModelSerializerExtension.java +++ b/jps/model-serialization/src/org/jetbrains/jps/model/serialization/JpsEncodingModelSerializerExtension.java @@ -1,6 +1,7 @@ package org.jetbrains.jps.model.serialization; import com.intellij.openapi.util.JDOMUtil; +import com.intellij.openapi.util.text.StringUtil; import org.jdom.Element; import org.jetbrains.annotations.NotNull; import org.jetbrains.jps.model.JpsEncodingConfigurationService; @@ -64,7 +65,8 @@ public class JpsEncodingModelSerializerExtension extends JpsModelSerializerExten @Override public void loadExtension(@NotNull JpsGlobal global, @NotNull Element componentTag) { - JpsEncodingConfigurationService.getInstance().setGlobalEncoding(global, componentTag.getAttributeValue(ENCODING_ATTRIBUTE)); + String encoding = componentTag.getAttributeValue(ENCODING_ATTRIBUTE); + JpsEncodingConfigurationService.getInstance().setGlobalEncoding(global, StringUtil.nullize(encoding)); } @Override diff --git a/jps/model-serialization/src/org/jetbrains/jps/model/serialization/JpsProjectExtensionSerializer.java b/jps/model-serialization/src/org/jetbrains/jps/model/serialization/JpsProjectExtensionSerializer.java index 881fc0831ec6..27faec954aab 100644 --- a/jps/model-serialization/src/org/jetbrains/jps/model/serialization/JpsProjectExtensionSerializer.java +++ b/jps/model-serialization/src/org/jetbrains/jps/model/serialization/JpsProjectExtensionSerializer.java @@ -8,6 +8,7 @@ import org.jetbrains.jps.model.JpsProject; * @author nik */ public abstract class JpsProjectExtensionSerializer extends JpsElementExtensionSerializerBase { + public static final String WORKSPACE_FILE = "workspace.xml"; /** * @param configFileName name of file in .idea directory where the extension settings are stored diff --git a/jps/model-serialization/src/org/jetbrains/jps/model/serialization/JpsProjectLoader.java b/jps/model-serialization/src/org/jetbrains/jps/model/serialization/JpsProjectLoader.java index 3c527e73d177..fb5a6e2e8de5 100644 --- a/jps/model-serialization/src/org/jetbrains/jps/model/serialization/JpsProjectLoader.java +++ b/jps/model-serialization/src/org/jetbrains/jps/model/serialization/JpsProjectLoader.java @@ -102,19 +102,24 @@ public class JpsProjectLoader extends JpsLoaderBase { } private void loadFromIpr(File iprFile) { - final Element root = loadRootElement(iprFile); - JpsSdkType projectSdkType = loadProjectRoot(root); + final Element iprRoot = loadRootElement(iprFile); + + File iwsFile = new File(iprFile.getParent(), FileUtil.getNameWithoutExtension(iprFile) + ".iws"); + Element iwsRoot = iwsFile.exists() ? loadRootElement(iwsFile) : null; + + JpsSdkType projectSdkType = loadProjectRoot(iprRoot); for (JpsModelSerializerExtension extension : JpsModelSerializerExtension.getExtensions()) { for (JpsProjectExtensionSerializer serializer : extension.getProjectExtensionSerializers()) { - Element component = JDomSerializationUtil.findComponent(root, serializer.getComponentName()); + Element rootTag = JpsProjectExtensionSerializer.WORKSPACE_FILE.equals(serializer.getConfigFileName()) ? iwsRoot : iprRoot; + Element component = JDomSerializationUtil.findComponent(rootTag, serializer.getComponentName()); if (component != null) { serializer.loadExtension(myProject, component); } } } - loadModules(root, projectSdkType); - loadProjectLibraries(JDomSerializationUtil.findComponent(root, "libraryTable")); - loadArtifacts(JDomSerializationUtil.findComponent(root, "ArtifactManager")); + loadModules(iprRoot, projectSdkType); + loadProjectLibraries(JDomSerializationUtil.findComponent(iprRoot, "libraryTable")); + loadArtifacts(JDomSerializationUtil.findComponent(iprRoot, "ArtifactManager")); } private void loadArtifacts(Element artifactManagerComponent) { diff --git a/jps/model-serialization/src/org/jetbrains/jps/model/serialization/java/JpsJavaModelSerializerExtension.java b/jps/model-serialization/src/org/jetbrains/jps/model/serialization/java/JpsJavaModelSerializerExtension.java index 4aa4a3ccf766..1d76acabd851 100644 --- a/jps/model-serialization/src/org/jetbrains/jps/model/serialization/java/JpsJavaModelSerializerExtension.java +++ b/jps/model-serialization/src/org/jetbrains/jps/model/serialization/java/JpsJavaModelSerializerExtension.java @@ -12,6 +12,9 @@ import org.jetbrains.jps.model.library.JpsOrderRootType; import org.jetbrains.jps.model.module.JpsDependencyElement; import org.jetbrains.jps.model.module.JpsModule; import org.jetbrains.jps.model.module.JpsModuleReference; +import org.jetbrains.jps.model.serialization.java.compiler.JpsJavaCompilerConfigurationSerializer; +import org.jetbrains.jps.model.serialization.java.compiler.JpsJavaCompilerOptionsSerializer; +import org.jetbrains.jps.model.serialization.java.compiler.JpsJavaCompilerWorkspaceConfigurationSerializer; import org.jetbrains.jps.model.serialization.library.JpsLibraryRootTypeSerializer; import org.jetbrains.jps.model.serialization.JpsModelSerializerExtension; import org.jetbrains.jps.model.serialization.JpsProjectExtensionSerializer; @@ -54,7 +57,11 @@ public class JpsJavaModelSerializerExtension extends JpsModelSerializerExtension @NotNull @Override public List getProjectExtensionSerializers() { - return Arrays.asList(new JavaProjectExtensionSerializer()); + return Arrays.asList(new JavaProjectExtensionSerializer(), + new JpsJavaCompilerConfigurationSerializer(), + new JpsJavaCompilerWorkspaceConfigurationSerializer(), + new JpsJavaCompilerOptionsSerializer("JavacSettings", "Javac"), + new JpsJavaCompilerOptionsSerializer("EclipseCompilerSettings", "Eclipse")); } @Override diff --git a/jps/model-serialization/src/org/jetbrains/jps/model/serialization/java/compiler/AnnotationProcessorProfileSerializer.java b/jps/model-serialization/src/org/jetbrains/jps/model/serialization/java/compiler/AnnotationProcessorProfileSerializer.java new file mode 100644 index 000000000000..279a3e402b84 --- /dev/null +++ b/jps/model-serialization/src/org/jetbrains/jps/model/serialization/java/compiler/AnnotationProcessorProfileSerializer.java @@ -0,0 +1,146 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.jps.model.serialization.java.compiler; + +import com.intellij.openapi.util.io.FileUtil; +import com.intellij.openapi.util.text.StringUtil; +import org.jdom.Element; +import org.jetbrains.jps.model.java.compiler.ProcessorConfigProfile; + +import java.io.File; +import java.util.*; + +/** + * @author nik + */ +public class AnnotationProcessorProfileSerializer { + private static final Comparator ALPHA_COMPARATOR = new Comparator() { + @Override + public int compare(String o1, String o2) { + return o1.compareToIgnoreCase(o2); + } + }; + private static final String ENTRY = "entry"; + private static final String NAME = "name"; + private static final String VALUE = "value"; + private static final String ENABLED = "enabled"; + private static final String OPTION = "option"; + private static final String MODULE = "module"; + + public static void readExternal(ProcessorConfigProfile profile, Element element) { + profile.setName(element.getAttributeValue(NAME, "")); + profile.setEnabled(Boolean.valueOf(element.getAttributeValue(ENABLED, "false"))); + + final Element srcOutput = element.getChild("sourceOutputDir"); + profile.setGeneratedSourcesDirectoryName(srcOutput != null ? srcOutput.getAttributeValue(NAME) : null); + + profile.clearProcessorOptions(); + for (Object optionElement : element.getChildren(OPTION)) { + final Element elem = (Element)optionElement; + final String key = elem.getAttributeValue(NAME); + final String value = elem.getAttributeValue(VALUE); + if (!StringUtil.isEmptyOrSpaces(key) && value != null) { + profile.setOption(key, value); + } + } + + profile.clearProcessors(); + for (Object procElement : element.getChildren("processor")) { + final String name = ((Element)procElement).getAttributeValue(NAME); + if (StringUtil.isEmptyOrSpaces(name)) { + profile.addProcessor(name); + } + } + + final Element pathElement = element.getChild("processorPath"); + if (pathElement != null) { + profile.setObtainProcessorsFromClasspath(Boolean.parseBoolean(pathElement.getAttributeValue("useClasspath", "true"))); + final StringBuilder pathBuilder = new StringBuilder(); + for (Object entry : pathElement.getChildren(ENTRY)) { + final String path = ((Element)entry).getAttributeValue(NAME); + if (!StringUtil.isEmptyOrSpaces(path)) { + if (pathBuilder.length() > 0) { + pathBuilder.append(File.pathSeparator); + } + pathBuilder.append(FileUtil.toSystemDependentName(path)); + } + } + profile.setProcessorPath(pathBuilder.toString()); + } + + profile.clearModuleNames(); + for (Object moduleElement : element.getChildren(MODULE)) { + final String name = ((Element)moduleElement).getAttributeValue(NAME); + if (!StringUtil.isEmptyOrSpaces(name)) { + profile.addModuleName(name); + } + } + } + + public static void writeExternal(ProcessorConfigProfile profile, final Element element) { + element.setAttribute(NAME, profile.getName()); + element.setAttribute(ENABLED, Boolean.toString(profile.isEnabled())); + + final String srcDirName = profile.getGeneratedSourcesDirectoryName(); + if (srcDirName != null) { + addChild(element, "sourceOutputDir").setAttribute(NAME, srcDirName); + } + + final Map options = profile.getProcessorOptions(); + if (!options.isEmpty()) { + final List keys = new ArrayList(options.keySet()); + Collections.sort(keys, ALPHA_COMPARATOR); + for (String key : keys) { + addChild(element, OPTION).setAttribute(NAME, key).setAttribute(VALUE, options.get(key)); + } + } + + final Set processors = profile.getProcessors(); + if (!processors.isEmpty()) { + final List processorList = new ArrayList(processors); + Collections.sort(processorList, ALPHA_COMPARATOR); + for (String proc : processorList) { + addChild(element, "processor").setAttribute(NAME, proc); + } + } + + final Element pathElement = addChild(element, "processorPath").setAttribute("useClasspath", Boolean.toString( + profile.isObtainProcessorsFromClasspath())); + final String path = profile.getProcessorPath(); + if (!StringUtil.isEmpty(path)) { + final StringTokenizer tokenizer = new StringTokenizer(path, File.pathSeparator, false); + while (tokenizer.hasMoreTokens()) { + final String token = tokenizer.nextToken(); + addChild(pathElement, ENTRY).setAttribute(NAME, FileUtil.toSystemIndependentName(token)); + } + } + + final Set moduleNames = profile.getModuleNames(); + if (!moduleNames.isEmpty()) { + final List names = new ArrayList(moduleNames); + Collections.sort(names, ALPHA_COMPARATOR); + for (String name : names) { + addChild(element, MODULE).setAttribute(NAME, name); + } + } + } + + private static Element addChild(Element parent, final String childName) { + final Element child = new Element(childName); + parent.addContent(child); + return child; + } +} diff --git a/jps/model-serialization/src/org/jetbrains/jps/model/serialization/java/compiler/JpsJavaCompilerConfigurationSerializer.java b/jps/model-serialization/src/org/jetbrains/jps/model/serialization/java/compiler/JpsJavaCompilerConfigurationSerializer.java new file mode 100644 index 000000000000..82f6ffdefecf --- /dev/null +++ b/jps/model-serialization/src/org/jetbrains/jps/model/serialization/java/compiler/JpsJavaCompilerConfigurationSerializer.java @@ -0,0 +1,96 @@ +package org.jetbrains.jps.model.serialization.java.compiler; + +import com.intellij.openapi.util.JDOMExternalizerUtil; +import com.intellij.openapi.util.JDOMUtil; +import com.intellij.openapi.util.text.StringUtil; +import org.jdom.Element; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.jps.model.JpsProject; +import org.jetbrains.jps.model.java.JpsJavaExtensionService; +import org.jetbrains.jps.model.java.compiler.JpsJavaCompilerConfiguration; +import org.jetbrains.jps.model.serialization.JpsProjectExtensionSerializer; + +import java.util.List; + +/** + * @author nik + */ +public class JpsJavaCompilerConfigurationSerializer extends JpsProjectExtensionSerializer { + public static final String EXCLUDE_FROM_COMPILE = "excludeFromCompile"; + public static final String RESOURCE_EXTENSIONS = "resourceExtensions"; + public static final String ANNOTATION_PROCESSING = "annotationProcessing"; + public static final String BYTECODE_TARGET_LEVEL = "bytecodeTargetLevel"; + public static final String WILDCARD_RESOURCE_PATTERNS = "wildcardResourcePatterns"; + public static final String ADD_NOTNULL_ASSERTIONS = "addNotNullAssertions"; + public static final String ENTRY = "entry"; + public static final String NAME = "name"; + public static final String ENABLED = "enabled"; + public static final String MODULE = "module"; + public static final String TARGET_ATTRIBUTE = "target"; + + public JpsJavaCompilerConfigurationSerializer() { + super("compiler.xml", "CompilerConfiguration"); + } + + @Override + public void loadExtension(@NotNull JpsProject project, @NotNull Element componentTag) { + JpsJavaCompilerConfiguration configuration = JpsJavaExtensionService.getInstance().getOrCreateCompilerConfiguration(project); + Element addNotNullTag = componentTag.getChild(ADD_NOTNULL_ASSERTIONS); + if (addNotNullTag != null) { + configuration.setAddNotNullAssertions(Boolean.parseBoolean(addNotNullTag.getAttributeValue(ENABLED, "true"))); + } + + Element excludeFromCompileTag = componentTag.getChild(EXCLUDE_FROM_COMPILE); + if (excludeFromCompileTag != null) { + for (Element fileTag : JDOMUtil.getChildren(excludeFromCompileTag, "file")) { + configuration.getCompilerExcludes().addExcludedFile(fileTag.getAttributeValue("url")); + } + for (Element directoryTag : JDOMUtil.getChildren(excludeFromCompileTag, "directory")) { + boolean recursively = Boolean.parseBoolean(directoryTag.getAttributeValue("includeSubdirectories")); + configuration.getCompilerExcludes().addExcludedDirectory(directoryTag.getAttributeValue("url"), recursively); + } + } + + Element resourcePatternsTag = componentTag.getChild(WILDCARD_RESOURCE_PATTERNS); + for (Element entry : JDOMUtil.getChildren(resourcePatternsTag, ENTRY)) { + String pattern = entry.getAttributeValue(NAME); + if (!StringUtil.isEmpty(pattern)) { + configuration.addResourcePattern(pattern); + } + } + + Element annotationProcessingTag = componentTag.getChild(ANNOTATION_PROCESSING); + if (annotationProcessingTag != null) { + List profiles = JDOMUtil.getChildren(annotationProcessingTag, "profile"); + for (Element profileTag : profiles) { + boolean isDefault = Boolean.parseBoolean(profileTag.getAttributeValue("default")); + if (isDefault) { + AnnotationProcessorProfileSerializer.readExternal(configuration.getDefaultAnnotationProcessingConfiguration(), profileTag); + } + else { + AnnotationProcessorProfileSerializer.readExternal(configuration.addAnnotationProcessingProfile(), profileTag); + } + } + } + + Element targetLevelTag = componentTag.getChild(BYTECODE_TARGET_LEVEL); + if (targetLevelTag != null) { + configuration.setProjectByteCodeTargetLevel(targetLevelTag.getAttributeValue(TARGET_ATTRIBUTE)); + for (Element moduleTag : JDOMUtil.getChildren(targetLevelTag, MODULE)) { + String moduleName = moduleTag.getAttributeValue(NAME); + String level = moduleTag.getAttributeValue(TARGET_ATTRIBUTE); + if (moduleName != null && level != null) { + configuration.setModuleByteCodeTargetLevel(moduleName, level); + } + } + } + String compilerId = JDOMExternalizerUtil.readField(componentTag, "DEFAULT_COMPILER"); + if (compilerId != null) { + configuration.setJavaCompilerId(compilerId); + } + } + + @Override + public void saveExtension(@NotNull JpsProject project, @NotNull Element componentTag) { + } +} diff --git a/jps/model-serialization/src/org/jetbrains/jps/model/serialization/java/compiler/JpsJavaCompilerOptionsSerializer.java b/jps/model-serialization/src/org/jetbrains/jps/model/serialization/java/compiler/JpsJavaCompilerOptionsSerializer.java new file mode 100644 index 000000000000..4b845168c7dd --- /dev/null +++ b/jps/model-serialization/src/org/jetbrains/jps/model/serialization/java/compiler/JpsJavaCompilerOptionsSerializer.java @@ -0,0 +1,33 @@ +package org.jetbrains.jps.model.serialization.java.compiler; + +import com.intellij.util.xmlb.XmlSerializer; +import org.jdom.Element; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.jps.model.JpsProject; +import org.jetbrains.jps.model.java.JpsJavaExtensionService; +import org.jetbrains.jps.model.java.compiler.JpsJavaCompilerConfiguration; +import org.jetbrains.jps.model.java.compiler.JpsJavaCompilerOptions; +import org.jetbrains.jps.model.serialization.JpsProjectExtensionSerializer; + +/** + * @author nik + */ +public class JpsJavaCompilerOptionsSerializer extends JpsProjectExtensionSerializer { + private final String myCompilerId; + + public JpsJavaCompilerOptionsSerializer(String componentName, String compilerId) { + super("compiler.xml", componentName); + myCompilerId = compilerId; + } + + @Override + public void loadExtension(@NotNull JpsProject project, @NotNull Element componentTag) { + JpsJavaCompilerConfiguration configuration = JpsJavaExtensionService.getInstance().getOrCreateCompilerConfiguration(project); + JpsJavaCompilerOptions options = XmlSerializer.deserialize(componentTag, JpsJavaCompilerOptions.class); + configuration.setCompilerOptions(myCompilerId, options); + } + + @Override + public void saveExtension(@NotNull JpsProject project, @NotNull Element componentTag) { + } +} diff --git a/jps/model-serialization/src/org/jetbrains/jps/model/serialization/java/compiler/JpsJavaCompilerWorkspaceConfigurationSerializer.java b/jps/model-serialization/src/org/jetbrains/jps/model/serialization/java/compiler/JpsJavaCompilerWorkspaceConfigurationSerializer.java new file mode 100644 index 000000000000..d780d4b926cb --- /dev/null +++ b/jps/model-serialization/src/org/jetbrains/jps/model/serialization/java/compiler/JpsJavaCompilerWorkspaceConfigurationSerializer.java @@ -0,0 +1,33 @@ +package org.jetbrains.jps.model.serialization.java.compiler; + +import com.intellij.openapi.util.JDOMExternalizerUtil; +import org.jdom.Element; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.jps.model.JpsProject; +import org.jetbrains.jps.model.java.JpsJavaExtensionService; +import org.jetbrains.jps.model.java.compiler.JpsJavaCompilerConfiguration; +import org.jetbrains.jps.model.serialization.JpsProjectExtensionSerializer; + +/** + * @author nik + */ +public class JpsJavaCompilerWorkspaceConfigurationSerializer extends JpsProjectExtensionSerializer { + public JpsJavaCompilerWorkspaceConfigurationSerializer() { + super(WORKSPACE_FILE, "CompilerWorkspaceConfiguration"); + } + + @Override + public void loadExtension(@NotNull JpsProject project, @NotNull Element componentTag) { + JpsJavaCompilerConfiguration configuration = JpsJavaExtensionService.getInstance().getOrCreateCompilerConfiguration(project); + String assertNotNull = JDOMExternalizerUtil.readField(componentTag, "ASSERT_NOT_NULL"); + if (assertNotNull != null) { + configuration.setAddNotNullAssertions(Boolean.parseBoolean(assertNotNull)); + } + String clearOutputDirectory = JDOMExternalizerUtil.readField(componentTag, "CLEAR_OUTPUT_DIRECTORY"); + configuration.setClearOutputDirectoryOnRebuild(clearOutputDirectory == null || Boolean.parseBoolean(clearOutputDirectory)); + } + + @Override + public void saveExtension(@NotNull JpsProject project, @NotNull Element componentTag) { + } +} diff --git a/jps/jps-builders/testData/output/compilerConfiguration/compilerConfiguration.iml b/jps/model-serialization/testData/compilerConfiguration/compilerConfiguration.iml similarity index 100% rename from jps/jps-builders/testData/output/compilerConfiguration/compilerConfiguration.iml rename to jps/model-serialization/testData/compilerConfiguration/compilerConfiguration.iml diff --git a/jps/jps-builders/testData/output/compilerConfiguration/compilerConfiguration.ipr b/jps/model-serialization/testData/compilerConfiguration/compilerConfiguration.ipr similarity index 85% rename from jps/jps-builders/testData/output/compilerConfiguration/compilerConfiguration.ipr rename to jps/model-serialization/testData/compilerConfiguration/compilerConfiguration.ipr index 725f7f95afaf..fbff622fda98 100644 --- a/jps/jps-builders/testData/output/compilerConfiguration/compilerConfiguration.ipr +++ b/jps/model-serialization/testData/compilerConfiguration/compilerConfiguration.ipr @@ -33,6 +33,13 @@ + + diff --git a/jps/jps-builders/testData/output/compilerConfiguration/compilerConfiguration.iws b/jps/model-serialization/testData/compilerConfiguration/compilerConfiguration.iws similarity index 100% rename from jps/jps-builders/testData/output/compilerConfiguration/compilerConfiguration.iws rename to jps/model-serialization/testData/compilerConfiguration/compilerConfiguration.iws diff --git a/jps/jps-builders/testData/output/compilerConfigurationDir/.idea/compiler.xml b/jps/model-serialization/testData/compilerConfigurationDir/.idea/compiler.xml similarity index 79% rename from jps/jps-builders/testData/output/compilerConfigurationDir/.idea/compiler.xml rename to jps/model-serialization/testData/compilerConfigurationDir/.idea/compiler.xml index e9222f77bc4d..9f7f048c049f 100644 --- a/jps/jps-builders/testData/output/compilerConfigurationDir/.idea/compiler.xml +++ b/jps/model-serialization/testData/compilerConfigurationDir/.idea/compiler.xml @@ -32,5 +32,12 @@ + + diff --git a/jps/jps-builders/testData/output/compilerConfigurationDir/.idea/encodings.xml b/jps/model-serialization/testData/compilerConfigurationDir/.idea/encodings.xml similarity index 100% rename from jps/jps-builders/testData/output/compilerConfigurationDir/.idea/encodings.xml rename to jps/model-serialization/testData/compilerConfigurationDir/.idea/encodings.xml diff --git a/jps/jps-builders/testData/output/compilerConfigurationDir/.idea/misc.xml b/jps/model-serialization/testData/compilerConfigurationDir/.idea/misc.xml similarity index 100% rename from jps/jps-builders/testData/output/compilerConfigurationDir/.idea/misc.xml rename to jps/model-serialization/testData/compilerConfigurationDir/.idea/misc.xml diff --git a/jps/jps-builders/testData/output/compilerConfigurationDir/.idea/modules.xml b/jps/model-serialization/testData/compilerConfigurationDir/.idea/modules.xml similarity index 100% rename from jps/jps-builders/testData/output/compilerConfigurationDir/.idea/modules.xml rename to jps/model-serialization/testData/compilerConfigurationDir/.idea/modules.xml diff --git a/jps/jps-builders/testData/output/compilerConfigurationDir/.idea/workspace.xml b/jps/model-serialization/testData/compilerConfigurationDir/.idea/workspace.xml similarity index 100% rename from jps/jps-builders/testData/output/compilerConfigurationDir/.idea/workspace.xml rename to jps/model-serialization/testData/compilerConfigurationDir/.idea/workspace.xml diff --git a/jps/jps-builders/testData/output/compilerConfigurationDir/compilerConfiguration.iml b/jps/model-serialization/testData/compilerConfigurationDir/compilerConfiguration.iml similarity index 100% rename from jps/jps-builders/testData/output/compilerConfigurationDir/compilerConfiguration.iml rename to jps/model-serialization/testData/compilerConfigurationDir/compilerConfiguration.iml diff --git a/jps/model-serialization/testSrc/org/jetbrains/jps/model/serialization/JpsCompilerConfigurationTest.java b/jps/model-serialization/testSrc/org/jetbrains/jps/model/serialization/JpsCompilerConfigurationTest.java new file mode 100644 index 000000000000..9d554df40446 --- /dev/null +++ b/jps/model-serialization/testSrc/org/jetbrains/jps/model/serialization/JpsCompilerConfigurationTest.java @@ -0,0 +1,52 @@ +package org.jetbrains.jps.model.serialization; + +import com.intellij.openapi.util.io.FileUtil; +import org.jetbrains.jps.JpsPathUtil; +import org.jetbrains.jps.model.java.JpsJavaExtensionService; +import org.jetbrains.jps.model.java.compiler.JpsCompilerExcludes; +import org.jetbrains.jps.model.java.compiler.JpsJavaCompilerConfiguration; +import org.jetbrains.jps.model.java.compiler.JpsJavaCompilerOptions; +import org.jetbrains.jps.model.java.compiler.ProcessorConfigProfile; + +public class JpsCompilerConfigurationTest extends JpsSerializationTestCase { + public void testLoadFromIpr() { + doTest("jps/model-serialization/testData/compilerConfiguration/compilerConfiguration.ipr"); + } + + public void testLoadFromDirectory() { + doTest("jps/model-serialization/testData/compilerConfigurationDir"); + } + + private void doTest(final String path) { + loadProject(path); + JpsJavaCompilerConfiguration configuration = JpsJavaExtensionService.getInstance().getCompilerConfiguration(myProject); + assertNotNull(configuration); + assertFalse(configuration.isClearOutputDirectoryOnRebuild()); + assertFalse(configuration.isAddNotNullAssertions()); + ProcessorConfigProfile defaultProfile = configuration.getDefaultAnnotationProcessingConfiguration(); + assertTrue(defaultProfile.isEnabled()); + assertFalse(defaultProfile.isObtainProcessorsFromClasspath()); + assertEquals(FileUtil.toSystemDependentName(JpsPathUtil.urlToPath(getUrl("src"))), defaultProfile.getProcessorPath()); + assertEquals("b", defaultProfile.getProcessorOptions().get("a")); + assertEquals("d", defaultProfile.getProcessorOptions().get("c")); + assertEquals("gen", defaultProfile.getGeneratedSourcesDirectoryName()); + JpsCompilerExcludes excludes = configuration.getCompilerExcludes(); + assertFalse(isExcluded(excludes, "src/nonrec/x/Y.java")); + assertTrue(isExcluded(excludes, "src/nonrec/Y.java")); + assertTrue(isExcluded(excludes, "src/rec/x/Y.java")); + assertTrue(isExcluded(excludes, "src/rec/Y.java")); + assertTrue(isExcluded(excludes, "src/A.java")); + assertFalse(isExcluded(excludes, "src/B.java")); + + JpsJavaCompilerOptions options = configuration.getCurrentCompilerOptions(); + assertNotNull(options); + assertEquals(512, options.MAXIMUM_HEAP_SIZE); + assertFalse(options.DEBUGGING_INFO); + assertTrue(options.GENERATE_NO_WARNINGS); + assertEquals("-Xlint", options.ADDITIONAL_OPTIONS_STRING); + } + + private boolean isExcluded(JpsCompilerExcludes excludes, final String path) { + return excludes.isExcluded(JpsPathUtil.urlToFile(getUrl(path))); + } +} diff --git a/jps/model/src/org/jetbrains/jps/CompilerConfiguration.groovy b/jps/model/src/org/jetbrains/jps/CompilerConfiguration.groovy deleted file mode 100644 index 142e7b2ca136..000000000000 --- a/jps/model/src/org/jetbrains/jps/CompilerConfiguration.groovy +++ /dev/null @@ -1,35 +0,0 @@ -package org.jetbrains.jps - -/** - * @author nik - */ -class CompilerConfiguration { - List resourcePatterns = [] - List resourceIncludePatterns = "properties,xml,gif,png,jpeg,jpg,jtml,dtd,tld,ftl".split(",").collect {"**/?*.$it"} - List resourceExcludePatterns = [] - Map options = [:] - Map javacOptions = [:] - Map eclipseOptions = [:] - boolean clearOutputDirectoryOnRebuild = true - boolean addNotNullAssertions = true - AnnotationProcessingProfile defaultAnnotationProcessingProfile = new AnnotationProcessingProfile() - Collection moduleAnnotationProcessingProfiles = [] - BytecodeTargetConfiguration bytecodeTarget = new BytecodeTargetConfiguration() - CompilerExcludes excludes = new CompilerExcludes() -} - -class AnnotationProcessingProfile { - String name = "" - boolean enabled = false - boolean obtainProcessorsFromClasspath = true - String processorsPath - List processors = [] - Map processorsOptions = [:] - String generatedSourcesDirName = "" - List processModule = [] -} - -class BytecodeTargetConfiguration { - String projectBytecodeTarget - Map modulesBytecodeTarget = [:] -} \ No newline at end of file diff --git a/jps/model/src/org/jetbrains/jps/MacroExpander.java b/jps/model/src/org/jetbrains/jps/MacroExpander.java deleted file mode 100644 index d1fca640ece7..000000000000 --- a/jps/model/src/org/jetbrains/jps/MacroExpander.java +++ /dev/null @@ -1,8 +0,0 @@ -package org.jetbrains.jps; - -/** - * @author nik - */ -public interface MacroExpander { - String expandMacros(String path); -} diff --git a/jps/model/src/org/jetbrains/jps/Project.groovy b/jps/model/src/org/jetbrains/jps/Project.groovy deleted file mode 100644 index b66f4d96df46..000000000000 --- a/jps/model/src/org/jetbrains/jps/Project.groovy +++ /dev/null @@ -1,14 +0,0 @@ -package org.jetbrains.jps -/** - * @author max - */ -class Project { - final CompilerConfiguration compilerConfiguration = new CompilerConfiguration() - - def Project() { - } - - def String toString() { - return "Project" - } -} diff --git a/jps/model/src/org/jetbrains/jps/idea/CannotLoadProjectException.java b/jps/model/src/org/jetbrains/jps/idea/CannotLoadProjectException.java deleted file mode 100644 index 0d11ab1f77a0..000000000000 --- a/jps/model/src/org/jetbrains/jps/idea/CannotLoadProjectException.java +++ /dev/null @@ -1,10 +0,0 @@ -package org.jetbrains.jps.idea; - -/** - * @author nik - */ -public class CannotLoadProjectException extends RuntimeException { - public CannotLoadProjectException(String message) { - super(message); - } -} diff --git a/jps/model/src/org/jetbrains/jps/idea/IdeaProjectLoader.groovy b/jps/model/src/org/jetbrains/jps/idea/IdeaProjectLoader.groovy deleted file mode 100644 index 7a7c252ab8ed..000000000000 --- a/jps/model/src/org/jetbrains/jps/idea/IdeaProjectLoader.groovy +++ /dev/null @@ -1,243 +0,0 @@ -package org.jetbrains.jps.idea -import com.intellij.openapi.util.io.FileUtil -import org.jetbrains.jps.AnnotationProcessingProfile -import org.jetbrains.jps.CompilerConfiguration -import org.jetbrains.jps.JpsPathUtil -import org.jetbrains.jps.Project -/** - * @author max - */ -public class IdeaProjectLoader { - Project project - private Map pathVariables - private ProjectMacroExpander projectMacroExpander - private ProjectLoadingErrorReporter errorReporter - private final XmlParser xmlParser = new XmlParser(false, false) - - public static String guessHome(Script script) { - File home = new File(script["gant.file"].substring("file:".length())) - - while (home != null) { - if (home.isDirectory()) { - if (new File(home, ".idea").exists()) return home.getCanonicalPath() - } - - home = home.getParentFile() - } - - return null - } - - public static ProjectMacroExpander loadFromPath(Project project, String path, Map pathVariables) { - return loadFromPath(project, path, pathVariables, "") - } - - public static ProjectMacroExpander loadFromPath(Project project, String path, Map pathVariables, String script) { - return loadFromPath(project, path, pathVariables, script, new SystemOutErrorReporter(true)) - } - - public static ProjectMacroExpander loadFromPath(Project project, String path, Map pathVariables, String script, ProjectLoadingErrorReporter errorReporter) { - def loader = new IdeaProjectLoader(project, pathVariables, errorReporter) - - loader.doLoadFromPath(path); - - if (script != null) { - if (script.startsWith ("@")) { - new GroovyShell(new Binding(project:project)).evaluate(new File (script.substring(1))) - }; - else { - new GroovyShell(new Binding(project:project)).evaluate(script) - } - } - - return loader.projectMacroExpander; - } - - - private def IdeaProjectLoader(Project project, Map pathVariables, ProjectLoadingErrorReporter errorReporter) { - this.project = project; - this.pathVariables = pathVariables - this.errorReporter = errorReporter - } - - private def doLoadFromPath(String path) { - def fileAtPath = new File(path) - - if (fileAtPath.isFile() && path.endsWith(".ipr")) { - loadFromIpr(path) - return - } - else { - File directoryBased = null; - if (".idea".equals(fileAtPath.getName())) { - directoryBased = fileAtPath; - } - else { - def child = new File(fileAtPath, ".idea") - if (child.exists()) { - directoryBased = child - } - } - - if (directoryBased != null) { - loadFromDirectoryBased(directoryBased.getCanonicalFile()) - return - } - } - - errorReporter.error("Cannot find IntelliJ IDEA project files at $path") - } - - def loadFromIpr(String path) { - def iprFile = new File(path).getCanonicalFile() - projectMacroExpander = new ProjectMacroExpander(pathVariables, iprFile.parentFile.absolutePath) - - def root = xmlParser.parse(iprFile) - loadCompilerConfiguration(root) - loadWorkspaceConfiguration(new File(iprFile.parentFile, iprFile.name[0..-4]+"iws")) - } - - def loadFromDirectoryBased(File dir) { - projectMacroExpander = new ProjectMacroExpander(pathVariables, dir.parentFile.absolutePath) - - def compilerXml = new File(dir, "compiler.xml") - if (compilerXml.exists()) { - loadCompilerConfiguration(xmlParser.parse(compilerXml)) - } - loadWorkspaceConfiguration(new File(dir, "workspace.xml")) - } - - private def loadWorkspaceConfiguration(File workspaceFile) { - if (!workspaceFile.exists()) return - - def root = xmlParser.parse(workspaceFile) - def options = loadOptions(getComponent(root, "CompilerWorkspaceConfiguration")) - // compatibility: in older projects this setting was stored in workspace - if (project.compilerConfiguration.addNotNullAssertions == true) { // if is the same as default value - project.compilerConfiguration.addNotNullAssertions = parseBoolean(options["ASSERT_NOT_NULL"], true); - } - project.compilerConfiguration.clearOutputDirectoryOnRebuild = parseBoolean(options["CLEAR_OUTPUT_DIRECTORY"], true); - } - - private def loadCompilerConfiguration(Node root) { - def rawPatterns = [] - def includePatterns = [] - def excludePatterns = [] - def componentTag = getComponent(root, "CompilerConfiguration") - - componentTag?.wildcardResourcePatterns?.getAt(0)?.entry?.each {Node entryTag -> - String pattern = entryTag."@name" - rawPatterns << pattern; - if (pattern.startsWith("!")) { - excludePatterns << convertPattern(pattern.substring(1)) - } - else { - includePatterns << convertPattern(pattern) - } - } - CompilerConfiguration configuration = project.compilerConfiguration - if (!includePatterns.isEmpty() || !excludePatterns.isEmpty()) { - configuration.resourceIncludePatterns = includePatterns - configuration.resourceExcludePatterns = excludePatterns - } - if (!rawPatterns.isEmpty()) { - configuration.resourcePatterns = rawPatterns; - } - - def excludesTag = componentTag?.excludeFromCompile?.getAt(0) - if (excludesTag != null) { - excludesTag.file?.each { - configuration.excludes.addExcludedFile(getFileByUrl(it."@url")) - } - excludesTag.directory?.each { - configuration.excludes.addExcludedDirectory(getFileByUrl(it."@url"), Boolean.parseBoolean(it."@includeSubdirectories")) - } - } - configuration.options.putAll(loadOptions(componentTag)); - configuration.javacOptions.putAll(loadOptions(getComponent(root, "JavacSettings"))) - configuration.eclipseOptions.putAll(loadOptions(getComponent(root, "EclipseCompilerSettings"))) - - def annotationProcessingTag = componentTag?.annotationProcessing - if (annotationProcessingTag != null) { - configuration.moduleAnnotationProcessingProfiles = [] - annotationProcessingTag?.profile?.each {profileTag -> - AnnotationProcessingProfile profile - if (parseBoolean(profileTag."@default", false)) { - profile = configuration.defaultAnnotationProcessingProfile - } - else { - profile = new AnnotationProcessingProfile() - configuration.moduleAnnotationProcessingProfiles << profile - } - profile.name = profileTag."@name"; - profile.enabled = parseBoolean(profileTag."@enabled", false) - profile.generatedSourcesDirName = profileTag.sourceOutputDir?.getAt(0)?."@name" - profileTag.processor?.each { - profile.processors << it."@name" - } - profileTag.option?.each { - profile.processorsOptions[it."@name"] = it."@value" ?: "" - } - def pathTag = profileTag.processorPath?.getAt(0) - profile.obtainProcessorsFromClasspath = parseBoolean(pathTag?."@useClasspath", true) - List processorPaths = [] - pathTag?.each { - processorPaths << projectMacroExpander.expandMacros(it."@name") - } - profile.processorsPath = processorPaths.join(File.pathSeparator) - - profileTag.module?.each { - profile.processModule << it."@name" - } - } - } - - def targetLevels = componentTag?.bytecodeTargetLevel - if (targetLevels != null && !targetLevels.isEmpty()) { - def targetLevelTag = targetLevels.first() - configuration.bytecodeTarget.projectBytecodeTarget = targetLevelTag."@target" ?: null; - targetLevelTag.module?.each { - configuration.bytecodeTarget.modulesBytecodeTarget[it."@name"] = it."@target" ?: "" - } - } - - def addNotNullTag = componentTag?.addNotNullAssertions - if (addNotNullTag != null) { - project.compilerConfiguration.addNotNullAssertions = parseBoolean(addNotNullTag."@enabled", true); - } - } - - private File getFileByUrl(final String url) { - return new File(FileUtil.toCanonicalPath(projectMacroExpander.expandMacros(JpsPathUtil.urlToPath(url)))) - } - - private static boolean parseBoolean(Object value, boolean defaultValue) { - if (value instanceof NodeList) { - if (value.isEmpty()) return defaultValue - value = value[0] - } - return value != null ? Boolean.parseBoolean((String)value) : defaultValue - } - - private Map loadOptions(Node optionsTag) { - def result = new HashMap() - optionsTag?.option?.each {Node optionTag -> - result[optionTag."@name"] = optionTag."@value"; - } - return result - } - - private String convertPattern(String pattern) { - if (pattern.indexOf('/') == -1) { - return "**/" + pattern - } - if (pattern.startsWith("/")) { - return pattern.substring(1) - } - return pattern - } - - Node getComponent(Node root, String name) { - return root.component.find {it."@name" == name} - } -} diff --git a/jps/model/src/org/jetbrains/jps/idea/ProjectLoadingErrorReporter.java b/jps/model/src/org/jetbrains/jps/idea/ProjectLoadingErrorReporter.java deleted file mode 100644 index 9058d3226b84..000000000000 --- a/jps/model/src/org/jetbrains/jps/idea/ProjectLoadingErrorReporter.java +++ /dev/null @@ -1,12 +0,0 @@ -package org.jetbrains.jps.idea; - -/** - * @author nik - */ -public interface ProjectLoadingErrorReporter { - void error(String message); - - void warning(String message); - - void info(String message); -} diff --git a/jps/model/src/org/jetbrains/jps/idea/ProjectMacroExpander.groovy b/jps/model/src/org/jetbrains/jps/idea/ProjectMacroExpander.groovy deleted file mode 100644 index ca9cc4330093..000000000000 --- a/jps/model/src/org/jetbrains/jps/idea/ProjectMacroExpander.groovy +++ /dev/null @@ -1,27 +0,0 @@ -package org.jetbrains.jps.idea - -import com.intellij.openapi.util.io.FileUtil -import org.jetbrains.jps.MacroExpander - -/** - * @author nik - */ -public class ProjectMacroExpander implements MacroExpander { - private Map pathVariables - private String projectBasePath - - ProjectMacroExpander(Map pathVariables, String projectBasePath) { - this.pathVariables = pathVariables - this.projectBasePath = FileUtil.toSystemIndependentName(projectBasePath) - } - - @Override - String expandMacros(String path) { - if (path == null) return path - path = path.replace("\$PROJECT_DIR\$", projectBasePath) - pathVariables.each { name, value -> - path = path.replace("\$${name}\$", value) - } - return path - } -} diff --git a/jps/model/src/org/jetbrains/jps/idea/SystemOutErrorReporter.java b/jps/model/src/org/jetbrains/jps/idea/SystemOutErrorReporter.java deleted file mode 100644 index df73294214bd..000000000000 --- a/jps/model/src/org/jetbrains/jps/idea/SystemOutErrorReporter.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.jetbrains.jps.idea; - -public class SystemOutErrorReporter implements ProjectLoadingErrorReporter { - private boolean myFailOnError; - - public SystemOutErrorReporter(boolean failOnError) { - myFailOnError = failOnError; - } - - public void error(String message) { - if (myFailOnError) { - throw new CannotLoadProjectException(message); - } - System.out.println("error: " + message); - } - - public void warning(String message) { - System.out.println("warn: " + message); - } - - public void info(String message) { - System.out.println("info: " + message); - } -} diff --git a/jps/standalone-builder/src/org/jetbrains/jps/gant/JpsGantProjectBuilder.java b/jps/standalone-builder/src/org/jetbrains/jps/gant/JpsGantProjectBuilder.java index a497822a6e92..6c19c1d62d50 100644 --- a/jps/standalone-builder/src/org/jetbrains/jps/gant/JpsGantProjectBuilder.java +++ b/jps/standalone-builder/src/org/jetbrains/jps/gant/JpsGantProjectBuilder.java @@ -28,27 +28,20 @@ import java.util.*; public class JpsGantProjectBuilder { private final Project myProject; private final JpsModel myModel; - private final org.jetbrains.jps.Project myOldProject; private boolean myCompressJars; private File myDataStorageRoot; private JpsModelLoader myModelLoader; private boolean myDryRun; private BuildInfoPrinter myBuildInfoPrinter = new DefaultBuildInfoPrinter(); - public JpsGantProjectBuilder(Project project, JpsModel model, org.jetbrains.jps.Project oldProject) { + public JpsGantProjectBuilder(Project project, JpsModel model) { myProject = project; myModel = model; - myOldProject = oldProject; myModelLoader = new JpsModelLoader() { @Override public JpsModel loadModel() { return myModel; } - - @Override - public org.jetbrains.jps.Project loadOldProject() { - return myOldProject; - } }; } diff --git a/jps/standalone-builder/src/org/jetbrains/jps/gant/JpsGantTool.groovy b/jps/standalone-builder/src/org/jetbrains/jps/gant/JpsGantTool.groovy index 420fe178569f..be46f77700a7 100644 --- a/jps/standalone-builder/src/org/jetbrains/jps/gant/JpsGantTool.groovy +++ b/jps/standalone-builder/src/org/jetbrains/jps/gant/JpsGantTool.groovy @@ -1,7 +1,5 @@ package org.jetbrains.jps.gant import org.codehaus.gant.GantBinding -import org.jetbrains.jps.Project -import org.jetbrains.jps.idea.IdeaProjectLoader import org.jetbrains.jps.incremental.Utils import org.jetbrains.jps.model.JpsElementFactory import org.jetbrains.jps.model.JpsGlobal @@ -17,14 +15,12 @@ final class JpsGantTool { JpsGantTool(GantBinding binding) { JpsModel model = JpsElementFactory.getInstance().createModel(); JpsProject project = model.project - def oldProject = new Project() binding.setVariable("project", project) - binding.setVariable("oldProject", oldProject) binding.setVariable("global", model.global) - def builder = new JpsGantProjectBuilder(binding.ant.project, model, oldProject) + def builder = new JpsGantProjectBuilder(binding.ant.project, model) binding.setVariable("projectBuilder", builder) binding.setVariable("loadProjectFromPath", {String path -> - loadProject(path, model, oldProject, builder); + loadProject(path, model, builder); }) binding.setVariable("jdk", {Object[] args -> @@ -85,8 +81,7 @@ final class JpsGantTool { binding.ant.taskdef(name: "layout", classname: "jetbrains.antlayout.tasks.LayoutTask") } - private void loadProject(String path, JpsModel model, Project oldProject, JpsGantProjectBuilder builder) { - IdeaProjectLoader.loadFromPath(oldProject, path, [:]) + private void loadProject(String path, JpsModel model, JpsGantProjectBuilder builder) { JpsProjectLoader.loadProject(model.project, [:], path) builder.exportModuleOutputProperties(); if (builder.getDataStorageRoot() == null) { diff --git a/jps/standalone-builder/src/org/jetbrains/jps/idea/IdeaProjectLoader.groovy b/jps/standalone-builder/src/org/jetbrains/jps/idea/IdeaProjectLoader.groovy new file mode 100644 index 000000000000..21a7f0262b6a --- /dev/null +++ b/jps/standalone-builder/src/org/jetbrains/jps/idea/IdeaProjectLoader.groovy @@ -0,0 +1,19 @@ +package org.jetbrains.jps.idea +/** + * @author max + */ +public class IdeaProjectLoader { + public static String guessHome(Script script) { + File home = new File(script["gant.file"].substring("file:".length())) + + while (home != null) { + if (home.isDirectory()) { + if (new File(home, ".idea").exists()) return home.getCanonicalPath() + } + + home = home.getParentFile() + } + + return null + } +} diff --git a/native/fsNotifier/linux/main.c b/native/fsNotifier/linux/main.c index 8a2ea11b551c..54e47aede8f4 100644 --- a/native/fsNotifier/linux/main.c +++ b/native/fsNotifier/linux/main.c @@ -365,7 +365,7 @@ static bool register_roots(array* new_roots, array* unwatchable, array* mounts) static bool is_watchable(const char* dev, const char* mnt, const char* fs) { // don't watch special and network filesystems return !(strncmp(mnt, "/dev", 4) == 0 || strncmp(mnt, "/proc", 5) == 0 || strncmp(mnt, "/sys", 4) == 0 || - strcmp(fs, "fuse.gvfs-fuse-daemon") == 0 || strcmp(fs, "cifs") == 0 || strcmp(fs, "nfs") == 0); + strncmp(fs, "fuse.", 5) == 0 || strcmp(fs, "cifs") == 0 || strcmp(fs, "nfs") == 0); } #define MTAB_DELIMS " \t" diff --git a/platform/core-api/src/com/intellij/openapi/application/ReadAction.java b/platform/core-api/src/com/intellij/openapi/application/ReadAction.java index 9c1b26affcbe..9904eb79c814 100644 --- a/platform/core-api/src/com/intellij/openapi/application/ReadAction.java +++ b/platform/core-api/src/com/intellij/openapi/application/ReadAction.java @@ -15,30 +15,18 @@ */ package com.intellij.openapi.application; -import java.awt.*; +import com.intellij.openapi.util.Computable; public abstract class ReadAction extends BaseActionRunnable { - + @Override public RunResult execute() { final RunResult result = new RunResult(this); - - if (canReadNow()) { - result.run(); - return result; - } - - if (EventQueue.isDispatchThread()) { - return result.run(); - } else { - AccessToken r = start(); - try { - result.run(); - } finally { - r.finish(); + return ApplicationManager.getApplication().runReadAction(new Computable>() { + @Override + public RunResult compute() { + return result.run(); } - } - - return result; + }); } public static AccessToken start() { diff --git a/platform/core-api/src/com/intellij/openapi/editor/markup/TextAttributes.java b/platform/core-api/src/com/intellij/openapi/editor/markup/TextAttributes.java index a4c91b9525fe..461bcf70473d 100644 --- a/platform/core-api/src/com/intellij/openapi/editor/markup/TextAttributes.java +++ b/platform/core-api/src/com/intellij/openapi/editor/markup/TextAttributes.java @@ -75,10 +75,12 @@ public class TextAttributes implements JDOMExternalizable, Cloneable { private static final int EFFECT_BOLD_LINE = 4; private static final int EFFECT_BOLD_DOTTED_LINE = 5; + @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } + @Override public void readExternal(Element element) throws InvalidDataException { DefaultJDOMExternalizer.readExternal(this, element); if (FONT_TYPE < 0 || FONT_TYPE > 3) { @@ -87,6 +89,7 @@ public class TextAttributes implements JDOMExternalizable, Cloneable { } } + @Override public void writeExternal(Element element) throws WriteExternalException { DefaultJDOMExternalizer.writeExternal(this, element); } @@ -138,11 +141,20 @@ public class TextAttributes implements JDOMExternalizable, Cloneable { private AttributesFlyweight myAttrs; public TextAttributes() { - myAttrs = AttributesFlyweight.create(null, null, Font.PLAIN, null, EffectType.BOXED, null); + this(null, null, null, EffectType.BOXED, Font.PLAIN); } public TextAttributes(Color foregroundColor, Color backgroundColor, Color effectColor, EffectType effectType, @JdkConstants.FontStyle int fontType) { - myAttrs = AttributesFlyweight.create(foregroundColor, backgroundColor, fontType, effectColor, effectType, null); + setAttributes(foregroundColor, backgroundColor, effectColor, null, effectType, fontType); + } + + public void setAttributes(Color foregroundColor, + Color backgroundColor, + Color effectColor, + Color errorStripeColor, + EffectType effectType, + @JdkConstants.FontStyle int fontType) { + myAttrs = AttributesFlyweight.create(foregroundColor, backgroundColor, fontType, effectColor, effectType, errorStripeColor); } public boolean isEmpty(){ @@ -212,6 +224,7 @@ public class TextAttributes implements JDOMExternalizable, Cloneable { myAttrs = myAttrs.withFontType(type); } + @Override public TextAttributes clone() { TextAttributes cloned = new TextAttributes(); cloned.myAttrs = myAttrs; @@ -230,6 +243,7 @@ public class TextAttributes implements JDOMExternalizable, Cloneable { return myAttrs.hashCode(); } + @Override public void readExternal(Element element) throws InvalidDataException { Externalizable ext = new Externalizable(); ext.readExternal(element); @@ -241,6 +255,7 @@ public class TextAttributes implements JDOMExternalizable, Cloneable { ext.ERROR_STRIPE_COLOR); } + @Override public void writeExternal(Element element) throws WriteExternalException { Externalizable ext = new Externalizable(); diff --git a/platform/core-impl/src/com/intellij/openapi/editor/ex/DocumentEx.java b/platform/core-impl/src/com/intellij/openapi/editor/ex/DocumentEx.java index a90f7f240690..8d4115a26f19 100644 --- a/platform/core-impl/src/com/intellij/openapi/editor/ex/DocumentEx.java +++ b/platform/core-impl/src/com/intellij/openapi/editor/ex/DocumentEx.java @@ -37,18 +37,17 @@ public interface DocumentEx extends Document { void replaceText(@NotNull CharSequence chars, long newModificationStamp); /** - * Moves text from the [src start; src end) range to the [dstStart; dstEnd) range. + * Moves text from the [src start; src end) range to the dstOffset offset. *

* The benefit to use this method over usual {@link #deleteString(int, int)} and {@link #replaceString(int, int, CharSequence)} * is that {@link #createRangeMarker(int, int, boolean) range markers} from the [srcStart; srcEnd) range have * a chance to be preserved. - * + * * @param srcStart start offset of the text to move (inclusive) * @param srcEnd end offset of the text to move (exclusive) - * @param dstStart start offset of the range which text should be replaced (inclusive) - * @param dstEnd end offset of the range which text should be replaced (exclusive) + * @param dstOffset the offset to insert the text to. Must be outside of the (srcStart, srcEnd) range. */ - void moveText(int srcStart, int srcEnd, int dstStart, int dstEnd); + void moveText(int srcStart, int srcEnd, int dstOffset); int getListenersCount(); diff --git a/platform/core-impl/src/com/intellij/openapi/editor/impl/DocumentImpl.java b/platform/core-impl/src/com/intellij/openapi/editor/impl/DocumentImpl.java index c206819b06ba..09425a675133 100644 --- a/platform/core-impl/src/com/intellij/openapi/editor/impl/DocumentImpl.java +++ b/platform/core-impl/src/com/intellij/openapi/editor/impl/DocumentImpl.java @@ -368,49 +368,25 @@ public class DocumentImpl extends UserDataHolderBase implements DocumentEx { } @Override - public void moveText(int srcStart, int srcEnd, int dstStart, int dstEnd) { + public void moveText(int srcStart, int srcEnd, int dstOffset) { assertBounds(srcStart, srcEnd); - assertBounds(dstStart, dstEnd); - - if (srcStart == dstStart && srcEnd == dstEnd) { - return; - } + ProperTextRange srcRange = new ProperTextRange(srcStart, srcEnd); + if (dstOffset == srcEnd) return; + assert !srcRange.containsOffset(dstOffset); CharSequence replacement = getCharsSequence().subSequence(srcStart, srcEnd); - - // Handle a situation when target ranges don't cross. - if (srcEnd <= dstStart || srcStart >= dstEnd) { - replaceString(dstStart, dstEnd, replacement); - int shift = 0; - if (dstStart < srcStart) { - shift = (dstEnd - dstStart) - (srcEnd - srcStart); - } - deleteString(srcStart + shift, srcEnd + shift); - return; - } - - // _____|__________|__________|________|_____ - // DstStart SrcStart DstEnd SrcEnd - if (dstStart <= srcStart && dstEnd <= srcEnd) { - if (dstEnd < srcEnd) { - deleteString(dstEnd, srcEnd); - } - replaceString(dstStart, dstEnd, replacement); - } - // _____|__________|__________|________|_____ - // DstStart SrcStart SrcEnd DstEnd - // OR - // _____|__________|__________|________|_____ - // SrcStart DstStart DstEnd SrcEnd - else if ((dstStart <= srcStart && dstEnd > srcEnd) || (dstStart > srcStart && dstEnd <= srcEnd)) { - replaceString(dstStart, dstEnd, replacement); - } - // _____|__________|__________|________|_____ - // SrcStart DstStart SrcEnd DstEnd - else { - replaceString(dstStart, dstEnd, replacement); - deleteString(srcStart, dstStart); + + insertString(dstOffset, replacement); + int shift = 0; + if (dstOffset < srcStart) { + shift = srcEnd - srcStart; } + retargetRangeMarkers(srcStart+shift, srcEnd+shift, dstOffset); + deleteString(srcStart + shift, srcEnd + shift); + } + + private void retargetRangeMarkers(int start, int end, int newBase) { + myRangeMarkers.retarget(start, end, newBase); } @Override diff --git a/platform/core-impl/src/com/intellij/openapi/editor/impl/RangeMarkerImpl.java b/platform/core-impl/src/com/intellij/openapi/editor/impl/RangeMarkerImpl.java index 7d1343e5ad70..dbb80ac3d77d 100644 --- a/platform/core-impl/src/com/intellij/openapi/editor/impl/RangeMarkerImpl.java +++ b/platform/core-impl/src/com/intellij/openapi/editor/impl/RangeMarkerImpl.java @@ -89,7 +89,7 @@ public class RangeMarkerImpl extends UserDataHolderBase implements RangeMarkerEx return intervalEnd() + (node == null ? 0 : node.computeDeltaUpToRoot()); } - public void invalidate(final DocumentEvent e) { + public void invalidate(@NotNull final Object reason) { setValid(false); RangeMarkerTree.RMNode node = myNode; @@ -97,7 +97,7 @@ public class RangeMarkerImpl extends UserDataHolderBase implements RangeMarkerEx node.processAliveKeys(new Processor() { @Override public boolean process(RangeMarkerEx markerEx) { - myNode.getTree().reportInvalidation(markerEx, e); + myNode.getTree().reportInvalidation(markerEx, reason); return true; } }); diff --git a/platform/core-impl/src/com/intellij/openapi/editor/impl/RangeMarkerTree.java b/platform/core-impl/src/com/intellij/openapi/editor/impl/RangeMarkerTree.java index 6fc5bb1d8830..cfe4a3d12d1f 100644 --- a/platform/core-impl/src/com/intellij/openapi/editor/impl/RangeMarkerTree.java +++ b/platform/core-impl/src/com/intellij/openapi/editor/impl/RangeMarkerTree.java @@ -184,7 +184,7 @@ public class RangeMarkerTree extends IntervalTreeImpl extends IntervalTreeImpl> affected = new ArrayList>(); + collectNodesToRetarget(getRoot(), start, end, affected); + if (affected.isEmpty()) return; + + int shift = newBase - start; + for (IntervalNode node : affected) { + removeNode(node); + node.setLeft(null); + node.setRight(null); + node.setParent(null); + node.changeDelta(shift); + pushDelta(node); + findOrInsert(node); + } + } + finally { + l.writeLock().unlock(); + } + } + + private void collectNodesToRetarget(IntervalNode root, + int start, int end, + @NotNull List> affected) { + if (root == null) return; + pushDelta(root); + + int maxEnd = root.maxEnd; + assert root.isValid(); + + if (start > maxEnd) { + // no need to bother + return; + } + collectNodesToRetarget(root.getLeft(), start, end, affected); + if (start <= root.intervalStart() && root.intervalEnd() <= end) { + affected.add(root); + } + if (end < root.intervalStart()) { + return; + } + collectNodesToRetarget(root.getRight(), start, end, affected); + } } diff --git a/platform/lang-api/src/com/intellij/codeInsight/editorActions/moveUpDown/StatementUpDownMover.java b/platform/lang-api/src/com/intellij/codeInsight/editorActions/moveUpDown/StatementUpDownMover.java index d7a359e6e97d..8de2e77fb89f 100644 --- a/platform/lang-api/src/com/intellij/codeInsight/editorActions/moveUpDown/StatementUpDownMover.java +++ b/platform/lang-api/src/com/intellij/codeInsight/editorActions/moveUpDown/StatementUpDownMover.java @@ -34,10 +34,12 @@ public abstract class StatementUpDownMover { public static final ExtensionPointName STATEMENT_UP_DOWN_MOVER_EP = ExtensionPointName.create("com.intellij.statementUpDownMover"); public static class MoveInfo { + /** Source line range */ @NotNull public LineRange toMove; - @Nullable // if move is illegal + /** Target line range, or null if move not available */ + @Nullable public LineRange toMove2; public RangeMarker range1; diff --git a/platform/lang-api/src/com/intellij/find/FindManager.java b/platform/lang-api/src/com/intellij/find/FindManager.java index 7d07fd0e9efc..48c04f692a5c 100644 --- a/platform/lang-api/src/com/intellij/find/FindManager.java +++ b/platform/lang-api/src/com/intellij/find/FindManager.java @@ -156,6 +156,12 @@ public abstract class FindManager { */ public abstract void setFindWasPerformed(); + /** + * Explicitly tell FindManager that "Find Next" and "Find Previous" actions should not use + * find usages previous results. + */ + public abstract void clearFindingNextUsageInFile(); + /** * Sets the model containing the search settings to use for "Find Next" and * "Find Previous" operations. diff --git a/platform/lang-api/src/com/intellij/psi/codeStyle/arrangement/ArrangementEntry.java b/platform/lang-api/src/com/intellij/psi/codeStyle/arrangement/ArrangementEntry.java index d3ad9f9eefee..da4426b1dce6 100644 --- a/platform/lang-api/src/com/intellij/psi/codeStyle/arrangement/ArrangementEntry.java +++ b/platform/lang-api/src/com/intellij/psi/codeStyle/arrangement/ArrangementEntry.java @@ -19,7 +19,7 @@ import com.intellij.psi.codeStyle.arrangement.match.ArrangementEntryMatcher; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.Collection; +import java.util.List; /** * Represents a processing unit during 'rearrangement' operation. I.e. entry's position can be changed during the processing. @@ -54,8 +54,22 @@ public interface ArrangementEntry { * @see #getParent() */ @NotNull - Collection getChildren(); + List getChildren(); + /** + * There is a possible case that particular entry position depends on another entries positions. E.g. static initialization + * block which uses static fields from the same class must be declared after them. + *

+ * This method allows to answer what sibling entries must be located before the current one at the resulting arrangement algorithm. + *

+ * There is also a special case when a list with the single entry which is the current's entry {@link #getParent() parent} + * is returned - that means that current entry should be arranged to be the first child. + * + * @return current entry's dependencies (if any) + */ + @Nullable + List getDependencies(); + /** * @return start offset of the current entry (inclusive) within the target document. Rearranger engine uses this information * to move rearranged entries diff --git a/platform/lang-api/src/com/intellij/psi/codeStyle/arrangement/DefaultArrangementEntry.java b/platform/lang-api/src/com/intellij/psi/codeStyle/arrangement/DefaultArrangementEntry.java index b580ee928f37..dc57bed0dc95 100644 --- a/platform/lang-api/src/com/intellij/psi/codeStyle/arrangement/DefaultArrangementEntry.java +++ b/platform/lang-api/src/com/intellij/psi/codeStyle/arrangement/DefaultArrangementEntry.java @@ -19,17 +19,19 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; -import java.util.Collection; import java.util.List; /** + * Not thread-safe. + * * @author Denis Zhdanov * @since 7/20/12 4:53 PM */ public class DefaultArrangementEntry implements ArrangementEntry { + + @NotNull private final List myChildren = new ArrayList(); - private final List myChildren = new ArrayList(); - + @Nullable private List myDependencies; @Nullable ArrangementEntry myParent; private final int myStartOffset; private final int myEndOffset; @@ -51,7 +53,7 @@ public class DefaultArrangementEntry implements ArrangementEntry { @NotNull @Override - public Collection getChildren() { + public List getChildren() { return myChildren; } @@ -59,6 +61,19 @@ public class DefaultArrangementEntry implements ArrangementEntry { myChildren.add(entry); } + @Nullable + @Override + public List getDependencies() { + return myDependencies; + } + + public void addDependency(@NotNull ArrangementEntry dependency) { + if (myDependencies == null) { + myDependencies = new ArrayList(); + } + myDependencies.add(dependency); + } + @Override public int getStartOffset() { return myStartOffset; diff --git a/platform/lang-api/src/com/intellij/psi/codeStyle/arrangement/Rearranger.java b/platform/lang-api/src/com/intellij/psi/codeStyle/arrangement/Rearranger.java index 067f1bbe6be6..228d882c826a 100644 --- a/platform/lang-api/src/com/intellij/psi/codeStyle/arrangement/Rearranger.java +++ b/platform/lang-api/src/com/intellij/psi/codeStyle/arrangement/Rearranger.java @@ -24,6 +24,7 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collection; +import java.util.List; /** * Encapsulates language-specific rearrangement logic. @@ -38,16 +39,29 @@ public interface Rearranger { LanguageExtension> EXTENSION = new LanguageExtension>("com.intellij.lang.rearranger"); + /** + * Tries to wrap given element to the corresponding arrangement entry. + *

+ * This is useful in a situation when new element is generated and we're deciding where to insert it (e.g. new field is + * generated and we want to insert it according to the arrangement rules like 'fields before methods'). + * + * @param element element to wrap into format eligible for further processing by arrangement engine + * @return arrangement entry for the given element if it's possible to perform the mapping; + * null otherwise + */ + @Nullable + E wrap(@NotNull PsiElement element); + /** * Allows to build rearranger-interested data for the given element. * * @param root root element which children should be parsed for the rearrangement * @param document document which corresponds to the target PSI tree * @param ranges target offsets ranges to use for filtering given root's children - * @return given root's children which are subject for further rearrangement + * @return given root's children which are subject for further rearrangement */ @NotNull - Collection parse(@NotNull PsiElement root, @NotNull Document document, @NotNull Collection ranges); + List parse(@NotNull PsiElement root, @Nullable Document document, @NotNull Collection ranges); /** * Allows to answer how many blank lines should be inserted before the target arrangement entry which position is changed. diff --git a/platform/lang-api/src/com/intellij/psi/codeStyle/arrangement/match/ArrangementEntryType.java b/platform/lang-api/src/com/intellij/psi/codeStyle/arrangement/match/ArrangementEntryType.java index 394ed8bb2bdd..acf8cb418834 100644 --- a/platform/lang-api/src/com/intellij/psi/codeStyle/arrangement/match/ArrangementEntryType.java +++ b/platform/lang-api/src/com/intellij/psi/codeStyle/arrangement/match/ArrangementEntryType.java @@ -27,5 +27,5 @@ import com.intellij.psi.codeStyle.arrangement.ArrangementEntry; */ public enum ArrangementEntryType { - CLASS, FIELD, METHOD, ENUM, INTERFACE + CLASS, FIELD, CONSTRUCTOR, METHOD, ENUM, INTERFACE } diff --git a/platform/lang-api/src/com/intellij/psi/codeStyle/arrangement/settings/DefaultArrangementSettingsRepresentationManager.java b/platform/lang-api/src/com/intellij/psi/codeStyle/arrangement/settings/DefaultArrangementSettingsRepresentationManager.java index f7467a84f85d..03ab9672d34b 100644 --- a/platform/lang-api/src/com/intellij/psi/codeStyle/arrangement/settings/DefaultArrangementSettingsRepresentationManager.java +++ b/platform/lang-api/src/com/intellij/psi/codeStyle/arrangement/settings/DefaultArrangementSettingsRepresentationManager.java @@ -37,8 +37,8 @@ public class DefaultArrangementSettingsRepresentationManager implements Arrangem Object[] ids = { // Types. - ArrangementEntryType.FIELD, ArrangementEntryType.METHOD, ArrangementEntryType.CLASS, ArrangementEntryType.INTERFACE, - ArrangementEntryType.ENUM, + ArrangementEntryType.FIELD, ArrangementEntryType.CONSTRUCTOR, ArrangementEntryType.METHOD, ArrangementEntryType.CLASS, + ArrangementEntryType.INTERFACE, ArrangementEntryType.ENUM, // Visibility. ArrangementModifier.PUBLIC, ArrangementModifier.PROTECTED, ArrangementModifier.PACKAGE_PRIVATE, ArrangementModifier.PRIVATE, diff --git a/platform/lang-impl/src/com/intellij/application/options/codeStyle/arrangement/ArrangementRuleTree.java b/platform/lang-impl/src/com/intellij/application/options/codeStyle/arrangement/ArrangementRuleTree.java index 188708a4d7d9..176587316722 100644 --- a/platform/lang-impl/src/com/intellij/application/options/codeStyle/arrangement/ArrangementRuleTree.java +++ b/platform/lang-impl/src/com/intellij/application/options/codeStyle/arrangement/ArrangementRuleTree.java @@ -26,6 +26,7 @@ import com.intellij.psi.codeStyle.arrangement.settings.ArrangementConditionsGrou import com.intellij.ui.treeStructure.Tree; import com.intellij.util.Alarm; import com.intellij.util.Consumer; +import com.intellij.util.ui.tree.WideSelectionTreeUI; import gnu.trove.*; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -33,6 +34,7 @@ import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; +import javax.swing.plaf.TreeUI; import javax.swing.tree.*; import java.awt.*; import java.awt.event.ActionEvent; @@ -90,6 +92,17 @@ public class ArrangementRuleTree { }); myRoot = new ArrangementTreeNode(null); myTreeModel = new DefaultTreeModel(myRoot); + + final Condition wideSelectionCondition = new Condition() { + @Override + public boolean value(Integer row) { + TreePath path = myTree.getPathForRow(row); + if (path == null) { + return false; + } + return isEmptyCondition(((ArrangementTreeNode)path.getLastPathComponent()).getBackingCondition()); + } + }; myTree = new Tree(myTreeModel) { @Override @@ -103,16 +116,7 @@ public class ArrangementRuleTree { @NotNull @Override protected Condition getWideSelectionBackgroundCondition() { - return new Condition() { - @Override - public boolean value(Integer row) { - TreePath path = getPathForRow(row); - if (path == null) { - return false; - } - return isEmptyCondition(((ArrangementTreeNode)path.getLastPathComponent()).getBackingCondition()); - } - }; + return wideSelectionCondition; } @Override @@ -135,9 +139,10 @@ public class ArrangementRuleTree { mySkipSelectionChange = false; } } - }; + }; myTree.setSelectionModel(mySelectionModel); myTree.setRootVisible(false); + myTree.setRowHeight(0); // Don't insist on the same row height mySelectionModel.addTreeSelectionListener(new TreeSelectionListener() { @Override public void valueChanged(TreeSelectionEvent e) { @@ -184,6 +189,15 @@ public class ArrangementRuleTree { myTree.setShowsRootHandles(false); myTree.setCellRenderer(new MyCellRenderer()); + TreeUI ui = myTree.getUI(); + if (!(ui instanceof WideSelectionTreeUI)) { + // IJ wide selection tree ui is not applied for some LAFs (e.g. GTK) and default wide selection tree ui doesn't allow + // to customize selection background appliance algorithm (don't draw background for rule components; do draw for + // 'new rule' node). + // That's why we forcibly apply UI with custom selection strategy here. + // P.S. 'wide selection tree ui' appliance decision is taken at the com.intellij.ui.treeStructure.Tree.setUI(). + myTree.setUI(new WideSelectionTreeUI(true, wideSelectionCondition)); + } } private void selectPreviousRule() { diff --git a/platform/lang-impl/src/com/intellij/codeInsight/actions/ReformatCodeAction.java b/platform/lang-impl/src/com/intellij/codeInsight/actions/ReformatCodeAction.java index 21c81d1b00cd..c7e26b2201bb 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/actions/ReformatCodeAction.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/actions/ReformatCodeAction.java @@ -19,6 +19,7 @@ package com.intellij.codeInsight.actions; import com.intellij.application.options.editor.EditorOptions; import com.intellij.codeInsight.CodeInsightBundle; import com.intellij.formatting.FormattingModelBuilder; +import com.intellij.ide.util.PropertiesComponent; import com.intellij.lang.LanguageFormatting; import com.intellij.notification.Notification; import com.intellij.notification.NotificationListener; @@ -28,7 +29,6 @@ import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.editor.Editor; -import com.intellij.openapi.editor.RangeMarker; import com.intellij.openapi.editor.SelectionModel; import com.intellij.openapi.editor.ex.EditorSettingsExternalizable; import com.intellij.openapi.module.Module; @@ -150,8 +150,8 @@ public class ReformatCodeAction extends AnAction implements DumbAware { boolean optimizeImports = ReformatFilesDialog.isOptmizeImportsOptionOn(); boolean processWholeFile = false; - boolean processChangedTextOnly = false; - boolean rearrangeEntries = ReformatFilesDialog.isRearrangeEntriesOptionOn(); + boolean processChangedTextOnly = PropertiesComponent.getInstance().getBoolean(LayoutCodeConstants.PROCESS_CHANGED_TEXT_KEY, false); + boolean rearrangeEntries = PropertiesComponent.getInstance().getBoolean(LayoutCodeConstants.REARRANGE_ENTRIES_KEY, false); final boolean showDialog = EditorSettingsExternalizable.getInstance().getOptions().SHOW_REFORMAT_DIALOG; if (showDialog || (file == null && dir != null)) { final LayoutCodeDialog dialog = new LayoutCodeDialog(project, CodeInsightBundle.message("process.reformat.code"), file, dir, diff --git a/platform/lang-impl/src/com/intellij/codeInsight/actions/ReformatFilesDialog.java b/platform/lang-impl/src/com/intellij/codeInsight/actions/ReformatFilesDialog.java index 43c018a7f0f4..1699ced0c727 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/actions/ReformatFilesDialog.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/actions/ReformatFilesDialog.java @@ -75,8 +75,4 @@ public class ReformatFilesDialog extends DialogWrapper { static boolean isOptmizeImportsOptionOn() { return PropertiesComponent.getInstance().getBoolean(LayoutCodeConstants.OPTIMIZE_IMPORTS_KEY, false); } - - static boolean isRearrangeEntriesOptionOn() { - return PropertiesComponent.getInstance().getBoolean(LayoutCodeConstants.REARRANGE_ENTRIES_KEY, false); - } } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/BraceMatcherBasedSelectioner.java b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/BraceMatcherBasedSelectioner.java index d577a1a38c06..bddf785a2a95 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/BraceMatcherBasedSelectioner.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/BraceMatcherBasedSelectioner.java @@ -58,7 +58,7 @@ public abstract class BraceMatcherBasedSelectioner extends ExtendWordSelectionHa && !stack.isEmpty() && braceMatcher.isPairBraces((last = stack.getLast()).third, iterator.getTokenType())) { stack.removeLast(); result.addAll(expandToWholeLine(editorText, new TextRange(last.first, iterator.getEnd()))); - int bodyStart = last.second + 1; + int bodyStart = last.second; int bodyEnd = iterator.getStart(); while (bodyStart < textLength && Character.isWhitespace(editorText.charAt(bodyStart))) bodyStart ++; while (bodyEnd > 0 && Character.isWhitespace(editorText.charAt(bodyEnd - 1))) bodyEnd --; @@ -69,4 +69,5 @@ public abstract class BraceMatcherBasedSelectioner extends ExtendWordSelectionHa result.add(e.getTextRange()); return result; } + } \ No newline at end of file diff --git a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/TypedHandler.java b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/TypedHandler.java index 11aafcca23f3..52939e4ec0c1 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/TypedHandler.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/TypedHandler.java @@ -162,7 +162,6 @@ public class TypedHandler extends TypedActionHandlerBase { } final TypedHandlerDelegate[] delegates = Extensions.getExtensions(TypedHandlerDelegate.EP_NAME); - AutoPopupController autoPopupController = AutoPopupController.getInstance(project); boolean handled = false; for(TypedHandlerDelegate delegate: delegates) { @@ -174,13 +173,8 @@ public class TypedHandler extends TypedActionHandlerBase { } if (!handled) { - if (charTyped == '.') { - autoPopupController.autoPopupMemberLookup(editor, null); - } - - if ((charTyped == '(' || charTyped == ',') && !isInsideStringLiteral(editor, file)) { - autoPopupController.autoPopupParameterInfo(editor, null); - } + autoPopupCompletion(editor, charTyped, project); + autoPopupParameterInfo(editor, charTyped, project, file); } if (!editor.isInsertMode()){ @@ -242,6 +236,18 @@ public class TypedHandler extends TypedActionHandlerBase { } } + private static void autoPopupParameterInfo(Editor editor, char charTyped, Project project, PsiFile file) { + if ((charTyped == '(' || charTyped == ',') && !isInsideStringLiteral(editor, file)) { + AutoPopupController.getInstance(project).autoPopupParameterInfo(editor, null); + } + } + + public static void autoPopupCompletion(Editor editor, char charTyped, Project project) { + if (charTyped == '.') { + AutoPopupController.getInstance(project).autoPopupMemberLookup(editor, null); + } + } + private static boolean isInsideStringLiteral(final Editor editor, final PsiFile file) { int offset = editor.getCaretModel().getOffset(); PsiElement element = file.findElementAt(offset); diff --git a/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/CodeFoldingManagerImpl.java b/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/CodeFoldingManagerImpl.java index 9495a6bf8815..6a33a45fc5ee 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/CodeFoldingManagerImpl.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/CodeFoldingManagerImpl.java @@ -214,7 +214,8 @@ public class CodeFoldingManagerImpl extends CodeFoldingManager implements Projec final PsiFile file = PsiDocumentManager.getInstance(myProject).getPsiFile(document); if (file == null || !file.getViewProvider().isPhysical() && !ApplicationManager.getApplication().isUnitTestMode()) return; - if (!((FoldingModelEx)editor.getFoldingModel()).isFoldingEnabled()) return; + final FoldingModelEx foldingModel = (FoldingModelEx)editor.getFoldingModel(); + if (!foldingModel.isFoldingEnabled()) return; if (project.isDisposed() || editor.isDisposed() || !file.isValid()) return; PsiDocumentManager.getInstance(myProject).commitDocument(document); @@ -231,16 +232,21 @@ public class CodeFoldingManagerImpl extends CodeFoldingManager implements Projec @Override public void run() { if (myProject.isDisposed() || editor.isDisposed()) return; - DocumentFoldingInfo documentFoldingInfo = getDocumentFoldingInfo(document); - Editor[] editors = EditorFactory.getInstance().getEditors(document, myProject); - for (Editor otherEditor : editors) { - if (otherEditor == editor) continue; - documentFoldingInfo.loadFromEditor(otherEditor); - break; - } - documentFoldingInfo.setToEditor(editor); + foldingModel.runBatchFoldingOperation(new Runnable() { + @Override + public void run() { + DocumentFoldingInfo documentFoldingInfo = getDocumentFoldingInfo(document); + Editor[] editors = EditorFactory.getInstance().getEditors(document, myProject); + for (Editor otherEditor : editors) { + if (otherEditor == editor) continue; + documentFoldingInfo.loadFromEditor(otherEditor); + break; + } + documentFoldingInfo.setToEditor(editor); - documentFoldingInfo.clear(); + documentFoldingInfo.clear(); + } + }); } }); } diff --git a/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/DocumentFoldingInfo.java b/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/DocumentFoldingInfo.java index ea9abbae8a92..bcd077047657 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/DocumentFoldingInfo.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/DocumentFoldingInfo.java @@ -93,7 +93,7 @@ class DocumentFoldingInfo implements JDOMExternalizable, CodeFoldingState { } } - void setToEditor(@NotNull Editor editor) { + void setToEditor(@NotNull final Editor editor) { ApplicationManager.getApplication().assertIsDispatchThread(); final PsiManager psiManager = PsiManager.getInstance(myProject); if (psiManager.isDisposed()) return; diff --git a/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupTypedHandler.java b/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupTypedHandler.java index 6d9af2be8403..f3280579fc30 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupTypedHandler.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupTypedHandler.java @@ -20,6 +20,7 @@ import com.intellij.codeInsight.AutoPopupController; import com.intellij.codeInsight.completion.*; import com.intellij.codeInsight.completion.impl.CompletionServiceImpl; import com.intellij.codeInsight.editorActions.AutoHardWrapHandler; +import com.intellij.codeInsight.editorActions.TypedHandler; import com.intellij.codeInsight.editorActions.TypedHandlerDelegate; import com.intellij.codeInsight.lookup.CharFilter; import com.intellij.codeInsight.lookup.LookupElement; @@ -137,6 +138,7 @@ public class LookupTypedHandler extends TypedHandlerDelegate { } lookup.hide(); + TypedHandler.autoPopupCompletion(editor, charTyped, project); return Result.CONTINUE; } finally { diff --git a/platform/lang-impl/src/com/intellij/codeInspection/reference/RefElementImpl.java b/platform/lang-impl/src/com/intellij/codeInspection/reference/RefElementImpl.java index 3899fd5a402c..129bdde2d9ed 100644 --- a/platform/lang-impl/src/com/intellij/codeInspection/reference/RefElementImpl.java +++ b/platform/lang-impl/src/com/intellij/codeInspection/reference/RefElementImpl.java @@ -36,6 +36,7 @@ import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.SmartPointerManager; import com.intellij.psi.SmartPsiElementPointer; +import com.intellij.util.ArrayUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -252,10 +253,13 @@ public abstract class RefElementImpl extends RefEntityImpl implements RefElement mySuppressions = text.split("[, ]"); } - public boolean isSuppressed(final String toolId) { + public boolean isSuppressed(final String... toolId) { if (mySuppressions != null) { for (@NonNls String suppression : mySuppressions) { - if (suppression.equals(toolId) || suppression.equalsIgnoreCase(SuppressionUtil.ALL)){ + for (String id : toolId) { + if (suppression.equals(id)) return true; + } + if (suppression.equalsIgnoreCase(SuppressionUtil.ALL)){ return true; } } diff --git a/platform/lang-impl/src/com/intellij/execution/console/LanguageConsoleImpl.java b/platform/lang-impl/src/com/intellij/execution/console/LanguageConsoleImpl.java index d04606d5b767..c3b7f3d1bc28 100644 --- a/platform/lang-impl/src/com/intellij/execution/console/LanguageConsoleImpl.java +++ b/platform/lang-impl/src/com/intellij/execution/console/LanguageConsoleImpl.java @@ -30,6 +30,7 @@ import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.*; import com.intellij.openapi.editor.actions.EditorActionUtil; +import com.intellij.openapi.editor.colors.EditorColors; import com.intellij.openapi.editor.colors.EditorColorsScheme; import com.intellij.openapi.editor.colors.impl.DelegateColorScheme; import com.intellij.openapi.editor.event.*; @@ -522,8 +523,11 @@ public class LanguageConsoleImpl implements Disposable, TypeSafeDataProvider { for (RangeHighlighter rangeHighlighter : from.getAllHighlighters()) { if (!rangeHighlighter.isValid()) continue; Object tooltip = rangeHighlighter.getErrorStripeTooltip(); - HighlightSeverity severity = tooltip instanceof HighlightInfo? ((HighlightInfo)tooltip).getSeverity() : null; - if (severity != HighlightSeverity.INFORMATION) continue; + HighlightInfo highlightInfo = tooltip instanceof HighlightInfo? (HighlightInfo)tooltip : null; + if (highlightInfo != null) { + if (highlightInfo.getSeverity() != HighlightSeverity.INFORMATION) continue; + if (highlightInfo.type.getAttributesKey() == EditorColors.IDENTIFIER_UNDER_CARET_ATTRIBUTES) continue; + } final int localOffset = textRange.getStartOffset(); final int start = Math.max(rangeHighlighter.getStartOffset(), localOffset) - localOffset; final int end = Math.min(rangeHighlighter.getEndOffset(), textRange.getEndOffset()) - localOffset; diff --git a/platform/lang-impl/src/com/intellij/find/FindUtil.java b/platform/lang-impl/src/com/intellij/find/FindUtil.java index 015c1230541f..eec2ac92e1cc 100644 --- a/platform/lang-impl/src/com/intellij/find/FindUtil.java +++ b/platform/lang-impl/src/com/intellij/find/FindUtil.java @@ -182,6 +182,7 @@ public class FindUtil { FindSettings.getInstance().addStringToFind(s); findManager.getFindInFileModel().setStringToFind(s); findManager.setFindWasPerformed(); + findManager.clearFindingNextUsageInFile(); FindModel model = new FindModel(); model.setStringToFind(s); model.setCaseSensitive(true); diff --git a/platform/lang-impl/src/com/intellij/find/findUsages/FindUsagesHandler.java b/platform/lang-impl/src/com/intellij/find/findUsages/FindUsagesHandler.java index 553339fb593a..0dced3ff4134 100644 --- a/platform/lang-impl/src/com/intellij/find/findUsages/FindUsagesHandler.java +++ b/platform/lang-impl/src/com/intellij/find/findUsages/FindUsagesHandler.java @@ -17,10 +17,10 @@ package com.intellij.find.findUsages; import com.intellij.ide.DataManager; import com.intellij.openapi.actionSystem.DataContext; -import com.intellij.openapi.application.AccessToken; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ReadActionProcessor; import com.intellij.openapi.project.Project; +import com.intellij.openapi.util.Computable; import com.intellij.openapi.util.NullableComputable; import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiElement; @@ -181,13 +181,12 @@ public abstract class FindUsagesHandler { @Nullable protected Collection getStringsToSearch(final PsiElement element) { if (element instanceof PsiNamedElement) { - final AccessToken accessToken = ApplicationManager.getApplication().acquireReadActionLock(); - try { - return ContainerUtil.createMaybeSingletonList(((PsiNamedElement)element).getName()); - } - finally { - accessToken.finish(); - } + return ApplicationManager.getApplication().runReadAction(new Computable>() { + @Override + public Collection compute() { + return ContainerUtil.createMaybeSingletonList(((PsiNamedElement)element).getName()); + } + }); } return Collections.singleton(element.getText()); diff --git a/platform/lang-impl/src/com/intellij/find/impl/FindManagerImpl.java b/platform/lang-impl/src/com/intellij/find/impl/FindManagerImpl.java index 2d56b508aced..acf0b6eb42ae 100644 --- a/platform/lang-impl/src/com/intellij/find/impl/FindManagerImpl.java +++ b/platform/lang-impl/src/com/intellij/find/impl/FindManagerImpl.java @@ -719,6 +719,11 @@ public class FindManagerImpl extends FindManager implements PersistentStateCompo myFindUsagesManager.showSettingsAndFindUsages(targets); } + @Override + public void clearFindingNextUsageInFile() { + myFindUsagesManager.clearFindingNextUsageInFile(); + } + @Override public void findUsagesInEditor(@NotNull PsiElement element, @NotNull FileEditor fileEditor) { if (fileEditor instanceof TextEditor) { diff --git a/platform/lang-impl/src/com/intellij/ide/projectView/impl/nodes/AbstractPsiBasedNode.java b/platform/lang-impl/src/com/intellij/ide/projectView/impl/nodes/AbstractPsiBasedNode.java index b61212df543f..bf29bb19db8c 100644 --- a/platform/lang-impl/src/com/intellij/ide/projectView/impl/nodes/AbstractPsiBasedNode.java +++ b/platform/lang-impl/src/com/intellij/ide/projectView/impl/nodes/AbstractPsiBasedNode.java @@ -24,8 +24,7 @@ import com.intellij.ide.projectView.ViewSettings; import com.intellij.ide.util.treeView.AbstractTreeNode; import com.intellij.ide.util.treeView.ValidateableNode; import com.intellij.navigation.NavigationItem; -import com.intellij.openapi.application.AccessToken; -import com.intellij.openapi.application.ReadAction; +import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.colors.CodeInsightColors; import com.intellij.openapi.extensions.Extensions; @@ -129,42 +128,40 @@ public abstract class AbstractPsiBasedNode extends ProjectViewNode @Override public void update(final PresentationData data) { - AccessToken token = ReadAction.start(); - try { - if (!validate()) { - return; - } - - final PsiElement value = extractPsiFromValue(); - LOG.assertTrue(value.isValid()); - - int flags = getIconableFlags(); - - try { - Icon icon = value.getIcon(flags); - data.setIcon(icon); - } - catch (IndexNotReadyException ignored) { - } - data.setPresentableText(myName); - - try { - if (isDeprecated()) { - data.setAttributesKey(CodeInsightColors.DEPRECATED_ATTRIBUTES); + ApplicationManager.getApplication().runReadAction(new Runnable() { + public void run() { + if (!validate()) { + return; } - } - catch (IndexNotReadyException ignored) { - } - updateImpl(data); - for (ProjectViewNodeDecorator decorator : Extensions.getExtensions(ProjectViewNodeDecorator.EP_NAME, myProject)) { - decorator.decorate(this, data); - } - Iconable.LastComputedIcon.put(value, data.getIcon(false), flags); - } - finally { - token.finish(); - } + final PsiElement value = extractPsiFromValue(); + LOG.assertTrue(value.isValid()); + + int flags = getIconableFlags(); + + try { + Icon icon = value.getIcon(flags); + data.setIcon(icon); + } + catch (IndexNotReadyException ignored) { + } + data.setPresentableText(myName); + + try { + if (isDeprecated()) { + data.setAttributesKey(CodeInsightColors.DEPRECATED_ATTRIBUTES); + } + } + catch (IndexNotReadyException ignored) { + } + updateImpl(data); + for (ProjectViewNodeDecorator decorator : Extensions.getExtensions(ProjectViewNodeDecorator.EP_NAME, myProject)) { + decorator.decorate(AbstractPsiBasedNode.this, data); + } + + Iconable.LastComputedIcon.put(value, data.getIcon(false), flags); + } + }); } @Iconable.IconFlags diff --git a/platform/lang-impl/src/com/intellij/ide/util/FileStructurePopup.java b/platform/lang-impl/src/com/intellij/ide/util/FileStructurePopup.java index 8eca23e543c4..4b90e8bde7c8 100644 --- a/platform/lang-impl/src/com/intellij/ide/util/FileStructurePopup.java +++ b/platform/lang-impl/src/com/intellij/ide/util/FileStructurePopup.java @@ -304,13 +304,11 @@ public class FileStructurePopup implements Disposable { ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { @Override public void run() { - final AccessToken token = ApplicationManager.getApplication().acquireReadActionLock(); - try { - myFilteringStructure.rebuild(); - } - finally { - token.finish(); - } + ApplicationManager.getApplication().runReadAction(new Runnable() { + public void run() { + myFilteringStructure.rebuild(); + } + }); SwingUtilities.invokeLater(new Runnable() { @Override diff --git a/platform/lang-impl/src/com/intellij/injected/editor/DocumentWindowImpl.java b/platform/lang-impl/src/com/intellij/injected/editor/DocumentWindowImpl.java index 5599dc3cdcc0..e30b194ae3ff 100644 --- a/platform/lang-impl/src/com/intellij/injected/editor/DocumentWindowImpl.java +++ b/platform/lang-impl/src/com/intellij/injected/editor/DocumentWindowImpl.java @@ -391,7 +391,7 @@ public class DocumentWindowImpl extends UserDataHolderBase implements Disposable } @Override - public void moveText(int srcStart, int srcEnd, int dstStart, int dstEnd) { + public void moveText(int srcStart, int srcEnd, int dstOffset) { // TODO den implement throw new UnsupportedOperationException(); } diff --git a/platform/lang-impl/src/com/intellij/psi/codeStyle/arrangement/MemberOrderService.java b/platform/lang-impl/src/com/intellij/psi/codeStyle/arrangement/MemberOrderService.java index e27df2693c96..01d81c56b193 100644 --- a/platform/lang-impl/src/com/intellij/psi/codeStyle/arrangement/MemberOrderService.java +++ b/platform/lang-impl/src/com/intellij/psi/codeStyle/arrangement/MemberOrderService.java @@ -15,11 +15,20 @@ */ package com.intellij.psi.codeStyle.arrangement; +import com.intellij.lang.Language; import com.intellij.psi.PsiElement; import com.intellij.psi.codeStyle.CommonCodeStyleSettings; +import com.intellij.psi.codeStyle.arrangement.engine.ArrangementEngine; +import com.intellij.psi.codeStyle.arrangement.settings.ArrangementStandardSettingsAware; +import com.intellij.util.containers.HashSet; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Set; + /** * The whole arrangement idea is to allow to change file entries order according to the user-provided rules. *

@@ -33,25 +42,82 @@ import org.jetbrains.annotations.Nullable; */ public class MemberOrderService { - public static final int UNDEFINED_WEIGHT = -1; - /** - * Allows to get a given member's weight according to the + * Tries to find an element at the given context which should be the previous sibling for the given 'member'element according to the * {@link CommonCodeStyleSettings#getArrangementRules() user-defined arrangement rules}. *

- * That means that we can call this method for different members and derive their relative order by comparing their weights. + * E.g. the IDE might generate given 'member' element and wants to know element after which it should be inserted * - * @param member target member which weight should be calculated + * @param member target member which anchor should be calculated * @param settings code style settings to use - * @param context given member's context (if any). Is useful when we have, say, an existing class and want to know where - * to insert a new field. Not only 'by type' filtering might be exploited (like 'fields before methods') but - * 'by name' as well, i.e. we want to insert a new field to the 'fidles' group and define its position - * according to the lexicographical fields order - * @return given member's weight if the one can be computed; - * {@link #UNDEFINED_WEIGHT} otherwise + * @param context given member's context + * @return given member's anchor if the one can be computed; + * given 'context' element if given member should be the first child + * null otherwise */ - public int getMemberOrderWeight(@NotNull PsiElement member, @NotNull CommonCodeStyleSettings settings, @Nullable PsiElement context) { - // TODO den implement - return UNDEFINED_WEIGHT; + @SuppressWarnings("MethodMayBeStatic") + @Nullable + public PsiElement getAnchor(@NotNull PsiElement member, @NotNull CommonCodeStyleSettings settings, @NotNull PsiElement context) { + Language language = context.getLanguage(); + Rearranger rearranger = Rearranger.EXTENSION.forLanguage(language); + if (rearranger == null) { + return null; + } + + List rules = settings.getArrangementRules(); + if (rules.isEmpty() && rearranger instanceof ArrangementStandardSettingsAware) { + rules = ((ArrangementStandardSettingsAware)rearranger).getDefaultRules(); + } + + if (rules == null) { + return null; + } + + ArrangementEntry memberEntry = rearranger.wrap(member); + if (memberEntry == null) { + return null; + } + + List entries = rearranger.parse(context, null, Collections.singleton(context.getTextRange())); + if (entries.isEmpty()) { + return null; + } + + ArrangementEntry parentEntry = entries.get(0); + List nonArranged = parentEntry.getChildren(); + List entriesWithNew = new ArrayList(nonArranged); + entriesWithNew.add(memberEntry); + List arranged = ArrangementEngine.arrange(entriesWithNew, rules); + int i = arranged.indexOf(memberEntry); + + if (i <= 0) { + return context; + } + + ArrangementEntry anchorEntry = null; + if (i >= arranged.size() - 1) { + anchorEntry = nonArranged.get(nonArranged.size() - 1); + } + else { + Set entriesBelow = new HashSet(); + entriesBelow.addAll(arranged.subList(i + 1, arranged.size())); + for (ArrangementEntry entry : nonArranged) { + if (entriesBelow.contains(entry)) { + break; + } + anchorEntry = entry; + } + } + + if (anchorEntry == null) { + return context; + } + + int offset = anchorEntry.getEndOffset() - 1 - context.getTextRange().getStartOffset(); + PsiElement element = context.findElementAt(offset); + for (PsiElement e = element; e != null && e.getTextRange().getStartOffset() >= anchorEntry.getStartOffset(); e = e.getParent()) { + element = e; + } + return element; } } diff --git a/platform/lang-impl/src/com/intellij/psi/codeStyle/arrangement/engine/ArrangementEngine.java b/platform/lang-impl/src/com/intellij/psi/codeStyle/arrangement/engine/ArrangementEngine.java index d570fe9b4360..a4019083c9da 100644 --- a/platform/lang-impl/src/com/intellij/psi/codeStyle/arrangement/engine/ArrangementEngine.java +++ b/platform/lang-impl/src/com/intellij/psi/codeStyle/arrangement/engine/ArrangementEngine.java @@ -18,6 +18,7 @@ package com.intellij.psi.codeStyle.arrangement.engine; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.ex.DocumentEx; +import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiDocumentManager; @@ -30,6 +31,7 @@ import com.intellij.psi.codeStyle.arrangement.ArrangementRule; import com.intellij.psi.codeStyle.arrangement.Rearranger; import com.intellij.psi.codeStyle.arrangement.StdArrangementRule; import com.intellij.psi.codeStyle.arrangement.settings.ArrangementStandardSettingsAware; +import com.intellij.util.containers.HashSet; import com.intellij.util.containers.Stack; import com.intellij.util.text.CharArrayUtil; import gnu.trove.TIntArrayList; @@ -192,29 +194,88 @@ public class ArrangementEngine { } } - @SuppressWarnings("unchecked") - private static void doArrange(@NotNull List> entries, - @NotNull Context context) + /** + * Arranges (re-orders) given entries according to the given rules. + * + * @param entries entries to arrange + * @param rules rules to use for arrangement + * @param arrangement entry type + * @return arranged list of the given rules + */ + @SuppressWarnings("AssignmentToForLoopParameter") + @NotNull + public static List arrange(@NotNull Collection entries, + @NotNull List rules) { - List> arranged = new ArrayList>(); - Set> unprocessed = new LinkedHashSet>(entries); - - for (ArrangementRule rule : context.rules) { - for (ArrangementEntryWrapper wrapper : entries) { - if (wrapper.getEntry().canBeMatched() && unprocessed.contains(wrapper) && rule.getMatcher().isMatched(wrapper.getEntry())) { - arranged.add(wrapper); - unprocessed.remove(wrapper); + List arranged = new ArrayList(); + Set unprocessed = new LinkedHashSet(); + List, E>> dependent = new ArrayList, E>>(); + for (E entry : entries) { + List dependencies = entry.getDependencies(); + if (dependencies == null) { + unprocessed.add(entry); + } + else { + if (dependencies.size() == 1 && dependencies.get(0) == entry.getParent()) { + // Handle a situation when the entry is condifured to be at the first parent's children. + arranged.add(entry); + } + else { + Set first = new HashSet(dependencies); + dependent.add(Pair.create(first, entry)); } } } - arranged.addAll(unprocessed); - context.prepare(arranged); + Set matched = new HashSet(); + + for (ArrangementRule rule : rules) { + matched.clear(); + for (E entry : unprocessed) { + if (entry.canBeMatched() && rule.getMatcher().isMatched(entry)) { + arranged.add(entry); + matched.add(entry); + } + } + unprocessed.removeAll(matched); + } + arranged.addAll(unprocessed); + + for (int i = 0; i < arranged.size() && !dependent.isEmpty(); i++) { + E e = arranged.get(i); + for (Iterator, E>> iterator = dependent.iterator(); iterator.hasNext(); ) { + Pair, E> pair = iterator.next(); + pair.first.remove(e); + if (pair.first.isEmpty()) { + iterator.remove(); + arranged.add(i + 1, pair.second); + i++; + } + } + } + + return arranged; + } + + @SuppressWarnings("unchecked") + private static void doArrange(@NotNull List> wrappers, + @NotNull Context context) { + if (wrappers.isEmpty()) { + return; + } + Map> map = new LinkedHashMap>(); + for (ArrangementEntryWrapper wrapper : wrappers) { + map.put(wrapper.getEntry(), wrapper); + } + List arranged = arrange(map.keySet(), context.rules); + + + context.prepare(wrappers.get(0).getParent()); // We apply changes from the last position to the first position in order not to bother with offsets shifts. for (int i = arranged.size() - 1; i >= 0; i--) { - ArrangementEntryWrapper arrangedWrapper = arranged.get(i); - ArrangementEntryWrapper initialWrapper = entries.get(i); - context.replace(arrangedWrapper, initialWrapper, i > 0 ? arranged.get(i - 1) : null); + ArrangementEntryWrapper arrangedWrapper = map.get(arranged.get(i)); + ArrangementEntryWrapper initialWrapper = wrappers.get(i); + context.replace(arrangedWrapper, initialWrapper, i > 0 ? map.get(arranged.get(i - 1)) : null); } } @@ -264,11 +325,7 @@ public class ArrangementEngine { return new Context(rearranger, wrappers, document, rules, settings); } - public void prepare(@NotNull List> arrangedEntries) { - if (arrangedEntries.isEmpty()) { - return; - } - ArrangementEntryWrapper parent = arrangedEntries.get(0).getParent(); + public void prepare(@Nullable ArrangementEntryWrapper parent) { if (parent == null) { myParentText = document.getText(); myParentShift = 0; diff --git a/platform/lang-impl/src/com/intellij/psi/formatter/common/AbstractBlock.java b/platform/lang-impl/src/com/intellij/psi/formatter/common/AbstractBlock.java index 8a0a6d170abd..b46c48dc1258 100644 --- a/platform/lang-impl/src/com/intellij/psi/formatter/common/AbstractBlock.java +++ b/platform/lang-impl/src/com/intellij/psi/formatter/common/AbstractBlock.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2012 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,24 +17,29 @@ package com.intellij.psi.formatter.common; import com.intellij.formatting.*; +import com.intellij.injected.editor.DocumentWindow; import com.intellij.lang.ASTNode; import com.intellij.openapi.util.TextRange; +import com.intellij.psi.PsiElement; +import com.intellij.psi.PsiFile; import com.intellij.psi.formatter.FormatterUtil; +import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import java.util.ArrayList; import java.util.Collections; import java.util.List; public abstract class AbstractBlock implements ASTBlock { public static final List EMPTY = Collections.emptyList(); - protected final ASTNode myNode; - protected final Wrap myWrap; - protected final Alignment myAlignment; + @NotNull protected final ASTNode myNode; + @Nullable protected final Wrap myWrap; + @Nullable protected final Alignment myAlignment; private List mySubBlocks; - private Boolean myIncomplete; + private Boolean myIncomplete; protected AbstractBlock(@NotNull ASTNode node, @Nullable Wrap wrap, @Nullable Alignment alignment) { myNode = node; @@ -53,14 +58,49 @@ public abstract class AbstractBlock implements ASTBlock { public List getSubBlocks() { if (mySubBlocks == null) { - final List list = buildChildren(); - mySubBlocks = list.size() > 0 ? list:EMPTY; + List list = buildChildren(); + if (list.isEmpty()) { + list = buildInjectedBlocks(); + } + mySubBlocks = list.size() > 0 ? list : EMPTY; } return mySubBlocks; } + @NotNull + private List buildInjectedBlocks() { + if (!(this instanceof SettingsAwareBlock)) { + return EMPTY; + } + PsiElement psi = myNode.getPsi(); + if (psi == null) { + return EMPTY; + } + PsiFile file = psi.getContainingFile(); + if (file == null) { + return EMPTY; + } + TextRange blockRange = myNode.getTextRange(); + List documentWindows = InjectedLanguageUtil.getCachedInjectedDocuments(file); + for (DocumentWindow documentWindow : documentWindows) { + int startOffset = documentWindow.injectedToHost(0); + int endOffset = startOffset + documentWindow.getTextLength(); + if (blockRange.containsRange(startOffset, endOffset)) { + PsiElement injected = InjectedLanguageUtil.findInjectedElementNoCommit(file, startOffset); + if (injected != null) { + List result = new ArrayList(); + DefaultInjectedLanguageBlockBuilder builder = new DefaultInjectedLanguageBlockBuilder(((SettingsAwareBlock)this).getSettings()); + builder.addInjectedBlocks(result, myNode, getWrap(), getAlignment(), getIndent()); + return result; + } + } + } + return EMPTY; + } + protected abstract List buildChildren(); + @Nullable @Override public Wrap getWrap() { return myWrap; @@ -71,11 +111,13 @@ public abstract class AbstractBlock implements ASTBlock { return null; } + @Nullable @Override public Alignment getAlignment() { return myAlignment; } + @NotNull @Override public ASTNode getNode() { return myNode; @@ -114,9 +156,6 @@ public abstract class AbstractBlock implements ASTBlock { @Override public String toString() { - if (myNode == null) { - return super.toString(); - } return myNode.getText() + " " + getTextRange(); } } diff --git a/platform/lang-impl/src/com/intellij/psi/formatter/common/DefaultInjectedLanguageBlockBuilder.java b/platform/lang-impl/src/com/intellij/psi/formatter/common/DefaultInjectedLanguageBlockBuilder.java new file mode 100644 index 000000000000..877e039f323a --- /dev/null +++ b/platform/lang-impl/src/com/intellij/psi/formatter/common/DefaultInjectedLanguageBlockBuilder.java @@ -0,0 +1,104 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.intellij.psi.formatter.common; + +import com.intellij.formatting.*; +import com.intellij.lang.ASTNode; +import com.intellij.openapi.util.TextRange; +import com.intellij.psi.codeStyle.CodeStyleSettings; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.List; + +/** + * @author Denis Zhdanov + * @since 9/6/12 9:22 AM + */ +public class DefaultInjectedLanguageBlockBuilder extends InjectedLanguageBlockBuilder { + + @NotNull private final CodeStyleSettings mySettings; + + public DefaultInjectedLanguageBlockBuilder(@NotNull CodeStyleSettings settings) { + mySettings = settings; + } + + @NotNull + @Override + public CodeStyleSettings getSettings() { + return mySettings; + } + + @Override + public boolean canProcessFragment(String text, ASTNode injectionHost) { + return true; + } + + @Override + public Block createBlockBeforeInjection(ASTNode node, Wrap wrap, Alignment alignment, Indent indent, final TextRange range) { + return new GlueBlock(node, wrap, alignment, indent, range); + } + + @Override + public Block createBlockAfterInjection(ASTNode node, Wrap wrap, Alignment alignment, Indent indent, TextRange range) { + return new GlueBlock(node, wrap, alignment, Indent.getNoneIndent(), range); + } + + private static class GlueBlock extends AbstractBlock { + + @NotNull private final Indent myIndent; + @NotNull private final TextRange myRange; + + private GlueBlock(@NotNull ASTNode node, + @Nullable Wrap wrap, + @Nullable Alignment alignment, + @NotNull Indent indent, + @NotNull TextRange range) + { + super(node, wrap, alignment); + myIndent = indent; + myRange = range; + } + + @NotNull + @Override + public TextRange getTextRange() { + return myRange; + } + + @Override + protected List buildChildren() { + return AbstractBlock.EMPTY; + } + + @NotNull + @Override + public Indent getIndent() { + return myIndent; + } + + @Nullable + @Override + public Spacing getSpacing(@Nullable Block child1, @NotNull Block child2) { + return null; + } + + @Override + public boolean isLeaf() { + return true; + } + } +} diff --git a/platform/lang-impl/src/com/intellij/psi/formatter/common/SettingsAwareBlock.java b/platform/lang-impl/src/com/intellij/psi/formatter/common/SettingsAwareBlock.java new file mode 100644 index 000000000000..9e000e16dc18 --- /dev/null +++ b/platform/lang-impl/src/com/intellij/psi/formatter/common/SettingsAwareBlock.java @@ -0,0 +1,30 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.intellij.psi.formatter.common; + +import com.intellij.formatting.Block; +import com.intellij.psi.codeStyle.CodeStyleSettings; +import org.jetbrains.annotations.NotNull; + +/** + * @author Denis Zhdanov + * @since 9/6/12 9:17 AM + */ +public interface SettingsAwareBlock extends Block { + + @NotNull + CodeStyleSettings getSettings(); +} diff --git a/platform/platform-api/src/com/intellij/ide/diff/DirDiffSettings.java b/platform/platform-api/src/com/intellij/ide/diff/DirDiffSettings.java index 034d30e7195d..8e5b8506bd70 100644 --- a/platform/platform-api/src/com/intellij/ide/diff/DirDiffSettings.java +++ b/platform/platform-api/src/com/intellij/ide/diff/DirDiffSettings.java @@ -67,7 +67,7 @@ public class DirDiffSettings { return filterPattern; } - public static enum CompareMode { + public enum CompareMode { CONTENT, // the most honest, the slowest. Compares size, if equal compares contents. Ignores timestamps SIZE, // Compares size only TIMESTAMP; // Compares size, if equal compares timestamps @@ -84,16 +84,10 @@ public class DirDiffSettings { } } - public void addExtraAction(@NotNull T action) { + public void addExtraAction(@NotNull T action) { extraToolbarActions.add(action); } - public void setModelToExtraActions(DirDiffModel model) { - for (AnAction action : extraToolbarActions) { - ((DirDiffModelHolder)action).setModel(model); - } - } - public List getExtraActions() { return extraToolbarActions; } diff --git a/platform/platform-impl/src/com/intellij/ide/ui/laf/DarculaLaf.java b/platform/platform-impl/src/com/intellij/ide/ui/laf/DarculaLaf.java index 84cde35fc34f..a0e59a3559f5 100644 --- a/platform/platform-impl/src/com/intellij/ide/ui/laf/DarculaLaf.java +++ b/platform/platform-impl/src/com/intellij/ide/ui/laf/DarculaLaf.java @@ -171,6 +171,10 @@ public final class DarculaLaf extends BasicLookAndFeel { Integer.parseInt(numbers.get(1)), Integer.parseInt(numbers.get(2)), Integer.parseInt(numbers.get(3)))); + } else if (key.endsWith(".border")) { + try { + defaults.put(key, Class.forName(value).newInstance()); + } catch (Exception ignore) {} } else { final Color color = ColorUtil.fromHex(value, null); final Integer invVal = getInteger(value); diff --git a/platform/platform-impl/src/com/intellij/ide/ui/laf/borders/DarculaButtonPainter.java b/platform/platform-impl/src/com/intellij/ide/ui/laf/borders/DarculaButtonPainter.java new file mode 100644 index 000000000000..22d0cd543cd5 --- /dev/null +++ b/platform/platform-impl/src/com/intellij/ide/ui/laf/borders/DarculaButtonPainter.java @@ -0,0 +1,64 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.intellij.ide.ui.laf.borders; + +import com.intellij.openapi.ui.GraphicsConfig; +import com.intellij.ui.Gray; +import com.intellij.util.ui.JBInsets; +import com.intellij.util.ui.MacUIUtil; + +import javax.swing.border.Border; +import javax.swing.plaf.UIResource; +import java.awt.*; + +/** + * @author Konstantin Bulenkov + */ +public class DarculaButtonPainter implements Border, UIResource { + private static final JBInsets myInsets = new JBInsets(6, 12, 6, 12); + private static final int offset = 4; + + @Override + public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) { + final Graphics2D g2d = (Graphics2D)g; + final int yOff = myInsets.height() / 4; + if (c.hasFocus()) { + MacUIUtil.paintFocusRing(g2d, new Color(89, 157, 231), new Rectangle(offset, yOff, width-2*offset, height - 2*yOff)); + } else { + final GraphicsConfig config = new GraphicsConfig(g); + g2d.setPaint(new GradientPaint(width / 2, y + yOff + 1, Gray._120, width / 2, height - 2*yOff, Gray._105)); + g.drawRoundRect(x + offset, y + yOff + 1, width - 2 * offset, height - 2*yOff, 2, 2); + + g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE); + + ((Graphics2D)g).setPaint(Gray._30); + g.drawRoundRect(x + offset, y + yOff, width - 2 * offset, height - 2*yOff, 4, 4); + + config.restore(); + } + } + + @Override + public Insets getBorderInsets(Component c) { + return myInsets; + } + + @Override + public boolean isBorderOpaque() { + return false; + } +} diff --git a/platform/platform-impl/src/com/intellij/ide/ui/laf/darcula.properties b/platform/platform-impl/src/com/intellij/ide/ui/laf/darcula.properties index 5d17d9317a93..2b5fadb23aa4 100644 --- a/platform/platform-impl/src/com/intellij/ide/ui/laf/darcula.properties +++ b/platform/platform-impl/src/com/intellij/ide/ui/laf/darcula.properties @@ -3,53 +3,53 @@ MenuItem.maxGutterIconWidth=18 MenuItem.acceleratorDelimiter=- #Trees -Tree.background=444444 +Tree.background=535353 Tree.foreground=cccccc Tree.textForeground=cccccc -Tree.textBackground=444444 +Tree.textBackground=535353 #Tree.selectionBackground=BEBEBE -#Tree.selectionForeground=444444 +#Tree.selectionForeground=535353 #Lists -List.background=444444 +List.background=535353 List.foreground=cccccc #Tables -Table.background=444444 +Table.background=535353 Table.foreground=cccccc -control=444444 -Panel.background=404040 +control=535353 +Panel.background=535353 Panel.foreground=cccccc Menu.selectionBackground=bebebe -MenuBar.background=444444 -MenuBar.disabledBackground=444444 -MenuBar.shadow=444444 -Menu.background=444444 -MenuItem.background=444444 +MenuBar.background=535353 +MenuBar.disabledBackground=535353 +MenuBar.shadow=535353 +Menu.background=535353 +MenuItem.background=535353 Menu.foreground=cccccc MenuItem.foreground=cccccc TabbedPane.tabInsets=0,4,0,4 ToggleButton.foreground=cccccc -Separator.background=444444 +Separator.background=535353 Separator.foreground=888888 -Label.background=404040 +Label.background=535353 Label.foreground=cccccc Focus.color=ff0000 -TextField.background=444444 +TextField.background=535353 TextField.foreground=cccccc TextField.caretForeground=cccccc -TextArea.background=444444 +TextArea.background=535353 TextArea.foreground=cccccc TextArea.caretForeground=cccccc -TextPane.background=444444 +TextPane.background=535353 TextPane.foreground=cccccc TextPane.caretForeground=cccccc -CheckBox.background=444444 +CheckBox.background=535353 CheckBox.foreground=cccccc RadioButton.foreground=cccccc @@ -58,6 +58,10 @@ StatusBar.top2Color=2c2c2c StatusBar.bottomColor=2c2c2c +Button.foreground=cccccc +Button.background=535353 +Button.border=com.intellij.ide.ui.laf.borders.DarculaButtonPainter + MenuItem.acceleratorForeground=cccccc -PopupMenu.background=444444 -PopupMenu.translucentBackground=444444 +PopupMenu.background=535353 +PopupMenu.translucentBackground=535353 diff --git a/platform/platform-impl/src/com/intellij/internal/ReloadProjectAction.java b/platform/platform-impl/src/com/intellij/internal/ReloadProjectAction.java index 80dd75075c4a..ddbeede86ebe 100644 --- a/platform/platform-impl/src/com/intellij/internal/ReloadProjectAction.java +++ b/platform/platform-impl/src/com/intellij/internal/ReloadProjectAction.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2012 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,6 +30,8 @@ import com.intellij.openapi.project.impl.ProjectManagerImpl; public class ReloadProjectAction extends AnAction implements DumbAware { public void actionPerformed(AnActionEvent e) { Project project = PlatformDataKeys.PROJECT.getData(e.getDataContext()); - ((ProjectManagerImpl)ProjectManager.getInstance()).reloadProject(project, true); + if (project != null) { + ((ProjectManagerImpl)ProjectManager.getInstance()).reloadProjectImpl(project, false); + } } } diff --git a/platform/platform-impl/src/com/intellij/openapi/application/impl/ApplicationImpl.java b/platform/platform-impl/src/com/intellij/openapi/application/impl/ApplicationImpl.java index 08f4bc7d7e2c..ab63636d4c94 100644 --- a/platform/platform-impl/src/com/intellij/openapi/application/impl/ApplicationImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/application/impl/ApplicationImpl.java @@ -99,6 +99,8 @@ public class ApplicationImpl extends ComponentManagerImpl implements Application private final String myName; private final ReentrantWriterPreferenceReadWriteLock myActionsLock = new ReentrantWriterPreferenceReadWriteLock(); + //private final AppLock myActionsLock = new AppLockImpl(); + private final Stack myWriteActionsStack = new Stack(); // accessed from EDT only, no need to sync private volatile Runnable myExceptionalThreadWithReadAccessRunnable; @@ -912,13 +914,21 @@ public class ApplicationImpl extends ComponentManagerImpl implements Application @Override public void runReadAction(@NotNull final Runnable action) { - final AccessToken token = acquireReadActionLockImpl(false); - - try { + if (isReadAccessAllowed()) { action.run(); } - finally { - token.finish(); + else { + assertReadActionAllowed(); + try { + myActionsLock.readLock().acquire(); + action.run(); + } + catch (InterruptedException e) { + throw new RuntimeInterruptedException(e); + } + finally { + myActionsLock.readLock().release(); + } } } @@ -941,13 +951,21 @@ public class ApplicationImpl extends ComponentManagerImpl implements Application @Override public T runReadAction(@NotNull final Computable computation) { - final AccessToken token = acquireReadActionLockImpl(false); - - try { + if (isReadAccessAllowed()) { return computation.compute(); } - finally { - token.finish(); + else { + assertReadActionAllowed(); + try { + myActionsLock.readLock().acquire(); + return computation.compute(); + } + catch (InterruptedException e) { + throw new RuntimeInterruptedException(e); + } + finally { + myActionsLock.readLock().release(); + } } } @@ -1021,7 +1039,6 @@ public class ApplicationImpl extends ComponentManagerImpl implements Application return ourDispatchThread == currentThread || isExceptionalThreadWithReadAccess() || myActionsLock.isReadLockAcquired() || - myActionsLock.isWriteLockAcquired() || isDispatchThread(); } @@ -1161,15 +1178,11 @@ public class ApplicationImpl extends ComponentManagerImpl implements Application @Override public AccessToken acquireReadActionLock() { - return acquireReadActionLockImpl(true); - } - - private AccessToken acquireReadActionLockImpl(boolean explicit) { /** if we are inside read action, do not try to acquire read lock again since it will deadlock if there is a pending writeAction * see {@link com.intellij.util.concurrency.ReentrantWriterPreferenceReadWriteLock#allowReader()} */ if (isReadAccessAllowed()) return AccessToken.EMPTY_ACCESS_TOKEN; - return new ReadAccessToken(explicit); + return new ReadAccessToken(); } @Override @@ -1238,14 +1251,11 @@ public class ApplicationImpl extends ComponentManagerImpl implements Application } private class ReadAccessToken extends AccessToken { - private final boolean myExplicit; - - ReadAccessToken(boolean explicit) { - myExplicit = explicit; - LOG.assertTrue(!Thread.holdsLock(PsiLock.LOCK), "Thread must not hold PsiLock while performing readAction"); + private ReadAccessToken() { + assertReadActionAllowed(); try { myActionsLock.readLock().acquire(); - if (myExplicit) acquired(); + acquired(); } catch (InterruptedException e) { throw new RuntimeInterruptedException(e); @@ -1255,10 +1265,14 @@ public class ApplicationImpl extends ComponentManagerImpl implements Application @Override public void finish() { myActionsLock.readLock().release(); - if (myExplicit) released(); + released(); } } + private static void assertReadActionAllowed() { + LOG.assertTrue(!Thread.holdsLock(PsiLock.LOCK), "Thread must not hold PsiLock while performing readAction"); + } + @Override public void assertWriteAccessAllowed() { LOG.assertTrue(isWriteAccessAllowed(), diff --git a/platform/platform-impl/src/com/intellij/openapi/diff/impl/DiffPanelImpl.java b/platform/platform-impl/src/com/intellij/openapi/diff/impl/DiffPanelImpl.java index 39ef4bbb306e..8b10264ac8cc 100644 --- a/platform/platform-impl/src/com/intellij/openapi/diff/impl/DiffPanelImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/diff/impl/DiffPanelImpl.java @@ -323,8 +323,9 @@ public class DiffPanelImpl implements DiffPanelEx, ContentChangeListener, TwoSid } } - private static String addReadOnly(@NotNull String title, @Nullable Editor editor) { - if (editor == null) { + @Nullable + private static String addReadOnly(@Nullable String title, @Nullable Editor editor) { + if (editor == null || title == null) { return title; } boolean readonly = editor.isViewer() || !editor.getDocument().isWritable(); @@ -578,7 +579,7 @@ public class DiffPanelImpl implements DiffPanelEx, ContentChangeListener, TwoSid String title1 = addReadOnly(data.getContentTitles()[0], myLeftSide.getEditor()); String title2 = addReadOnly(data.getContentTitles()[1], myRightSide.getEditor()); - if (sep1 != null && sep2 != null && !sep1.equals(sep2)) { + if (title1 != null && title2 != null && sep1 != null && sep2 != null && !sep1.equals(sep2)) { setTitle1(createComponentForTitle(title1, sep1, true)); setTitle2(createComponentForTitle(title2, sep2, false)); } diff --git a/platform/platform-impl/src/com/intellij/openapi/diff/impl/DiffSideView.java b/platform/platform-impl/src/com/intellij/openapi/diff/impl/DiffSideView.java index de59385798de..dd9198d2bb4c 100644 --- a/platform/platform-impl/src/com/intellij/openapi/diff/impl/DiffSideView.java +++ b/platform/platform-impl/src/com/intellij/openapi/diff/impl/DiffSideView.java @@ -253,10 +253,12 @@ public class DiffSideView { SyncScrollSupport.scrollEditor(editor, logicalLine); } + @Nullable public Editor getEditor() { return myEditorSource.getEditor(); } + @Nullable public FragmentSide getSide() { return myEditorSource.getSide(); } diff --git a/platform/platform-impl/src/com/intellij/openapi/editor/impl/IterationState.java b/platform/platform-impl/src/com/intellij/openapi/editor/impl/IterationState.java index 39d4b554ede4..d1169db10e98 100644 --- a/platform/platform-impl/src/com/intellij/openapi/editor/impl/IterationState.java +++ b/platform/platform-impl/src/com/intellij/openapi/editor/impl/IterationState.java @@ -36,7 +36,6 @@ import java.util.Iterator; import java.util.List; public final class IterationState { - private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.editor.impl.IterationState"); private static final Comparator HIGHLIGHTER_COMPARATOR = new Comparator() { @@ -90,7 +89,7 @@ public final class IterationState { private final int mySelectionStart; private final int mySelectionEnd; - private final List myCurrentHighlighters; + private final List myCurrentHighlighters = new ArrayList(); private final FoldingModelEx myFoldingModel; @@ -103,7 +102,7 @@ public final class IterationState { private final Color myDefaultForeground; private final int myCaretRowStart; private final int myCaretRowEnd; - private final List myCachedAttributesList; + private final List myCachedAttributesList = new ArrayList(5); private final DocumentEx myDocument; private final EditorEx myEditor; private final Color myReadOnlyColor; @@ -113,7 +112,7 @@ public final class IterationState { */ public IterationState(@NotNull EditorEx editor, int start, int end, boolean useCaretAndSelection) { ApplicationManager.getApplication().assertReadAccessAllowed(); - myDocument = (DocumentEx)editor.getDocument(); + myDocument = editor.getDocument(); myStartOffset = start; myEnd = end; @@ -139,9 +138,6 @@ public final class IterationState { myCaretRowStart = caretModel.getVisualLineStart(); myCaretRowEnd = caretModel.getVisualLineEnd(); - myCachedAttributesList = new ArrayList(5); - - myCurrentHighlighters = new ArrayList(); MarkupModelEx editorMarkup = (MarkupModelEx)editor.getMarkupModel(); myView = new HighlighterSweep(editorMarkup, start, myEnd); @@ -467,11 +463,7 @@ public final class IterationState { if (back == null) back = myDefaultBackground; if (effectType == null) effectType = EffectType.BOXED; - myMergedAttributes.setForegroundColor(fore); - myMergedAttributes.setBackgroundColor(back); - myMergedAttributes.setFontType(fontType); - myMergedAttributes.setEffectColor(effect); - myMergedAttributes.setEffectType(effectType); + myMergedAttributes.setAttributes(fore, back, effect, null, effectType, fontType); } @Nullable @@ -492,6 +484,7 @@ public final class IterationState { return myEndOffset; } + @NotNull public TextAttributes getMergedAttributes() { return myMergedAttributes; } diff --git a/platform/platform-impl/src/com/intellij/openapi/options/newEditor/OptionsTree.java b/platform/platform-impl/src/com/intellij/openapi/options/newEditor/OptionsTree.java index 75e37f50034f..3c6115037c4b 100644 --- a/platform/platform-impl/src/com/intellij/openapi/options/newEditor/OptionsTree.java +++ b/platform/platform-impl/src/com/intellij/openapi/options/newEditor/OptionsTree.java @@ -802,7 +802,7 @@ public class OptionsTree extends JPanel implements Disposable, OptionsEditorColl return result.doWhenDone(new Runnable() { public void run() { myRefilteringNow = false; - if (!myContext.isHoldingFilter()) { + if (!myContext.isHoldingFilter() && getSelectedElements().isEmpty()) { restoreExpandedState(toRestore); } } diff --git a/platform/platform-impl/src/com/intellij/openapi/project/impl/ProjectManagerImpl.java b/platform/platform-impl/src/com/intellij/openapi/project/impl/ProjectManagerImpl.java index a58dccc3d20f..fe04d1b429bb 100644 --- a/platform/platform-impl/src/com/intellij/openapi/project/impl/ProjectManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/project/impl/ProjectManagerImpl.java @@ -59,6 +59,7 @@ import com.intellij.openapi.wm.impl.IdeFrameImpl; import com.intellij.openapi.wm.impl.WindowManagerImpl; import com.intellij.util.Alarm; import com.intellij.util.ArrayUtil; +import com.intellij.util.TimeoutUtil; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.HashMap; import com.intellij.util.io.fs.IFile; @@ -80,8 +81,8 @@ import java.util.*; import java.util.concurrent.atomic.AtomicInteger; public class ProjectManagerImpl extends ProjectManagerEx implements NamedJDOMExternalizable, ExportableApplicationComponent { - private static final boolean LOG_PROJECT_LEAKAGE_IN_TESTS = false; private static final Logger LOG = Logger.getInstance("#com.intellij.project.impl.ProjectManagerImpl"); + public static final int CURRENT_FORMAT_VERSION = 4; private static final Key> LISTENERS_IN_PROJECT_KEY = Key.create("LISTENERS_IN_PROJECT_KEY"); @@ -105,7 +106,7 @@ public class ProjectManagerImpl extends ProjectManagerEx implements NamedJDOMExt private final Alarm myChangedFilesAlarm = new Alarm(); private final List> myChangedApplicationFiles = new ArrayList>(); private final AtomicInteger myReloadBlockCount = new AtomicInteger(0); - private final Map myProjects = new WeakHashMap(); + @SuppressWarnings("FieldCanBeLocal") private final Map myProjects = new WeakHashMap(); private static final int MAX_LEAKY_PROJECTS = 42; private final ProgressManager myProgressManager; private volatile boolean myDefaultProjectWasDisposed = false; @@ -126,7 +127,6 @@ public class ProjectManagerImpl extends ProjectManagerEx implements NamedJDOMExt @Override public void storageFileChanged(final VirtualFileEvent event, @NotNull final StateStorage storage) { VirtualFile file = event.getFile(); - LOG.debug("[RELOAD] Storage file changed: " + file.getPath()); if (!file.isDirectory() && !(event.getRequestor() instanceof StateStorage.SaveSession)) { saveChangedProjectFile(file, null, storage); } @@ -207,22 +207,19 @@ public class ProjectManagerImpl extends ProjectManagerEx implements NamedJDOMExt public void initComponent() { } + private static final boolean LOG_PROJECT_LEAKAGE_IN_TESTS = false; + @Override @Nullable public Project newProject(final String projectName, String filePath, boolean useDefaultProjectSettings, boolean isDummy) { - filePath = canonicalize(filePath); + filePath = toCanonicalName(filePath); + //noinspection ConstantConditions if (LOG_PROJECT_LEAKAGE_IN_TESTS && ApplicationManager.getApplication().isUnitTestMode()) { for (int i = 0; i < 42; i++) { if (myProjects.size() < MAX_LEAKY_PROJECTS) break; System.gc(); - try { - Thread.sleep(100); - } - catch (InterruptedException e) { - throw new RuntimeException(e); - } - + TimeoutUtil.sleep(100); System.gc(); } @@ -235,8 +232,7 @@ public class ProjectManagerImpl extends ProjectManagerEx implements NamedJDOMExt ProjectImpl project = createProject(projectName, filePath, false, ApplicationManager.getApplication().isUnitTestMode()); try { - initProject(project, useDefaultProjectSettings ? (ProjectImpl)getDefaultProject() : null - ); + initProject(project, useDefaultProjectSettings ? (ProjectImpl)getDefaultProject() : null); if (LOG_PROJECT_LEAKAGE_IN_TESTS) { myProjects.put(project, null); } @@ -324,7 +320,7 @@ public class ProjectManagerImpl extends ProjectManagerEx implements NamedJDOMExt } private void doLoadProject(String filePath, ProjectImpl project) throws IOException, StateStorageException { - filePath = canonicalize(filePath); + filePath = toCanonicalName(filePath); final ProgressIndicator indicator = myProgressManager.getProgressIndicator(); if (indicator != null) { indicator.setText(ProjectBundle.message("loading.components.for", FileUtil.toSystemDependentName(filePath))); @@ -334,7 +330,7 @@ public class ProjectManagerImpl extends ProjectManagerEx implements NamedJDOMExt } @NotNull - private static String canonicalize(@NotNull final String filePath) { + private static String toCanonicalName(@NotNull final String filePath) { try { return FileUtil.resolveShortWindowsName(filePath); } @@ -349,6 +345,7 @@ public class ProjectManagerImpl extends ProjectManagerEx implements NamedJDOMExt public synchronized boolean isDefaultProjectInitialized() { return myDefaultProject != null; } + @Override @NotNull public synchronized Project getDefaultProject() { @@ -509,7 +506,7 @@ public class ProjectManagerImpl extends ProjectManagerEx implements NamedJDOMExt */ @Nullable public Project convertAndLoadProject(String filePath) throws IOException { - final String fp = canonicalize(filePath); + final String fp = toCanonicalName(filePath); final ConversionResult conversionResult = ConversionService.getInstance().convert(fp); if (conversionResult.openingIsCanceled()) { return null; @@ -537,7 +534,7 @@ public class ProjectManagerImpl extends ProjectManagerEx implements NamedJDOMExt */ @Nullable private Project loadProjectWithProgress(@NotNull final String filePath) throws IOException { - final ProjectImpl project = createProject(null, canonicalize(filePath), false, false); + final ProjectImpl project = createProject(null, toCanonicalName(filePath), false, false); try { myProgressManager.runProcessWithProgressSynchronously(new ThrowableComputable() { @Override @@ -594,10 +591,9 @@ public class ProjectManagerImpl extends ProjectManagerEx implements NamedJDOMExt } for (final Project projectToReload : projectsToReload) { - reloadProjectImpl(projectToReload, false, false); + reloadProjectImpl(projectToReload, false); } } - } private boolean tryToReloadApplication(){ @@ -797,15 +793,17 @@ public class ProjectManagerImpl extends ProjectManagerEx implements NamedJDOMExt registerProjectToReload(project, file, null); } - private void saveChangedProjectFile(final VirtualFile file, final Project project, final StateStorage storage) { + private void saveChangedProjectFile(final VirtualFile file, @Nullable final Project project, final StateStorage storage) { if (file.exists()) { copyToTemp(file); } registerProjectToReload(project, file, storage); } - private void registerProjectToReload(final Project project, final VirtualFile cause, final StateStorage storage) { - LOG.debug("[RELOAD] Registering project to reload."); + private void registerProjectToReload(@Nullable final Project project, final VirtualFile cause, @Nullable final StateStorage storage) { + if (LOG.isDebugEnabled()) { + LOG.debug("[RELOAD] Registering project to reload: " + cause, new Exception()); + } if (project != null) { synchronized (myChangedProjectFiles) { @@ -819,16 +817,7 @@ public class ProjectManagerImpl extends ProjectManagerEx implements NamedJDOMExt } } else { - // todo[pegov] uncomment & check after X release - // do not schedule app reload for project files! - //try { - // if(FileUtil.isAncestor(new File(PathManager.getOptionsPathWithoutDialog()), new File(cause.getPath()), false)) { - myChangedApplicationFiles.add(new Pair(cause, storage)); - //} - //} - //catch (IOException e) { - // LOG.info(e.getMessage()); - //} + myChangedApplicationFiles.add(new Pair(cause, storage)); } myChangedFilesAlarm.cancelAllRequests(); @@ -878,18 +867,15 @@ public class ProjectManagerImpl extends ProjectManagerEx implements NamedJDOMExt @Override public void reloadProject(@NotNull final Project p) { - reloadProjectImpl(p, true, false); + reloadProjectImpl(p, true); } - public void reloadProjectImpl(final Project p, final boolean clearCopyToRestore, boolean takeMemorySnapshot) { + public void reloadProjectImpl(@NotNull final Project p, final boolean clearCopyToRestore) { if (clearCopyToRestore) { mySavedCopies.clear(); mySavedTimestamps.clear(); } - reloadProject(p, takeMemorySnapshot); - } - public void reloadProject(@NotNull Project p, final boolean takeMemorySnapshot) { final Project[] project = {p}; ProjectReloadState.getInstance(project[0]).onBeforeAutomaticProjectReload(); @@ -933,12 +919,6 @@ public class ProjectManagerImpl extends ProjectManagerEx implements NamedJDOMExt }, ModalityState.NON_MODAL); } - /* - public boolean isOpeningProject() { - return myCountOfProjectsBeingOpen > 0; - } - */ - @Override public boolean closeProject(@NotNull final Project project) { return closeProject(project, true, false, true); @@ -991,7 +971,7 @@ public class ProjectManagerImpl extends ProjectManagerEx implements NamedJDOMExt } public static boolean isLight(@NotNull Project project) { - return ApplicationManager.getApplication().isUnitTestMode() && project.toString().contains("lighttemp"); + return ApplicationManager.getApplication().isUnitTestMode() && project.toString().contains("light_temp_"); } @Override diff --git a/platform/platform-tests/testSrc/com/intellij/openapi/editor/RangeMarkerTest.java b/platform/platform-tests/testSrc/com/intellij/openapi/editor/RangeMarkerTest.java index ac649e979174..80bcd0ce9a00 100644 --- a/platform/platform-tests/testSrc/com/intellij/openapi/editor/RangeMarkerTest.java +++ b/platform/platform-tests/testSrc/com/intellij/openapi/editor/RangeMarkerTest.java @@ -26,6 +26,7 @@ import com.intellij.testFramework.LeakHunter; import com.intellij.testFramework.LightPlatformTestCase; import com.intellij.testFramework.Timings; import org.jetbrains.annotations.NonNls; +import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.List; @@ -139,9 +140,7 @@ public class RangeMarkerTest extends LightPlatformTestCase { public void testReplaceWholeRange() throws Exception { RangeMarker marker = createMarker("0123456789", 1, 7); marker.getDocument().replaceString(1, 7, "abc"); - assertTrue(marker.isValid()); - assertEquals(1, marker.getStartOffset()); - assertEquals(4, marker.getEndOffset()); + assertValidMarker(marker, 1, 4); } public void testUpdateInvalid() throws Exception { @@ -173,9 +172,7 @@ public class RangeMarkerTest extends LightPlatformTestCase { marker.getDocument().deleteString(4, 6); - assertTrue(marker.isValid()); - assertEquals(2, marker.getStartOffset()); - assertEquals(4, marker.getEndOffset()); + assertValidMarker(marker, 2, 4); } public void testDeleteStartPart() throws Exception { @@ -183,9 +180,7 @@ public class RangeMarkerTest extends LightPlatformTestCase { marker.getDocument().deleteString(0, 4); - assertTrue(marker.isValid()); - assertEquals(0, marker.getStartOffset()); - assertEquals(1, marker.getEndOffset()); + assertValidMarker(marker, 0, 1); } public void testReplaceStartPartInvalid() throws Exception { @@ -193,9 +188,7 @@ public class RangeMarkerTest extends LightPlatformTestCase { marker.getDocument().replaceString(0, 4, "xxxx"); - assertTrue(marker.isValid()); - assertEquals(4, marker.getStartOffset()); - assertEquals(5, marker.getEndOffset()); + assertValidMarker(marker, 4, 5); } public void testDeleteFirstChar() throws Exception { @@ -203,9 +196,7 @@ public class RangeMarkerTest extends LightPlatformTestCase { marker.getDocument().deleteString(0, 1); - assertTrue(marker.isValid()); - assertEquals(0, marker.getStartOffset()); - assertEquals(4, marker.getEndOffset()); + assertValidMarker(marker, 0, 4); } public void testInsertBeforeStart() throws Exception { @@ -223,9 +214,7 @@ public class RangeMarkerTest extends LightPlatformTestCase { marker.getDocument().insertString(2, "xxx"); - assertTrue(marker.isValid()); - assertEquals(5, marker.getStartOffset()); - assertEquals(8, marker.getEndOffset()); + assertValidMarker(marker, 5, 8); } public void testInsertIntoStartExpandToLeft() throws Exception { @@ -277,9 +266,7 @@ public class RangeMarkerTest extends LightPlatformTestCase { marker.getDocument().replaceString(0, s.length(), s.replaceAll(" ", "")); - assertTrue(marker.isValid()); - assertEquals(6, marker.getStartOffset()); - assertEquals(7, marker.getEndOffset()); + assertValidMarker(marker, 6, 7); } public void testDeleteRightPart() throws Exception { @@ -287,9 +274,7 @@ public class RangeMarkerTest extends LightPlatformTestCase { marker.getDocument().deleteString(4, 6); - assertTrue(marker.isValid()); - assertEquals(2, marker.getStartOffset()); - assertEquals(4, marker.getEndOffset()); + assertValidMarker(marker, 2, 4); } public void testDeleteRightPart2() throws Exception { @@ -297,9 +282,7 @@ public class RangeMarkerTest extends LightPlatformTestCase { marker.getDocument().deleteString(4, 5); - assertTrue(marker.isValid()); - assertEquals(2, marker.getStartOffset()); - assertEquals(4, marker.getEndOffset()); + assertValidMarker(marker, 2, 4); } public void testReplaceRightPartInvalid() throws Exception { @@ -307,9 +290,7 @@ public class RangeMarkerTest extends LightPlatformTestCase { marker.getDocument().replaceString(4, 6, "xxx"); - assertTrue(marker.isValid()); - assertEquals(2, marker.getStartOffset()); - assertEquals(4, marker.getEndOffset()); + assertValidMarker(marker, 2, 4); } public void testDeleteWholeRange() throws Exception { @@ -322,36 +303,28 @@ public class RangeMarkerTest extends LightPlatformTestCase { RangeMarker marker = createMarker("0123456789", 2, 5); marker.getDocument().deleteString(2, 5); - assertTrue(marker.isValid()); - assertEquals(2, marker.getStartOffset()); - assertEquals(2, marker.getEndOffset()); + assertValidMarker(marker, 2, 2); } public void testDeleteJustBeforeStart() throws Exception { RangeMarker marker = createMarker("0123456789", 2, 5); marker.getDocument().deleteString(0, 2); - assertTrue(marker.isValid()); - assertEquals(0, marker.getStartOffset()); - assertEquals(3, marker.getEndOffset()); + assertValidMarker(marker, 0, 3); } public void testDeleteRightAfterEnd() throws Exception { RangeMarker marker = createMarker("0123456789", 2, 2); marker.getDocument().deleteString(2, 5); - assertTrue(marker.isValid()); - assertEquals(2, marker.getStartOffset()); - assertEquals(2, marker.getEndOffset()); + assertValidMarker(marker, 2, 2); } public void testReplacementWithOldTextOverlap() throws Exception { RangeMarker marker = createMarker("0123456789", 2, 5); marker.getDocument().replaceString(0, 10, "0123456789"); - assertTrue(marker.isValid()); - assertEquals(2, marker.getStartOffset()); - assertEquals(5, marker.getEndOffset()); + assertValidMarker(marker, 2, 5); } // Psi -> Document synchronization @@ -369,9 +342,7 @@ public class RangeMarkerTest extends LightPlatformTestCase { assertEquals(buffer.toString(), marker.getDocument().getText()); - assertTrue(marker.isValid()); - assertEquals(2, marker.getStartOffset()); - assertEquals(6, marker.getEndOffset()); + assertValidMarker(marker, 2, 6); } public void testDocSynchronizerPrefersLineBoundaryChanges() throws Exception { @@ -416,9 +387,7 @@ public class RangeMarkerTest extends LightPlatformTestCase { assertEquals(buffer.toString(), marker.getDocument().getText()); - assertTrue(marker.isValid()); - assertEquals(3, marker.getStartOffset()); - assertEquals(6, marker.getEndOffset()); + assertValidMarker(marker, 3, 6); } public void testPsi2DocMergeReplaceAfterAdd() throws Exception { @@ -443,9 +412,7 @@ public class RangeMarkerTest extends LightPlatformTestCase { assertEquals(buffer.toString(), marker.getDocument().getText()); - assertTrue(marker.isValid()); - assertEquals(3, marker.getStartOffset()); - assertEquals(6, marker.getEndOffset()); + assertValidMarker(marker, 3, 6); } public void testPsi2DocMergeReplaceWithMultipleAdditions() throws Exception { @@ -469,9 +436,7 @@ public class RangeMarkerTest extends LightPlatformTestCase { assertEquals(buffer.toString(), marker.getDocument().getText()); - assertTrue(marker.isValid()); - assertEquals(2, marker.getStartOffset()); - assertEquals(5, marker.getEndOffset()); + assertValidMarker(marker, 2, 5); } public void testPsi2DocMergeMultipleAdditionsWithReplace() throws Exception { @@ -498,9 +463,7 @@ public class RangeMarkerTest extends LightPlatformTestCase { assertEquals(buffer.toString(), marker.getDocument().getText()); - assertTrue(marker.isValid()); - assertEquals(2, marker.getStartOffset()); - assertEquals(5, marker.getEndOffset()); + assertValidMarker(marker, 2, 5); } public void testPsi2DocSurround() throws Exception { @@ -526,9 +489,7 @@ public class RangeMarkerTest extends LightPlatformTestCase { assertEquals(buffer.toString(), marker.getDocument().getText()); - assertTrue(marker.isValid()); - assertEquals(2, marker.getStartOffset()); - assertEquals(7, marker.getEndOffset()); + assertValidMarker(marker, 2, 7); } public void testPsi2DocForwardRangesChanges() throws Exception { @@ -551,9 +512,13 @@ public class RangeMarkerTest extends LightPlatformTestCase { assertEquals(buffer.toString(), document.getText()); + assertValidMarker(marker, 3, 8); + } + + private static void assertValidMarker(@NotNull RangeMarker marker, int start, int end) { assertTrue(marker.isValid()); - assertEquals(3, marker.getStartOffset()); - assertEquals(8, marker.getEndOffset()); + assertEquals(start, marker.getStartOffset()); + assertEquals(end, marker.getEndOffset()); } public void testNested() { @@ -1056,4 +1021,28 @@ public class RangeMarkerTest extends LightPlatformTestCase { assertTrue(marker.isValid()); } + + public void testMoveTextRetargetsMarkers() throws Exception { + RangeMarkerEx marker1 = createMarker("01234567890", 1, 3); + DocumentEx document = (DocumentEx)marker1.getDocument(); + RangeMarker marker2 = document.createRangeMarker(2, 4); + + document.moveText(0, 5, 8); + assertEquals("56701234890", document.getText()); + + assertValidMarker(marker1, 4, 6); + assertValidMarker(marker2, 5, 7); + } + + public void testMoveTextToTheBeginningRetargetsMarkers() throws Exception { + RangeMarkerEx marker1 = createMarker("01234567890", 5, 5); + DocumentEx document = (DocumentEx)marker1.getDocument(); + RangeMarker marker2 = document.createRangeMarker(5, 7); + + document.moveText(4, 7, 1); + assertEquals("04561237890", document.getText()); + + assertValidMarker(marker1, 2, 2); + assertValidMarker(marker2, 2, 4); + } } diff --git a/platform/testFramework/src/com/intellij/mock/MockDocument.java b/platform/testFramework/src/com/intellij/mock/MockDocument.java index ebe9888f4c86..beb5c3383a55 100644 --- a/platform/testFramework/src/com/intellij/mock/MockDocument.java +++ b/platform/testFramework/src/com/intellij/mock/MockDocument.java @@ -127,7 +127,7 @@ public class MockDocument implements DocumentEx { } @Override - public void moveText(int srcStart, int srcEnd, int dstStart, int dstEnd) { + public void moveText(int srcStart, int srcEnd, int dstOffset) { // TODO den implement throw new UnsupportedOperationException(); } diff --git a/platform/testFramework/src/com/intellij/testFramework/LightPlatformTestCase.java b/platform/testFramework/src/com/intellij/testFramework/LightPlatformTestCase.java index e7e6aa9a64a0..992d8d512abc 100644 --- a/platform/testFramework/src/com/intellij/testFramework/LightPlatformTestCase.java +++ b/platform/testFramework/src/com/intellij/testFramework/LightPlatformTestCase.java @@ -193,7 +193,7 @@ public abstract class LightPlatformTestCase extends UsefulTestCase implements Da private static void initProject(final LightProjectDescriptor descriptor) throws Exception { ourProjectDescriptor = descriptor; - final File projectFile = FileUtil.createTempFile("lighttemp", ProjectFileType.DOT_DEFAULT_EXTENSION); + final File projectFile = FileUtil.createTempFile("light_temp_", ProjectFileType.DOT_DEFAULT_EXTENSION); new WriteCommandAction.Simple(null) { @Override diff --git a/platform/testFramework/src/com/intellij/testFramework/PlatformTestUtil.java b/platform/testFramework/src/com/intellij/testFramework/PlatformTestUtil.java index 3a6c9d5b912c..7f6130985b7d 100644 --- a/platform/testFramework/src/com/intellij/testFramework/PlatformTestUtil.java +++ b/platform/testFramework/src/com/intellij/testFramework/PlatformTestUtil.java @@ -364,10 +364,10 @@ public class PlatformTestUtil { action.actionPerformed(event); } - public static void assertTiming(final String message, final long expected, final long actual) { + public static void assertTiming(final String message, final long expectedMs, final long actual) { if (COVERAGE_ENABLED_BUILD) return; - final long expectedOnMyMachine = Math.max(1, expected * Timings.MACHINE_TIMING / Timings.ETALON_TIMING); + final long expectedOnMyMachine = Math.max(1, expectedMs * Timings.MACHINE_TIMING / Timings.ETALON_TIMING); final double acceptableChangeFactor = 1.1; // Allow 10% more in case of test machine is busy. @@ -378,7 +378,7 @@ public class PlatformTestUtil { } logMessage += ". Expected on my machine: " + expectedOnMyMachine + "." + " Actual: " + actual + "." + - " Expected on Standard machine: " + expected + ";" + + " Expected on Standard machine: " + expectedMs + ";" + " Actual on Standard: " + actual * Timings.ETALON_TIMING / Timings.MACHINE_TIMING + ";" + " Timings: CPU=" + Timings.CPU_TIMING + ", I/O=" + Timings.IO_TIMING + "." + @@ -400,8 +400,8 @@ public class PlatformTestUtil { /** * example usage: startPerformanceTest("calculating pi",100, testRunnable).cpuBound().assertTiming(); */ - public static TestInfo startPerformanceTest(@NonNls @NotNull String message, int expected, @NotNull ThrowableRunnable test) { - return new TestInfo(test, expected,message); + public static TestInfo startPerformanceTest(@NonNls @NotNull String message, int expectedMs, @NotNull ThrowableRunnable test) { + return new TestInfo(test, expectedMs,message); } // calculates average of the median values in the selected part of the array. E.g. for part=3 returns average in the middle third. @@ -430,7 +430,7 @@ public class PlatformTestUtil { public static class TestInfo { private final ThrowableRunnable test; // runnable to measure - private final int expected; // millis the test is expected to run + private final int expectedMs; // millis the test is expected to run private ThrowableRunnable setup; // to run before each test private boolean usesAllCPUCores; // true if the test runs faster on multi-core private int attempts = 4; // number of retries if performance failed @@ -438,10 +438,10 @@ public class PlatformTestUtil { private boolean adjustForIO = true; // true if test uses IO, timings need to be re-calibrated according to this agent disk performance private boolean adjustForCPU = true; // true if test uses CPU, timings need to be re-calibrated according to this agent CPU speed - private TestInfo(@NotNull ThrowableRunnable test, int expected, String message) { + private TestInfo(@NotNull ThrowableRunnable test, int expectedMs, String message) { this.test = test; - this.expected = expected; - assert expected > 0 : "Expected must be > 0. Was: "+ expected; + this.expectedMs = expectedMs; + assert expectedMs > 0 : "Expected must be > 0. Was: "+ expectedMs; this.message = message; } @@ -452,7 +452,7 @@ public class PlatformTestUtil { public TestInfo attempts(int attempts) { this.attempts = attempts; return this; } public void assertTiming() { - assert expected != 0 : "Must call .expect() before run test"; + assert expectedMs != 0 : "Must call .expect() before run test"; if (COVERAGE_ENABLED_BUILD) return; while (true) { @@ -469,7 +469,7 @@ public class PlatformTestUtil { long finish = System.currentTimeMillis(); long duration = finish - start; - int expectedOnMyMachine = expected; + int expectedOnMyMachine = expectedMs; if (adjustForCPU) { expectedOnMyMachine = adjust(expectedOnMyMachine, Timings.CPU_TIMING, Timings.ETALON_CPU_TIMING); diff --git a/platform/testFramework/testSrc/com/intellij/testFramework/vcs/TestClientRunner.java b/platform/testFramework/testSrc/com/intellij/testFramework/vcs/TestClientRunner.java index 923520c68bd4..4f7b3c6dbcd4 100644 --- a/platform/testFramework/testSrc/com/intellij/testFramework/vcs/TestClientRunner.java +++ b/platform/testFramework/testSrc/com/intellij/testFramework/vcs/TestClientRunner.java @@ -91,7 +91,7 @@ public class TestClientRunner { } final CapturingProcessHandler handler = new CapturingProcessHandler(clientProcess, CharsetToolkit.getDefaultSystemCharset()); - final ProcessOutput result = handler.runProcess(60*1000); + final ProcessOutput result = handler.runProcess(100*1000); if (myTraceClient || result.isTimeout()) { ChangeListManagerImpl.log("*** result: " + result.getExitCode()); final String out = result.getStdout().trim(); diff --git a/platform/util/src/com/intellij/util/ui/MacUIUtil.java b/platform/util/src/com/intellij/util/ui/MacUIUtil.java index 61abf6e95954..93d63e16555f 100644 --- a/platform/util/src/com/intellij/util/ui/MacUIUtil.java +++ b/platform/util/src/com/intellij/util/ui/MacUIUtil.java @@ -44,6 +44,46 @@ public class MacUIUtil { private MacUIUtil() { } + public static void paintFocusRing(Graphics2D g2d, Color ringColor, Rectangle bounds) { + int correction = UIUtil.isUnderDarcula() ? 50 : 0; + final Color[] colors = new Color[]{ + ColorUtil.toAlpha(ringColor, 180 - correction), + ColorUtil.toAlpha(ringColor, 120 - correction), + ColorUtil.toAlpha(ringColor, 70 - correction), + ColorUtil.toAlpha(ringColor, 100 - correction), + ColorUtil.toAlpha(ringColor, 50 - correction) + }; + + final Object oldAntialiasingValue = g2d.getRenderingHint(RenderingHints.KEY_ANTIALIASING); + final Object oldStrokeControlValue = g2d.getRenderingHint(RenderingHints.KEY_STROKE_CONTROL); + + g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, + USE_QUARTZ ? RenderingHints.VALUE_STROKE_PURE : RenderingHints.VALUE_STROKE_NORMALIZE); + + + final Rectangle r = new Rectangle(bounds.x - 3, bounds.y - 3, bounds.width + 6, bounds.height + 6); + + g2d.setColor(colors[0]); + g2d.drawRoundRect(r.x + 2, r.y + 2, r.width - 5, r.height - 5, 5, 5); + + g2d.setColor(colors[1]); + g2d.drawRoundRect(r.x + 1, r.y + 1, r.width - 3, r.height - 3, 7, 7); + + g2d.setColor(colors[2]); + g2d.drawRoundRect(r.x, r.y, r.width - 1, r.height - 1, 9, 9); + + g2d.setColor(colors[3]); + g2d.drawRect(r.x + 3, r.y + 3, r.width - 7, r.height - 7); + + g2d.setColor(colors[4]); + g2d.drawRect(r.x + 4, r.y + 4, r.width - 9, r.height - 9); + + // restore rendering hints + g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, oldAntialiasingValue); + g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, oldStrokeControlValue); + } + public static void hideCursor() { if (SystemInfo.isMac && Registry.is("ide.mac.hide.cursor.when.typing")) { Foundation.invoke("NSCursor", "setHiddenUntilMouseMoves:", true); @@ -133,43 +173,7 @@ public class MacUIUtil { } public static void paintTextFieldFocusRing(@NotNull final Graphics2D g2d, @NotNull final Rectangle bounds) { - final Color color = getFocusRingColor(); - final Color[] colors = new Color[]{ - ColorUtil.toAlpha(color, 180), - ColorUtil.toAlpha(color, 120), - ColorUtil.toAlpha(color, 70), - ColorUtil.toAlpha(color, 100), - ColorUtil.toAlpha(color, 50) - }; - - final Object oldAntialiasingValue = g2d.getRenderingHint(RenderingHints.KEY_ANTIALIASING); - final Object oldStrokeControlValue = g2d.getRenderingHint(RenderingHints.KEY_STROKE_CONTROL); - - g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, - USE_QUARTZ ? RenderingHints.VALUE_STROKE_PURE : RenderingHints.VALUE_STROKE_NORMALIZE); - - - final Rectangle r = new Rectangle(bounds.x - 3, bounds.y - 3, bounds.width + 6, bounds.height + 6); - - g2d.setColor(colors[0]); - g2d.drawRoundRect(r.x + 2, r.y + 2, r.width - 5, r.height - 5, 5, 5); - - g2d.setColor(colors[1]); - g2d.drawRoundRect(r.x + 1, r.y + 1, r.width - 3, r.height - 3, 7, 7); - - g2d.setColor(colors[2]); - g2d.drawRoundRect(r.x, r.y, r.width - 1, r.height - 1, 9, 9); - - g2d.setColor(colors[3]); - g2d.drawRect(r.x + 3, r.y + 3, r.width - 7, r.height - 7); - - g2d.setColor(colors[4]); - g2d.drawRect(r.x + 4, r.y + 4, r.width - 9, r.height - 9); - - // restore rendering hints - g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, oldAntialiasingValue); - g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, oldStrokeControlValue); + paintFocusRing(g2d, getFocusRingColor(), bounds); } public static void paintComboboxFocusRing(@NotNull final Graphics2D g2d, @NotNull final Rectangle bounds) { diff --git a/platform/util/testSrc/com/intellij/openapi/util/io/FileAttributesReadingTest.java b/platform/util/testSrc/com/intellij/openapi/util/io/FileAttributesReadingTest.java index deb98101a82a..0b50a0265621 100644 --- a/platform/util/testSrc/com/intellij/openapi/util/io/FileAttributesReadingTest.java +++ b/platform/util/testSrc/com/intellij/openapi/util/io/FileAttributesReadingTest.java @@ -45,7 +45,7 @@ public class FileAttributesReadingTest { @Before public void setUp() throws Exception { - myTempDirectory = FileUtil.createTempDirectory(getClass().getName(), ".tmp"); + myTempDirectory = FileUtil.createTempDirectory(getClass().getSimpleName() + ".", ".tmp"); } @After @@ -325,7 +325,7 @@ public class FileAttributesReadingTest { private static FileAttributes getAttributes(@NotNull final File file, final boolean checkList) { final FileAttributes attributes = FileSystemUtil.getAttributes(file); assertNotNull(attributes); - System.out.println(attributes); + System.out.println(attributes + ": " + file); if (SystemInfo.isWindows && checkList) { final String parent = file.getParent(); diff --git a/platform/vcs-impl/src/com/intellij/openapi/diff/impl/dir/DirDiffPanel.form b/platform/vcs-impl/src/com/intellij/openapi/diff/impl/dir/DirDiffPanel.form index 058754e895dd..609f9a117247 100644 --- a/platform/vcs-impl/src/com/intellij/openapi/diff/impl/dir/DirDiffPanel.form +++ b/platform/vcs-impl/src/com/intellij/openapi/diff/impl/dir/DirDiffPanel.form @@ -91,11 +91,6 @@ - - - - - @@ -106,7 +101,7 @@ - + @@ -121,6 +116,11 @@ + + + + + diff --git a/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/UpdateRequestsQueue.java b/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/UpdateRequestsQueue.java index 17e46f90878b..3ec302258f26 100644 --- a/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/UpdateRequestsQueue.java +++ b/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/UpdateRequestsQueue.java @@ -159,7 +159,7 @@ public class UpdateRequestsQueue { semaphore.down(); myWaitingUpdateCompletionSemaphores.add(semaphore); } - if (!semaphore.waitFor(10000)) { + if (!semaphore.waitFor(100*1000)) { LOG.error("Too long VCS update"); return; } diff --git a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/ui/BreakpointEditor.java b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/ui/BreakpointEditor.java index d4bf5b52e11d..df9a22a52f0a 100644 --- a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/ui/BreakpointEditor.java +++ b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/ui/BreakpointEditor.java @@ -15,10 +15,10 @@ */ package com.intellij.xdebugger.impl.ui; -import com.intellij.openapi.actionSystem.AnAction; -import com.intellij.openapi.actionSystem.AnActionEvent; -import com.intellij.openapi.actionSystem.CompositeShortcutSet; -import com.intellij.openapi.actionSystem.CustomShortcutSet; +import com.intellij.codeInsight.lookup.LookupManager; +import com.intellij.openapi.actionSystem.*; +import com.intellij.openapi.editor.Editor; +import com.intellij.openapi.util.text.StringUtil; import com.intellij.ui.components.labels.LinkLabel; import com.intellij.ui.components.labels.LinkListener; @@ -75,6 +75,14 @@ public class BreakpointEditor { }); final AnAction doneAction = new AnAction() { + @Override + public void update(AnActionEvent e) { + super.update(e); + boolean lookup = LookupManager.getInstance(getEventProject(e)).getActiveLookup() != null; + Editor editor = e.getData(PlatformDataKeys.EDITOR); + e.getPresentation().setEnabled(!lookup && (editor == null || StringUtil.isEmpty(editor.getSelectionModel().getSelectedText())) ); + } + public void actionPerformed(AnActionEvent e) { done(); } diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/controlflow/IfMayBeConditionalInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/controlflow/IfMayBeConditionalInspection.java index d6cbe937e438..003d693e51dd 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/controlflow/IfMayBeConditionalInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/controlflow/IfMayBeConditionalInspection.java @@ -196,6 +196,16 @@ public class IfMayBeConditionalInspection extends BaseInspection { if (!(elseStatement instanceof PsiReturnStatement)) { return; } + final PsiReturnStatement thenReturnStatement = (PsiReturnStatement)thenStatement; + final PsiExpression thenReturnValue = ParenthesesUtils.stripParentheses(thenReturnStatement.getReturnValue()); + if (thenReturnValue instanceof PsiConditionalExpression) { + return; + } + final PsiReturnStatement elseReturnStatement = (PsiReturnStatement)elseStatement; + final PsiExpression elseReturnValue = ParenthesesUtils.stripParentheses(elseReturnStatement.getReturnValue()); + if (elseReturnValue instanceof PsiConditionalExpression) { + return; + } registerStatementError(statement); } else if (thenStatement instanceof PsiExpressionStatement) { @@ -220,6 +230,14 @@ public class IfMayBeConditionalInspection extends BaseInspection { if (!EquivalenceChecker.expressionsAreEquivalent(thenLhs, elseLhs)) { return; } + final PsiExpression thenRhs = ParenthesesUtils.stripParentheses(thenAssignmentExpression.getRExpression()); + if (thenRhs instanceof PsiConditionalExpression) { + return; + } + final PsiExpression elseRhs = ParenthesesUtils.stripParentheses(elseAssignmentExpression.getRExpression()); + if (elseRhs instanceof PsiConditionalExpression) { + return; + } registerStatementError(statement); } else if (reportMethodCalls && thenExpression instanceof PsiMethodCallExpression) { diff --git a/plugins/InspectionGadgets/src/inspectionDescriptions/PublicMethodWithoutLogging.html b/plugins/InspectionGadgets/src/inspectionDescriptions/PublicMethodWithoutLogging.html index 9acf62cd5970..9da75e59d591 100644 --- a/plugins/InspectionGadgets/src/inspectionDescriptions/PublicMethodWithoutLogging.html +++ b/plugins/InspectionGadgets/src/inspectionDescriptions/PublicMethodWithoutLogging.html @@ -1,6 +1,7 @@ -This inspection reports any public method which does not contain a logging statement. +This inspection reports any public method which does not contain a logging statement. This inspection does not report +simple getters and setters.

Use the table below to specify below to specify Logger class names. diff --git a/plugins/InspectionGadgets/test/com/siyeh/igtest/controlflow/if_may_be_conditional/IfMayBeConditional.java b/plugins/InspectionGadgets/test/com/siyeh/igtest/controlflow/if_may_be_conditional/IfMayBeConditional.java index 7eaad4416b06..1109243d24a2 100644 --- a/plugins/InspectionGadgets/test/com/siyeh/igtest/controlflow/if_may_be_conditional/IfMayBeConditional.java +++ b/plugins/InspectionGadgets/test/com/siyeh/igtest/controlflow/if_may_be_conditional/IfMayBeConditional.java @@ -20,4 +20,26 @@ public class IfMayBeConditional { sb.append("DescriptorUtils.getFQName(cd)",0, 1); } } + + int foo4(int a, int b) { + if (a < b) return a; + else return b; + } + + int foo5(int a, int b, int c) { + if (a < b) { + return a; + } else { + return b < c ? b : c; + } + } + + void foo6(int a, int b, int c) { + int i; + if (a < b) { + i = a; + } else { + i = b < c ? b : c; + } + } } diff --git a/plugins/InspectionGadgets/test/com/siyeh/igtest/controlflow/if_may_be_conditional/expected.xml b/plugins/InspectionGadgets/test/com/siyeh/igtest/controlflow/if_may_be_conditional/expected.xml index 6d0c371f2349..3ecb05a6e414 100644 --- a/plugins/InspectionGadgets/test/com/siyeh/igtest/controlflow/if_may_be_conditional/expected.xml +++ b/plugins/InspectionGadgets/test/com/siyeh/igtest/controlflow/if_may_be_conditional/expected.xml @@ -14,4 +14,11 @@ 'if' statement could be replaced with simple conditional expression <code>if</code> could be replaced with simple conditional expression #loc + + + IfMayBeConditional.java + 25 + 'if' statement could be replaced with conditional expression + <code>if</code> could be replaced with conditional expression #loc + \ No newline at end of file diff --git a/plugins/IntelliLang/src/icons/IntelliLangIcons.java b/plugins/IntelliLang/src/icons/IntelliLangIcons.java deleted file mode 100644 index be953a60051a..000000000000 --- a/plugins/IntelliLang/src/icons/IntelliLangIcons.java +++ /dev/null @@ -1,18 +0,0 @@ -package icons; - -import com.intellij.openapi.util.IconLoader; - -import javax.swing.*; - -/** - * NOTE THIS FILE IS AUTO-GENERATED by the build/scripts/icons.gant - * Don't repeat mistakes of others ;-) - */ -public class IntelliLangIcons { - private static Icon load(String path) { - return IconLoader.getIcon(path, IntelliLangIcons.class); - } - - public static final Icon Icon = load("/org/intellij/plugins/intelliLang/icon.png"); // 32x32 - public static final Icon Icon_small = load("/org/intellij/plugins/intelliLang/icon_small.png"); // 16x16 -} diff --git a/plugins/IntelliLang/src/org/intellij/plugins/intelliLang/icon.png b/plugins/IntelliLang/src/org/intellij/plugins/intelliLang/icon.png deleted file mode 100644 index 8479d95afa36..000000000000 Binary files a/plugins/IntelliLang/src/org/intellij/plugins/intelliLang/icon.png and /dev/null differ diff --git a/plugins/IntelliLang/src/org/intellij/plugins/intelliLang/icon_small.png b/plugins/IntelliLang/src/org/intellij/plugins/intelliLang/icon_small.png deleted file mode 100644 index 612cea31dcd6..000000000000 Binary files a/plugins/IntelliLang/src/org/intellij/plugins/intelliLang/icon_small.png and /dev/null differ diff --git a/plugins/IntentionPowerPak/src/com/siyeh/ipp/types/InferLambdaParameterTypeIntention.java b/plugins/IntentionPowerPak/src/com/siyeh/ipp/types/InferLambdaParameterTypeIntention.java index 38362a9798dc..9e9658f0f354 100644 --- a/plugins/IntentionPowerPak/src/com/siyeh/ipp/types/InferLambdaParameterTypeIntention.java +++ b/plugins/IntentionPowerPak/src/com/siyeh/ipp/types/InferLambdaParameterTypeIntention.java @@ -63,7 +63,7 @@ public class InferLambdaParameterTypeIntention extends Intention { if (parameters.length != lambdaParameters.length) return null; for (int i = 0; i < parameters.length; i++) { PsiParameter parameter = parameters[i]; - final PsiType psiType = GenericsUtil.eliminateWildcards(resolveResult.getSubstitutor().substitute(parameter.getType())); + final PsiType psiType = GenericsUtil.eliminateWildcards(LambdaUtil.getSubstitutor(interfaceMethod, resolveResult).substitute(parameter.getType())); if (psiType != null) { buf.append(psiType.getPresentableText()).append(" ").append(lambdaParameters[i].getName()); } diff --git a/plugins/android/jps-plugin/android-jps-plugin.iml b/plugins/android/jps-plugin/android-jps-plugin.iml index 88bff67eb8cc..db00e53362c4 100644 --- a/plugins/android/jps-plugin/android-jps-plugin.iml +++ b/plugins/android/jps-plugin/android-jps-plugin.iml @@ -8,7 +8,6 @@ - diff --git a/plugins/android/jps-plugin/src/org/jetbrains/jps/android/AndroidPackagingBuilder.java b/plugins/android/jps-plugin/src/org/jetbrains/jps/android/AndroidPackagingBuilder.java index 08ac8981423a..98679663b6aa 100644 --- a/plugins/android/jps-plugin/src/org/jetbrains/jps/android/AndroidPackagingBuilder.java +++ b/plugins/android/jps-plugin/src/org/jetbrains/jps/android/AndroidPackagingBuilder.java @@ -25,6 +25,9 @@ import org.jetbrains.jps.incremental.messages.CompilerMessage; import org.jetbrains.jps.incremental.messages.ProgressMessage; import org.jetbrains.jps.incremental.storage.TimestampStorage; import org.jetbrains.jps.incremental.storage.TimestampValidityState; +import org.jetbrains.jps.model.JpsProject; +import org.jetbrains.jps.model.java.JpsJavaExtensionService; +import org.jetbrains.jps.model.java.compiler.JpsCompilerExcludes; import org.jetbrains.jps.model.module.JpsModule; import java.io.File; @@ -377,7 +380,7 @@ public class AndroidPackagingBuilder extends ProjectLevelBuilder { final List additionalNativeLibs = extension.getAdditionalNativeLibs(); final AndroidFileSetState currentFileSetState = - buildCurrentApkBuilderState(context.getProjectDescriptor().project, resPackagePath, classesDexFilePath, nativeLibDirs, sourceRoots, + buildCurrentApkBuilderState(context.getProjectDescriptor().jpsProject, resPackagePath, classesDexFilePath, nativeLibDirs, sourceRoots, externalJars, release); final AndroidApkBuilderConfigState currentApkBuilderConfigState = @@ -397,7 +400,7 @@ public class AndroidPackagingBuilder extends ProjectLevelBuilder { final Map> messages = AndroidApkBuilder .execute(resPackagePath, classesDexFilePath, sourceRoots, externalJars, nativeLibDirs, additionalNativeLibs, - outputApkPath, release, sdkPath, customKeyStorePath, new MyExcludedSourcesFilter(context.getProjectDescriptor().project)); + outputApkPath, release, sdkPath, customKeyStorePath, new MyExcludedSourcesFilter(context.getProjectDescriptor().jpsProject)); AndroidJpsUtil.addMessages(context, messages, BUILDER_NAME, module.getName()); final boolean success = messages.get(AndroidCompilerMessageKind.ERROR).isEmpty(); @@ -408,7 +411,7 @@ public class AndroidPackagingBuilder extends ProjectLevelBuilder { } @SuppressWarnings("unchecked") - private static AndroidFileSetState buildCurrentApkBuilderState(@NotNull Project project, + private static AndroidFileSetState buildCurrentApkBuilderState(@NotNull JpsProject project, @NotNull String resPackagePath, @NotNull String classesDexFilePath, @NotNull String[] nativeLibDirs, @@ -562,10 +565,10 @@ public class AndroidPackagingBuilder extends ProjectLevelBuilder { } private static class MyExcludedSourcesFilter implements Condition { - private final CompilerExcludes myExcludes; + private final JpsCompilerExcludes myExcludes; - public MyExcludedSourcesFilter(@NotNull Project project) { - myExcludes = project.getCompilerConfiguration().getExcludes(); + public MyExcludedSourcesFilter(@NotNull JpsProject project) { + myExcludes = JpsJavaExtensionService.getInstance().getOrCreateCompilerConfiguration(project).getCompilerExcludes(); } @Override diff --git a/plugins/copyright/src/META-INF/plugin.xml b/plugins/copyright/src/META-INF/plugin.xml index cdede4285882..9bd98018d7f6 100644 --- a/plugins/copyright/src/META-INF/plugin.xml +++ b/plugins/copyright/src/META-INF/plugin.xml @@ -38,15 +38,15 @@ - + - + - + diff --git a/plugins/copyright/src/icons/CopyrightIcons.java b/plugins/copyright/src/icons/CopyrightIcons.java deleted file mode 100644 index 6c1de5210c45..000000000000 --- a/plugins/copyright/src/icons/CopyrightIcons.java +++ /dev/null @@ -1,18 +0,0 @@ -package icons; - -import com.intellij.openapi.util.IconLoader; - -import javax.swing.*; - -/** - * NOTE THIS FILE IS AUTO-GENERATED by the build/scripts/icons.gant - * Don't repeat mistakes of others ;-) - */ -public class CopyrightIcons { - private static Icon load(String path) { - return IconLoader.getIcon(path, CopyrightIcons.class); - } - - public static final Icon Copyright18x18 = load("/resources/copyright18x18.png"); // 18x18 - public static final Icon Copyright32x32 = load("/resources/copyright32x32.png"); // 32x32 -} diff --git a/plugins/copyright/src/resources/copyright18x18.png b/plugins/copyright/src/resources/copyright18x18.png deleted file mode 100644 index f3be45867f8c..000000000000 Binary files a/plugins/copyright/src/resources/copyright18x18.png and /dev/null differ diff --git a/plugins/copyright/src/resources/copyright32x32.png b/plugins/copyright/src/resources/copyright32x32.png deleted file mode 100644 index d6abdc758a05..000000000000 Binary files a/plugins/copyright/src/resources/copyright32x32.png and /dev/null differ diff --git a/plugins/devkit/jps-plugin/devkit-jps-plugin.iml b/plugins/devkit/jps-plugin/devkit-jps-plugin.iml index 71a64138555c..82ad67edbcab 100644 --- a/plugins/devkit/jps-plugin/devkit-jps-plugin.iml +++ b/plugins/devkit/jps-plugin/devkit-jps-plugin.iml @@ -8,7 +8,6 @@ - diff --git a/plugins/generate-tostring/resources/configurableToStringPlugin.png b/plugins/generate-tostring/resources/configurableToStringPlugin.png deleted file mode 100644 index 015501fa8905..000000000000 Binary files a/plugins/generate-tostring/resources/configurableToStringPlugin.png and /dev/null differ diff --git a/plugins/generate-tostring/resources/icons/GenerateTostringIcons.java b/plugins/generate-tostring/resources/icons/GenerateTostringIcons.java deleted file mode 100644 index 05d29ced7697..000000000000 --- a/plugins/generate-tostring/resources/icons/GenerateTostringIcons.java +++ /dev/null @@ -1,17 +0,0 @@ -package icons; - -import com.intellij.openapi.util.IconLoader; - -import javax.swing.*; - -/** - * NOTE THIS FILE IS AUTO-GENERATED by the build/scripts/icons.gant - * Don't repeat mistakes of others ;-) - */ -public class GenerateTostringIcons { - private static Icon load(String path) { - return IconLoader.getIcon(path, GenerateTostringIcons.class); - } - - public static final Icon ConfigurableToStringPlugin = load("/configurableToStringPlugin.png"); // 32x33 -} diff --git a/plugins/groovy/jetgroovy.iml b/plugins/groovy/jetgroovy.iml index c74d30f5eab7..bb64ecbe2d34 100644 --- a/plugins/groovy/jetgroovy.iml +++ b/plugins/groovy/jetgroovy.iml @@ -34,6 +34,7 @@ + diff --git a/jps/model/jps-model.iml b/plugins/groovy/jps-plugin/groovy-jps-plugin.iml similarity index 65% rename from jps/model/jps-model.iml rename to plugins/groovy/jps-plugin/groovy-jps-plugin.iml index 3571c5219fe6..c55d620328f1 100644 --- a/jps/model/jps-model.iml +++ b/plugins/groovy/jps-plugin/groovy-jps-plugin.iml @@ -7,11 +7,9 @@ - - - - + + diff --git a/plugins/groovy/rt/src/META-INF/services/org.jetbrains.jps.incremental.BuilderService b/plugins/groovy/jps-plugin/src/META-INF/services/org.jetbrains.jps.incremental.BuilderService similarity index 100% rename from plugins/groovy/rt/src/META-INF/services/org.jetbrains.jps.incremental.BuilderService rename to plugins/groovy/jps-plugin/src/META-INF/services/org.jetbrains.jps.incremental.BuilderService diff --git a/plugins/groovy/rt/src/org/jetbrains/jps/incremental/groovy/GroovyBuilder.java b/plugins/groovy/jps-plugin/src/org/jetbrains/jps/incremental/groovy/GroovyBuilder.java similarity index 94% rename from plugins/groovy/rt/src/org/jetbrains/jps/incremental/groovy/GroovyBuilder.java rename to plugins/groovy/jps-plugin/src/org/jetbrains/jps/incremental/groovy/GroovyBuilder.java index 4bf2560a3e00..bb5471c6eef2 100644 --- a/plugins/groovy/rt/src/org/jetbrains/jps/incremental/groovy/GroovyBuilder.java +++ b/plugins/groovy/jps-plugin/src/org/jetbrains/jps/incremental/groovy/GroovyBuilder.java @@ -7,13 +7,11 @@ import com.intellij.openapi.util.io.FileUtil; import com.intellij.util.ArrayUtil; import com.intellij.util.Consumer; import com.intellij.util.SystemProperties; -import groovy.util.CharsetToolkit; import org.jetbrains.annotations.Nullable; import org.jetbrains.asm4.ClassReader; -import org.jetbrains.ether.dependencyView.Callbacks; -import org.jetbrains.ether.dependencyView.Mappings; -import org.jetbrains.groovy.compiler.rt.GroovyCompilerWrapper; import org.jetbrains.jps.ModuleChunk; +import org.jetbrains.jps.builders.java.dependencyView.Callbacks; +import org.jetbrains.jps.builders.java.dependencyView.Mappings; import org.jetbrains.jps.cmdline.ClasspathBootstrap; import org.jetbrains.jps.incremental.*; import org.jetbrains.jps.incremental.fs.RootDescriptor; @@ -25,7 +23,9 @@ import org.jetbrains.jps.incremental.messages.FileGeneratedEvent; import org.jetbrains.jps.incremental.messages.ProgressMessage; import org.jetbrains.jps.incremental.storage.SourceToOutputMapping; import org.jetbrains.jps.javac.OutputFileObject; +import org.jetbrains.jps.model.java.JpsJavaExtensionService; import org.jetbrains.jps.model.java.JpsJavaSdkType; +import org.jetbrains.jps.model.java.compiler.JpsJavaCompilerConfiguration; import org.jetbrains.jps.model.library.sdk.JpsSdk; import org.jetbrains.jps.model.module.JpsModule; import org.jetbrains.jps.service.SharedThreadPool; @@ -95,7 +95,7 @@ public class GroovyBuilder extends ModuleLevelBuilder { "org.jetbrains.groovy.compiler.rt.GroovycRunner", Collections.emptyList(), new ArrayList(generateClasspath(context, chunk)), Arrays.asList("-Xmx384m", - "-Dfile.encoding=" + CharsetToolkit.getDefaultSystemCharset().name()/*, + "-Dfile.encoding=" + System.getProperty("file.encoding")/*, "-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5239"*/), Arrays.asList(myForStubs ? "stubs" : "groovyc", tempFile.getPath()) @@ -283,7 +283,7 @@ public class GroovyBuilder extends ModuleLevelBuilder { final Set cp = new LinkedHashSet(); //groovy_rt.jar // IMPORTANT! must be the first in classpath - cp.add(ClasspathBootstrap.getResourcePath(GroovyCompilerWrapper.class).getPath()); + cp.add(getGroovyRtRoot().getPath()); for (File file : context.getProjectPaths().getCompilationClasspathFiles(chunk, chunk.isTests(), false, false)) { cp.add(FileUtil.toCanonicalPath(file.getPath())); @@ -291,18 +291,27 @@ public class GroovyBuilder extends ModuleLevelBuilder { return new ArrayList(cp); } + private static File getGroovyRtRoot() { + File root = ClasspathBootstrap.getResourcePath(GroovyBuilder.class); + if (root.isFile()) { + return new File(root.getParentFile().getParentFile(), "groovy_rt.jar"); + } + return new File(root.getParentFile(), "groovy_rt"); + } + private static boolean isGroovyFile(String path) { return path.endsWith(".groovy") || path.endsWith(".gpp"); } private static Map buildClassToSourceMap(ModuleChunk chunk, CompileContext context, Set toCompilePaths, Map finalOutputs) throws IOException { final Map class2Src = new HashMap(); + JpsJavaCompilerConfiguration configuration = JpsJavaExtensionService.getInstance().getOrCreateCompilerConfiguration(context.getProjectDescriptor().jpsProject); for (ModuleBuildTarget target : chunk.getTargets()) { String moduleOutputPath = finalOutputs.get(target.getModule()); final SourceToOutputMapping srcToOut = context.getProjectDescriptor().dataManager.getSourceToOutputMap(target); for (String src : srcToOut.getKeys()) { if (!toCompilePaths.contains(src) && isGroovyFile(src) && - !context.getProjectDescriptor().project.getCompilerConfiguration().getExcludes().isExcluded(new File(src))) { + !configuration.getCompilerExcludes().isExcluded(new File(src))) { final Collection outs = srcToOut.getState(src); if (outs != null) { for (String out : outs) { diff --git a/plugins/groovy/rt/src/org/jetbrains/jps/incremental/groovy/GroovyBuilderService.java b/plugins/groovy/jps-plugin/src/org/jetbrains/jps/incremental/groovy/GroovyBuilderService.java similarity index 100% rename from plugins/groovy/rt/src/org/jetbrains/jps/incremental/groovy/GroovyBuilderService.java rename to plugins/groovy/jps-plugin/src/org/jetbrains/jps/incremental/groovy/GroovyBuilderService.java diff --git a/plugins/groovy/rt/src/org/jetbrains/jps/incremental/groovy/GroovycOSProcessHandler.java b/plugins/groovy/jps-plugin/src/org/jetbrains/jps/incremental/groovy/GroovycOSProcessHandler.java similarity index 81% rename from plugins/groovy/rt/src/org/jetbrains/jps/incremental/groovy/GroovycOSProcessHandler.java rename to plugins/groovy/jps-plugin/src/org/jetbrains/jps/incremental/groovy/GroovycOSProcessHandler.java index c95a7176573a..a78d701ff710 100644 --- a/plugins/groovy/rt/src/org/jetbrains/jps/incremental/groovy/GroovycOSProcessHandler.java +++ b/plugins/groovy/jps-plugin/src/org/jetbrains/jps/incremental/groovy/GroovycOSProcessHandler.java @@ -25,7 +25,8 @@ import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.Consumer; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.Nullable; -import org.jetbrains.groovy.compiler.rt.GroovycRunner; +import org.jetbrains.groovy.compiler.rt.GroovyCompilerMessageCategories; +import org.jetbrains.groovy.compiler.rt.GroovyRtConstants; import org.jetbrains.jps.incremental.messages.BuildMessage; import org.jetbrains.jps.incremental.messages.CompilerMessage; @@ -80,12 +81,12 @@ public class GroovycOSProcessHandler extends BaseOSProcessHandler { private void parseOutput(String text) { final String trimmed = text.trim(); - if (trimmed.startsWith(GroovycRunner.PRESENTABLE_MESSAGE)) { - updateStatus(trimmed.substring(GroovycRunner.PRESENTABLE_MESSAGE.length())); + if (trimmed.startsWith(GroovyRtConstants.PRESENTABLE_MESSAGE)) { + updateStatus(trimmed.substring(GroovyRtConstants.PRESENTABLE_MESSAGE.length())); return; } - if (GroovycRunner.CLEAR_PRESENTABLE.equals(trimmed)) { + if (GroovyRtConstants.CLEAR_PRESENTABLE.equals(trimmed)) { updateStatus(null); return; } @@ -95,33 +96,33 @@ public class GroovycOSProcessHandler extends BaseOSProcessHandler { outputBuffer.append(text); //compiled start marker have to be in the beginning on each string - if (outputBuffer.indexOf(GroovycRunner.COMPILED_START) != -1) { - if (outputBuffer.indexOf(GroovycRunner.COMPILED_END) == -1) { + if (outputBuffer.indexOf(GroovyRtConstants.COMPILED_START) != -1) { + if (outputBuffer.indexOf(GroovyRtConstants.COMPILED_END) == -1) { return; } - final String compiled = handleOutputBuffer(GroovycRunner.COMPILED_START, GroovycRunner.COMPILED_END); - final List list = StringUtil.split(compiled, GroovycRunner.SEPARATOR); + final String compiled = handleOutputBuffer(GroovyRtConstants.COMPILED_START, GroovyRtConstants.COMPILED_END); + final List list = StringUtil.split(compiled, GroovyRtConstants.SEPARATOR); String outputPath = list.get(0); String sourceFile = list.get(1); ContainerUtil.addIfNotNull(getOutputItem(outputPath, sourceFile), myCompiledItems); } - else if (outputBuffer.indexOf(GroovycRunner.TO_RECOMPILE_START) != -1) { - if (outputBuffer.indexOf(GroovycRunner.TO_RECOMPILE_END) != -1) { - String url = handleOutputBuffer(GroovycRunner.TO_RECOMPILE_START, GroovycRunner.TO_RECOMPILE_END); + else if (outputBuffer.indexOf(GroovyRtConstants.TO_RECOMPILE_START) != -1) { + if (outputBuffer.indexOf(GroovyRtConstants.TO_RECOMPILE_END) != -1) { + String url = handleOutputBuffer(GroovyRtConstants.TO_RECOMPILE_START, GroovyRtConstants.TO_RECOMPILE_END); toRecompileFiles.add(new File(url)); } } - else if (outputBuffer.indexOf(GroovycRunner.MESSAGES_START) != -1) { - if (!(outputBuffer.indexOf(GroovycRunner.MESSAGES_END) != -1)) { + else if (outputBuffer.indexOf(GroovyRtConstants.MESSAGES_START) != -1) { + if (outputBuffer.indexOf(GroovyRtConstants.MESSAGES_END) == -1) { return; } - text = handleOutputBuffer(GroovycRunner.MESSAGES_START, GroovycRunner.MESSAGES_END); + text = handleOutputBuffer(GroovyRtConstants.MESSAGES_START, GroovyRtConstants.MESSAGES_END); - List tokens = StringUtil.split(text, GroovycRunner.SEPARATOR); + List tokens = StringUtil.split(text, GroovyRtConstants.SEPARATOR); LOG.assertTrue(tokens.size() > 4, "Wrong number of output params"); String category = tokens.get(0); @@ -143,9 +144,9 @@ public class GroovycOSProcessHandler extends BaseOSProcessHandler { columnInt = 0; } - BuildMessage.Kind kind = category.equals(org.jetbrains.groovy.compiler.rt.CompilerMessage.ERROR) + BuildMessage.Kind kind = category.equals(GroovyCompilerMessageCategories.ERROR) ? BuildMessage.Kind.ERROR - : category.equals(org.jetbrains.groovy.compiler.rt.CompilerMessage.WARNING) + : category.equals(GroovyCompilerMessageCategories.WARNING) ? BuildMessage.Kind.WARNING : BuildMessage.Kind.INFO; @@ -224,7 +225,7 @@ public class GroovycOSProcessHandler extends BaseOSProcessHandler { final Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tempFile))); try { for (String file : changedSources) { - writer.write(GroovycRunner.SRC_FILE + "\n"); + writer.write(GroovyRtConstants.SRC_FILE + "\n"); writer.write(file); writer.write("\n"); } @@ -234,21 +235,21 @@ public class GroovycOSProcessHandler extends BaseOSProcessHandler { writer.write(entry.getKey() + "\n"); writer.write(entry.getValue() + "\n"); } - writer.write(GroovycRunner.END + "\n"); + writer.write(GroovyRtConstants.END + "\n"); - writer.write(GroovycRunner.PATCHERS + "\n"); + writer.write(GroovyRtConstants.PATCHERS + "\n"); for (String patcher : patchers) { writer.write(patcher + "\n"); } - writer.write(GroovycRunner.END + "\n"); + writer.write(GroovyRtConstants.END + "\n"); if (encoding != null) { - writer.write(GroovycRunner.ENCODING + "\n"); + writer.write(GroovyRtConstants.ENCODING + "\n"); writer.write(encoding + "\n"); } - writer.write(GroovycRunner.OUTPUTPATH + "\n"); + writer.write(GroovyRtConstants.OUTPUTPATH + "\n"); writer.write(outputDir); writer.write("\n"); - writer.write(GroovycRunner.FINAL_OUTPUTPATH + "\n"); + writer.write(GroovyRtConstants.FINAL_OUTPUTPATH + "\n"); writer.write(finalOutput); writer.write("\n"); } diff --git a/plugins/groovy/resources/standardDsls/closuresInMethod.gdsl b/plugins/groovy/resources/standardDsls/closuresInMethod.gdsl index c8799b342d75..ff8b660db0fe 100644 --- a/plugins/groovy/resources/standardDsls/closuresInMethod.gdsl +++ b/plugins/groovy/resources/standardDsls/closuresInMethod.gdsl @@ -1,24 +1,20 @@ contributor(ctype: 'org.codehaus.groovy.runtime.DefaultGroovyMethods') { - closureInMethod(method: [name: 'eachWithIndex', params: ['java.lang.Object', 'groovy.lang.Closure']], params: [entry: null, i: 'int']) + closureInMethod(method: [name: 'eachWithIndex', params: ['T', 'groovy.lang.Closure']], params: [entry: null, i: 'int']) closureInMethod(method: [name: 'inject', params: ['java.lang.Object', 'groovy.lang.Closure']], params: [acc: null, val: null]) closureInMethod(method: [name: 'min', params: ['java.util.Collection', 'groovy.lang.Closure']], params: [a: null, b: null]) closureInMethod(method: [name: 'min', params: ['java.util.Iterator', 'groovy.lang.Closure']], params: [a: null, b: null]) closureInMethod(method: [name: 'min', params: ['java.util.Map', 'groovy.lang.Closure']], params: [a: null, b: null]) - /* closureInMethod(method: [name: 'min', params: ['java.util.Collection', 'groovy.lang.Closure']], params: [a: null]) closureInMethod(method: [name: 'min', params: ['java.util.Iterator', 'groovy.lang.Closure']], params: [a: null]) closureInMethod(method: [name: 'min', params: ['java.util.Map', 'groovy.lang.Closure']], params: [a: null]) - */ closureInMethod(method: [name: 'max', params: ['java.util.Collection', 'groovy.lang.Closure']], params: [a: null, b: null]) closureInMethod(method: [name: 'max', params: ['java.util.Iterator', 'groovy.lang.Closure']], params: [a: null, b: null]) closureInMethod(method: [name: 'max', params: ['java.util.Map', 'groovy.lang.Closure']], params: [a: null, b: null]) - /* closureInMethod(method: [name: 'max', params: ['java.util.Collection', 'groovy.lang.Closure']], params: [a: null]) closureInMethod(method: [name: 'max', params: ['java.util.Iterator', 'groovy.lang.Closure']], params: [a: null]) closureInMethod(method: [name: 'max', params: ['java.util.Map', 'groovy.lang.Closure']], params: [a: null]) - */ } diff --git a/plugins/groovy/rt-constants/groovy-rt-constants.iml b/plugins/groovy/rt-constants/groovy-rt-constants.iml new file mode 100644 index 000000000000..d5c074327501 --- /dev/null +++ b/plugins/groovy/rt-constants/groovy-rt-constants.iml @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/plugins/groovy/rt-constants/src/org/jetbrains/groovy/compiler/rt/GroovyCompilerMessageCategories.java b/plugins/groovy/rt-constants/src/org/jetbrains/groovy/compiler/rt/GroovyCompilerMessageCategories.java new file mode 100644 index 000000000000..43e9d74b7b86 --- /dev/null +++ b/plugins/groovy/rt-constants/src/org/jetbrains/groovy/compiler/rt/GroovyCompilerMessageCategories.java @@ -0,0 +1,26 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.groovy.compiler.rt; + +/** + * @author nik + */ +public class GroovyCompilerMessageCategories { + public static final String ERROR = "error"; + public static final String WARNING = "warning"; + public static final String INFORMATION = "information"; + public static final String STATISTICS = "statistic"; +} diff --git a/plugins/groovy/rt-constants/src/org/jetbrains/groovy/compiler/rt/GroovyRtConstants.java b/plugins/groovy/rt-constants/src/org/jetbrains/groovy/compiler/rt/GroovyRtConstants.java new file mode 100644 index 000000000000..ff764c09d0a7 --- /dev/null +++ b/plugins/groovy/rt-constants/src/org/jetbrains/groovy/compiler/rt/GroovyRtConstants.java @@ -0,0 +1,38 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jetbrains.groovy.compiler.rt; + +/** + * @author nik + */ +public class GroovyRtConstants { + public static final String PATCHERS = "patchers"; + public static final String ENCODING = "encoding"; + public static final String OUTPUTPATH = "outputpath"; + public static final String FINAL_OUTPUTPATH = "final_outputpath"; + public static final String END = "end"; + public static final String SRC_FILE = "src_file"; + public static final String COMPILED_START = "%%c"; + public static final String COMPILED_END = "/%c"; + public static final String TO_RECOMPILE_START = "%%rc"; + public static final String TO_RECOMPILE_END = "/%rc"; + public static final String MESSAGES_START = "%%m"; + public static final String MESSAGES_END = "/%m"; + public static final String SEPARATOR = "#%%#%%%#%%%%%%%%%#"; + //public static final Controller ourController = initController(); + public static final String PRESENTABLE_MESSAGE = "@#$%@# Presentable:"; + public static final String CLEAR_PRESENTABLE = "$@#$%^ CLEAR_PRESENTABLE"; +} diff --git a/plugins/groovy/rt/groovy_rt.iml b/plugins/groovy/rt/groovy_rt.iml index 5fc709a6b9d8..dd7338a70348 100644 --- a/plugins/groovy/rt/groovy_rt.iml +++ b/plugins/groovy/rt/groovy_rt.iml @@ -10,6 +10,7 @@ + diff --git a/plugins/groovy/rt/src/org/jetbrains/groovy/compiler/rt/CompilerMessage.java b/plugins/groovy/rt/src/org/jetbrains/groovy/compiler/rt/CompilerMessage.java index a1d3da1b33e8..66dc3eec3989 100644 --- a/plugins/groovy/rt/src/org/jetbrains/groovy/compiler/rt/CompilerMessage.java +++ b/plugins/groovy/rt/src/org/jetbrains/groovy/compiler/rt/CompilerMessage.java @@ -6,10 +6,6 @@ public class CompilerMessage { private final String myUrl; private final int myLineNum; private final int myColumnNum; - public static final String ERROR = "error"; - public static final String WARNING = "warning"; - public static final String INFORMATION = "information"; - public static final String STATISTICS = "statistic"; public CompilerMessage(String category, String message, String url, int lineNum, int columnNum) { myCategory = category; diff --git a/plugins/groovy/rt/src/org/jetbrains/groovy/compiler/rt/GroovyCompilerWrapper.java b/plugins/groovy/rt/src/org/jetbrains/groovy/compiler/rt/GroovyCompilerWrapper.java index a9ce6893f049..6e12cf688c44 100644 --- a/plugins/groovy/rt/src/org/jetbrains/groovy/compiler/rt/GroovyCompilerWrapper.java +++ b/plugins/groovy/rt/src/org/jetbrains/groovy/compiler/rt/GroovyCompilerWrapper.java @@ -127,7 +127,7 @@ public class GroovyCompilerWrapper { private static void addWarnings(ErrorCollector errorCollector, List collector) { for (int i = 0; i < errorCollector.getWarningCount(); i++) { WarningMessage warning = errorCollector.getWarning(i); - collector.add(new CompilerMessage(CompilerMessage.WARNING, warning.getMessage(), null, -1, -1)); + collector.add(new CompilerMessage(GroovyCompilerMessageCategories.WARNING, warning.getMessage(), null, -1, -1)); } } @@ -165,18 +165,18 @@ public class GroovyCompilerWrapper { } if (forStubs) { - collector.add(new CompilerMessage(CompilerMessage.INFORMATION, + collector.add(new CompilerMessage(GroovyCompilerMessageCategories.INFORMATION, "Groovyc stub generation failed", null, -1, -1)); } final StringWriter writer = new StringWriter(); //noinspection IOResourceOpenedButNotSafelyClosed exception.printStackTrace(new PrintWriter(writer)); - collector.add(new CompilerMessage(forStubs ? CompilerMessage.INFORMATION : CompilerMessage.ERROR, writer.toString(), null, -1, -1)); + collector.add(new CompilerMessage(forStubs ? GroovyCompilerMessageCategories.INFORMATION : GroovyCompilerMessageCategories.ERROR, writer.toString(), null, -1, -1)); } private static void addMessageWithoutLocation(List collector, String message, boolean error) { - collector.add(new CompilerMessage(error ? CompilerMessage.ERROR : CompilerMessage.WARNING, message, null, -1, -1)); + collector.add(new CompilerMessage(error ? GroovyCompilerMessageCategories.ERROR : GroovyCompilerMessageCategories.WARNING, message, null, -1, -1)); } private static final String LINE_AT = " @ line "; @@ -184,7 +184,7 @@ public class GroovyCompilerWrapper { private static void addErrorMessage(SyntaxException exception, List collector) { String message = exception.getMessage(); String justMessage = message.substring(0, message.lastIndexOf(LINE_AT)); - collector.add(new CompilerMessage(CompilerMessage.ERROR, justMessage, exception.getSourceLocator(), + collector.add(new CompilerMessage(GroovyCompilerMessageCategories.ERROR, justMessage, exception.getSourceLocator(), exception.getLine(), exception.getStartColumn())); } @@ -194,7 +194,7 @@ public class GroovyCompilerWrapper { if (module == null) { module = findModule(astNode); } - collector.add(new CompilerMessage(CompilerMessage.ERROR, exception.getMessageWithoutLocationText(), + collector.add(new CompilerMessage(GroovyCompilerMessageCategories.ERROR, exception.getMessageWithoutLocationText(), module == null ? "" : module.getDescription(), astNode.getLineNumber(), astNode.getColumnNumber())); } diff --git a/plugins/groovy/rt/src/org/jetbrains/groovy/compiler/rt/GroovycRunner.java b/plugins/groovy/rt/src/org/jetbrains/groovy/compiler/rt/GroovycRunner.java index 4101793b0732..e2324a7b1496 100644 --- a/plugins/groovy/rt/src/org/jetbrains/groovy/compiler/rt/GroovycRunner.java +++ b/plugins/groovy/rt/src/org/jetbrains/groovy/compiler/rt/GroovycRunner.java @@ -43,28 +43,6 @@ import java.util.*; public class GroovycRunner { - public static final String PATCHERS = "patchers"; - public static final String ENCODING = "encoding"; - public static final String OUTPUTPATH = "outputpath"; - public static final String FINAL_OUTPUTPATH = "final_outputpath"; - public static final String END = "end"; - - public static final String SRC_FILE = "src_file"; - public static final String COMPILED_START = "%%c"; - - public static final String COMPILED_END = "/%c"; - public static final String TO_RECOMPILE_START = "%%rc"; - - public static final String TO_RECOMPILE_END = "/%rc"; - public static final String MESSAGES_START = "%%m"; - - public static final String MESSAGES_END = "/%m"; - public static final String SEPARATOR = "#%%#%%%#%%%%%%%%%#"; - - //public static final Controller ourController = initController(); - public static final String PRESENTABLE_MESSAGE = "@#$%@# Presentable:"; - public static final String CLEAR_PRESENTABLE = "$@#$%^ CLEAR_PRESENTABLE"; - private GroovycRunner() { } @@ -132,7 +110,7 @@ public class GroovycRunner { config.setJointCompilationOptions(options); } - System.out.println(PRESENTABLE_MESSAGE + "Groovyc: loading sources..."); + System.out.println(GroovyRtConstants.PRESENTABLE_MESSAGE + "Groovyc: loading sources..."); final AstAwareResourceLoader resourceLoader = new AstAwareResourceLoader(class2File); final CompilationUnit unit = createCompilationUnit(forStubs, config, finalOutput[0], buildClassLoaderFor(config, resourceLoader)); unit.addPhaseOperation(new CompilationUnit.SourceUnitOperation() { @@ -147,9 +125,9 @@ public class GroovycRunner { addSources(forStubs, srcFiles, unit); runPatchers(patchers, compilerMessages, unit, resourceLoader); - System.out.println(PRESENTABLE_MESSAGE + "Groovyc: compiling..."); + System.out.println(GroovyRtConstants.PRESENTABLE_MESSAGE + "Groovyc: compiling..."); final List compiledFiles = GroovyCompilerWrapper.compile(compilerMessages, forStubs, unit); - System.out.println(CLEAR_PRESENTABLE); + System.out.println(GroovyRtConstants.CLEAR_PRESENTABLE); System.out.println(); reportCompiledItems(compiledFiles); @@ -161,7 +139,7 @@ public class GroovycRunner { int errorCount = 0; for (CompilerMessage message : compilerMessages) { - if (message.getCategory() == CompilerMessage.ERROR) { + if (message.getCategory() == GroovyCompilerMessageCategories.ERROR) { if (errorCount > 100) { continue; } @@ -203,7 +181,7 @@ public class GroovycRunner { String line; while ((line = reader.readLine()) != null) { - if (!SRC_FILE.equals(line)) { + if (!GroovyRtConstants.SRC_FILE.equals(line)) { break; } @@ -213,13 +191,13 @@ public class GroovycRunner { while (line != null) { if (line.equals("class2src")) { - while (!END.equals(line = reader.readLine())) { + while (!GroovyRtConstants.END.equals(line = reader.readLine())) { class2File.put(line, new File(reader.readLine())); } } - else if (line.startsWith(PATCHERS)) { + else if (line.startsWith(GroovyRtConstants.PATCHERS)) { String s; - while (!END.equals(s = reader.readLine())) { + while (!GroovyRtConstants.END.equals(s = reader.readLine())) { try { final CompilationUnitPatcher patcher = (CompilationUnitPatcher)Class.forName(s).newInstance(); patchers.add(patcher); @@ -235,13 +213,13 @@ public class GroovycRunner { } } } - else if (line.startsWith(ENCODING)) { + else if (line.startsWith(GroovyRtConstants.ENCODING)) { compilerConfiguration.setSourceEncoding(reader.readLine()); } - else if (line.startsWith(OUTPUTPATH)) { + else if (line.startsWith(GroovyRtConstants.OUTPUTPATH)) { compilerConfiguration.setTargetDirectory(reader.readLine()); } - else if (line.startsWith(FINAL_OUTPUTPATH)) { + else if (line.startsWith(GroovyRtConstants.FINAL_OUTPUTPATH)) { finalOutput[0] = reader.readLine(); } @@ -277,9 +255,9 @@ public class GroovycRunner { unit.addSource(new SourceUnit(file, unit.getConfiguration(), unit.getClassLoader(), unit.getErrorCollector()) { public void parse() throws CompilationFailedException { - System.out.println(PRESENTABLE_MESSAGE + "Parsing " + file.getName() + "..."); + System.out.println(GroovyRtConstants.PRESENTABLE_MESSAGE + "Parsing " + file.getName() + "..."); super.parse(); - System.out.println(CLEAR_PRESENTABLE); + System.out.println(GroovyRtConstants.CLEAR_PRESENTABLE); } }); } @@ -300,9 +278,9 @@ public class GroovycRunner { private static void reportNotCompiledItems(Collection toRecompile) { for (File file : toRecompile) { - System.out.print(TO_RECOMPILE_START); + System.out.print(GroovyRtConstants.TO_RECOMPILE_START); System.out.print(file.getAbsolutePath()); - System.out.print(TO_RECOMPILE_END); + System.out.print(GroovyRtConstants.TO_RECOMPILE_END); System.out.println(); } } @@ -314,35 +292,35 @@ public class GroovycRunner { * source file * output root directory */ - System.out.print(COMPILED_START); + System.out.print(GroovyRtConstants.COMPILED_START); System.out.print(compiledFile.getOutputPath()); - System.out.print(SEPARATOR); + System.out.print(GroovyRtConstants.SEPARATOR); System.out.print(compiledFile.getSourceFile()); - System.out.print(COMPILED_END); + System.out.print(GroovyRtConstants.COMPILED_END); System.out.println(); } } private static void printMessage(CompilerMessage message) { - System.out.print(MESSAGES_START); + System.out.print(GroovyRtConstants.MESSAGES_START); System.out.print(message.getCategory()); - System.out.print(SEPARATOR); + System.out.print(GroovyRtConstants.SEPARATOR); System.out.print(message.getMessage()); - System.out.print(SEPARATOR); + System.out.print(GroovyRtConstants.SEPARATOR); System.out.print(message.getUrl()); - System.out.print(SEPARATOR); + System.out.print(GroovyRtConstants.SEPARATOR); System.out.print(message.getLineNum()); - System.out.print(SEPARATOR); + System.out.print(GroovyRtConstants.SEPARATOR); System.out.print(message.getColumnNum()); - System.out.print(SEPARATOR); - System.out.print(MESSAGES_END); + System.out.print(GroovyRtConstants.SEPARATOR); + System.out.print(GroovyRtConstants.MESSAGES_END); System.out.println(); } private static void addExceptionInfo(List compilerMessages, Throwable e, String message) { final StringWriter writer = new StringWriter(); e.printStackTrace(new PrintWriter(writer)); - compilerMessages.add(new CompilerMessage(CompilerMessage.WARNING, message + ":\n" + writer, "", -1, -1)); + compilerMessages.add(new CompilerMessage(GroovyCompilerMessageCategories.WARNING, message + ":\n" + writer, "", -1, -1)); } private static CompilationUnit createCompilationUnit(final boolean forStubs, @@ -386,7 +364,7 @@ public class GroovycRunner { public void gotoPhase(int phase) throws CompilationFailedException { super.gotoPhase(phase); if (phase <= Phases.ALL) { - System.out.println(PRESENTABLE_MESSAGE + "Groovyc: " + getPhaseDescription()); + System.out.println(GroovyRtConstants.PRESENTABLE_MESSAGE + "Groovyc: " + getPhaseDescription()); } } }; @@ -398,7 +376,7 @@ public class GroovycRunner { public void gotoPhase(int phase) throws CompilationFailedException { super.gotoPhase(phase); if (phase <= Phases.ALL) { - System.out.println(PRESENTABLE_MESSAGE + "Groovyc: " + getPhaseDescription()); + System.out.println(GroovyRtConstants.PRESENTABLE_MESSAGE + "Groovyc: " + getPhaseDescription()); } } }; @@ -458,7 +436,7 @@ public class GroovycRunner { public void gotoPhase(int phase) throws CompilationFailedException { if (phase == Phases.SEMANTIC_ANALYSIS) { - System.out.println(PRESENTABLE_MESSAGE + "Generating Groovy stubs..."); + System.out.println(GroovyRtConstants.PRESENTABLE_MESSAGE + "Generating Groovy stubs..."); // clear javaSources field so that no javac is invoked try { Field field = JavaAwareCompilationUnit.class.getDeclaredField("javaSources"); @@ -471,7 +449,7 @@ public class GroovycRunner { } } else if (phase <= Phases.ALL) { - System.out.println(PRESENTABLE_MESSAGE + "Groovy stub generator: " + getPhaseDescription()); + System.out.println(GroovyRtConstants.PRESENTABLE_MESSAGE + "Groovy stub generator: " + getPhaseDescription()); } super.gotoPhase(phase); diff --git a/plugins/groovy/src/META-INF/plugin.xml b/plugins/groovy/src/META-INF/plugin.xml index 5a54ad594050..e183e3a28f07 100644 --- a/plugins/groovy/src/META-INF/plugin.xml +++ b/plugins/groovy/src/META-INF/plugin.xml @@ -364,7 +364,7 @@ - + diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/codeInspection/confusing/GrUnusedIncDecInspection.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/codeInspection/confusing/GrUnusedIncDecInspection.java index fadb994f0ec0..c3416e7ff466 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/codeInspection/confusing/GrUnusedIncDecInspection.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/codeInspection/confusing/GrUnusedIncDecInspection.java @@ -18,6 +18,7 @@ package org.jetbrains.plugins.groovy.codeInspection.confusing; import com.intellij.codeInspection.LocalQuickFix; import com.intellij.codeInspection.ProblemDescriptor; import com.intellij.codeInspection.ProblemHighlightType; +import com.intellij.diagnostic.LogMessageEx; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiElement; @@ -100,7 +101,7 @@ public class GrUnusedIncDecInspection extends BaseInspection { final Instruction cur = ControlFlowUtils.findInstruction(operand, owner.getControlFlow()); if (cur == null) { - LOG.error("no instruction found in flow." + "operand: " + operand.getText() + " cfo: " + owner.getText()); + LogMessageEx.error(LOG, "no instruction found in flow." + "operand: " + operand.getText(), owner.getText()); } //get write access for inc or dec diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/dsl/holders/NonCodeMembersHolder.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/dsl/holders/NonCodeMembersHolder.java index 3e65ab58db25..66102e0698f7 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/dsl/holders/NonCodeMembersHolder.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/dsl/holders/NonCodeMembersHolder.java @@ -18,9 +18,12 @@ package org.jetbrains.plugins.groovy.dsl.holders; import com.intellij.openapi.util.Key; import com.intellij.psi.*; import com.intellij.psi.scope.PsiScopeProcessor; -import com.intellij.psi.util.*; +import com.intellij.psi.util.CachedValueProvider; +import com.intellij.psi.util.CachedValuesManager; +import com.intellij.psi.util.PsiModificationTracker; import com.intellij.util.containers.ConcurrentSoftHashMap; import com.intellij.util.containers.ContainerUtil; +import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.groovy.dsl.CustomMembersGenerator; import org.jetbrains.plugins.groovy.dsl.GroovyClassDescriptor; import org.jetbrains.plugins.groovy.extensions.NamedArgumentDescriptor; @@ -61,7 +64,9 @@ public class NonCodeMembersHolder implements CustomMembersHolder { for (Map prop : data) { if (prop.get("closure") == Boolean.TRUE) { PsiElement closureDescriptor = createClosureDescriptor(prop, place, manager); - myMethods.add(closureDescriptor); + if (closureDescriptor != null) { + myMethods.add(closureDescriptor); + } } else { final PsiElement method = createMethod(prop, place, manager); @@ -70,64 +75,39 @@ public class NonCodeMembersHolder implements CustomMembersHolder { } } + @Nullable private static PsiElement createClosureDescriptor(Map prop, PsiElement place, PsiManager manager) { final ClosureDescriptor closure = new ClosureDescriptor(manager); - { -// closure.setReturnType(convertToPsiType(String.valueOf(prop.get("type")), place)); - final Object params = prop.get("params"); - if (params instanceof Map) { - boolean first = true; - for (Object paramName : ((Map)params).keySet()) { - Object value = ((Map)params).get(paramName); - boolean isNamed = first && value instanceof List; - first = false; - String typeName = isNamed ? CommonClassNames.JAVA_UTIL_MAP : String.valueOf(value); - closure.addParameter(typeName, String.valueOf(paramName)); - } - } - - Object doc = prop.get("doc"); - if (doc instanceof String) { - closure.putUserData(DOCUMENTATION, (String)doc); - } - - Object docUrl = prop.get("docUrl"); - if (docUrl instanceof String) { - closure.putUserData(DOCUMENTATION_URL, (String)docUrl); - } - } - - final Object method = prop.get("method"); - if (method instanceof Map) { + if (!(method instanceof Map)) return null; - String name = String.valueOf(((Map)method).get("name")); + closure.setMethod(((Map)method)); - - List types = new ArrayList(); - final Object params = ((Map)method).get("params"); - if (params instanceof Map) { - boolean first = true; - for (Object paramName : ((Map)params).keySet()) { - Object value = ((Map)params).get(paramName); - boolean isNamed = first && value instanceof List; - first = false; - String typeName = isNamed ? CommonClassNames.JAVA_UTIL_MAP : String.valueOf(value); - types.add(convertToPsiType(typeName, place)); - } +// closure.setReturnType(convertToPsiType(String.valueOf(prop.get("type")), place)); + final Object closureParams = prop.get("params"); + if (closureParams instanceof Map) { + boolean first = true; + for (Object paramName : ((Map)closureParams).keySet()) { + Object value = ((Map)closureParams).get(paramName); + boolean isNamed = first && value instanceof List; + first = false; + String typeName = isNamed ? CommonClassNames.JAVA_UTIL_MAP : String.valueOf(value); + closure.addParameter(typeName, String.valueOf(paramName)); } - else if (params instanceof List) { - for (Object param : ((List)params)) { - types.add(convertToPsiType(String.valueOf(param), place)); - } - } - final boolean isConstructor = Boolean.TRUE.equals(((Map)method).get("constructor")); - final PsiType[] typeArray = types.toArray(new PsiType[types.size()]); - final MethodSignature signature = - MethodSignatureUtil.createMethodSignature(name, typeArray, PsiTypeParameter.EMPTY_ARRAY, PsiSubstitutor.EMPTY, isConstructor); - closure.setMethodSignature(signature); } + + Object doc = prop.get("doc"); + if (doc instanceof String) { + closure.putUserData(DOCUMENTATION, (String)doc); + } + + Object docUrl = prop.get("docUrl"); + if (docUrl instanceof String) { + closure.putUserData(DOCUMENTATION_URL, (String)docUrl); + } + + return closure; } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/highlighter/GroovySlashyStringLexer.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/highlighter/GroovySlashyStringLexer.java index e959000f032b..01e91278577e 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/highlighter/GroovySlashyStringLexer.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/highlighter/GroovySlashyStringLexer.java @@ -15,7 +15,9 @@ */ package org.jetbrains.plugins.groovy.highlighter; +import com.intellij.diagnostic.LogMessageEx; import com.intellij.lexer.LexerBase; +import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.StringEscapesTokenTypes; import com.intellij.psi.tree.IElementType; @@ -26,6 +28,8 @@ import org.jetbrains.plugins.groovy.lang.lexer.GroovyTokenTypes; * @author Max Medvedev */ public class GroovySlashyStringLexer extends LexerBase { + private static final Logger LOG = Logger.getInstance(GroovySlashyStringLexer.class); + private CharSequence myBuffer; private int myStart; private int myBufferEnd; @@ -38,7 +42,9 @@ public class GroovySlashyStringLexer extends LexerBase { @Override public void start(CharSequence buffer, int startOffset, int endOffset, int initialState) { - assert buffer.length() >= endOffset : "buffer Length: " + buffer.length() + ", endOffset: " + endOffset + "buffer: " + buffer; + if (buffer.length() { public void handleInsert(InsertionContext context, LookupElement item) { @NonNls Object obj = item.getObject(); + PsiSubstitutor substitutor = PsiSubstitutor.EMPTY; if (obj instanceof GroovyResolveResult) { + substitutor = ((GroovyResolveResult)obj).getSubstitutor(); obj = ((GroovyResolveResult)obj).getElement(); } @@ -114,7 +116,7 @@ public class GroovyInsertHandler implements InsertHandler { document.insertString(offset, " "); offset++; } - if (processClosureWithParams(context, method, document, offset, parent)) return; + if (processClosureWithParams(context, method, substitutor, document, offset, parent)) return; if (context.getCompletionChar() == Lookup.COMPLETE_STATEMENT_SELECT_CHAR) { //smart enter invoked document.insertString(offset, "{\n}"); @@ -186,6 +188,7 @@ public class GroovyInsertHandler implements InsertHandler { private static boolean processClosureWithParams(InsertionContext context, PsiMethod method, + PsiSubstitutor substitutor, Document document, int offset, PsiElement parent) { @@ -204,8 +207,8 @@ public class GroovyInsertHandler implements InsertHandler { }, ResolveState.initial()); for (ClosureDescriptor descriptor : descriptors) { - if (descriptor.isMethodApplicable(method, (GrReferenceExpression)parent)) { - if (runClosureTemplate(context, document, offset, descriptor)) { + if (descriptor.isMethodApplicable(method, substitutor, (GrReferenceExpression)parent)) { + if (runClosureTemplate(context, document, offset, descriptor, substitutor, method)) { return true; } } @@ -213,14 +216,19 @@ public class GroovyInsertHandler implements InsertHandler { return false; } - private static boolean runClosureTemplate(InsertionContext context, Document document, int offset, ClosureDescriptor descriptor) { + private static boolean runClosureTemplate(InsertionContext context, + Document document, + int offset, + ClosureDescriptor descriptor, + PsiSubstitutor substitutor, + PsiMethod method) { document.insertString(offset, "{\n}"); PsiDocumentManager.getInstance(context.getProject()).commitDocument(document); final GrClosableBlock closure = PsiTreeUtil.findElementOfClassAtOffset(context.getFile(), offset + 1, GrClosableBlock.class, false); if (closure == null) return false; - ClosureTemplateBuilder.runTemplate(descriptor.getParameters(), closure, context.getProject(), context.getEditor()); + ClosureTemplateBuilder.runTemplate(descriptor.getParameters(), closure, substitutor, method, context.getProject(), context.getEditor()); return true; } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/closureParameters/ClosureDescriptor.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/closureParameters/ClosureDescriptor.java index 6bff9968c9d2..c3015b9131fc 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/closureParameters/ClosureDescriptor.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/closureParameters/ClosureDescriptor.java @@ -18,7 +18,7 @@ package org.jetbrains.plugins.groovy.lang.completion.closureParameters; import com.intellij.psi.*; import com.intellij.psi.impl.light.LightElement; import com.intellij.psi.util.MethodSignature; -import com.intellij.psi.util.TypeConversionUtil; +import com.intellij.psi.util.MethodSignatureUtil; import com.intellij.util.Function; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.Nullable; @@ -30,15 +30,14 @@ import org.jetbrains.plugins.groovy.lang.psi.impl.signatures.GrClosureSignatureU import java.util.ArrayList; import java.util.Collections; import java.util.List; +import java.util.Map; /** * @author Max Medvedev */ public class ClosureDescriptor extends LightElement implements PsiElement { private final List myParams = new ArrayList(); - private MethodSignature myMethodSignature; - private GrClosureSignature myClosureSignature; - + private Map myMethod; public ClosureDescriptor(PsiManager manager) { super(manager, GroovyFileType.GROOVY_LANGUAGE); @@ -58,24 +57,48 @@ public class ClosureDescriptor extends LightElement implements PsiElement { return "closure descriptor"; } - public void setMethodSignature(MethodSignature methodSignature) { - myMethodSignature = methodSignature; - myClosureSignature = GrClosureSignatureUtil.createSignature(methodSignature); + public void setMethod(Map method) { + this.myMethod = method; } - public boolean isMethodApplicable(PsiMethod method, GroovyPsiElement place) { - assert myMethodSignature != null; - assert myClosureSignature != null; + public boolean isMethodApplicable(PsiMethod method, PsiSubstitutor substitutor, GroovyPsiElement place) { + String name = String.valueOf(myMethod.get("name")); + if (name == null || !name.equals(method.getName())) return false; + + List types = new ArrayList(); + final Object params = myMethod.get("params"); + if (params instanceof Map) { + boolean first = true; + for (Object paramName : ((Map)params).keySet()) { + Object value = ((Map)params).get(paramName); + boolean isNamed = first && value instanceof List; + first = false; + String typeName = isNamed ? CommonClassNames.JAVA_UTIL_MAP : String.valueOf(value); + types.add(convertToPsiType(typeName, place)); + } + } + else if (params instanceof List) { + for (Object param : ((List)params)) { + types.add(convertToPsiType(String.valueOf(param), method.getTypeParameterList())); + } + } + final boolean isConstructor = Boolean.TRUE.equals(myMethod.get("constructor")); + final MethodSignature signature = MethodSignatureUtil + .createMethodSignature(name, types.toArray(new PsiType[types.size()]), method.getTypeParameters(), substitutor, isConstructor); + final GrClosureSignature closureSignature = GrClosureSignatureUtil.createSignature(signature); final PsiParameter[] parameters = method.getParameterList().getParameters(); - final PsiType[] types = new PsiType[parameters.length]; + final PsiType[] typeArray = new PsiType[parameters.length]; ContainerUtil.map(parameters, new Function() { @Override public PsiType fun(PsiParameter parameter) { - return TypeConversionUtil.erasure(parameter.getType()); + return parameter.getType(); } - }, types); - return method.getName().equals(myMethodSignature.getName()) && - GrClosureSignatureUtil.isSignatureApplicable(myClosureSignature, types, place); + }, typeArray); + return GrClosureSignatureUtil.isSignatureApplicable(closureSignature, typeArray, place); + } + + private static PsiType convertToPsiType(String type, PsiElement place) { + return JavaPsiFacade.getElementFactory(place.getProject()).createTypeFromText(type, place); } } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/closureParameters/ClosureTemplateBuilder.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/closureParameters/ClosureTemplateBuilder.java index 8967145798fa..e79540d4f939 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/closureParameters/ClosureTemplateBuilder.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/closureParameters/ClosureTemplateBuilder.java @@ -23,12 +23,10 @@ import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.TextRange; -import com.intellij.psi.PsiDocumentManager; -import com.intellij.psi.PsiElement; -import com.intellij.psi.PsiFile; -import com.intellij.psi.PsiManager; +import com.intellij.psi.*; import com.intellij.psi.codeStyle.CodeStyleManager; import com.intellij.psi.util.PsiTreeUtil; +import com.intellij.psi.util.TypeConversionUtil; import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory; import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock; import org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter; @@ -44,7 +42,11 @@ import java.util.List; * @author Max Medvedev */ public class ClosureTemplateBuilder { - public static void runTemplate(List parameters, GrClosableBlock block, final Project project, final Editor editor) { + public static void runTemplate(List parameters, + GrClosableBlock block, + PsiSubstitutor substitutor, + PsiMethod method, final Project project, + final Editor editor) { assert block.getArrow() == null; if (parameters.isEmpty()) return; @@ -54,7 +56,9 @@ public class ClosureTemplateBuilder { final String type = parameter.getType(); final String name = parameter.getName(); if (type != null) { - buffer.append(type).append(" "); + final PsiType fromText = JavaPsiFacade.getElementFactory(project).createTypeFromText(type, method); + final PsiType substituted = TypeConversionUtil.erasure(substitutor.substitute(fromText)); + buffer.append(substituted.getCanonicalText()).append(" "); } else { buffer.append("def "); diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/GrIfStatementImpl.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/GrIfStatementImpl.java index 1d51be93e5f9..965315246430 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/GrIfStatementImpl.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/GrIfStatementImpl.java @@ -17,7 +17,6 @@ package org.jetbrains.plugins.groovy.lang.psi.impl.statements; import com.intellij.lang.ASTNode; -import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiElement; import com.intellij.util.IncorrectOperationException; import org.jetbrains.annotations.NotNull; @@ -29,6 +28,7 @@ import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrStatement; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression; import org.jetbrains.plugins.groovy.lang.psi.impl.GroovyPsiElementImpl; import org.jetbrains.plugins.groovy.lang.psi.impl.PsiImplUtil; +import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil; /** * @autor: ilyas @@ -51,12 +51,9 @@ public class GrIfStatementImpl extends GroovyPsiElementImpl implements GrIfState PsiElement lParenth = getLParenth(); if (lParenth == null) return null; - PsiElement afterLParen = lParenth.getNextSibling(); - while (afterLParen != null && StringUtil.isEmptyOrSpaces(afterLParen.getText())) { - afterLParen = afterLParen.getNextSibling(); - } + PsiElement afterLParenth = PsiUtil.skipWhitespaces(lParenth.getNextSibling(), true); - if (afterLParen instanceof GrExpression) return (GrExpression)afterLParen; + if (afterLParenth instanceof GrExpression) return (GrExpression)afterLParenth; return null; } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/GrWhileStatementImpl.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/GrWhileStatementImpl.java index 4ed7e275a08f..f74f211a5e03 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/GrWhileStatementImpl.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/GrWhileStatementImpl.java @@ -28,6 +28,7 @@ import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrStatement; import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrWhileStatement; import org.jetbrains.plugins.groovy.lang.psi.impl.GroovyPsiElementImpl; import org.jetbrains.plugins.groovy.lang.psi.impl.PsiImplUtil; +import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil; /** * @autor: ilyas @@ -50,9 +51,9 @@ public class GrWhileStatementImpl extends GroovyPsiElementImpl implements GrWhil PsiElement lParenth = getLParenth(); if (lParenth == null) return null; - PsiElement afterLParen = lParenth.getNextSibling(); + PsiElement afterLParenth = PsiUtil.skipWhitespaces(lParenth.getNextSibling(), true); - if (afterLParen instanceof GrCondition) return ((GrCondition) afterLParen); + if (afterLParenth instanceof GrCondition) return ((GrCondition) afterLParenth); return null; } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/util/PsiUtil.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/util/PsiUtil.java index 5f8352025d66..8f2c81ed7803 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/util/PsiUtil.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/util/PsiUtil.java @@ -235,13 +235,14 @@ public class PsiUtil { public static PsiType[] getArgumentTypes(PsiElement place, boolean nullAsBottom) { return getArgumentTypes(place, nullAsBottom, null, false); } + @Nullable public static PsiType[] getArgumentTypes(PsiElement place, boolean nullAsBottom, @Nullable GrExpression stopAt, boolean byShape) { PsiElement parent = place instanceof GrEnumConstant ? place : place.getParent(); if (parent instanceof GrIndexProperty) { GrIndexProperty index = (GrIndexProperty)parent; - PsiType[] argTypes = getArgumentTypes(index.getNamedArguments(), index.getExpressionArguments(), index.getClosureArguments(), false, null, byShape); + PsiType[] argTypes = getArgumentTypes(index.getNamedArguments(), index.getExpressionArguments(), index.getClosureArguments(), nullAsBottom, stopAt, byShape); if (isLValue(index) && argTypes != null) { return ArrayUtil.append(argTypes, TypeInferenceHelper.getInitializerFor(index)); } @@ -260,10 +261,10 @@ public class PsiUtil { else if (parent instanceof GrAnonymousClassDefinition) { final GrArgumentList argList = ((GrAnonymousClassDefinition)parent).getArgumentListGroovy(); if (argList == null) { - return getArgumentTypes(GrNamedArgument.EMPTY_ARRAY, GrExpression.EMPTY_ARRAY, GrClosableBlock.EMPTY_ARRAY, false, null, byShape); + return getArgumentTypes(GrNamedArgument.EMPTY_ARRAY, GrExpression.EMPTY_ARRAY, GrClosableBlock.EMPTY_ARRAY, nullAsBottom, stopAt, byShape); } else { - return getArgumentTypes(argList.getNamedArguments(), argList.getExpressionArguments(), GrClosableBlock.EMPTY_ARRAY, false, null, byShape); + return getArgumentTypes(argList.getNamedArguments(), argList.getExpressionArguments(), GrClosableBlock.EMPTY_ARRAY, nullAsBottom, stopAt, byShape); } } @@ -280,7 +281,8 @@ public class PsiUtil { GrExpression[] expressions, GrClosableBlock[] closures, boolean nullAsBottom, - @Nullable GrExpression stopAt, boolean byShape) { + @Nullable GrExpression stopAt, + boolean byShape) { List result = new ArrayList(); if (namedArgs.length > 0) { diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/MavenModuleImporter.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/MavenModuleImporter.java index a4d4b8483281..a9f726154ff7 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/MavenModuleImporter.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/MavenModuleImporter.java @@ -17,7 +17,7 @@ package org.jetbrains.idea.maven.importing; import com.intellij.compiler.CompilerConfiguration; import com.intellij.compiler.CompilerConfigurationImpl; -import com.intellij.compiler.ProcessorConfigProfile; +import org.jetbrains.jps.model.java.compiler.ProcessorConfigProfile; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleType; import com.intellij.openapi.projectRoots.Sdk; @@ -37,6 +37,7 @@ import org.jetbrains.idea.maven.model.MavenArtifact; import org.jetbrains.idea.maven.model.MavenConstants; import org.jetbrains.idea.maven.project.*; import org.jetbrains.idea.maven.utils.MavenUtil; +import org.jetbrains.jps.model.java.impl.compiler.ProcessorConfigProfileImpl; import java.io.File; import java.nio.charset.Charset; @@ -276,7 +277,7 @@ public class MavenModuleImporter { } if (defaultMavenProfile == null) { - defaultMavenProfile = new ProcessorConfigProfile(MAVEN_DEFAULT_ANNOTATION_PROFILE); + defaultMavenProfile = new ProcessorConfigProfileImpl(MAVEN_DEFAULT_ANNOTATION_PROFILE); defaultMavenProfile.setEnabled(true); defaultMavenProfile.setObtainProcessorsFromClasspath(true); defaultMavenProfile.setGeneratedSourcesDirectoryName("target/generated-sources/annotations"); @@ -295,7 +296,7 @@ public class MavenModuleImporter { } if (moduleProfile == null) { - moduleProfile = new ProcessorConfigProfile(moduleProfileName); + moduleProfile = new ProcessorConfigProfileImpl(moduleProfileName); moduleProfile.setEnabled(true); moduleProfile.setObtainProcessorsFromClasspath(true); moduleProfile.addModuleName(myModule.getName()); diff --git a/plugins/rearranger/src/com/wrq/rearranger/ClassInitializer.png b/plugins/rearranger/src/com/wrq/rearranger/ClassInitializer.png deleted file mode 100644 index 069d412ce72c..000000000000 Binary files a/plugins/rearranger/src/com/wrq/rearranger/ClassInitializer.png and /dev/null differ diff --git a/plugins/rearranger/src/com/wrq/rearranger/RearrangerIcon.png b/plugins/rearranger/src/com/wrq/rearranger/RearrangerIcon.png deleted file mode 100644 index f4047ce53faa..000000000000 Binary files a/plugins/rearranger/src/com/wrq/rearranger/RearrangerIcon.png and /dev/null differ diff --git a/plugins/rearranger/src/com/wrq/rearranger/ShowComments.png b/plugins/rearranger/src/com/wrq/rearranger/ShowComments.png deleted file mode 100644 index 150f22dcaa76..000000000000 Binary files a/plugins/rearranger/src/com/wrq/rearranger/ShowComments.png and /dev/null differ diff --git a/plugins/rearranger/src/com/wrq/rearranger/ShowFields.png b/plugins/rearranger/src/com/wrq/rearranger/ShowFields.png deleted file mode 100644 index d85a07398be3..000000000000 Binary files a/plugins/rearranger/src/com/wrq/rearranger/ShowFields.png and /dev/null differ diff --git a/plugins/rearranger/src/com/wrq/rearranger/ShowMatchedRules.png b/plugins/rearranger/src/com/wrq/rearranger/ShowMatchedRules.png deleted file mode 100644 index 2d861498cc9b..000000000000 Binary files a/plugins/rearranger/src/com/wrq/rearranger/ShowMatchedRules.png and /dev/null differ diff --git a/plugins/rearranger/src/com/wrq/rearranger/ShowParamNames.png b/plugins/rearranger/src/com/wrq/rearranger/ShowParamNames.png deleted file mode 100644 index 3b9362e7f141..000000000000 Binary files a/plugins/rearranger/src/com/wrq/rearranger/ShowParamNames.png and /dev/null differ diff --git a/plugins/rearranger/src/com/wrq/rearranger/ShowParamTypes.png b/plugins/rearranger/src/com/wrq/rearranger/ShowParamTypes.png deleted file mode 100644 index 474a783ed31e..000000000000 Binary files a/plugins/rearranger/src/com/wrq/rearranger/ShowParamTypes.png and /dev/null differ diff --git a/plugins/rearranger/src/com/wrq/rearranger/ShowRules.png b/plugins/rearranger/src/com/wrq/rearranger/ShowRules.png deleted file mode 100644 index b28f8da4909c..000000000000 Binary files a/plugins/rearranger/src/com/wrq/rearranger/ShowRules.png and /dev/null differ diff --git a/plugins/rearranger/src/com/wrq/rearranger/ShowTypeAfterMethod.png b/plugins/rearranger/src/com/wrq/rearranger/ShowTypeAfterMethod.png deleted file mode 100644 index 83aa87e0a474..000000000000 Binary files a/plugins/rearranger/src/com/wrq/rearranger/ShowTypeAfterMethod.png and /dev/null differ diff --git a/plugins/rearranger/src/com/wrq/rearranger/StaticClassInitializer.png b/plugins/rearranger/src/com/wrq/rearranger/StaticClassInitializer.png deleted file mode 100644 index dad14aa70729..000000000000 Binary files a/plugins/rearranger/src/com/wrq/rearranger/StaticClassInitializer.png and /dev/null differ diff --git a/plugins/rearranger/src/icons/RearrangerIcons.java b/plugins/rearranger/src/icons/RearrangerIcons.java deleted file mode 100644 index 2be4d295f1e4..000000000000 --- a/plugins/rearranger/src/icons/RearrangerIcons.java +++ /dev/null @@ -1,26 +0,0 @@ -package icons; - -import com.intellij.openapi.util.IconLoader; - -import javax.swing.*; - -/** - * NOTE THIS FILE IS AUTO-GENERATED by the build/scripts/icons.gant - * Don't repeat mistakes of others ;-) - */ -public class RearrangerIcons { - private static Icon load(String path) { - return IconLoader.getIcon(path, RearrangerIcons.class); - } - - public static final Icon ClassInitializer = load("/com/wrq/rearranger/ClassInitializer.png"); // 18x18 - public static final Icon RearrangerIcon = load("/com/wrq/rearranger/RearrangerIcon.png"); // 32x32 - public static final Icon ShowComments = load("/com/wrq/rearranger/ShowComments.png"); // 28x28 - public static final Icon ShowFields = load("/com/wrq/rearranger/ShowFields.png"); // 28x28 - public static final Icon ShowMatchedRules = load("/com/wrq/rearranger/ShowMatchedRules.png"); // 28x28 - public static final Icon ShowParamNames = load("/com/wrq/rearranger/ShowParamNames.png"); // 28x28 - public static final Icon ShowParamTypes = load("/com/wrq/rearranger/ShowParamTypes.png"); // 28x28 - public static final Icon ShowRules = load("/com/wrq/rearranger/ShowRules.png"); // 28x28 - public static final Icon ShowTypeAfterMethod = load("/com/wrq/rearranger/ShowTypeAfterMethod.png"); // 28x28 - public static final Icon StaticClassInitializer = load("/com/wrq/rearranger/StaticClassInitializer.png"); // 18x18 -} diff --git a/plugins/spellchecker/src/com/intellij/spellchecker/compress/Alphabet.java b/plugins/spellchecker/src/com/intellij/spellchecker/compress/Alphabet.java index eca82090fd3b..d3560f0ca3b4 100644 --- a/plugins/spellchecker/src/com/intellij/spellchecker/compress/Alphabet.java +++ b/plugins/spellchecker/src/com/intellij/spellchecker/compress/Alphabet.java @@ -1,3 +1,18 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.intellij.spellchecker.compress; import org.jetbrains.annotations.NotNull; @@ -43,6 +58,7 @@ public final class Alphabet { } public int add(char c) { + if(lastIndexUsed>=letters.length-1) return -1; lastIndexUsed++; letters[lastIndexUsed] = c; return lastIndexUsed; diff --git a/plugins/spellchecker/src/com/intellij/spellchecker/compress/CompressedDictionary.java b/plugins/spellchecker/src/com/intellij/spellchecker/compress/CompressedDictionary.java index 6c09684c963b..12f474d34b7a 100644 --- a/plugins/spellchecker/src/com/intellij/spellchecker/compress/CompressedDictionary.java +++ b/plugins/spellchecker/src/com/intellij/spellchecker/compress/CompressedDictionary.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2010 JetBrains s.r.o. + * Copyright 2000-2012 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -121,23 +121,20 @@ public final class CompressedDictionary implements Dictionary { if (word == null) { return false; } - try { - UnitBitSet bs = encoder.encode(word, false); - if (bs == Encoder.WORD_OF_ENTIRELY_UNKNOWN_LETTERS) return false; // TODO: polyglot.dic contains word typppo , wtf ?! also make tests for your changes!!! - if (bs == null) return false; // fail faster w/o search - byte[] compressed = UnitBitSet.getBytes(bs); - int index = -1; - for (int i = 0; i < lengths.length; i++) { - if (lengths[i] == compressed.length) { - index = i; - break; - } + UnitBitSet bs = encoder.encode(word, false); + if (bs == Encoder.WORD_OF_ENTIRELY_UNKNOWN_LETTERS) + throw new EncodingException("WORD_OF_ENTIRELY_UNKNOWN_LETTERS"); + if (bs == null) return false; + //TODO throw new EncodingException("WORD_WITH_SOME_UNKNOWN_LETTERS"); + byte[] compressed = UnitBitSet.getBytes(bs); + int index = -1; + for (int i = 0; i < lengths.length; i++) { + if (lengths[i] == compressed.length) { + index = i; + break; } - return index != -1 && contains(compressed, words[index]); - } - catch (EncodingException ignored) { - return false; } + return index != -1 && contains(compressed, words[index]); } @@ -153,10 +150,6 @@ public final class CompressedDictionary implements Dictionary { throw new UnsupportedOperationException(); } - public int getAlphabetLength() { - return alphabet.getLastIndexUsed(); - } - public int size() { return wordsCount; } diff --git a/plugins/spellchecker/src/com/intellij/spellchecker/dictionary/ProjectDictionary.java b/plugins/spellchecker/src/com/intellij/spellchecker/dictionary/ProjectDictionary.java index b3ac0e314d41..df9157f1b77f 100644 --- a/plugins/spellchecker/src/com/intellij/spellchecker/dictionary/ProjectDictionary.java +++ b/plugins/spellchecker/src/com/intellij/spellchecker/dictionary/ProjectDictionary.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2012 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,6 +15,7 @@ */ package com.intellij.spellchecker.dictionary; +import com.intellij.spellchecker.compress.EncodingException; import com.intellij.util.Consumer; import gnu.trove.THashSet; import org.jetbrains.annotations.NotNull; @@ -59,11 +60,21 @@ public class ProjectDictionary implements EditableDictionary { if (word == null || dictionaries == null) { return false; } + int negatives = 0; for (Dictionary dictionary : dictionaries) { - if (dictionary.contains(word)) { - return true; + try { + if (dictionary.contains(word)) { + return true; + } + else { + negatives++; + } + } + catch (EncodingException e) { + //System.out.println("e.getMessage() = " + e.getMessage() + " " + word); } } + if (negatives==dictionaries.size()) throw new EncodingException("WORD_OF_ENTIRELY_UNKNOWN_LETTERS_FOR_ALL"); return false; } diff --git a/plugins/spellchecker/src/com/intellij/spellchecker/engine/BaseSpellChecker.java b/plugins/spellchecker/src/com/intellij/spellchecker/engine/BaseSpellChecker.java index 323641fc81c9..c612459c767e 100644 --- a/plugins/spellchecker/src/com/intellij/spellchecker/engine/BaseSpellChecker.java +++ b/plugins/spellchecker/src/com/intellij/spellchecker/engine/BaseSpellChecker.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2012 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,6 +28,7 @@ import com.intellij.openapi.startup.StartupManager; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.text.StringUtil; import com.intellij.spellchecker.compress.CompressedDictionary; +import com.intellij.spellchecker.compress.EncodingException; import com.intellij.spellchecker.dictionary.Dictionary; import com.intellij.spellchecker.dictionary.EditableDictionary; import com.intellij.spellchecker.dictionary.EditableDictionaryLoader; @@ -269,7 +270,13 @@ public class BaseSpellChecker implements SpellCheckerEngine { return true; } - return dictionary.contains(transformed); + try { + return dictionary.contains(transformed); + } + catch (EncodingException e) { + //System.out.println("e.getMessage() = " + e.getMessage() + " " + transformed); + return true; + } } public boolean isCorrect(@NotNull String word) { diff --git a/plugins/spellchecker/src/com/intellij/spellchecker/jetbrains.dic b/plugins/spellchecker/src/com/intellij/spellchecker/jetbrains.dic index f8539d5f3f11..989b0b38c818 100644 --- a/plugins/spellchecker/src/com/intellij/spellchecker/jetbrains.dic +++ b/plugins/spellchecker/src/com/intellij/spellchecker/jetbrains.dic @@ -113,6 +113,7 @@ filename fileset filesets filesystem +filesystems finalizer finalizers foreach diff --git a/plugins/spellchecker/testData/inspection/commentsWithMistakes/test.txt b/plugins/spellchecker/testData/inspection/commentsWithMistakes/test.txt index 0f2937c30b4b..b5c3a46c78b1 100644 --- a/plugins/spellchecker/testData/inspection/commentsWithMistakes/test.txt +++ b/plugins/spellchecker/testData/inspection/commentsWithMistakes/test.txt @@ -1 +1,2 @@ -simple ttest file (just plain text) \ No newline at end of file +simple ttest file (just plain text) +русский (например) без словаря не проверять!!! \ No newline at end of file diff --git a/plugins/spellchecker/testSrc/com/intellij/spellchecker/compress/EncoderTest.java b/plugins/spellchecker/testSrc/com/intellij/spellchecker/compress/EncoderTest.java index 67938d453857..ce7eecf366bd 100644 --- a/plugins/spellchecker/testSrc/com/intellij/spellchecker/compress/EncoderTest.java +++ b/plugins/spellchecker/testSrc/com/intellij/spellchecker/compress/EncoderTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2010 JetBrains s.r.o. + * Copyright 2000-2012 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,6 +24,7 @@ public class EncoderTest extends TestCase { Encoder encoder = new Encoder(); final String wordToTest = "abc"; final UnitBitSet bitSet = encoder.encode(wordToTest, true); + assertNotNull(bitSet); assertEquals(3, encoder.getAlphabet().getLastIndexUsed()); assertEquals(3, bitSet.getUnitValue(0)); assertEquals(1, bitSet.getUnitValue(1)); @@ -39,6 +40,7 @@ public class EncoderTest extends TestCase { Encoder encoder = new Encoder(); final String wordToTest = "aaa"; final UnitBitSet bitSet = encoder.encode(wordToTest, true); + assertNotNull(bitSet); assertEquals(1, encoder.getAlphabet().getLastIndexUsed()); assertEquals(3, bitSet.getUnitValue(0)); assertEquals(1, bitSet.getUnitValue(1)); @@ -53,6 +55,7 @@ public class EncoderTest extends TestCase { Encoder encoder = new Encoder(); final String wordToTest = "aba"; final UnitBitSet bitSet = encoder.encode(wordToTest, true); + assertNotNull(bitSet); assertEquals(2, encoder.getAlphabet().getLastIndexUsed()); assertEquals(3, bitSet.getUnitValue(0)); assertEquals(1, bitSet.getUnitValue(1)); @@ -67,6 +70,7 @@ public class EncoderTest extends TestCase { Encoder encoder = new Encoder(); final String wordToTest1 = "abc"; final UnitBitSet bitSet = encoder.encode(wordToTest1, true); + assertNotNull(bitSet); assertEquals(3, encoder.getAlphabet().getLastIndexUsed()); assertEquals(3, bitSet.getUnitValue(0)); assertEquals(1, bitSet.getUnitValue(1)); @@ -79,6 +83,7 @@ public class EncoderTest extends TestCase { final String wordToTest2 = "cba"; final UnitBitSet bitSet2 = encoder.encode(wordToTest2, true); assertEquals(3, encoder.getAlphabet().getLastIndexUsed()); + assertNotNull(bitSet); assertEquals(3, bitSet2.getUnitValue(0)); assertEquals(3, bitSet2.getUnitValue(1)); assertEquals(3, bitSet2.getUnitValue(2)); @@ -94,6 +99,7 @@ public class EncoderTest extends TestCase { final String wordToTest1 = "asia"; //letter 'a' will be added at the end final UnitBitSet bitSet = encoder.encode(wordToTest1, true); + assertNotNull(bitSet); assertEquals(20, encoder.getAlphabet().getLastIndexUsed()); assertEquals(4, bitSet.getUnitValue(0)); assertEquals(1, bitSet.getUnitValue(1)); @@ -107,5 +113,12 @@ public class EncoderTest extends TestCase { } + public void testUnknown() { + Encoder encoder = new Encoder(new Alphabet("abc")); + final String wordToTest1 = "def"; + final UnitBitSet bitSet = encoder.encode(wordToTest1, true); + assertEquals(bitSet, Encoder.WORD_OF_ENTIRELY_UNKNOWN_LETTERS); + } + } diff --git a/plugins/tasks/tasks-core/src/com/intellij/tasks/actions/GotoTaskAction.java b/plugins/tasks/tasks-core/src/com/intellij/tasks/actions/GotoTaskAction.java index e51c66e3c6e4..bd4fef3495a5 100644 --- a/plugins/tasks/tasks-core/src/com/intellij/tasks/actions/GotoTaskAction.java +++ b/plugins/tasks/tasks-core/src/com/intellij/tasks/actions/GotoTaskAction.java @@ -45,6 +45,11 @@ public class GotoTaskAction extends GotoActionBase { protected void gotoActionPerformed(final AnActionEvent e) { final Project project = e.getProject(); if (project == null) return; + perform(project); + } + + void perform(final Project project) { + myInAction = getClass(); final Ref shiftPressed = Ref.create(false); ChooseByNamePopup popup = ChooseByNamePopup.createPopup(project, new GotoTaskPopupModel(project), new ChooseByNameItemProvider() { diff --git a/plugins/tasks/tasks-core/src/com/intellij/tasks/actions/SwitchTaskAction.java b/plugins/tasks/tasks-core/src/com/intellij/tasks/actions/SwitchTaskAction.java index f095c5071ee8..857e49ace87c 100644 --- a/plugins/tasks/tasks-core/src/com/intellij/tasks/actions/SwitchTaskAction.java +++ b/plugins/tasks/tasks-core/src/com/intellij/tasks/actions/SwitchTaskAction.java @@ -16,11 +16,11 @@ package com.intellij.tasks.actions; +import com.intellij.ide.DataManager; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.Messages; -import com.intellij.openapi.ui.popup.JBPopupFactory; -import com.intellij.openapi.util.IconLoader; +import com.intellij.openapi.ui.popup.*; import com.intellij.openapi.util.Ref; import com.intellij.openapi.vcs.changes.ChangeListManager; import com.intellij.openapi.vcs.changes.LocalChangeList; @@ -28,7 +28,7 @@ import com.intellij.tasks.ChangeListInfo; import com.intellij.tasks.LocalTask; import com.intellij.tasks.TaskManager; import com.intellij.tasks.impl.TaskManagerImpl; -import com.intellij.tasks.impl.TaskUtil; +import com.intellij.tools.SimpleActionGroup; import com.intellij.ui.popup.list.ListPopupImpl; import com.intellij.util.NullableFunction; import com.intellij.util.containers.ContainerUtil; @@ -39,6 +39,7 @@ import javax.swing.*; import java.awt.event.ActionEvent; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; import java.util.List; /** @@ -46,26 +47,59 @@ import java.util.List; */ public class SwitchTaskAction extends BaseTaskAction { - private static final int MAX_ROW_COUNT = 20; - @Override public void actionPerformed(AnActionEvent e) { DataContext dataContext = e.getDataContext(); final Project project = PlatformDataKeys.PROJECT.getData(dataContext); assert project != null; - final ListPopupImpl popup = createPopup(dataContext, null, true); + final ListPopupImpl popup = createPopup(dataContext, true); popup.showCenteredInCurrentWindow(project); } - public static ListPopupImpl createPopup(DataContext dataContext, @Nullable Runnable onDispose, boolean withTitle) { + public static ListPopupImpl createPopup(final DataContext dataContext, boolean withTitle) { final Project project = PlatformDataKeys.PROJECT.getData(dataContext); final Ref shiftPressed = Ref.create(false); - final DefaultActionGroup group = project == null ? new DefaultActionGroup() : createPopupActionGroup(project, shiftPressed); + final Ref componentRef = Ref.create(); + List items = project == null ? Collections.emptyList() : + createPopupActionGroup(project, shiftPressed); final String title = withTitle ? "Switch to Task" : null; - final ListPopupImpl popup = (ListPopupImpl)JBPopupFactory.getInstance() - .createActionGroupPopup(title, group, dataContext, JBPopupFactory.ActionSelectionAid.SPEEDSEARCH, false, onDispose, MAX_ROW_COUNT); - - if (group.getChildrenCount() <= 2) { + ListPopupStep step = new MultiSelectionListPopupStep(title, items) { + @Override + public PopupStep onChosen(List selectedValues, boolean finalChoice) { + if (finalChoice) { + selectedValues.get(0).select(); + return FINAL_CHOICE; + } + ActionGroup group = createActionsStep(selectedValues, project, shiftPressed); + return JBPopupFactory.getInstance().createActionsStep(group, DataManager.getInstance().getDataContext(componentRef.get()), false, false, null, null, true); + } + + @Override + public Icon getIconFor(TaskListItem aValue) { + return aValue.getIcon(); + } + + @NotNull + @Override + public String getTextFor(TaskListItem value) { + return value.getText(); + } + + @Nullable + @Override + public ListSeparator getSeparatorAbove(TaskListItem value) { + return value.getSeparator() == null ? null : new ListSeparator(value.getSeparator()); + } + + @Override + public boolean hasSubstep(List selectedValues) { + return selectedValues.size() > 1 || selectedValues.get(0).getTask() != null; + } + }; + + final ListPopupImpl popup = (ListPopupImpl)JBPopupFactory.getInstance().createListPopup(step); + componentRef.set(popup.getComponent()); + if (items.size() <= 2) { return popup; } @@ -91,15 +125,48 @@ public class SwitchTaskAction extends BaseTaskAction { return popup; } - @NotNull - private static DefaultActionGroup createPopupActionGroup(@NotNull Project project, final Ref shiftPressed) { - DefaultActionGroup group = new DefaultActionGroup(); + private static ActionGroup createActionsStep(final List tasks, final Project project, final Ref shiftPressed) { + + SimpleActionGroup group = new SimpleActionGroup(); final TaskManager manager = TaskManager.getManager(project); + final LocalTask task = tasks.get(0).getTask(); + if (tasks.size() == 1 && task != null) { + group.add(new AnAction("&Switch to") { + public void actionPerformed(AnActionEvent e) { + manager.activateTask(task, !shiftPressed.get(), !tasks.get(0).isTemp()); + } + }); + } + final AnAction remove = new AnAction("&Remove") { + @Override + public void actionPerformed(AnActionEvent e) { + for (TaskListItem item : tasks) { + LocalTask itemTask = item.getTask(); + if (itemTask != null) { + removeTask(project, itemTask, manager); + } + } + } + }; + group.add(remove); - group.add(new GotoTaskAction()); - - group.addSeparator(); + return group; + } + @NotNull + private static List createPopupActionGroup(@NotNull final Project project, final Ref shiftPressed) { + List group = new ArrayList(); + + final GotoTaskAction gotoTaskAction = new GotoTaskAction(); + group.add(new TaskListItem(gotoTaskAction.getTemplatePresentation().getText(), + gotoTaskAction.getTemplatePresentation().getIcon()) { + @Override + void select() { + gotoTaskAction.perform(project); + } + }); + + final TaskManager manager = TaskManager.getManager(project); LocalTask activeTask = manager.getActiveTask(); LocalTask[] localTasks = manager.getLocalTasks(); Arrays.sort(localTasks, TaskManagerImpl.TASK_UPDATE_COMPARATOR); @@ -113,58 +180,29 @@ public class SwitchTaskAction extends BaseTaskAction { temp.add(task); continue; } - group.add(createActivateTaskAction(manager, project, task, shiftPressed, false)); + + group.add(new TaskListItem(task, group.size() == 1 ? "" : null, false) { + @Override + void select() { + manager.activateTask(task, !shiftPressed.get(), false); + } + }); } if (vcsEnabled && !temp.isEmpty()) { - group.addSeparator(); for (int i = 0, tempSize = temp.size(); i < Math.min(tempSize, 15); i++) { - LocalTask task = temp.get(i); - group.add(createActivateTaskAction(manager, project, task, shiftPressed, true)); + final LocalTask task = temp.get(i); + + group.add(new TaskListItem(task, i == 0 ? "Recently Closed Tasks" : null, true) { + @Override + void select() { + manager.activateTask(task, !shiftPressed.get(), true); + } + }); } } return group; } - private static AnAction createActivateTaskAction(final TaskManager manager, - final Project project, - final LocalTask task, - final Ref shiftPressed, - final boolean temp) { - String trimmedSummary = TaskUtil.getTrimmedSummary(task); - - Icon icon = temp ? IconLoader.getTransparentIcon(task.getIcon(), 0.5f) : task.getIcon(); - final AnAction switchAction = new AnAction("&Switch to") { - public void actionPerformed(AnActionEvent e) { - manager.activateTask(task, !shiftPressed.get(), !temp); - } - }; - ActionGroup group = new ActionGroup(trimmedSummary, task.getSummary(), icon) { - - @NotNull - @Override - public AnAction[] getChildren(@Nullable AnActionEvent e) { - return new AnAction[]{switchAction, new AnAction("&Remove") { - @Override - public void actionPerformed(AnActionEvent e) { - removeTask(project, task, manager); - } - }}; - } - - @Override - public void actionPerformed(AnActionEvent e) { - switchAction.actionPerformed(e); - } - - @Override - public boolean canBePerformed(DataContext context) { - return true; - } - }; - group.setPopup(true); - return group; - } - public static void removeTask(final @NotNull Project project, LocalTask task, TaskManager manager) { if (task.isDefault()) { Messages.showInfoMessage(project, "Default task cannot be removed", "Cannot Remove"); @@ -183,7 +221,7 @@ public class SwitchTaskAction extends BaseTaskAction { l: for (LocalChangeList list : lists) { if (!list.getChanges().isEmpty()) { int result = Messages.showYesNoCancelDialog(project, - "Changelist associated with this task is not empty.\n" + + "Changelist associated with '" + task.getSummary() + "' is not empty.\n" + "Do you want to remove it and move the changes to the active changelist?", "Changelist Not Empty", Messages.getWarningIcon()); switch (result) { diff --git a/plugins/tasks/tasks-core/src/com/intellij/tasks/actions/SwitchTaskCombo.java b/plugins/tasks/tasks-core/src/com/intellij/tasks/actions/SwitchTaskCombo.java index 300981ef56ea..a975a0e52e68 100644 --- a/plugins/tasks/tasks-core/src/com/intellij/tasks/actions/SwitchTaskCombo.java +++ b/plugins/tasks/tasks-core/src/com/intellij/tasks/actions/SwitchTaskCombo.java @@ -66,7 +66,7 @@ public class SwitchTaskCombo extends ComboBoxAction implements DumbAware { @Override protected JBPopup createPopup(Runnable onDispose) { - return SwitchTaskAction.createPopup(DataManager.getInstance().getDataContext(this), onDispose, false); + return SwitchTaskAction.createPopup(DataManager.getInstance().getDataContext(this), false); } }; } diff --git a/plugins/tasks/tasks-core/src/com/intellij/tasks/actions/TaskListItem.java b/plugins/tasks/tasks-core/src/com/intellij/tasks/actions/TaskListItem.java new file mode 100644 index 000000000000..9ce413b638ff --- /dev/null +++ b/plugins/tasks/tasks-core/src/com/intellij/tasks/actions/TaskListItem.java @@ -0,0 +1,76 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.intellij.tasks.actions; + +import com.intellij.openapi.util.IconLoader; +import com.intellij.tasks.LocalTask; +import com.intellij.tasks.impl.TaskUtil; +import org.jetbrains.annotations.Nullable; + +import javax.swing.*; + +/** + * @author Dmitry Avdeev + * Date: 9/6/12 + */ +abstract class TaskListItem { + + private final String myText; + private final Icon myIcon; + private final String mySeparator; + private final boolean myTemp; + private final LocalTask myTask; + + public TaskListItem(String text, Icon icon) { + myText = text; + myIcon = icon; + mySeparator = null; + myTask = null; + myTemp = false; + } + + protected TaskListItem(LocalTask task, String separator, boolean temp) { + myTask = task; + mySeparator = separator; + myTemp = temp; + myText = TaskUtil.getTrimmedSummary(task); + myIcon = temp ? IconLoader.getTransparentIcon(task.getIcon(), 0.5f) : task.getIcon(); + } + + public String getText() { + return myText; + } + + public Icon getIcon() { + return myIcon; + } + + @Nullable + public String getSeparator() { + return mySeparator; + } + + abstract void select(); + + @Nullable + public LocalTask getTask() { + return myTask; + } + + public boolean isTemp() { + return myTemp; + } +} diff --git a/plugins/ui-designer/src/com/intellij/uiDesigner/make/Form2SourceCompiler.java b/plugins/ui-designer/src/com/intellij/uiDesigner/make/Form2SourceCompiler.java index 2ac8c543806e..05ba5140707a 100644 --- a/plugins/ui-designer/src/com/intellij/uiDesigner/make/Form2SourceCompiler.java +++ b/plugins/ui-designer/src/com/intellij/uiDesigner/make/Form2SourceCompiler.java @@ -23,7 +23,7 @@ import com.intellij.openapi.compiler.*; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.fileTypes.StdFileTypes; import com.intellij.openapi.module.Module; -import com.intellij.openapi.module.ModuleUtil; +import com.intellij.openapi.module.ModuleUtilCore; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiDocumentManager; @@ -88,9 +88,7 @@ public final class Form2SourceCompiler implements SourceInstrumentingCompiler{ continue; } catch (Exception e) { - addError(context, - new FormErrorInfo(null, UIDesignerBundle.message("error.cannot.process.form.file", e)), - formFile); + addError(context, new FormErrorInfo(null, UIDesignerBundle.message("error.cannot.process.form.file", e)), formFile); continue; } @@ -101,9 +99,7 @@ public final class Form2SourceCompiler implements SourceInstrumentingCompiler{ final VirtualFile sourceFile = Form2ByteCodeCompiler.findSourceFile(context, formFile, classToBind); if (sourceFile == null) { if (scope.belongs(formFile.getUrl())) { - addError(context, - new FormErrorInfo(null, UIDesignerBundle.message("error.class.to.bind.does.not.exist", classToBind)), - formFile); + addError(context, new FormErrorInfo(null, UIDesignerBundle.message("error.class.to.bind.does.not.exist", classToBind)), formFile); } continue; } @@ -113,12 +109,7 @@ public final class Form2SourceCompiler implements SourceInstrumentingCompiler{ final VirtualFile alreadyProcessedForm = class2form.get(classToBind); if (alreadyProcessedForm != null) { if (inScope) { - addError( - context, - new FormErrorInfo(null, UIDesignerBundle.message("error.duplicate.bind", - classToBind, alreadyProcessedForm.getPresentableUrl())), - formFile - ); + addError(context, new FormErrorInfo(null, UIDesignerBundle.message("error.duplicate.bind", classToBind, alreadyProcessedForm.getPresentableUrl())), formFile); } continue; } @@ -128,8 +119,7 @@ public final class Form2SourceCompiler implements SourceInstrumentingCompiler{ continue; } - final ProcessingItem item = new MyInstrumentationItem(sourceFile, formFile); - items.add(item); + items.add(new MyInstrumentationItem(sourceFile, formFile)); } } finally { @@ -164,7 +154,7 @@ public final class Form2SourceCompiler implements SourceInstrumentingCompiler{ if (GuiDesignerConfiguration.getInstance(project).COPY_FORMS_RUNTIME_TO_OUTPUT) { ApplicationManager.getApplication().runReadAction(new Runnable() { public void run() { - final Module module = ModuleUtil.findModuleForFile(formFile, project); + final Module module = ModuleUtilCore.findModuleForFile(formFile, project); if (module != null && !processedModules.contains(module)) { processedModules.add(module); final String moduleOutputPath = CompilerPaths.getModuleOutputPath(module, false); diff --git a/plugins/ui-designer/src/com/intellij/uiDesigner/make/SourceInstrumentationTask.java b/plugins/ui-designer/src/com/intellij/uiDesigner/make/SourceInstrumentationTask.java new file mode 100644 index 000000000000..4c63db0dd23e --- /dev/null +++ b/plugins/ui-designer/src/com/intellij/uiDesigner/make/SourceInstrumentationTask.java @@ -0,0 +1,117 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.intellij.uiDesigner.make; + +import com.intellij.compiler.CompilerWorkspaceConfiguration; +import com.intellij.compiler.impl.CompilerCacheManager; +import com.intellij.compiler.impl.CompilerUtil; +import com.intellij.compiler.impl.FileProcessingCompilerStateCache; +import com.intellij.openapi.application.ApplicationManager; +import com.intellij.openapi.compiler.*; +import com.intellij.openapi.project.DumbService; +import com.intellij.openapi.project.Project; +import com.intellij.openapi.util.Ref; +import com.intellij.openapi.vfs.LocalFileSystem; +import com.intellij.openapi.vfs.VirtualFile; +import com.intellij.util.ThrowableRunnable; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +/** + * This is an adapter for Form2SourceCompiler to CompileTask interface + * + * + * @author Eugene Zhuravlev + * Date: 9/5/12 + */ +public class SourceInstrumentationTask implements CompileTask{ + private final Form2SourceCompiler myCompiler = new Form2SourceCompiler(); + + @Override + public boolean execute(CompileContext context) { + final Project project = context.getProject(); + if (!CompilerWorkspaceConfiguration.getInstance(project).useOutOfProcessBuild()) { + return true; + } + try { + final FileProcessingCompiler.ProcessingItem[] items = myCompiler.getProcessingItems(context); + if (items.length == 0) { + return true; + } + final List toProcess = new ArrayList(); + final Ref ex = new Ref(null); + + DumbService.getInstance(project).waitForSmartMode(); + + final FileProcessingCompilerStateCache cache = CompilerCacheManager.getInstance(project).getFileProcessingCompilerCache(myCompiler); + final boolean isMake = context.isMake(); + ApplicationManager.getApplication().runReadAction(new Runnable() { + public void run() { + try { + for (FileProcessingCompiler.ProcessingItem item : items) { + final VirtualFile file = item.getFile(); + final String url = file.getUrl(); + if (isMake && cache.getTimestamp(url) == file.getTimeStamp()) { + final ValidityState state = cache.getExtState(url); + final ValidityState itemState = item.getValidityState(); + if (state != null ? state.equalsTo(itemState) : itemState == null) { + continue; + } + } + toProcess.add(item); + } + } + catch (IOException e) { + ex.set(e); + } + } + }); + + if (ex.get() != null) { + throw ex.get(); + } + + if (toProcess.isEmpty()) { + return true; + } + + final FileProcessingCompiler.ProcessingItem[] processed = myCompiler.process(context, toProcess.toArray(new FileProcessingCompiler.ProcessingItem[toProcess.size()])); + + if (processed.length == 0) { + return true; + } + + CompilerUtil.runInContext(context, CompilerBundle.message("progress.updating.caches"), new ThrowableRunnable() { + public void run() throws IOException{ + final List vFiles = new ArrayList(processed.length); + for (FileProcessingCompiler.ProcessingItem item : processed) { + vFiles.add(item.getFile()); + } + LocalFileSystem.getInstance().refreshFiles(vFiles); + for (FileProcessingCompiler.ProcessingItem item : processed) { + cache.update(item.getFile(), item.getValidityState()); + } + } + }); + } + catch (IOException e) { + throw new RuntimeException(e); + } + return true; + } +} diff --git a/plugins/ui-designer/src/com/intellij/uiDesigner/propertyInspector/UIDesignerToolWindowManager.java b/plugins/ui-designer/src/com/intellij/uiDesigner/propertyInspector/UIDesignerToolWindowManager.java index 82bff0979708..e7ed3b70a7ea 100644 --- a/plugins/ui-designer/src/com/intellij/uiDesigner/propertyInspector/UIDesignerToolWindowManager.java +++ b/plugins/ui-designer/src/com/intellij/uiDesigner/propertyInspector/UIDesignerToolWindowManager.java @@ -18,6 +18,7 @@ package com.intellij.uiDesigner.propertyInspector; import com.intellij.openapi.actionSystem.DataProvider; import com.intellij.openapi.application.ApplicationManager; +import com.intellij.openapi.compiler.CompilerManager; import com.intellij.openapi.components.ProjectComponent; import com.intellij.openapi.fileEditor.FileEditor; import com.intellij.openapi.fileEditor.FileEditorManager; @@ -39,6 +40,7 @@ import com.intellij.uiDesigner.componentTree.ComponentTree; import com.intellij.uiDesigner.componentTree.ComponentTreeBuilder; import com.intellij.uiDesigner.designSurface.GuiEditor; import com.intellij.uiDesigner.editor.UIFormEditor; +import com.intellij.uiDesigner.make.SourceInstrumentationTask; import com.intellij.util.ui.update.MergingUpdateQueue; import com.intellij.util.ui.update.Update; import icons.UIDesignerIcons; @@ -80,6 +82,7 @@ public class UIDesignerToolWindowManager implements ProjectComponent { StartupManager.getInstance(myProject).registerPostStartupActivity(new Runnable() { public void run() { myToolWindowReady = true; + CompilerManager.getInstance(myProject).addBeforeTask(new SourceInstrumentationTask()); } }); } diff --git a/plugins/ui-designer/testData/sourceCodeGenerator/duplicateSetupCall/BindingTest.java.after b/plugins/ui-designer/testData/sourceCodeGenerator/duplicateSetupCall/BindingTest.java.after index d5709bedaac7..7b4a8aaacc3e 100644 --- a/plugins/ui-designer/testData/sourceCodeGenerator/duplicateSetupCall/BindingTest.java.after +++ b/plugins/ui-designer/testData/sourceCodeGenerator/duplicateSetupCall/BindingTest.java.after @@ -57,4 +57,5 @@ public class BindingTest { public JComponent $$$getRootComponent$$$() { return myRootComponent; } + }