diff --git a/java/compiler/impl/src/com/intellij/compiler/CompilerConfigurationImpl.java b/java/compiler/impl/src/com/intellij/compiler/CompilerConfigurationImpl.java index 7ba9cbc25da2..338b47336feb 100644 --- a/java/compiler/impl/src/com/intellij/compiler/CompilerConfigurationImpl.java +++ b/java/compiler/impl/src/com/intellij/compiler/CompilerConfigurationImpl.java @@ -1,4 +1,3 @@ - /* * Copyright 2000-2014 JetBrains s.r.o. * @@ -23,17 +22,11 @@ package com.intellij.compiler; import com.intellij.CommonBundle; import com.intellij.ProjectTopics; -import com.intellij.compiler.impl.TranslatingCompilerFilesMonitor; import com.intellij.compiler.impl.javaCompiler.BackendCompiler; -import com.intellij.compiler.impl.javaCompiler.api.CompilerAPICompiler; import com.intellij.compiler.impl.javaCompiler.eclipse.EclipseCompiler; -import com.intellij.compiler.impl.javaCompiler.eclipse.EclipseEmbeddedCompiler; import com.intellij.compiler.impl.javaCompiler.javac.JavacCompiler; -import com.intellij.compiler.options.ExternalBuildOptionListener; -import com.intellij.compiler.server.BuildManager; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ApplicationNamesInfo; -import com.intellij.openapi.application.ex.ApplicationManagerEx; import com.intellij.openapi.compiler.CompilerBundle; import com.intellij.openapi.compiler.CompilerManager; import com.intellij.openapi.compiler.options.ExcludedEntriesConfiguration; @@ -80,7 +73,6 @@ import java.util.*; public class CompilerConfigurationImpl extends CompilerConfiguration implements PersistentStateComponent, ProjectComponent { 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; @SuppressWarnings({"WeakerAccess"}) public String DEFAULT_COMPILER; @NotNull private BackendCompiler myDefaultJavaCompiler; @@ -128,33 +120,6 @@ public class CompilerConfigurationImpl extends CompilerConfiguration implements myProcessorsProfilesMap = null; // clear cache } }); - - connection.subscribe(ExternalBuildOptionListener.TOPIC, new ExternalBuildOptionListener() { - @Override - public void externalBuildOptionChanged(boolean externalBuildEnabled) { - // this will schedule for compilation all files that might become compilable after resource patterns' changing - final TranslatingCompilerFilesMonitor monitor = TranslatingCompilerFilesMonitor.getInstance(); - if (externalBuildEnabled) { - monitor.suspendProject(myProject); - } - else { - monitor.watchProject(myProject); - monitor.scanSourcesForCompilableFiles(myProject); - if (!myProject.isDefault()) { - final File buildSystem = BuildManager.getInstance().getBuildSystemDirectory(); - final File[] subdirs = buildSystem.listFiles(); - if (subdirs != null) { - final String prefix = myProject.getName().toLowerCase(Locale.US) + "_"; - for (File subdir : subdirs) { - if (subdir.getName().startsWith(prefix)) { - FileUtil.asyncDelete(subdir); - } - } - } - } - } - } - }); } public Element getState() { @@ -290,35 +255,14 @@ public class CompilerConfigurationImpl extends CompilerConfiguration implements myRegisteredCompilers.add(JAVAC_EXTERNAL_BACKEND); if (!ApplicationManager.getApplication().isUnitTestMode()) { - //final BackendCompiler JIKES_BACKEND = new JikesCompiler(myProject); - //myRegisteredCompilers.add(JIKES_BACKEND); - if (EclipseCompiler.isInitialized()) { final EclipseCompiler eclipse = new EclipseCompiler(myProject); myRegisteredCompilers.add(eclipse); } - - if (ApplicationManagerEx.getApplicationEx().isInternal()) { - try { - final EclipseEmbeddedCompiler eclipseEmbedded = new EclipseEmbeddedCompiler(myProject); - myRegisteredCompilers.add(eclipseEmbedded); - } - catch (NoClassDefFoundError e) { - // eclipse jar must be not in the classpath - } - try { - CompilerAPICompiler inProcessJavaCompiler = new CompilerAPICompiler(myProject); - myRegisteredCompilers.add(inProcessJavaCompiler); - } - catch (NoClassDefFoundError e) { - // wrong JDK - } - } } - final BackendCompiler[] compilers = Extensions.getExtensions(BackendCompiler.EP_NAME, myProject); final Set types = new HashSet(); - for (BackendCompiler compiler : compilers) { + for (BackendCompiler compiler : Extensions.getExtensions(BackendCompiler.EP_NAME, myProject)) { myRegisteredCompilers.add(compiler); types.addAll(compiler.getCompilableFileTypes()); } @@ -327,7 +271,7 @@ public class CompilerConfigurationImpl extends CompilerConfiguration implements for (FileType type : types) { compilerManager.addCompilableFileType(type); } - + myDefaultJavaCompiler = JAVAC_EXTERNAL_BACKEND; for (BackendCompiler compiler : myRegisteredCompilers) { if (compiler.getId().equals(DEFAULT_COMPILER)) { @@ -338,11 +282,6 @@ public class CompilerConfigurationImpl extends CompilerConfiguration implements DEFAULT_COMPILER = myDefaultJavaCompiler.getId(); } - public Collection getRegisteredJavaCompilers() { - createCompilers(); - return myRegisteredCompilers; - } - public String[] getResourceFilePatterns() { return getWildcardPatterns(); } diff --git a/java/compiler/impl/src/com/intellij/compiler/CompilerManagerImpl.java b/java/compiler/impl/src/com/intellij/compiler/CompilerManagerImpl.java index 64356bf491b2..14158f178d35 100644 --- a/java/compiler/impl/src/com/intellij/compiler/CompilerManagerImpl.java +++ b/java/compiler/impl/src/com/intellij/compiler/CompilerManagerImpl.java @@ -16,10 +16,6 @@ package com.intellij.compiler; import com.intellij.compiler.impl.*; -import com.intellij.compiler.impl.javaCompiler.AnnotationProcessingCompiler; -import com.intellij.compiler.impl.javaCompiler.JavaCompiler; -import com.intellij.compiler.impl.resourceCompiler.ResourceCompiler; -import com.intellij.compiler.impl.rmiCompiler.RmicCompiler; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.compiler.*; @@ -35,11 +31,6 @@ import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.ArrayUtil; -import com.intellij.util.Chunk; -import com.intellij.util.containers.ContainerUtil; -import com.intellij.util.graph.CachingSemiGraph; -import com.intellij.util.graph.Graph; -import com.intellij.util.graph.GraphGenerator; import com.intellij.util.messages.MessageBus; import com.intellij.util.messages.MessageBusConnection; import org.jetbrains.annotations.NotNull; @@ -54,28 +45,20 @@ public class CompilerManagerImpl extends CompilerManager { private final Project myProject; private final List myCompilers = new ArrayList(); - private final List myTranslators = new ArrayList(); private final List myBeforeTasks = new ArrayList(); private final List myAfterTasks = new ArrayList(); private final Set myCompilableTypes = new HashSet(); private final CompilationStatusListener myEventPublisher; private final Semaphore myCompilationSemaphore = new Semaphore(1, true); - private final Map> myCompilerToInputTypes = new HashMap>(); - private final Map> myCompilerToOutputTypes = new HashMap>(); private final Set myValidationDisabledModuleTypes = new HashSet(); private final Set myWatchRoots; - public CompilerManagerImpl(final Project project, CompilerConfigurationImpl compilerConfiguration, MessageBus messageBus) { + public CompilerManagerImpl(final Project project, MessageBus messageBus) { myProject = project; myEventPublisher = messageBus.syncPublisher(CompilerTopics.COMPILATION_STATUS); // predefined compilers - addTranslatingCompiler(new AnnotationProcessingCompiler(project), new HashSet(Arrays.asList(StdFileTypes.JAVA)), new HashSet(Arrays.asList(StdFileTypes.JAVA, StdFileTypes.CLASS))); - addTranslatingCompiler(new JavaCompiler(project), new HashSet(Arrays.asList(StdFileTypes.JAVA)), new HashSet(Arrays.asList(StdFileTypes.CLASS))); - addCompiler(new ResourceCompiler(project, compilerConfiguration)); - addCompiler(new RmicCompiler()); - for(Compiler compiler: Extensions.getExtensions(Compiler.EP_NAME, myProject)) { addCompiler(compiler); } @@ -87,7 +70,7 @@ public class CompilerManagerImpl extends CompilerManager { } addCompilableFileType(StdFileTypes.JAVA); - + final File projectGeneratedSrcRoot = CompilerPaths.getGeneratedDataDirectory(project); projectGeneratedSrcRoot.mkdirs(); final LocalFileSystem lfs = LocalFileSystem.getInstance(); @@ -100,28 +83,6 @@ public class CompilerManagerImpl extends CompilerManager { } } }); - - // - //addCompiler(new DummyTransformingCompiler()); // this one is for testing purposes only - //addCompiler(new DummySourceGeneratingCompiler(myProject)); // this one is for testing purposes only - /* - // for testing only - ApplicationManager.getApplication().invokeLater(new Runnable() { - public void run() { - ApplicationManager.getApplication().runWriteAction(new Runnable() { - public void run() { - FileTypeManager.getInstance().registerFileType(DummyTranslatingCompiler.INPUT_FILE_TYPE, DummyTranslatingCompiler.FILETYPE_EXTENSION); - addTranslatingCompiler( - new DummyTranslatingCompiler(), - new HashSet(Arrays.asList(DummyTranslatingCompiler.INPUT_FILE_TYPE)), - new HashSet(Arrays.asList( StdFileTypes.JAVA)) - ); - } - }); - - } - }); - */ } public Semaphore getCompilationSemaphore() { @@ -132,68 +93,32 @@ public class CompilerManagerImpl extends CompilerManager { return myCompilationSemaphore.availablePermits() == 0; } - public void addTranslatingCompiler(@NotNull final TranslatingCompiler compiler, final Set inputTypes, final Set outputTypes) { - myTranslators.add(compiler); - myCompilerToInputTypes.put(compiler, inputTypes); - myCompilerToOutputTypes.put(compiler, outputTypes); - - final List> chunks = ModuleCompilerUtil.getSortedChunks(createCompilerGraph((List)(List)myTranslators)); - - myTranslators.clear(); - for (Chunk chunk : chunks) { - for (Compiler chunkCompiler : chunk.getNodes()) { - myTranslators.add((TranslatingCompiler)chunkCompiler); - } - } - } - - @NotNull - public Set getRegisteredInputTypes(@NotNull final TranslatingCompiler compiler) { - final Set inputs = myCompilerToInputTypes.get(compiler); - return inputs != null? Collections.unmodifiableSet(inputs) : Collections.emptySet(); - } - - @NotNull - public Set getRegisteredOutputTypes(@NotNull final TranslatingCompiler compiler) { - final Set outs = myCompilerToOutputTypes.get(compiler); - return outs != null? Collections.unmodifiableSet(outs) : Collections.emptySet(); - } - public final void addCompiler(@NotNull Compiler compiler) { - if (compiler instanceof TranslatingCompiler) { - myTranslators.add((TranslatingCompiler)compiler); + myCompilers.add(compiler); + // supporting file instrumenting compilers and validators for external build + // Since these compilers are IDE-specific and use PSI, it is ok to run them before and after the build in the IDE + if (compiler instanceof SourceInstrumentingCompiler) { + addBeforeTask(new FileProcessingCompilerAdapterTask((FileProcessingCompiler)compiler)); } - else { - myCompilers.add(compiler); - // supporting file instrumenting compilers and validators for external build - // Since these compilers are IDE-specific and use PSI, it is ok to run them before and after the build in the IDE - if (compiler instanceof SourceInstrumentingCompiler) { - addBeforeTask(new FileProcessingCompilerAdapterTask((FileProcessingCompiler)compiler)); - } - else if (compiler instanceof Validator) { - addAfterTask(new FileProcessingCompilerAdapterTask((FileProcessingCompiler)compiler)); - } + else if (compiler instanceof Validator) { + addAfterTask(new FileProcessingCompilerAdapterTask((FileProcessingCompiler)compiler)); } } + @Deprecated + public void addTranslatingCompiler(@NotNull TranslatingCompiler compiler, Set inputTypes, Set outputTypes) { + // empty + } + public final void removeCompiler(@NotNull Compiler compiler) { - if (compiler instanceof TranslatingCompiler) { - myTranslators.remove(compiler); - } - else { - if (myCompilers.remove(compiler)) { - for (List tasks : Arrays.asList(myBeforeTasks, myAfterTasks)) { - for (Iterator iterator = tasks.iterator(); iterator.hasNext(); ) { - CompileTask task = iterator.next(); - if (task instanceof FileProcessingCompilerAdapterTask && ((FileProcessingCompilerAdapterTask)task).getCompiler() == compiler) { - iterator.remove(); - } - } + for (List tasks : Arrays.asList(myBeforeTasks, myAfterTasks)) { + for (Iterator iterator = tasks.iterator(); iterator.hasNext(); ) { + CompileTask task = iterator.next(); + if (task instanceof FileProcessingCompilerAdapterTask && ((FileProcessingCompilerAdapterTask)task).getCompiler() == compiler) { + iterator.remove(); } } } - myCompilerToInputTypes.remove(compiler); - myCompilerToOutputTypes.remove(compiler); } @NotNull @@ -209,11 +134,6 @@ public class CompilerManagerImpl extends CompilerManager { compilers.add((T)item); } } - for (final Compiler item : myTranslators) { - if (compilerClass.isAssignableFrom(item.getClass()) && filter.acceptCompiler(item)) { - compilers.add((T)item); - } - } final T[] array = (T[])Array.newInstance(compilerClass, compilers.size()); return compilers.toArray(array); } @@ -263,11 +183,11 @@ public class CompilerManagerImpl extends CompilerManager { } public void compile(@NotNull Module module, CompileStatusNotification callback) { - new CompileDriver(myProject).compile(createModuleCompileScope(module, false), new ListenerNotificator(callback), true); + new CompileDriver(myProject).compile(createModuleCompileScope(module, false), new ListenerNotificator(callback)); } public void compile(@NotNull CompileScope scope, CompileStatusNotification callback) { - new CompileDriver(myProject).compile(scope, new ListenerNotificator(callback), false); + new CompileDriver(myProject).compile(scope, new ListenerNotificator(callback)); } public void make(CompileStatusNotification callback) { @@ -372,20 +292,6 @@ public class CompilerManagerImpl extends CompilerManager { return CompilerConfiguration.getInstance(myProject).isExcludedFromCompilation(file); } - private static final OutputToSourceMapping OUTPUT_TO_SOURCE_MAPPING = new OutputToSourceMapping() { - public String getSourcePath(final String outputPath) { - final LocalFileSystem lfs = LocalFileSystem.getInstance(); - final VirtualFile outputFile = lfs.findFileByPath(outputPath); - - final VirtualFile sourceFile = outputFile != null ? TranslatingCompilerFilesMonitor.getSourceFileByOutput(outputFile) : null; - return sourceFile != null? sourceFile.getPath() : null; - } - }; - @NotNull - public OutputToSourceMapping getJavaCompilerOutputMapping() { - return OUTPUT_TO_SOURCE_MAPPING; - } - @NotNull public CompileScope createFilesCompileScope(@NotNull final VirtualFile[] files) { CompileScope[] scopes = new CompileScope[files.length]; @@ -438,32 +344,6 @@ public class CompilerManagerImpl extends CompilerManager { return !myValidationDisabledModuleTypes.contains(ModuleType.get(module)); } - private Graph createCompilerGraph(final List compilers) { - return GraphGenerator.create(CachingSemiGraph.create(new GraphGenerator.SemiGraph() { - public Collection getNodes() { - return compilers; - } - - public Iterator getIn(Compiler compiler) { - final Set compilerInput = myCompilerToInputTypes.get(compiler); - if (compilerInput == null || compilerInput.isEmpty()) { - return Collections.emptySet().iterator(); - } - - final Set inCompilers = new HashSet(); - - for (Map.Entry> entry : myCompilerToOutputTypes.entrySet()) { - final Set outputs = entry.getValue(); - Compiler comp = entry.getKey(); - if (outputs != null && ContainerUtil.intersects(compilerInput, outputs)) { - inCompilers.add(comp); - } - } - return inCompilers.iterator(); - } - })); - } - private class ListenerNotificator implements CompileStatusNotification { private final @Nullable CompileStatusNotification myDelegate; diff --git a/java/compiler/impl/src/com/intellij/compiler/CompilerSettingsUsageCollector.java b/java/compiler/impl/src/com/intellij/compiler/CompilerSettingsUsageCollector.java index 06bf055246c3..7110947c291b 100644 --- a/java/compiler/impl/src/com/intellij/compiler/CompilerSettingsUsageCollector.java +++ b/java/compiler/impl/src/com/intellij/compiler/CompilerSettingsUsageCollector.java @@ -23,7 +23,6 @@ import com.intellij.openapi.project.Project; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.Collections; import java.util.HashSet; import java.util.Set; @@ -38,12 +37,8 @@ public class CompilerSettingsUsageCollector extends UsagesCollector{ @Override public Set getUsages(@Nullable Project project) throws CollectUsagesException { final CompilerWorkspaceConfiguration wsConfig = CompilerWorkspaceConfiguration.getInstance(project); - if (!wsConfig.useOutOfProcessBuild()) { - return Collections.emptySet(); - } final Set result = new HashSet(); - result.add(new UsageDescriptor("external_build", 1)); if (wsConfig.MAKE_PROJECT_ON_SAVE) { result.add(new UsageDescriptor("auto_make", 1)); } diff --git a/java/compiler/impl/src/com/intellij/compiler/DependencyProcessor.java b/java/compiler/impl/src/com/intellij/compiler/DependencyProcessor.java deleted file mode 100644 index 3907eb81c040..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/DependencyProcessor.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.compiler; - -import com.intellij.compiler.make.CacheCorruptedException; -import com.intellij.compiler.make.CachingSearcher; -import com.intellij.openapi.compiler.CompileContext; -import com.intellij.openapi.extensions.ExtensionPointName; - -/** - * @author Eugene Zhuravlev - * Date: Aug 19, 2008 - */ -public interface DependencyProcessor { - ExtensionPointName EXTENSION_POINT_NAME = ExtensionPointName.create("com.intellij.compiler.makeDependencyProcessor"); - - void processDependencies(CompileContext context, int classQualifiedName, CachingSearcher searcher) throws CacheCorruptedException; -} diff --git a/java/compiler/impl/src/com/intellij/compiler/OutputParser.java b/java/compiler/impl/src/com/intellij/compiler/OutputParser.java index 37f688263173..8897a2434129 100644 --- a/java/compiler/impl/src/com/intellij/compiler/OutputParser.java +++ b/java/compiler/impl/src/com/intellij/compiler/OutputParser.java @@ -15,7 +15,6 @@ */ package com.intellij.compiler; -import com.intellij.compiler.impl.javaCompiler.FileObject; import com.intellij.openapi.compiler.CompilerMessageCategory; import com.intellij.openapi.util.text.StringUtil; import org.jetbrains.annotations.NonNls; @@ -27,12 +26,12 @@ public abstract class OutputParser { protected final List myParserActions = new ArrayList(10); public interface Callback { - @NonNls String getNextLine(); - @NonNls String getCurrentLine(); + String getNextLine(); + String getCurrentLine(); void pushBack(String line); void setProgressText(String text); - void fileProcessed(@NonNls String path); - void fileGenerated(@NonNls FileObject path); + void fileProcessed(String path); + void fileGenerated(String path); void message(CompilerMessageCategory category, String message, @NonNls String url, int lineNum, int columnNum); } @@ -65,8 +64,4 @@ public abstract class OutputParser { protected static void addMessage(Callback callback, CompilerMessageCategory type, String text, String url, int line, int column){ callback.message(type, text, url, line, column); } - - public boolean isTrimLines() { - return true; - } } \ No newline at end of file diff --git a/java/compiler/impl/src/com/intellij/compiler/SymbolTable.java b/java/compiler/impl/src/com/intellij/compiler/SymbolTable.java deleted file mode 100644 index 48603f534ad2..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/SymbolTable.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * @author: Eugene Zhuravlev - * Date: Mar 3, 2003 - * Time: 12:34:44 PM - */ -package com.intellij.compiler; - -import com.intellij.compiler.make.CacheCorruptedException; -import com.intellij.openapi.compiler.CompilerBundle; -import com.intellij.openapi.util.io.FileUtil; -import com.intellij.util.containers.SLRUCache; -import com.intellij.util.io.PersistentEnumerator; -import com.intellij.util.io.PersistentStringEnumerator; -import org.jetbrains.annotations.NotNull; - -import java.io.File; -import java.io.IOException; - -public class SymbolTable { - private final PersistentStringEnumerator myTrie; - - // both caches should have equal size - private static final int STRING_CACHE_SIZE = 1024; - - private final SLRUCache myIndexStringCache = new SLRUCache(STRING_CACHE_SIZE * 2, STRING_CACHE_SIZE) { - @NotNull - public String createValue(Integer key) { - try { - return myTrie.valueOf(key.intValue()); - } - catch (IOException e) { - throw new RuntimeException(e); - } - } - }; - - private final SLRUCache myStringIndexCache = new SLRUCache(STRING_CACHE_SIZE * 2, STRING_CACHE_SIZE) { - @NotNull - public Integer createValue(String key) { - try { - return myTrie.enumerate(key); - } - catch (IOException e) { - throw new RuntimeException(e); - } - } - }; - - - public SymbolTable(File file) throws CacheCorruptedException { - try { - if (!file.exists()) { - FileUtil.createIfDoesntExist(file); - } - myTrie = new PersistentStringEnumerator(file); - } - catch (PersistentEnumerator.CorruptedException e) { - throw new CacheCorruptedException(CompilerBundle.message("error.compiler.caches.corrupted"), e); - } - catch (IOException e) { - throw new CacheCorruptedException(e); - } - } - - public synchronized int getId(@NotNull String symbol) throws CacheCorruptedException { - if (symbol.length() == 0) { - return -1; - } - try { - return myStringIndexCache.get(symbol); - } - catch (RuntimeException e) { - if (e.getCause() instanceof IOException) { - throw new CacheCorruptedException(e.getCause()); - } - throw e; - } - } - - public synchronized String getSymbol(int id) throws CacheCorruptedException { - if (id == -1) { - return ""; - } - try { - return myIndexStringCache.get(id); - } - catch (RuntimeException e) { - if (e.getCause() instanceof IOException) { - throw new CacheCorruptedException(e.getCause()); - } - throw e; - } - } - - public synchronized void dispose() throws CacheCorruptedException { - try { - myIndexStringCache.clear(); - myStringIndexCache.clear(); - myTrie.close(); // will call "flush()" if needed - } - catch (IOException e) { - throw new CacheCorruptedException(e); - } - } -} diff --git a/java/compiler/impl/src/com/intellij/compiler/actions/BuildArtifactAction.java b/java/compiler/impl/src/com/intellij/compiler/actions/BuildArtifactAction.java index ca18acaf0919..a77064f59ee7 100644 --- a/java/compiler/impl/src/com/intellij/compiler/actions/BuildArtifactAction.java +++ b/java/compiler/impl/src/com/intellij/compiler/actions/BuildArtifactAction.java @@ -15,7 +15,6 @@ */ package com.intellij.compiler.actions; -import com.intellij.compiler.CompilerWorkspaceConfiguration; import com.intellij.notification.NotificationGroup; import com.intellij.notification.NotificationType; import com.intellij.openapi.actionSystem.AnActionEvent; @@ -126,13 +125,8 @@ public class BuildArtifactAction extends DumbAwareAction { final CompileScope scope = ArtifactCompileScope.createArtifactsScope(project, artifacts, rebuild); ArtifactsWorkspaceSettings.getInstance(project).setArtifactsToBuild(artifacts); - if (!rebuild || CompilerWorkspaceConfiguration.getInstance(project).useOutOfProcessBuild()) { - //in external build we can set 'rebuild' flag per target type - CompilerManager.getInstance(project).make(scope, null); - } - else { - CompilerManager.getInstance(project).compile(scope, null); - } + //in external build we can set 'rebuild' flag per target type + CompilerManager.getInstance(project).make(scope, null); } private static Set getArtifacts(final List items, final Project project) { diff --git a/java/compiler/impl/src/com/intellij/compiler/actions/ProcessAnnotationsAction.java b/java/compiler/impl/src/com/intellij/compiler/actions/ProcessAnnotationsAction.java deleted file mode 100644 index eae7060f56af..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/actions/ProcessAnnotationsAction.java +++ /dev/null @@ -1,208 +0,0 @@ -/* - * Copyright 2000-2013 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.compiler.actions; - -import com.intellij.compiler.CompilerConfiguration; -import com.intellij.compiler.CompilerWorkspaceConfiguration; -import com.intellij.compiler.impl.FileSetCompileScope; -import com.intellij.compiler.impl.ModuleCompileScope; -import com.intellij.compiler.impl.javaCompiler.AnnotationProcessingCompiler; -import com.intellij.compiler.impl.resourceCompiler.ResourceCompiler; -import com.intellij.idea.ActionsBundle; -import com.intellij.openapi.actionSystem.*; -import com.intellij.openapi.compiler.CompilerBundle; -import com.intellij.openapi.compiler.CompilerFilter; -import com.intellij.openapi.compiler.CompilerManager; -import com.intellij.openapi.fileTypes.FileType; -import com.intellij.openapi.module.Module; -import com.intellij.openapi.project.Project; -import com.intellij.openapi.roots.ProjectFileIndex; -import com.intellij.openapi.roots.ProjectRootManager; -import com.intellij.openapi.util.text.StringUtil; -import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.psi.*; -import com.intellij.util.containers.ContainerUtil; -import org.jetbrains.annotations.Nullable; -import org.jetbrains.jps.model.java.compiler.AnnotationProcessingConfiguration; - -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -public class ProcessAnnotationsAction extends CompileActionBase { - - protected void doAction(DataContext dataContext, Project project) { - final Module module = LangDataKeys.MODULE_CONTEXT.getData(dataContext); - final CompilerFilter filter = new CompilerFilter() { - public boolean acceptCompiler(com.intellij.openapi.compiler.Compiler compiler) { - // EclipseLink CanonicalModelProcessor reads input from output hence adding ResourcesCompiler - return compiler instanceof AnnotationProcessingCompiler || compiler instanceof ResourceCompiler; - } - }; - if (module != null) { - CompilerManager.getInstance(project).make(new ModuleCompileScope(module, false), filter, null); - } - else { - final FileSetCompileScope scope = getCompilableFiles(project, CommonDataKeys.VIRTUAL_FILE_ARRAY.getData(dataContext)); - if (scope != null) { - CompilerManager.getInstance(project).make(scope, filter, null); - } - } - } - - public void update(AnActionEvent event) { - super.update(event); - Presentation presentation = event.getPresentation(); - if (!presentation.isEnabled()) { - return; - } - DataContext dataContext = event.getDataContext(); - presentation.setVisible(false); - - Project project = CommonDataKeys.PROJECT.getData(dataContext); - if (project == null) { - presentation.setEnabled(false); - return; - } - - if (CompilerWorkspaceConfiguration.getInstance(project).useOutOfProcessBuild()) { - presentation.setEnabled(false); - return; - } - - final CompilerConfiguration compilerConfiguration = CompilerConfiguration.getInstance(project); - - final Module module = LangDataKeys.MODULE.getData(dataContext); - final Module moduleContext = LangDataKeys.MODULE_CONTEXT.getData(dataContext); - - if (module == null) { - presentation.setEnabled(false); - return; - } - final AnnotationProcessingConfiguration profile = compilerConfiguration.getAnnotationProcessingConfiguration(module); - if (!profile.isEnabled() || (!profile.isObtainProcessorsFromClasspath() && profile.getProcessors().isEmpty())) { - presentation.setEnabled(false); - return; - } - - presentation.setVisible(true); - presentation.setText(createPresentationText(""), true); - final FileSetCompileScope scope = getCompilableFiles(project, CommonDataKeys.VIRTUAL_FILE_ARRAY.getData(dataContext)); - if (moduleContext == null && scope == null) { - presentation.setEnabled(false); - return; - } - - String elementDescription = null; - if (moduleContext != null) { - elementDescription = CompilerBundle.message("action.compile.description.module", moduleContext.getName()); - } - else { - PsiPackage aPackage = null; - final Collection files = scope.getRootFiles(); - if (files.size() == 1) { - final PsiDirectory directory = PsiManager.getInstance(project).findDirectory(files.iterator().next()); - if (directory != null) { - aPackage = JavaDirectoryService.getInstance().getPackage(directory); - } - } - else { - PsiElement element = CommonDataKeys.PSI_ELEMENT.getData(dataContext); - if (element instanceof PsiPackage) { - aPackage = (PsiPackage)element; - } - } - - if (aPackage != null) { - String name = aPackage.getQualifiedName(); - if (name.length() == 0) { - //noinspection HardCodedStringLiteral - name = ""; - } - elementDescription = "'" + name + "'"; - } - else if (files.size() == 1) { - final VirtualFile file = files.iterator().next(); - FileType fileType = file.getFileType(); - if (CompilerManager.getInstance(project).isCompilableFileType(fileType)) { - elementDescription = "'" + file.getName() + "'"; - } - else { - if (!ActionPlaces.MAIN_MENU.equals(event.getPlace())) { - // the action should be invisible in popups for non-java files - presentation.setEnabled(false); - presentation.setVisible(false); - return; - } - } - } - else { - elementDescription = CompilerBundle.message("action.compile.description.selected.files"); - } - } - - if (elementDescription == null) { - presentation.setEnabled(false); - return; - } - - presentation.setText(createPresentationText(elementDescription), true); - presentation.setEnabled(true); - } - - private static String createPresentationText(final String elementDescription) { - int length = elementDescription.length(); - String target = length > 23 ? (StringUtil.startsWithChar(elementDescription, '\'') ? "'..." : "...") + elementDescription.substring(length - 20, length) : elementDescription; - return MessageFormat.format(ActionsBundle.actionText(StringUtil.isEmpty(target)? "RunAPT" : "RunAPT.1"), target); - } - - @Nullable - private static FileSetCompileScope getCompilableFiles(Project project, VirtualFile[] files) { - if (files == null || files.length == 0) { - return null; - } - final PsiManager psiManager = PsiManager.getInstance(project); - final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex(); - final CompilerManager compilerManager = CompilerManager.getInstance(project); - final List filesToCompile = new ArrayList(); - final List affectedModules = new ArrayList(); - for (final VirtualFile file : files) { - if (!fileIndex.isInSourceContent(file)) { - continue; - } - if (!file.isInLocalFileSystem()) { - continue; - } - if (file.isDirectory()) { - final PsiDirectory directory = psiManager.findDirectory(file); - if (directory == null || JavaDirectoryService.getInstance().getPackage(directory) == null) { - continue; - } - } - else { - FileType fileType = file.getFileType(); - if (!(compilerManager.isCompilableFileType(fileType))) { - continue; - } - } - filesToCompile.add(file); - ContainerUtil.addIfNotNull(fileIndex.getModuleForFile(file), affectedModules); - } - if (filesToCompile.isEmpty()) return null; - return new FileSetCompileScope(filesToCompile, affectedModules.toArray(new Module[affectedModules.size()])); - } -} \ No newline at end of file diff --git a/java/compiler/impl/src/com/intellij/compiler/classParsing/AnnotationConstantValue.java b/java/compiler/impl/src/com/intellij/compiler/classParsing/AnnotationConstantValue.java deleted file mode 100644 index 4d4bfc461a98..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/classParsing/AnnotationConstantValue.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.compiler.classParsing; - -import java.io.DataInput; -import java.io.DataOutput; -import java.io.IOException; -import java.util.Arrays; - -/** - * @author Eugene Zhuravlev - * Date: Apr 2, 2004 - */ -public class AnnotationConstantValue extends ConstantValue { - public static final AnnotationConstantValue[] EMPTY_ARRAY = new AnnotationConstantValue[0]; - public static final AnnotationConstantValue[][] EMPTY_ARRAY_ARRAY = new AnnotationConstantValue[0][]; - public final int myQName; - public final AnnotationNameValuePair[] myMemberValues; - - public AnnotationConstantValue(int qName, AnnotationNameValuePair[] memberValues) { - myQName = qName; - myMemberValues = memberValues; - } - - public int getAnnotationQName() { - return myQName; - } - - /** - * @return an array of Integer -> ConstantValue pairs - */ - public AnnotationNameValuePair[] getMemberValues() { - return myMemberValues; - } - - public AnnotationConstantValue(DataInput in) throws IOException { - myQName = in.readInt(); - final int size = in.readInt(); - myMemberValues = new AnnotationNameValuePair[size]; - for (int idx = 0; idx < myMemberValues.length; idx++) { - final int name = in.readInt(); - final ConstantValue constantValue = MemberInfoExternalizer.loadConstantValue(in); - myMemberValues[idx] = new AnnotationNameValuePair(name, constantValue); - } - } - - public void save(DataOutput out) throws IOException { - out.writeInt(myQName); - out.writeInt(myMemberValues.length); - for (int idx = 0; idx < myMemberValues.length; idx++) { - final AnnotationNameValuePair nameValuePair = myMemberValues[idx]; - out.writeInt(nameValuePair.getName()); - MemberInfoExternalizer.saveConstantValue(out, nameValuePair.getValue()); - } - } - - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof AnnotationConstantValue)) return false; - - final AnnotationConstantValue annotationConstantValue = (AnnotationConstantValue)o; - - if (myQName != annotationConstantValue.myQName) return false; - if (!Arrays.equals(myMemberValues, annotationConstantValue.myMemberValues)) return false; - - return true; - } - - public int hashCode() { - return myQName; - } -} diff --git a/java/compiler/impl/src/com/intellij/compiler/classParsing/AnnotationNameValuePair.java b/java/compiler/impl/src/com/intellij/compiler/classParsing/AnnotationNameValuePair.java deleted file mode 100644 index e5598756809c..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/classParsing/AnnotationNameValuePair.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.compiler.classParsing; - -/** - * @author Eugene Zhuravlev - * Date: Apr 8, 2004 - */ -public class AnnotationNameValuePair { - private final int myName; - private final ConstantValue myValue; - - public AnnotationNameValuePair(int name, ConstantValue value) { - myName = name; - myValue = value; - } - - public int getName() { - return myName; - } - - public ConstantValue getValue() { - return myValue; - } -} diff --git a/java/compiler/impl/src/com/intellij/compiler/classParsing/AnnotationPrimitiveConstantValue.java b/java/compiler/impl/src/com/intellij/compiler/classParsing/AnnotationPrimitiveConstantValue.java deleted file mode 100644 index 24ade7107c64..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/classParsing/AnnotationPrimitiveConstantValue.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.compiler.classParsing; - -import java.io.DataInput; -import java.io.DataOutput; -import java.io.IOException; - -/** - * @author Eugene Zhuravlev - * Date: Apr 2, 2004 - */ -public class AnnotationPrimitiveConstantValue extends ConstantValue{ - private final char myValueTag; - private final ConstantValue myValue; - - public AnnotationPrimitiveConstantValue(char valueTag, ConstantValue value) { - myValueTag = valueTag; - myValue = value; - } - - public AnnotationPrimitiveConstantValue(DataInput in) throws IOException { - myValueTag = in.readChar(); - myValue = MemberInfoExternalizer.loadConstantValue(in); - } - - public char getValueTag() { - return myValueTag; - } - - public ConstantValue getValue() { - return myValue; - } - - public void save(DataOutput out) throws IOException { - out.writeChar(myValueTag); - MemberInfoExternalizer.saveConstantValue(out, myValue); - } - - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof AnnotationPrimitiveConstantValue)) return false; - - final AnnotationPrimitiveConstantValue memberValue = (AnnotationPrimitiveConstantValue)o; - - if (myValueTag != memberValue.myValueTag) return false; - if (!myValue.equals(memberValue.myValue)) return false; - - return true; - } - - public int hashCode() { - int result; - result = (int)myValueTag; - result = 29 * result + myValue.hashCode(); - return result; - } - -} diff --git a/java/compiler/impl/src/com/intellij/compiler/classParsing/ClassFileReader.java b/java/compiler/impl/src/com/intellij/compiler/classParsing/ClassFileReader.java deleted file mode 100644 index bd805709fb3b..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/classParsing/ClassFileReader.java +++ /dev/null @@ -1,770 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * created at Jan 2, 2002 - * @author Jeka - */ -package com.intellij.compiler.classParsing; - -import com.intellij.compiler.SymbolTable; -import com.intellij.compiler.make.CacheCorruptedException; -import com.intellij.openapi.compiler.CompilerBundle; -import com.intellij.openapi.util.io.FileUtil; -import com.intellij.psi.CommonClassNames; -import com.intellij.util.ArrayUtil; -import com.intellij.util.cls.BytePointer; -import com.intellij.util.cls.ClsFormatException; -import com.intellij.util.cls.ClsUtil; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -public class ClassFileReader { - private final File myFile; - private byte[] myData; - private int[] myConstantPoolOffsets = null; // the last offset points to the constant pool end - - private String myQualifiedName; - private String myGenericSignature; - private List myReferences; - private List myFields; - private List myMethods; - private String mySourceFileName; - private String mySuperClassName; - private String[] mySuperInterfaces; - private final SymbolTable mySymbolTable; - private AnnotationConstantValue[] myRuntimeVisibleAnnotations; - private AnnotationConstantValue[] myRuntimeInvisibleAnnotations; - private static final String CONSTRUCTOR_NAME = ""; - private boolean myParsingDone; - - public ClassFileReader(@NotNull File file, SymbolTable symbolTable, @Nullable final byte[] fileContent) { - mySymbolTable = symbolTable; - myFile = file; - myData = fileContent; - } - - public String getPath() { - return myFile.getAbsolutePath(); - } - - public Collection getReferences() throws ClsFormatException { - parseConstantPool(); - return myReferences; - } - - public MethodInfo[] getMethods() throws ClsFormatException{ - parseMembers(); - return myMethods.toArray(new MethodInfo[myMethods.size()]); - } - - public FieldInfo[] getFields() throws ClsFormatException{ - parseMembers(); - return myFields.toArray(new FieldInfo[myFields.size()]); - } - - private void parseMembers() throws ClsFormatException { - if (myParsingDone) { - return; - } - initConstantPool(); - myMethods = new ArrayList(); - myFields = new ArrayList(); - BytePointer ptr = new BytePointer(getData(), getConstantPoolEnd()); - ptr.offset += 2; // access flags - ptr.offset += 2; // this class - ptr.offset += 2; // super class - int count = ClsUtil.readU2(ptr); // interface count - ptr.offset += 2 * count; // skip interface infos - count = ClsUtil.readU2(ptr); // field count - while (count-- > 0) { - FieldInfo field = (FieldInfo)readMemberStructure(ptr, true); - String name = getSymbol(field.getName()); - if (name.indexOf('$') < 0 && name.indexOf('<') < 0){ // skip synthetic fields - myFields.add(field); - } - } - count = ClsUtil.readU2(ptr); // method count - while (count-- > 0) { - MethodInfo method = (MethodInfo)readMemberStructure(ptr, false); - String name = getSymbol(method.getName()); - if (name.indexOf('$') < 0 && name.indexOf('<') < 0) { // skip synthetic methods - myMethods.add(method); - } - else - if (CONSTRUCTOR_NAME.equals(name)) { // store constructors - myMethods.add(method); - } - } - - final ClsAttributeTable attributeTable = readAttributes(ptr); - mySourceFileName = attributeTable.sourceFile; - myGenericSignature = attributeTable.genericSignature; - myRuntimeVisibleAnnotations = attributeTable.runtimeVisibleAnnotations; - myRuntimeInvisibleAnnotations = attributeTable.runtimeInvisibleAnnotations; - myParsingDone = true; - } - - private String getSymbol(final int id) throws ClsFormatException { - try { - return mySymbolTable.getSymbol(id); - } - catch (CacheCorruptedException e) { - throw new ClsFormatException(e.getLocalizedMessage()); - } - } - - private MemberInfo readMemberStructure(BytePointer ptr, boolean isField) throws ClsFormatException { - int flags = ClsUtil.readU2(ptr); - int nameIndex = ClsUtil.readU2(ptr); - int descriptorIndex = ClsUtil.readU2(ptr); - - BytePointer p = new BytePointer(getData(), getOffsetInConstantPool(nameIndex)); - String name = ClsUtil.readUtf8Info(p); - p.offset = getOffsetInConstantPool(descriptorIndex); - String descriptor = ClsUtil.readUtf8Info(p); - - if (isField) { - final ClsAttributeTable attributeTable = readAttributes(ptr); - return new FieldInfo( - getSymbolId(name), - getSymbolId(descriptor), - attributeTable.genericSignature != null? getSymbolId(attributeTable.genericSignature) : -1, - flags, - attributeTable.constantValue, - attributeTable.runtimeVisibleAnnotations, - attributeTable.runtimeInvisibleAnnotations - ); - } - else { - final ClsAttributeTable attributeTable = readAttributes(ptr); - int[] intExceptions = null; - if (attributeTable.exceptions != null) { - intExceptions = ArrayUtil.newIntArray(attributeTable.exceptions.length); - for (int idx = 0; idx < intExceptions.length; idx++) { - intExceptions[idx] = getSymbolId(attributeTable.exceptions[idx]); - } - } - return new MethodInfo( - getSymbolId(name), - getSymbolId(descriptor), - attributeTable.genericSignature != null? getSymbolId(attributeTable.genericSignature) : -1, - flags, - intExceptions, - CONSTRUCTOR_NAME.equals(name), - attributeTable.runtimeVisibleAnnotations, - attributeTable.runtimeInvisibleAnnotations, - attributeTable.runtimeVisibleParameterAnnotations, - attributeTable.runtimeInvisibleParameterAnnotations, - attributeTable.annotationDefault - ); - } - } - - private int getSymbolId(final String symbol) throws ClsFormatException{ - try { - return mySymbolTable.getId(symbol); - } - catch (CacheCorruptedException e) { - throw new ClsFormatException(e.getLocalizedMessage()); - } - } - - public String getQualifiedName() throws ClsFormatException { - if (myQualifiedName == null) { - BytePointer ptr = new BytePointer(getData(), getConstantPoolEnd() + 2); - ptr.offset = getOffsetInConstantPool(ClsUtil.readU2(ptr)); - int tag = ClsUtil.readU1(ptr); - if (tag != ClsUtil.CONSTANT_Class){ - throw new ClsFormatException(); - } - ptr.offset = getOffsetInConstantPool(ClsUtil.readU2(ptr)); - myQualifiedName = ClsUtil.readUtf8Info(ptr, '/', '.'); // keep '$' in the names - } - return myQualifiedName; - } - - /** - * @return fully qualified name of the class' superclass. In case there is no super return "" - */ - public String getSuperClass() throws ClsFormatException { - if (mySuperClassName == null) { - BytePointer ptr = new BytePointer(getData(), getConstantPoolEnd() + 4); - int index = ClsUtil.readU2(ptr); - if (index == 0) { - if (CommonClassNames.JAVA_LANG_OBJECT.equals(getQualifiedName())) { - mySuperClassName = ""; - } - else { - throw new ClsFormatException(); - } - } - else { - ptr.offset = getOffsetInConstantPool(index); - mySuperClassName = readClassInfo(ptr); // keep '$' in the name for anonymous classes - if (isInterface()) { - if (!CommonClassNames.JAVA_LANG_OBJECT.equals(mySuperClassName)) { - throw new ClsFormatException(); - } - } - /* - else { - if (!MakeUtil.isAnonymous(mySuperClassName)) { - mySuperClassName = mySuperClassName.replace('$', '.'); - } - } - */ - } - } - return mySuperClassName; - } - - public String[] getSuperInterfaces() throws ClsFormatException { - if (mySuperInterfaces == null) { - BytePointer ptr = new BytePointer(getData(), getConstantPoolEnd() + 6); - int count = ClsUtil.readU2(ptr); - mySuperInterfaces = ArrayUtil.newStringArray(count); - BytePointer auxPtr = new BytePointer(ptr.bytes, 0); - for (int idx = 0; idx < mySuperInterfaces.length; idx++) { - auxPtr.offset = getOffsetInConstantPool(ClsUtil.readU2(ptr)); - mySuperInterfaces[idx] = readClassInfo(auxPtr); - } - } - return mySuperInterfaces; - } - - - public String getSourceFileName() throws ClsFormatException { - parseMembers(); - final String fName = mySourceFileName; - return fName != null? fName : ""; - } - - public String getGenericSignature() throws ClsFormatException { - parseMembers(); - final String genericSignature = myGenericSignature; - return genericSignature != null && !genericSignature.isEmpty() ? genericSignature : null; - } - - public AnnotationConstantValue[] getRuntimeVisibleAnnotations() throws ClsFormatException { - parseMembers(); - final AnnotationConstantValue[] annotations = myRuntimeVisibleAnnotations; - return annotations != null? annotations : AnnotationConstantValue.EMPTY_ARRAY; - } - - public AnnotationConstantValue[] getRuntimeInvisibleAnnotations() throws ClsFormatException { - parseMembers(); - final AnnotationConstantValue[] annotations = myRuntimeInvisibleAnnotations; - return annotations != null? annotations : AnnotationConstantValue.EMPTY_ARRAY; - } - - private boolean isInterface(){ - return (getAccessFlags() & ClsUtil.ACC_INTERFACE) != 0; - } - -// helper methods - private void parseConstantPool() throws ClsFormatException { - if (myReferences != null) { - return; - } - myReferences = new ArrayList(); - initConstantPool(); - final BytePointer ptr = new BytePointer(getData(), 0); - ConstantPoolIterator iterator = new ConstantPoolIterator(ptr); - while (iterator.hasMoreEntries()) { - final int tag = ClsUtil.readU1(ptr); - if (tag == ClsUtil.CONSTANT_Fieldref || tag == ClsUtil.CONSTANT_Methodref || tag == ClsUtil.CONSTANT_InterfaceMethodref) { - //ptr.offset -= 1; // position to the beginning of the structure - MemberReferenceInfo refInfo = readRefStructure(tag, ptr); - if (refInfo != null) { - myReferences.add(refInfo); - } - /* - String name = mySymbolTable.getSymbol(refInfo.getMemberInfo().getName()); - if (name.indexOf('$') < 0 && name.indexOf('<') < 0) { // skip refs to synthetic members - myReferences.add(refInfo); - } - else if ("".equals(name)) { // add instance initializers (constructors) - myReferences.add(refInfo); - } - else { - System.out.println("ReferenceInfo thrown out: " + mySymbolTable.getSymbol(refInfo.getClassName()) + "." + mySymbolTable.getSymbol(refInfo.getMemberInfo().getName())); - ourWasteReferenceObjectsCounter += 1; - } - */ - } - else if (tag == ClsUtil.CONSTANT_Class) { - ptr.offset -= 1; // position to the beginning of the structure - String className = readClassInfo(ptr); - myReferences.add(new ReferenceInfo(getSymbolId(className))); - } - iterator.next(); - } - //System.out.println("ourWasteReferenceObjectsCounter = " + ourWasteReferenceObjectsCounter); - } - - private MemberReferenceInfo readRefStructure(int tag, BytePointer ptr) throws ClsFormatException { - /* - if (tag != ClsUtil.CONSTANT_Fieldref && tag != ClsUtil.CONSTANT_Methodref && tag != ClsUtil.CONSTANT_InterfaceMethodref) { - throw new ClsFormatException(); - } - */ - int classInfoIndex = ClsUtil.readU2(ptr); - int nameTypeInfoIndex = ClsUtil.readU2(ptr); - - ptr.offset = getOffsetInConstantPool(classInfoIndex); - if (ClsUtil.CONSTANT_Class != ClsUtil.readU1(ptr)) { - throw new ClsFormatException(); - } - ptr.offset = getOffsetInConstantPool(ClsUtil.readU2(ptr)); - String className = ClsUtil.readUtf8Info(ptr, '/', '.'); // keep '$' in names - - ptr.offset = getOffsetInConstantPool(nameTypeInfoIndex); - if (ClsUtil.CONSTANT_NameAndType != ClsUtil.readU1(ptr)) { - throw new ClsFormatException(); - } - int memberNameIndex = ClsUtil.readU2(ptr); - int descriptorIndex = ClsUtil.readU2(ptr); - - ptr.offset = getOffsetInConstantPool(memberNameIndex); - String memberName = ClsUtil.readUtf8Info(ptr); - - if ((memberName.indexOf('$') >= 0 || memberName.indexOf('<') >= 0) && !CONSTRUCTOR_NAME.equals(memberName)) { // skip refs to synthetic members - return null; - } - - ptr.offset = getOffsetInConstantPool(descriptorIndex); - String descriptor = ClsUtil.readUtf8Info(ptr); - - MemberInfo info = ClsUtil.CONSTANT_Fieldref == tag? new FieldInfo(getSymbolId(memberName), getSymbolId(descriptor)) : new MethodInfo(getSymbolId(memberName), getSymbolId(descriptor), CONSTRUCTOR_NAME.equals(memberName)); - return new MemberReferenceInfo(getSymbolId(className), info); - } - - public int getAccessFlags(){ - try{ - int offset = getConstantPoolEnd(); - byte[] data = getData(); - if (offset + 2 > data.length){ - throw new ClsFormatException(); - } - int b1 = data[offset++] & 0xFF; - int b2 = data[offset++] & 0xFF; - return (b1 << 8) + b2; - } - catch(ClsFormatException e){ - return 0; - } - } - - private byte[] getData(){ - if (myData == null) { - try{ - myData = FileUtil.loadFileBytes(myFile); - } - catch(IOException e){ - myData = ArrayUtil.EMPTY_BYTE_ARRAY; - } - } - return myData; - } - - private int getOffsetInConstantPool(int index) throws ClsFormatException { - initConstantPool(); - if (index < 1 || index >= myConstantPoolOffsets.length){ - throw new ClsFormatException(); - } - return myConstantPoolOffsets[index - 1]; - } - - private int getConstantPoolEnd() throws ClsFormatException { - initConstantPool(); - return myConstantPoolOffsets[myConstantPoolOffsets.length - 1]; - } - - private void initConstantPool() throws ClsFormatException { - if (myConstantPoolOffsets == null){ - BytePointer ptr = new BytePointer(getData(), 0); - ConstantPoolIterator iterator = new ConstantPoolIterator(ptr); - myConstantPoolOffsets = new int[iterator.getEntryCount()]; - myConstantPoolOffsets[0] = iterator.getCurrentOffset(); - int index = 1; - while (iterator.hasMoreEntries()) { - int tag = ClsUtil.readU1(ptr); - if (tag == ClsUtil.CONSTANT_Long || tag == ClsUtil.CONSTANT_Double) { - myConstantPoolOffsets[index++] = ptr.offset + 8; // takes 2 entries! - } - iterator.next(); - myConstantPoolOffsets[index++] = iterator.getCurrentOffset(); - } - } - } - - private String readClassInfo(BytePointer ptr) throws ClsFormatException{ - final int tag = ClsUtil.readU1(ptr); - if (tag != ClsUtil.CONSTANT_Class){ - throw new ClsFormatException(CompilerBundle.message("class.parsing.error.wrong.record.tag.expected.another", tag, ClsUtil.CONSTANT_Class)); - } - int index = ClsUtil.readU2(ptr); - return ClsUtil.readUtf8Info(new BytePointer(ptr.bytes, getOffsetInConstantPool(index)), '/', '.'); - } - - @SuppressWarnings({"HardCodedStringLiteral"}) - private ClsAttributeTable readAttributes(BytePointer ptr) throws ClsFormatException { - int count = ClsUtil.readU2(ptr); // attributeCount - final ClsAttributeTable attributes = new ClsAttributeTable(); - while (count-- > 0) { - final String attrName = readAttributeName(ptr); - if ("Exceptions".equals(attrName)) { - attributes.exceptions = readExceptions(ptr); - } - else if ("Signature".equals(attrName)) { - attributes.genericSignature = readSignatureAttribute(ptr); - } - else if ("SourceFile".equals(attrName)) { - attributes.sourceFile = readSourceFileAttribute(ptr); - } - else if ("ConstantValue".equals(attrName)){ - attributes.constantValue = readFieldConstantValue(ptr); - } - else if ("RuntimeVisibleAnnotations".equals(attrName)) { - attributes.runtimeVisibleAnnotations = readAnnotations(ptr); - } - else if ("RuntimeInvisibleAnnotations".equals(attrName)) { - attributes.runtimeInvisibleAnnotations = readAnnotations(ptr); - } - else if ("RuntimeVisibleParameterAnnotations".equals(attrName)) { - attributes.runtimeVisibleParameterAnnotations = readParameterAnnotations(ptr); - } - else if ("RuntimeInvisibleParameterAnnotations".equals(attrName)) { - attributes.runtimeInvisibleParameterAnnotations = readParameterAnnotations(ptr); - } - else if ("AnnotationDefault".equals(attrName)) { - attributes.annotationDefault = readAnnotationMemberValue(new BytePointer(ptr.bytes, ptr.offset + 6)); - } - gotoNextAttribute(ptr); - } - return attributes; - } - - private String readAttributeName(BytePointer p) throws ClsFormatException { - final BytePointer ptr = new BytePointer(p.bytes, p.offset); - final int nameIndex = ClsUtil.readU2(ptr); - ptr.offset = getOffsetInConstantPool(nameIndex); - return ClsUtil.readUtf8Info(ptr); - } - - private static void gotoNextAttribute(BytePointer ptr) throws ClsFormatException { - ptr.offset += 2; // skip name index - final int length = ClsUtil.readU4(ptr); // important! Do not inline since ptr.offset is also changed inside ClsUtil.readU4() method - ptr.offset += length; - } - - /** - Signature_attribute { - u2 attribute_name_index; (must be equal to "Signature") - u4 attribute_length; (must be equal to 2) - u2 signature_index; - } - */ - private String readSignatureAttribute(BytePointer p) throws ClsFormatException { - final BytePointer ptr = new BytePointer(p.bytes, p.offset + 2); // position to the length - if (ClsUtil.readU4(ptr) != 2) { - return null; - } - ptr.offset = getOffsetInConstantPool(ClsUtil.readU2(ptr)); - return ClsUtil.readUtf8Info(ptr); - } - - private String[] readExceptions(BytePointer p) throws ClsFormatException{ - final BytePointer ptr = new BytePointer(p.bytes, p.offset + 6); // position to the count of exceptions - int count = ClsUtil.readU2(ptr); - final ArrayList array = new ArrayList(count); - while (count-- > 0) { - int idx = ClsUtil.readU2(ptr); - if (idx != 0) { - final String exceptionClass = readClassInfo(new BytePointer(ptr.bytes, getOffsetInConstantPool(idx))); - array.add(exceptionClass); - } - } - return ArrayUtil.toStringArray(array); - } - - private String readSourceFileAttribute(BytePointer p) throws ClsFormatException { - BytePointer ptr = new BytePointer(p.bytes, p.offset + 2); // position to the length - if (ClsUtil.readU4(ptr) != 2) { - return null; - } - ptr.offset = getOffsetInConstantPool(ClsUtil.readU2(ptr)); - String path = ClsUtil.readUtf8Info(ptr); - // jdk version 1.3.0 puts full path to the source, but later versions store only short name - final int slashIndex = path.lastIndexOf('/'); - if (slashIndex >= 0) { - path = path.substring(slashIndex + 1, path.length()); - } - return path; - } - - private ConstantValue readFieldConstantValue(BytePointer p) throws ClsFormatException{ - final BytePointer ptr = new BytePointer(p.bytes, p.offset + 2); - if (ClsUtil.readU4(ptr) != 2) { - throw new ClsFormatException(); // attribute length must be 2 - } - int valueIndex = ClsUtil.readU2(ptr); - ptr.offset = getOffsetInConstantPool(valueIndex); - return readConstant(ptr); - } - - private ConstantValue readConstant(final BytePointer ptr) throws ClsFormatException { - final int tag = ClsUtil.readU1(ptr); - switch (tag) { - case ClsUtil.CONSTANT_Integer : - int value = ClsUtil.readU4(ptr); - return new IntegerConstantValue(value); - case ClsUtil.CONSTANT_Float: - float floatValue = ClsUtil.readFloat(ptr); - return new FloatConstantValue(floatValue); - case ClsUtil.CONSTANT_Long : - int high = ClsUtil.readU4(ptr); - int low = ClsUtil.readU4(ptr); - long v = ((long)high << 32) | (low & 0xFFFFFFFFL); - return new LongConstantValue(v); - case ClsUtil.CONSTANT_Double : - double doubleValue = ClsUtil.readDouble(ptr); - return new DoubleConstantValue(doubleValue); - case ClsUtil.CONSTANT_String : - int stringIndex = ClsUtil.readU2(ptr); - ptr.offset = getOffsetInConstantPool(stringIndex); - return new StringConstantValue(ClsUtil.readUtf8Info(ptr)); - default : throw new ClsFormatException(); - } - } - - private AnnotationConstantValue[] readAnnotations(BytePointer p) throws ClsFormatException { - final BytePointer ptr = new BytePointer(p.bytes, p.offset + 6); - return readAnnotationsArray(ptr); - } - - private AnnotationConstantValue[][] readParameterAnnotations(BytePointer p) throws ClsFormatException { - final BytePointer ptr = new BytePointer(p.bytes, p.offset + 6); // position to the number of parameters - final int numberOfParams = ClsUtil.readU1(ptr); - if (numberOfParams == 0) { - return null; - } - final AnnotationConstantValue[][] annotations = new AnnotationConstantValue[numberOfParams][]; - for (int parameterIndex = 0; parameterIndex < numberOfParams; parameterIndex++) { - annotations[parameterIndex] = readAnnotationsArray(ptr); - } - return annotations; - } - - private AnnotationConstantValue[] readAnnotationsArray(BytePointer ptr) throws ClsFormatException { - final int numberOfAnnotations = ClsUtil.readU2(ptr); - if (numberOfAnnotations == 0) { - return AnnotationConstantValue.EMPTY_ARRAY; - } - AnnotationConstantValue[] annotations = new AnnotationConstantValue[numberOfAnnotations]; - for (int attributeIndex = 0; attributeIndex < numberOfAnnotations; attributeIndex++) { - annotations[attributeIndex] = readAnnotation(ptr); - } - return annotations; - } - - private AnnotationConstantValue readAnnotation(BytePointer ptr) throws ClsFormatException { - final int classInfoIndex = ClsUtil.readU2(ptr); - final String qName = readAnnotationClassName(new BytePointer(ptr.bytes, getOffsetInConstantPool(classInfoIndex))); - final List memberValues = new ArrayList(); - final int numberOfPairs = ClsUtil.readU2(ptr); - for (int idx = 0; idx < numberOfPairs; idx++) { - final int memberNameIndex = ClsUtil.readU2(ptr); - final String memberName = ClsUtil.readUtf8Info(ptr.bytes, getOffsetInConstantPool(memberNameIndex)); - final ConstantValue memberValue = readAnnotationMemberValue(ptr); - memberValues.add(new AnnotationNameValuePair(getSymbolId(memberName), memberValue)); - } - return new AnnotationConstantValue(getSymbolId(qName), memberValues.toArray(new AnnotationNameValuePair[memberValues.size()])); - } - - private String readAnnotationClassName(BytePointer ptr) throws ClsFormatException { - // TODO: need this method because because of incomplete class format spec at the moment of writing - // it is not clear what structure is expected: CONSTANT_Utf8 or CONSTANT_Class - final int tag = ClsUtil.readU1(ptr); - if (tag == ClsUtil.CONSTANT_Utf8) { - return ClsUtil.getTypeText(ptr.bytes, ptr.offset + 2); //skip length - } - if (tag == ClsUtil.CONSTANT_Class){ - ptr.offset -= 1; // rollback - return readClassInfo(ptr); - } - //noinspection HardCodedStringLiteral - throw new ClsFormatException(CompilerBundle.message("class.parsing.error.wrong.record.tag.expected.another", tag, "CONSTANT_Utf8(" + ClsUtil.CONSTANT_Utf8 + ") / CONSTANT_Class(" + ClsUtil.CONSTANT_Class + ")")); - } - - private ConstantValue readAnnotationMemberValue(BytePointer ptr) throws ClsFormatException { - final char tag = (char)ClsUtil.readU1(ptr); - switch (tag) { - case 'B': - case 'C': - case 'D': - case 'F': - case 'I': - case 'J': - case 'S': - case 'Z': { - final int valueIndex = ClsUtil.readU2(ptr); - return new AnnotationPrimitiveConstantValue(tag, readConstant(new BytePointer(ptr.bytes, getOffsetInConstantPool(valueIndex)))); - } - case 's': { - final int valueIndex = ClsUtil.readU2(ptr); - return new StringConstantValue(ClsUtil.readUtf8Info(ptr.bytes, getOffsetInConstantPool(valueIndex))); - } - case 'e': { - final int typeNameIndex = ClsUtil.readU2(ptr); - final int constantNameIndex = ClsUtil.readU2(ptr); - final String typeName = ClsUtil.readUtf8Info(ptr.bytes, getOffsetInConstantPool(typeNameIndex)); - final String constantName = ClsUtil.readUtf8Info(ptr.bytes, getOffsetInConstantPool(constantNameIndex)); - return new EnumConstantValue(getSymbolId(typeName), getSymbolId(constantName)); - } - case 'c' : { - final int classInfoIndex = ClsUtil.readU2(ptr); - BytePointer p = new BytePointer(ptr.bytes, getOffsetInConstantPool(classInfoIndex)); - final int recordTag = ClsUtil.readU1(p); - if (recordTag != ClsUtil.CONSTANT_Utf8) { - throw new ClsFormatException(CompilerBundle.message("class.parsing.error.wrong.record.tag.expected.another", recordTag, ClsUtil.CONSTANT_Utf8)); - } - p.offset += 2; //Skip length - final String className = ClsUtil.getTypeText(p.bytes, p.offset); - return new ClassInfoConstantValue(getSymbolId(className)); - } - case '@' : { - return readAnnotation(ptr); - } - case '[' : { - final int numberOfValues = ClsUtil.readU2(ptr); - final ConstantValue[] values = new ConstantValue[numberOfValues]; - for (int idx = 0; idx < numberOfValues; idx++) { - values[idx] = readAnnotationMemberValue(ptr); - } - return new ConstantValueArray(values); - } - default : throw new ClsFormatException(CompilerBundle.message("class.parsing.error.wrong.tag.annotation.member.value", tag)); - } - } - - private static class ClsAttributeTable { - public String[] exceptions; - public String genericSignature; - public String sourceFile; - public ConstantValue constantValue; - public AnnotationConstantValue[] runtimeVisibleAnnotations; - public AnnotationConstantValue[] runtimeInvisibleAnnotations; - public AnnotationConstantValue[][] runtimeVisibleParameterAnnotations; - public AnnotationConstantValue[][] runtimeInvisibleParameterAnnotations; - public ConstantValue annotationDefault; - } - - private static class ConstantPoolIterator { - private final BytePointer myPtr; - private final int myEntryCount; - private int myCurrentEntryIndex; - private int myCurrentOffset; - - public ConstantPoolIterator(BytePointer ptr) throws ClsFormatException { - myPtr = ptr; - myPtr.offset = 0; - int magic = ClsUtil.readU4(myPtr); - if (magic != ClsUtil.MAGIC){ - throw new ClsFormatException(); - } - myPtr.offset += 2; // minor version - myPtr.offset += 2; // major version - myEntryCount = ClsUtil.readU2(myPtr); - if (myEntryCount < 1){ - throw new ClsFormatException(); - } - myCurrentEntryIndex = 1; // Entry at index 0 is included in the count but is not present in the constant pool - myCurrentOffset = myPtr.offset; - } - - public int getEntryCount() { - return myEntryCount; - } - - public int getCurrentOffset() { - return myCurrentOffset; - } - - /** - * tests if there are unread entries - */ - public boolean hasMoreEntries() { - return myCurrentEntryIndex < myEntryCount; - } - - /** - * Positions the pointer to the next entry - */ - public void next() throws ClsFormatException { - myPtr.offset = myCurrentOffset; - int tag = ClsUtil.readU1(myPtr); - switch(tag){ - default: - throw new ClsFormatException(); - - case ClsUtil.CONSTANT_Class: - case ClsUtil.CONSTANT_String: - myPtr.offset += 2; - break; - - case ClsUtil.CONSTANT_Fieldref: - case ClsUtil.CONSTANT_Methodref: - case ClsUtil.CONSTANT_InterfaceMethodref: - case ClsUtil.CONSTANT_Integer: - case ClsUtil.CONSTANT_Float: - case ClsUtil.CONSTANT_NameAndType: - myPtr.offset += 4; - break; - - case ClsUtil.CONSTANT_Long: - case ClsUtil.CONSTANT_Double: - myPtr.offset += 8; - myCurrentEntryIndex++; // takes 2 entries - break; - - case ClsUtil.CONSTANT_Utf8: - int length = ClsUtil.readU2(myPtr); - myPtr.offset += length; - break; - - case ClsUtil.CONSTANT_MethodHandle: - myPtr.offset += 3; - break; - case ClsUtil.CONSTANT_MethodType: - myPtr.offset += 2; - break; - case ClsUtil.CONSTANT_InvokeDynamic: - myPtr.offset += 4; - break; - } - myCurrentEntryIndex++; - myCurrentOffset = myPtr.offset; - } - } -} diff --git a/java/compiler/impl/src/com/intellij/compiler/classParsing/ClassInfo.java b/java/compiler/impl/src/com/intellij/compiler/classParsing/ClassInfo.java deleted file mode 100644 index 2d816ef7dc99..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/classParsing/ClassInfo.java +++ /dev/null @@ -1,229 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.compiler.classParsing; - -import com.intellij.compiler.SymbolTable; -import com.intellij.compiler.make.CacheCorruptedException; -import com.intellij.openapi.diagnostic.Logger; -import com.intellij.openapi.util.Comparing; -import com.intellij.util.ArrayUtil; -import com.intellij.util.cls.ClsFormatException; - -import java.io.DataInput; -import java.io.DataOutput; -import java.io.IOException; -import java.util.Collection; - -/** - @author Eugene Zhuravlev -*/ -public final class ClassInfo implements Cloneable { - private static final Logger LOG = Logger.getInstance("#com.intellij.compiler.classParsing.ClassInfo"); - - private static final ReferenceInfo[] EMPTY_REF_ARRAY = new ReferenceInfo[0]; - - private final int myQualifiedName; - private final int myGenericSignature; - private final int mySuperQualifiedName; - private final int myFlags; - private String myPath; - private final String mySourceFileName; - private final int[] mySuperInterfaces; - private final FieldInfo[] myFields; - private final MethodInfo[] myMethods; - private ReferenceInfo[] myReferences; - private final AnnotationConstantValue[] myRuntimeVisibleAnnotations; - private final AnnotationConstantValue[] myRuntimeInvisibleAnnotations; - private boolean myIsDirty = false; - - public ClassInfo(ClassFileReader reader, SymbolTable symbolTable) throws CacheCorruptedException { - try { - final int qName = symbolTable.getId(reader.getQualifiedName()); - myQualifiedName = qName; - - final String genericSignature = reader.getGenericSignature(); - myGenericSignature = genericSignature != null? symbolTable.getId(genericSignature) : -1; - - myPath = reader.getPath(); - - final String superClass = reader.getSuperClass(); - final int superQName = "".equals(superClass)? -1 : symbolTable.getId(superClass); - mySuperQualifiedName = superQName; - - LOG.assertTrue(superQName != qName); - - final String[] superInterfaces = reader.getSuperInterfaces(); - mySuperInterfaces = ArrayUtil.newIntArray(superInterfaces.length); - for (int idx = 0; idx < superInterfaces.length; idx++) { - mySuperInterfaces[idx] = symbolTable.getId(superInterfaces[idx]); - } - - final String sourceFileName = reader.getSourceFileName(); - mySourceFileName = sourceFileName != null? sourceFileName : ""; - - myFlags = reader.getAccessFlags(); - - myRuntimeVisibleAnnotations = reader.getRuntimeVisibleAnnotations(); - myRuntimeInvisibleAnnotations = reader.getRuntimeInvisibleAnnotations(); - - final Collection refs = reader.getReferences(); - myReferences = refs.toArray(new ReferenceInfo[refs.size()]); - - myFields = reader.getFields(); - myMethods = reader.getMethods(); - } - catch (ClsFormatException e) { - throw new CacheCorruptedException(e); - } - } - - public ClassInfo(DataInput in) throws IOException { - myQualifiedName = in.readInt(); - mySuperQualifiedName = in.readInt(); - myGenericSignature = in.readInt(); - myFlags = in.readInt(); - myPath = in.readUTF(); - mySourceFileName = in.readUTF(); - - final int ifaceCount = in.readInt(); - mySuperInterfaces = new int[ifaceCount]; - for (int idx = 0; idx < ifaceCount; idx++) { - mySuperInterfaces[idx] = in.readInt(); - } - - final int fieldCount = in.readInt(); - myFields = new FieldInfo[fieldCount]; - for (int idx = 0; idx < fieldCount; idx++) { - myFields[idx] = new FieldInfo(in); - } - - final int methodCount = in.readInt(); - myMethods = new MethodInfo[methodCount]; - for (int idx = 0; idx < methodCount; idx++) { - myMethods[idx] = new MethodInfo(in); - } - - final int refCount = in.readInt(); - myReferences = refCount > 0? new ReferenceInfo[refCount] : EMPTY_REF_ARRAY; - for (int idx = 0; idx < refCount; idx++) { - myReferences[idx] = MemberInfoExternalizer.loadReferenceInfo(in); - } - - myRuntimeVisibleAnnotations = MemberInfoExternalizer.readAnnotationConstantValueArray1(in); - myRuntimeInvisibleAnnotations = MemberInfoExternalizer.readAnnotationConstantValueArray1(in); - } - - public ClassInfo clone() { - try { - return (ClassInfo)super.clone(); - } - catch (CloneNotSupportedException e) { - throw new RuntimeException(e); - } - } - - public void save(DataOutput out) throws IOException { - out.writeInt(myQualifiedName); - out.writeInt(mySuperQualifiedName); - out.writeInt(myGenericSignature); - out.writeInt(myFlags); - out.writeUTF(myPath); - out.writeUTF(mySourceFileName); - out.writeInt(mySuperInterfaces.length); - for (int ifaceQName : mySuperInterfaces) { - out.writeInt(ifaceQName); - } - - out.writeInt(myFields.length); - for (FieldInfo field : myFields) { - field.save(out); - } - - out.writeInt(myMethods.length); - for (MethodInfo method : myMethods) { - method.save(out); - } - - out.writeInt(myReferences.length); - for (ReferenceInfo info : myReferences) { - MemberInfoExternalizer.saveReferenceInfo(out, info); - } - - MemberInfoExternalizer.writeConstantValueArray1(out, myRuntimeVisibleAnnotations); - MemberInfoExternalizer.writeConstantValueArray1(out, myRuntimeInvisibleAnnotations); - } - - public boolean isDirty() { - return myIsDirty; - } - - public int getQualifiedName() throws IOException { - return myQualifiedName; - } - - public int getGenericSignature() throws IOException { - return myGenericSignature; - } - - public int getSuperQualifiedName() throws IOException { - return mySuperQualifiedName; - } - - public int[] getSuperInterfaces() throws IOException { - return mySuperInterfaces; - } - - public int getFlags() throws IOException { - return myFlags; - } - - public String getPath() throws IOException { - return myPath; - } - - public void setPath(String path) { - myIsDirty |= !Comparing.equal(myPath, path); - myPath = path; - } - - public String getSourceFileName() throws IOException { - return mySourceFileName; - } - - public AnnotationConstantValue[] getRuntimeVisibleAnnotations() throws IOException { - return myRuntimeVisibleAnnotations; - } - - public AnnotationConstantValue[] getRuntimeInvisibleAnnotations() throws IOException { - return myRuntimeInvisibleAnnotations; - } - - public ReferenceInfo[] getReferences() { - return myReferences; - } - - public void clearReferences() { - myReferences = EMPTY_REF_ARRAY; - } - - public FieldInfo[] getFields() { - return myFields; - } - - public MethodInfo[] getMethods() { - return myMethods; - } -} \ No newline at end of file diff --git a/java/compiler/impl/src/com/intellij/compiler/classParsing/ClassInfoConstantValue.java b/java/compiler/impl/src/com/intellij/compiler/classParsing/ClassInfoConstantValue.java deleted file mode 100644 index a444d325f195..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/classParsing/ClassInfoConstantValue.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.compiler.classParsing; - -import java.io.DataInput; -import java.io.DataOutput; -import java.io.IOException; - -public class ClassInfoConstantValue extends ConstantValue{ - private final int myValue; - - public ClassInfoConstantValue(int value) { - myValue = value; - } - - public ClassInfoConstantValue(DataInput in) throws IOException{ - myValue = in.readInt(); - } - - public int getValue() { - return myValue; - } - - public void save(DataOutput out) throws IOException { - super.save(out); - out.writeInt(myValue); - } - - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ClassInfoConstantValue)) return false; - - final ClassInfoConstantValue classInfoConstantValue = (ClassInfoConstantValue)o; - - if (myValue != classInfoConstantValue.myValue) return false; - - return true; - } - - public int hashCode() { - return myValue; - } -} diff --git a/java/compiler/impl/src/com/intellij/compiler/classParsing/ConstantValue.java b/java/compiler/impl/src/com/intellij/compiler/classParsing/ConstantValue.java deleted file mode 100644 index 31615b2e86e1..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/classParsing/ConstantValue.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * created at Feb 24, 2002 - * @author Jeka - */ -package com.intellij.compiler.classParsing; - -import java.io.DataOutput; -import java.io.IOException; - -public class ConstantValue { - public static final ConstantValue EMPTY_CONSTANT_VALUE = new ConstantValue(); - - protected ConstantValue() { - } - - public void save(DataOutput out) throws IOException { - } - -} diff --git a/java/compiler/impl/src/com/intellij/compiler/classParsing/ConstantValueArray.java b/java/compiler/impl/src/com/intellij/compiler/classParsing/ConstantValueArray.java deleted file mode 100644 index 850564a63a4b..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/classParsing/ConstantValueArray.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.compiler.classParsing; - -import java.io.DataInput; -import java.io.DataOutput; -import java.io.IOException; -import java.util.Arrays; - -/** - * @author Eugene Zhuravlev - * Date: Apr 2, 2004 - */ -public class ConstantValueArray extends ConstantValue{ - private final ConstantValue[] myValue; - - public ConstantValueArray(ConstantValue[] value) { - myValue = value; - } - - public ConstantValueArray(DataInput in) throws IOException { - final int size = in.readInt(); - myValue = new ConstantValue[size]; - for (int idx = 0; idx < size; idx++) { - myValue[idx] = MemberInfoExternalizer.loadConstantValue(in); - } - } - - public ConstantValue[] getValue() { - return myValue; - } - - public void save(DataOutput out) throws IOException { - out.writeInt(myValue.length); - for (int idx = 0; idx < myValue.length; idx++) { - MemberInfoExternalizer.saveConstantValue(out, myValue[idx]); - } - } - - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ConstantValueArray)) return false; - - final ConstantValueArray constantValueArray = (ConstantValueArray)o; - - if (!Arrays.equals(myValue, constantValueArray.myValue)) return false; - - return true; - } - - public int hashCode() { - return 0; - } - -} diff --git a/java/compiler/impl/src/com/intellij/compiler/classParsing/DoubleConstantValue.java b/java/compiler/impl/src/com/intellij/compiler/classParsing/DoubleConstantValue.java deleted file mode 100644 index 7e7b8e63e99a..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/classParsing/DoubleConstantValue.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * created at Feb 24, 2002 - * @author Jeka - */ -package com.intellij.compiler.classParsing; - -import java.io.DataInput; -import java.io.DataOutput; -import java.io.IOException; - -public class DoubleConstantValue extends ConstantValue{ - private final double myValue; - - public DoubleConstantValue(double value) { - myValue = value; - } - - public DoubleConstantValue(DataInput in) throws IOException{ - myValue = in.readDouble(); - } - - public double getValue() { - return myValue; - } - - public void save(DataOutput out) throws IOException { - super.save(out); - out.writeDouble(myValue); - } - - public boolean equals(Object obj) { - return (obj instanceof DoubleConstantValue) && (((DoubleConstantValue)obj).myValue == myValue); - } -} diff --git a/java/compiler/impl/src/com/intellij/compiler/classParsing/EnumConstantValue.java b/java/compiler/impl/src/com/intellij/compiler/classParsing/EnumConstantValue.java deleted file mode 100644 index 548bda1a8a1f..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/classParsing/EnumConstantValue.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * created at Feb 24, 2002 - * @author Jeka - */ -package com.intellij.compiler.classParsing; - -import java.io.DataInput; -import java.io.DataOutput; -import java.io.IOException; - -public class EnumConstantValue extends ConstantValue{ - private final int myTypeName; - private final int myConstantName; - - public EnumConstantValue(int typeName, int constantName) { - myTypeName = typeName; - myConstantName = constantName; - } - - public EnumConstantValue(DataInput in) throws IOException{ - myTypeName = in.readInt(); - myConstantName = in.readInt(); - } - - public int getTypeName() { - return myTypeName; - } - - public int getConstantName() { - return myConstantName; - } - - public void save(DataOutput out) throws IOException { - super.save(out); - out.writeInt(myTypeName); - out.writeInt(myConstantName); - } - - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof EnumConstantValue)) return false; - - final EnumConstantValue enumConstantValue = (EnumConstantValue)o; - - if (myConstantName != enumConstantValue.myConstantName) return false; - if (myTypeName != enumConstantValue.myTypeName) return false; - - return true; - } - - public int hashCode() { - int result; - result = myTypeName; - result = 29 * result + myConstantName; - return result; - } -} diff --git a/java/compiler/impl/src/com/intellij/compiler/classParsing/FieldInfo.java b/java/compiler/impl/src/com/intellij/compiler/classParsing/FieldInfo.java deleted file mode 100644 index 4611f082edf1..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/classParsing/FieldInfo.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * created at Jan 10, 2002 - * @author Jeka - */ -package com.intellij.compiler.classParsing; - -import java.io.DataInput; -import java.io.DataOutput; -import java.io.IOException; - -public class FieldInfo extends MemberInfo { - public static final FieldInfo[] EMPTY_ARRAY = new FieldInfo[0]; - private final ConstantValue myConstantValue; - - public FieldInfo(int name, int descriptor) { - super(name, descriptor); - myConstantValue = ConstantValue.EMPTY_CONSTANT_VALUE; - } - - public FieldInfo(int name, int descriptor, final int genericSignature, int flags, ConstantValue value, final AnnotationConstantValue[] runtimeVisibleAnnotations, final AnnotationConstantValue[] runtimeInvisibleAnnotations) { - super(name, descriptor, genericSignature, flags, runtimeVisibleAnnotations, runtimeInvisibleAnnotations); - myConstantValue = value == null ? ConstantValue.EMPTY_CONSTANT_VALUE : value; - } - - public FieldInfo(DataInput in) throws IOException { - super(in); - myConstantValue = MemberInfoExternalizer.loadConstantValue(in); - } - - public ConstantValue getConstantValue() { - return myConstantValue; - } - - public void save(DataOutput out) throws IOException { - super.save(out); - MemberInfoExternalizer.saveConstantValue(out, myConstantValue); - } - -} diff --git a/java/compiler/impl/src/com/intellij/compiler/classParsing/FloatConstantValue.java b/java/compiler/impl/src/com/intellij/compiler/classParsing/FloatConstantValue.java deleted file mode 100644 index f818cbf72fee..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/classParsing/FloatConstantValue.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * created at Feb 24, 2002 - * @author Jeka - */ -package com.intellij.compiler.classParsing; - -import java.io.DataInput; -import java.io.DataOutput; -import java.io.IOException; - -public class FloatConstantValue extends ConstantValue{ - private final float myValue; - - public FloatConstantValue(float value) { - myValue = value; - } - - public FloatConstantValue(DataInput in) throws IOException{ - myValue = in.readFloat(); - } - - public float getValue() { - return myValue; - } - - public void save(DataOutput out) throws IOException { - super.save(out); - out.writeFloat(myValue); - } - - public boolean equals(Object obj) { - return (obj instanceof FloatConstantValue) && (((FloatConstantValue)obj).myValue == myValue); - } -} diff --git a/java/compiler/impl/src/com/intellij/compiler/classParsing/GenericMethodSignature.java b/java/compiler/impl/src/com/intellij/compiler/classParsing/GenericMethodSignature.java deleted file mode 100644 index 10c01b4c5b4b..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/classParsing/GenericMethodSignature.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.compiler.classParsing; - -import com.intellij.openapi.compiler.CompilerBundle; -import com.intellij.util.ArrayUtil; - -import java.text.CharacterIterator; -import java.text.StringCharacterIterator; -import java.util.ArrayList; -import java.util.List; - -/** - * @author Eugene Zhuravlev - * Date: Mar 4, 2004 - */ -public class GenericMethodSignature { - private final String myFormalTypeParams; - private final String[] myParamSignatures; - private final String myReturnTypeSignature; - private final String myThrowsSignature; - - private GenericMethodSignature(String formalTypeParams, String[] paramSignatures, String returnTypeSignature, String throwsSignature) { - myFormalTypeParams = formalTypeParams; - myParamSignatures = paramSignatures; - myReturnTypeSignature = returnTypeSignature; - myThrowsSignature = throwsSignature; - } - - public String getFormalTypeParams() { - return myFormalTypeParams; - } - - public String[] getParamSignatures() { - return myParamSignatures; - } - - public String getReturnTypeSignature() { - return myReturnTypeSignature; - } - - public String getThrowsSignature() { - return myThrowsSignature; - } - - public static GenericMethodSignature parse(String methodSignature) throws SignatureParsingException { - final StringCharacterIterator it = new StringCharacterIterator(methodSignature); - - final StringBuilder formals = new StringBuilder(); - if (it.current() == '<') { - SignatureParser.INSTANCE.parseFormalTypeParameters(it, formals); - } - - if (it.current() != '(') { - throw new SignatureParsingException(CompilerBundle.message("error.signature.parsing.expected.other.symbol", "(", formals.toString())); - } - - it.next(); // skip '(' - - final String[] paramSignatures; - if (it.current() != ')') { - final List params = new ArrayList(); - while (it.current() != ')') { - final StringBuilder typeSignature = new StringBuilder(); - SignatureParser.INSTANCE.parseTypeSignature(it, typeSignature); - params.add(typeSignature.toString()); - } - paramSignatures = ArrayUtil.toStringArray(params); - } - else { - paramSignatures = ArrayUtil.EMPTY_STRING_ARRAY; - } - it.next(); // skip ')' - - final StringBuilder returnTypeSignature = new StringBuilder(); - SignatureParser.INSTANCE.parseReturnType(it, returnTypeSignature); - - final StringBuilder throwsSignature = new StringBuilder(); - if (it.current() != CharacterIterator.DONE) { - SignatureParser.INSTANCE.parseThrowsSignature(it, throwsSignature); - } - - return new GenericMethodSignature(formals.toString(), paramSignatures, returnTypeSignature.toString(), throwsSignature.toString()); - } -} diff --git a/java/compiler/impl/src/com/intellij/compiler/classParsing/IntegerConstantValue.java b/java/compiler/impl/src/com/intellij/compiler/classParsing/IntegerConstantValue.java deleted file mode 100644 index d59a727018ea..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/classParsing/IntegerConstantValue.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * created at Feb 24, 2002 - * @author Jeka - */ -package com.intellij.compiler.classParsing; - -import java.io.DataInput; -import java.io.DataOutput; -import java.io.IOException; - -public class IntegerConstantValue extends ConstantValue{ - private final int myValue; - - public IntegerConstantValue(int value) { - myValue = value; - } - - public IntegerConstantValue(DataInput in) throws IOException{ - myValue = in.readInt(); - } - - public int getValue() { - return myValue; - } - - public void save(DataOutput out) throws IOException { - super.save(out); - out.writeInt(myValue); - } - - public boolean equals(Object obj) { - return (obj instanceof IntegerConstantValue) && (((IntegerConstantValue)obj).myValue == myValue); - } -} diff --git a/java/compiler/impl/src/com/intellij/compiler/classParsing/LongConstantValue.java b/java/compiler/impl/src/com/intellij/compiler/classParsing/LongConstantValue.java deleted file mode 100644 index 2cbe2d7fc539..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/classParsing/LongConstantValue.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * created at Feb 24, 2002 - * @author Jeka - */ -package com.intellij.compiler.classParsing; - -import java.io.DataInput; -import java.io.DataOutput; -import java.io.IOException; - -public class LongConstantValue extends ConstantValue{ - private final long myValue; - - public LongConstantValue(long value) { - myValue = value; - } - public LongConstantValue(DataInput in) throws IOException{ - myValue = in.readLong(); - } - - public long getValue() { - return myValue; - } - - public void save(DataOutput out) throws IOException { - super.save(out); - out.writeLong(myValue); - } - - public boolean equals(Object obj) { - return (obj instanceof LongConstantValue) && (((LongConstantValue)obj).myValue == myValue); - } -} diff --git a/java/compiler/impl/src/com/intellij/compiler/classParsing/MemberInfo.java b/java/compiler/impl/src/com/intellij/compiler/classParsing/MemberInfo.java deleted file mode 100644 index 3394a580e2ad..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/classParsing/MemberInfo.java +++ /dev/null @@ -1,152 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * created at Jan 8, 2002 - * @author Jeka - */ -package com.intellij.compiler.classParsing; - -import com.intellij.util.cls.ClsUtil; - -import java.io.DataInput; -import java.io.DataOutput; -import java.io.IOException; - -public abstract class MemberInfo { - public static final MemberInfo[] EMPTY_MEMBER_INFO_ARRAY = new MemberInfo[0]; - private static final int FLAG_INFO_UNAVAILABLE = 0x8000; - private final int myName; - private final int myDescriptor; - private final int myGenericSignature; - private final int myFlags; - private final AnnotationConstantValue[] myRuntimeVisibleAnnotations; - private final AnnotationConstantValue[] myRuntimeInvisibleAnnotations; - - protected MemberInfo(int name, int descriptor) { - this(name, descriptor, -1, FLAG_INFO_UNAVAILABLE, AnnotationConstantValue.EMPTY_ARRAY, AnnotationConstantValue.EMPTY_ARRAY); - } - - protected MemberInfo(int name, int descriptor, int genericSignature, int flags, final AnnotationConstantValue[] runtimeVisibleAnnotations, final AnnotationConstantValue[] runtimeInvisibleAnnotations) { - myDescriptor = descriptor; - myGenericSignature = genericSignature; - myName = name; - myFlags = flags; - myRuntimeVisibleAnnotations = runtimeVisibleAnnotations != null? runtimeVisibleAnnotations : AnnotationConstantValue.EMPTY_ARRAY; - myRuntimeInvisibleAnnotations = runtimeInvisibleAnnotations != null? runtimeInvisibleAnnotations : AnnotationConstantValue.EMPTY_ARRAY; - } - - protected MemberInfo(DataInput in) throws IOException { - myName = in.readInt(); - myDescriptor = in.readInt(); - myGenericSignature = in.readInt(); - myFlags = in.readInt(); - myRuntimeVisibleAnnotations = loadAnnotations(in); - myRuntimeInvisibleAnnotations = loadAnnotations(in); - } - - public void save(DataOutput out) throws IOException { - out.writeInt(myName); - out.writeInt(myDescriptor); - out.writeInt(myGenericSignature); - out.writeInt(myFlags); - saveAnnotations(out, myRuntimeVisibleAnnotations); - saveAnnotations(out, myRuntimeInvisibleAnnotations); - } - - public int getName() { - return myName; - } - - public int getDescriptor() { - return myDescriptor; - } - - public int getGenericSignature() { - return myGenericSignature; - } - - public boolean isFlagInfoAvailable() { - return myFlags != FLAG_INFO_UNAVAILABLE; - } - - public int getFlags() { - return myFlags; - } - - public boolean isPublic() { - return ClsUtil.isPublic(myFlags); - } - - public boolean isProtected() { - return ClsUtil.isProtected(myFlags); - } - - public boolean isFinal() { - return ClsUtil.isFinal(myFlags); - } - - public boolean isPrivate() { - return ClsUtil.isPrivate(myFlags); - } - - public boolean isPackageLocal() { - return ClsUtil.isPackageLocal(myFlags); - } - - public boolean isStatic() { - return ClsUtil.isStatic(myFlags); - } - - public boolean equals(Object obj) { - if (!(obj instanceof MemberInfo)) return false; - MemberInfo info = (MemberInfo)obj; - return (myName == info.myName) && (myDescriptor == info.myDescriptor); - } - - public int hashCode() { - return myName + myDescriptor; - } - - public AnnotationConstantValue[] getRuntimeVisibleAnnotations() { - return myRuntimeVisibleAnnotations; - } - - public AnnotationConstantValue[] getRuntimeInvisibleAnnotations() { - return myRuntimeInvisibleAnnotations; - } - - protected final void saveAnnotations(DataOutput out, final AnnotationConstantValue[] annotations) throws IOException { - out.writeInt(annotations.length); - for (AnnotationConstantValue annotation : annotations) { - MemberInfoExternalizer.saveConstantValue(out, annotation); - } - } - - protected final AnnotationConstantValue[] loadAnnotations(DataInput in) throws IOException { - final int size = in.readInt(); - if (size == 0) { - return AnnotationConstantValue.EMPTY_ARRAY; - } - final AnnotationConstantValue[] annotations = new AnnotationConstantValue[size]; - for (int idx = 0; idx < size; idx++) { - annotations[idx] = (AnnotationConstantValue)MemberInfoExternalizer.loadConstantValue(in); - } - return annotations; - } - -} - diff --git a/java/compiler/impl/src/com/intellij/compiler/classParsing/MemberInfoExternalizer.java b/java/compiler/impl/src/com/intellij/compiler/classParsing/MemberInfoExternalizer.java deleted file mode 100644 index a807bd59f126..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/classParsing/MemberInfoExternalizer.java +++ /dev/null @@ -1,219 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * created at Jan 10, 2002 - * @author Jeka - */ -package com.intellij.compiler.classParsing; - -import com.intellij.openapi.diagnostic.Logger; - -import java.io.DataInput; -import java.io.DataOutput; -import java.io.IOException; - -public class MemberInfoExternalizer { - private static final Logger LOG = Logger.getInstance("#com.intellij.compiler.classParsing.MemberInfoExternalizer"); - - public static final byte FIELD_INFO_TAG = 1; - public static final byte METHOD_INFO_TAG = 2; - - public static final byte DECLARATION_INFO_TAG = 9; - - public static final byte REFERENCE_INFO_TAG = 11; - public static final byte MEMBER_REFERENCE_INFO_TAG = 12; - - public static final byte LONG_CONSTANT_TAG = 3; - public static final byte FLOAT_CONSTANT_TAG = 4; - public static final byte DOUBLE_CONSTANT_TAG = 5; - public static final byte INTEGER_CONSTANT_TAG = 6; - public static final byte STRING_CONSTANT_TAG = 7; - public static final byte CONSTANT_TAG = 8; - public static final byte ANNOTATION_CONSTANT_TAG = 13; - public static final byte ANNOTATION_PRIMITIVE_CONSTANT_TAG = 14; - public static final byte CONSTANT_VALUE_ARRAY_TAG = 15; - public static final byte CLASS_CONSTANT_VALUE_TAG = 16; - public static final byte ENUM_CONSTANT_VALUE_TAG = 17; - - public static MemberInfo loadMemberInfo(DataInput in) throws IOException { - byte tag = in.readByte(); - if (tag == METHOD_INFO_TAG) { - return new MethodInfo(in); - } - else if (tag == FIELD_INFO_TAG) { - return new FieldInfo(in); - } - LOG.error("Unknown member info"); - return null; - } - - public static ReferenceInfo loadReferenceInfo(DataInput in) throws IOException { - final byte tag = in.readByte(); - if (tag == REFERENCE_INFO_TAG) { - return new ReferenceInfo(in); - } - else if (tag == MEMBER_REFERENCE_INFO_TAG) { - return new MemberReferenceInfo(in); - } - LOG.error("Unknown declaration info tag: " + tag); - return null; - } - - public static ConstantValue loadConstantValue(DataInput in) throws IOException { - final byte tag = in.readByte(); - if (tag == LONG_CONSTANT_TAG) { - return new LongConstantValue(in); - } - else if (tag == FLOAT_CONSTANT_TAG) { - return new FloatConstantValue(in); - } - else if (tag == DOUBLE_CONSTANT_TAG) { - return new DoubleConstantValue(in); - } - else if (tag == INTEGER_CONSTANT_TAG) { - return new IntegerConstantValue(in); - } - else if (tag == STRING_CONSTANT_TAG) { - return new StringConstantValue(in); - } - else if (tag == CONSTANT_TAG) { - return ConstantValue.EMPTY_CONSTANT_VALUE; - } - else if (tag == ANNOTATION_CONSTANT_TAG) { - return new AnnotationConstantValue(in); - } - else if (tag == ANNOTATION_PRIMITIVE_CONSTANT_TAG) { - return new AnnotationPrimitiveConstantValue(in); - } - else if (tag == CONSTANT_VALUE_ARRAY_TAG) { - return new ConstantValueArray(in); - } - else if (tag == CLASS_CONSTANT_VALUE_TAG) { - return new ClassInfoConstantValue(in); - } - else if (tag == ENUM_CONSTANT_VALUE_TAG) { - return new EnumConstantValue(in); - } - LOG.error("Unknown constant value type " + tag); - return null; - } - - public static void saveMemberInfo(DataOutput out, MemberInfo info) throws IOException { - if (info instanceof MethodInfo) { - out.writeByte(METHOD_INFO_TAG); - } - else if (info instanceof FieldInfo){ - out.writeByte(FIELD_INFO_TAG); - } - else { - LOG.error("Unknown member info"); - } - info.save(out); - } - - public static void saveReferenceInfo(DataOutput out, ReferenceInfo info) throws IOException { - if (info instanceof MemberReferenceInfo) { - out.writeByte(MEMBER_REFERENCE_INFO_TAG); - } - else{ - out.writeByte(REFERENCE_INFO_TAG); - } - info.save(out); - } - - public static void saveConstantValue(DataOutput out, ConstantValue value) throws IOException { - if (value instanceof LongConstantValue) { - out.writeByte(LONG_CONSTANT_TAG); - } - else if (value instanceof FloatConstantValue){ - out.writeByte(FLOAT_CONSTANT_TAG); - } - else if (value instanceof DoubleConstantValue){ - out.writeByte(DOUBLE_CONSTANT_TAG); - } - else if (value instanceof IntegerConstantValue){ - out.writeByte(INTEGER_CONSTANT_TAG); - } - else if (value instanceof StringConstantValue){ - out.writeByte(STRING_CONSTANT_TAG); - } - else if (value instanceof AnnotationConstantValue) { - out.writeByte(ANNOTATION_CONSTANT_TAG); - } - else if (value instanceof AnnotationPrimitiveConstantValue) { - out.writeByte(ANNOTATION_PRIMITIVE_CONSTANT_TAG); - } - else if (value instanceof ConstantValueArray) { - out.writeByte(CONSTANT_VALUE_ARRAY_TAG); - } - else if (value instanceof ClassInfoConstantValue) { - out.writeByte(CLASS_CONSTANT_VALUE_TAG); - } - else if (value instanceof EnumConstantValue) { - out.writeByte(ENUM_CONSTANT_VALUE_TAG); - } - else { - out.writeByte(CONSTANT_TAG); - } - if (value != null) { - value.save(out); - } - } - - public static AnnotationConstantValue[] readAnnotationConstantValueArray1(DataInput in) throws IOException { - final int size = in.readInt(); - final AnnotationConstantValue[] array = size > 0? new AnnotationConstantValue[size] : AnnotationConstantValue.EMPTY_ARRAY; - for (int idx = 0; idx < size; idx++) { - array[idx] = (AnnotationConstantValue)loadConstantValue(in); - } - return array; - } - - public static AnnotationConstantValue[][] readAnnotationConstantValueArray2(DataInput in) throws IOException { - final int size = in.readInt(); - final AnnotationConstantValue[][] array = size > 0? new AnnotationConstantValue[size][] : AnnotationConstantValue.EMPTY_ARRAY_ARRAY; - for (int idx = 0; idx < size; idx++) { - array[idx] = readAnnotationConstantValueArray1(in); - } - return array; - } - - public static void writeConstantValueArray1(DataOutput writer, final ConstantValue[] array) throws IOException { - if (array != null && array.length > 0) { - writer.writeInt(array.length); - for (ConstantValue value : array) { - saveConstantValue(writer, value); - } - } - else { - writer.writeInt(0); - } - } - - public static void writeConstantValueArray2(DataOutput writer, final ConstantValue[][] array) throws IOException { - if (array != null && array.length > 0) { - writer.writeInt(array.length); - for (ConstantValue[] aArray : array) { - writeConstantValueArray1(writer, aArray); - } - } - else { - writer.writeInt(0); - } - } - -} diff --git a/java/compiler/impl/src/com/intellij/compiler/classParsing/MemberReferenceInfo.java b/java/compiler/impl/src/com/intellij/compiler/classParsing/MemberReferenceInfo.java deleted file mode 100644 index 63d7c549bf1a..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/classParsing/MemberReferenceInfo.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * created at Jan 8, 2002 - * @author Jeka - */ -package com.intellij.compiler.classParsing; - -import org.jetbrains.annotations.NonNls; - -import java.io.DataInput; -import java.io.DataOutput; -import java.io.IOException; - -public class MemberReferenceInfo extends ReferenceInfo { - private final MemberInfo myMemberInfo; - - public MemberReferenceInfo(int declaringClass, MemberInfo memberInfo) { - super(declaringClass); - myMemberInfo = memberInfo; - } - - public MemberReferenceInfo(DataInput in) throws IOException { - super(in); - myMemberInfo = MemberInfoExternalizer.loadMemberInfo(in); - } - - public MemberInfo getMemberInfo() { - return myMemberInfo; - } - - public boolean isFieldReference() { - return myMemberInfo instanceof FieldInfo; - } - - public boolean isMethodReference() { - return myMemberInfo instanceof MethodInfo; - } - - public void save(DataOutput out) throws IOException { - super.save(out); - MemberInfoExternalizer.saveMemberInfo(out, myMemberInfo); - } - - public boolean equals(Object o) { - if (!super.equals(o)) { - return false; - } - return myMemberInfo.equals(((MemberReferenceInfo)o).myMemberInfo); - } - - public int hashCode() { - return super.hashCode() + myMemberInfo.hashCode(); - } - - public @NonNls String toString() { // for debug purposes - return "Member reference: [class name=" + getClassName() + ", member name = " + myMemberInfo.getName() + ", member descriptor=" + myMemberInfo.getDescriptor() + ", member signature=" + myMemberInfo.getGenericSignature() + "]"; - } -} diff --git a/java/compiler/impl/src/com/intellij/compiler/classParsing/MethodInfo.java b/java/compiler/impl/src/com/intellij/compiler/classParsing/MethodInfo.java deleted file mode 100644 index c18d9ae801d7..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/classParsing/MethodInfo.java +++ /dev/null @@ -1,263 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * created at Jan 10, 2002 - * @author Jeka - */ -package com.intellij.compiler.classParsing; - -import com.intellij.compiler.SymbolTable; -import com.intellij.compiler.make.CacheCorruptedException; -import com.intellij.compiler.make.CacheUtils; -import com.intellij.openapi.diagnostic.Logger; -import com.intellij.util.ArrayUtil; -import com.intellij.util.cls.ClsUtil; -import gnu.trove.TIntHashSet; -import org.jetbrains.annotations.NonNls; - -import java.io.DataInput; -import java.io.DataOutput; -import java.io.IOException; -import java.util.ArrayList; - -public class MethodInfo extends MemberInfo { - private static final Logger LOG = Logger.getInstance("#com.intellij.compiler.classParsing.MethodInfo"); - - private static final int[] EXCEPTION_INFO_UNAVAILABLE = ArrayUtil.EMPTY_INT_ARRAY; - public static final MethodInfo[] EMPTY_ARRAY = new MethodInfo[0]; - - private final int[] myThrownExceptions; - // cached (lazy initialized) data - private String mySignature = null; - private String[] myParameterDescriptors = null; - private String myReturnTypeSignature = null; - private final boolean myIsConstructor; - private final AnnotationConstantValue[][] myRuntimeVisibleParameterAnnotations; - private final AnnotationConstantValue[][] myRuntimeInvisibleParameterAnnotations; - private final ConstantValue myAnnotationDefault; - - public MethodInfo(int name, int descriptor, boolean isConstructor) { - super(name, descriptor); - myIsConstructor = isConstructor; - myThrownExceptions = EXCEPTION_INFO_UNAVAILABLE; - myRuntimeVisibleParameterAnnotations = AnnotationConstantValue.EMPTY_ARRAY_ARRAY; - myRuntimeInvisibleParameterAnnotations = AnnotationConstantValue.EMPTY_ARRAY_ARRAY; - myAnnotationDefault = ConstantValue.EMPTY_CONSTANT_VALUE; - } - - public MethodInfo(int name, - int descriptor, - final int genericSignature, - int flags, - int[] exceptions, - boolean isConstructor, - final AnnotationConstantValue[] runtimeVisibleAnnotations, - final AnnotationConstantValue[] runtimeInvisibleAnnotations, - final AnnotationConstantValue[][] runtimeVisibleParameterAnnotations, - final AnnotationConstantValue[][] runtimeInvisibleParameterAnnotations, ConstantValue annotationDefault) { - - super(name, descriptor, genericSignature, flags, runtimeVisibleAnnotations, runtimeInvisibleAnnotations); - myThrownExceptions = exceptions != null? exceptions : ArrayUtil.EMPTY_INT_ARRAY; - myIsConstructor = isConstructor; - myRuntimeVisibleParameterAnnotations = runtimeVisibleParameterAnnotations == null? AnnotationConstantValue.EMPTY_ARRAY_ARRAY : runtimeVisibleParameterAnnotations; - myRuntimeInvisibleParameterAnnotations = runtimeInvisibleParameterAnnotations == null? AnnotationConstantValue.EMPTY_ARRAY_ARRAY : runtimeInvisibleParameterAnnotations; - myAnnotationDefault = annotationDefault; - } - - public MethodInfo(DataInput in) throws IOException { - super(in); - myIsConstructor = in.readBoolean(); - int count = in.readInt(); - if (count == -1) { - myThrownExceptions = EXCEPTION_INFO_UNAVAILABLE; - } - else { - myThrownExceptions = ArrayUtil.newIntArray(count); - for (int idx = 0; idx < count; idx++) { - myThrownExceptions[idx] = in.readInt(); - } - } - myRuntimeVisibleParameterAnnotations = loadParameterAnnotations(in); - myRuntimeInvisibleParameterAnnotations = loadParameterAnnotations(in); - myAnnotationDefault = MemberInfoExternalizer.loadConstantValue(in); - } - - public void save(DataOutput out) throws IOException { - super.save(out); - out.writeBoolean(myIsConstructor); - if (isExceptionInfoAvailable()) { - out.writeInt(myThrownExceptions.length); - } - else { - out.writeInt(-1); - } - for (int thrownException : myThrownExceptions) { - out.writeInt(thrownException); - } - saveParameterAnnotations(out, myRuntimeVisibleParameterAnnotations); - saveParameterAnnotations(out, myRuntimeInvisibleParameterAnnotations); - MemberInfoExternalizer.saveConstantValue(out, myAnnotationDefault); - } - - private boolean isExceptionInfoAvailable() { - return myThrownExceptions != EXCEPTION_INFO_UNAVAILABLE; - } - - public boolean areExceptionsEqual(MethodInfo info) { - if (myThrownExceptions.length != info.myThrownExceptions.length) { - return false; - } - if (myThrownExceptions.length != 0) { // optimization - TIntHashSet exceptionsSet = new TIntHashSet(); - for (int thrownException : myThrownExceptions) { - exceptionsSet.add(thrownException); - } - for (int exception : info.myThrownExceptions) { - if (!exceptionsSet.contains(exception)) { - return false; - } - } - } - return true; - } - - public int[] getThrownExceptions() { - return myThrownExceptions; - } - - public String getDescriptor(SymbolTable symbolTable) throws CacheCorruptedException { - if (mySignature == null) { - final String descriptor = symbolTable.getSymbol(getDescriptor()); - final String name = symbolTable.getSymbol(getName()); - mySignature = CacheUtils.getMethodSignature(name, descriptor); - } - return mySignature; - } - - public String getReturnTypeDescriptor(SymbolTable symbolTable) throws CacheCorruptedException { - if (myReturnTypeSignature == null) { - String descriptor = symbolTable.getSymbol(getDescriptor()); - myReturnTypeSignature = descriptor.substring(descriptor.indexOf(')') + 1, descriptor.length()); - } - return myReturnTypeSignature; - } - - public String[] getParameterDescriptors(SymbolTable symbolTable) throws CacheCorruptedException { - if (myParameterDescriptors == null) { - String descriptor = symbolTable.getSymbol(getDescriptor()); - int endIndex = descriptor.indexOf(')'); - if (endIndex <= 0) { - LOG.error("Corrupted method descriptor: " + descriptor); - } - myParameterDescriptors = parseParameterDescriptors(descriptor.substring(1, endIndex)); - } - return myParameterDescriptors; - } - - public boolean isAbstract() { - return ClsUtil.isAbstract(getFlags()); - } - - public boolean isConstructor() { - return myIsConstructor; - } - - private String[] parseParameterDescriptors(String signature) { - ArrayList list = new ArrayList(); - String paramSignature = parseFieldType(signature); - while (paramSignature != null && !"".equals(paramSignature)) { - list.add(paramSignature); - signature = signature.substring(paramSignature.length()); - paramSignature = parseFieldType(signature); - } - return ArrayUtil.toStringArray(list); - } - - private @NonNls String parseFieldType(@NonNls String signature) { - if (signature.length() == 0) { - return null; - } - if (signature.charAt(0) == 'B') { - return "B"; - } - if (signature.charAt(0) == 'C') { - return "C"; - } - if (signature.charAt(0) == 'D') { - return "D"; - } - if (signature.charAt(0) == 'F') { - return "F"; - } - if (signature.charAt(0) == 'I') { - return "I"; - } - if (signature.charAt(0) == 'J') { - return "J"; - } - if (signature.charAt(0) == 'S') { - return "S"; - } - if (signature.charAt(0) == 'Z') { - return "Z"; - } - if (signature.charAt(0) == 'L') { - return signature.substring(0, signature.indexOf(";") + 1); - } - if (signature.charAt(0) == '[') { - String s = parseFieldType(signature.substring(1)); - return (s != null)? ("[" + s) : null; - } - return null; - } - - public AnnotationConstantValue[][] getRuntimeVisibleParameterAnnotations() { - return myRuntimeVisibleParameterAnnotations; - } - - public AnnotationConstantValue[][] getRuntimeInvisibleParameterAnnotations() { - return myRuntimeInvisibleParameterAnnotations; - } - - public String toString() { - return mySignature; - } - - private AnnotationConstantValue[][] loadParameterAnnotations(DataInput in) throws IOException { - final int size = in.readInt(); - if (size == 0) { - return AnnotationConstantValue.EMPTY_ARRAY_ARRAY; - } - final AnnotationConstantValue[][] paramAnnotations = new AnnotationConstantValue[size][]; - for (int idx = 0; idx < size; idx++) { - paramAnnotations[idx] = loadAnnotations(in); - } - return paramAnnotations; - } - - private void saveParameterAnnotations(DataOutput out, AnnotationConstantValue[][] parameterAnnotations) throws IOException { - out.writeInt(parameterAnnotations.length); - for (AnnotationConstantValue[] parameterAnnotation : parameterAnnotations) { - saveAnnotations(out, parameterAnnotation); - } - } - - public ConstantValue getAnnotationDefault() { - return myAnnotationDefault; - } - -} diff --git a/java/compiler/impl/src/com/intellij/compiler/classParsing/ReferenceInfo.java b/java/compiler/impl/src/com/intellij/compiler/classParsing/ReferenceInfo.java deleted file mode 100644 index 3cf9a191fe0b..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/classParsing/ReferenceInfo.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * @author Eugene Zhuravlev - */ -package com.intellij.compiler.classParsing; - -import org.jetbrains.annotations.NonNls; - -import java.io.DataInput; -import java.io.DataOutput; -import java.io.IOException; - -public class ReferenceInfo { - private final int myClassName; - - public ReferenceInfo(int declaringClassName) { - myClassName = declaringClassName; - } - - public ReferenceInfo(DataInput in) throws IOException { - this(in.readInt()); - } - - public @NonNls String toString() { // for debug purposes - return "Class reference[class name=" + String.valueOf(getClassName()) + "]"; - } - - public void save(DataOutput out) throws IOException { - out.writeInt(myClassName); - } - - public int getClassName() { - return myClassName; - } - - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - ReferenceInfo that = (ReferenceInfo)o; - - if (myClassName != that.myClassName) return false; - - return true; - } - - public int hashCode() { - return myClassName; - } -} diff --git a/java/compiler/impl/src/com/intellij/compiler/classParsing/SignatureParser.java b/java/compiler/impl/src/com/intellij/compiler/classParsing/SignatureParser.java deleted file mode 100644 index d195cf3e3515..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/classParsing/SignatureParser.java +++ /dev/null @@ -1,259 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.compiler.classParsing; - -import com.intellij.openapi.compiler.CompilerBundle; - -import java.text.CharacterIterator; - -/** - * @author Eugene Zhuravlev - * Date: Mar 4, 2004 - */ - -public class SignatureParser { - public static final SignatureParser INSTANCE = new SignatureParser(); - - public void parseIdentifier(CharacterIterator it, final StringBuilder buf) { - while (Character.isJavaIdentifierPart(it.current())) { - buf.append(it.current()); - it.next(); - } - } - - public void parseFormalTypeParameters(CharacterIterator it, final StringBuilder buf) throws SignatureParsingException { - if (it.current() != '<') { - throw new SignatureParsingException(CompilerBundle.message("error.signature.parsing.expected.other.symbol", "<", buf.toString())); - } - - buf.append(it.current()); // skip '<' - it.next(); - - while (it.current() != '>') { - parseFormalTypeParameter(it, buf); - } - - buf.append(it.current()); - it.next(); - } - - public void parseFormalTypeParameter(CharacterIterator it, final StringBuilder buf) throws SignatureParsingException { - parseIdentifier(it, buf); - parseClassBound(it, buf); - while (it.current() == ':') { - parseInterfaceBound(it, buf); - } - } - - public void parseClassBound(CharacterIterator it, final StringBuilder buf) throws SignatureParsingException { - if (it.current() != ':') { - throw new SignatureParsingException(CompilerBundle.message("error.signature.parsing.expected.other.symbol", ":", buf.toString())); - } - buf.append(it.current()); - it.next(); - - final char current = it.current(); - if (current != CharacterIterator.DONE && current != ':') { - parseFieldTypeSignature(it, buf); - } - } - - public void parseInterfaceBound(CharacterIterator it, final StringBuilder buf) throws SignatureParsingException { - if (it.current() != ':') { - throw new SignatureParsingException(CompilerBundle.message("error.signature.parsing.expected.other.symbol", ":", buf.toString())); - } - buf.append(it.current()); - it.next(); - parseFieldTypeSignature(it, buf); - } - - public void parseSuperclassSignature(CharacterIterator it, final StringBuilder buf) throws SignatureParsingException { - parseClassTypeSignature(it, buf); - } - - public void parseSuperinterfaceSignature(CharacterIterator it, final StringBuilder buf) throws SignatureParsingException { - parseClassTypeSignature(it, buf); - } - - public void parseFieldTypeSignature(CharacterIterator it, final StringBuilder buf) throws SignatureParsingException { - if (it.current() == 'L') { - parseClassTypeSignature(it, buf); - } - else if (it.current() == '[') { - parseArrayTypeSignature(it, buf); - } - else if (it.current() == 'T') { - parseTypeVariableSignature(it, buf); - } - else { - //noinspection HardCodedStringLiteral - throw new SignatureParsingException(CompilerBundle.message("error.signature.parsing.expected.other.symbol", "'L' / '[' / 'T'", buf.toString())); - } - } - - public void parseClassTypeSignature(CharacterIterator it, final StringBuilder buf) throws SignatureParsingException { - buf.append(it.current()); - it.next(); // consume 'L' - parseSimpleClassTypeSignature(it, buf); - while (it.current() == '/' || it.current() == '.') { // Eclipse compiler generates '.' for inner classes - parseClassTypeSignatureSuffix(it, buf); - } - if (it.current() != ';') { - throw new SignatureParsingException(CompilerBundle.message("error.signature.parsing.expected.other.symbol", ";", buf.toString())); - } - buf.append(it.current()); - it.next(); // consume ';' - } - - public void parseSimpleClassTypeSignature(CharacterIterator it, final StringBuilder buf) throws SignatureParsingException { - parseIdentifier(it, buf); - if (it.current() == '<') { - parseTypeArguments(it, buf); - } - } - - public void parseClassTypeSignatureSuffix(CharacterIterator it, final StringBuilder buf) throws SignatureParsingException { - buf.append(it.current()); - it.next(); - parseSimpleClassTypeSignature(it, buf); - } - - public void parseTypeVariableSignature(CharacterIterator it, final StringBuilder buf) throws SignatureParsingException { - buf.append(it.current()); - it.next(); // consume 'T' - parseIdentifier(it, buf); - if (it.current() != ';') { - throw new SignatureParsingException(CompilerBundle.message("error.signature.parsing.expected.other.symbol", ";", buf.toString())); - } - buf.append(it.current()); - it.next(); // consume ';' - } - - public void parseTypeArguments(CharacterIterator it, final StringBuilder buf) throws SignatureParsingException { - buf.append(it.current()); - it.next(); // consume '<' - while (it.current() != '>') { - parseTypeArgument(it, buf); - } - buf.append(it.current()); - it.next(); // consume '>' - } - - public void parseTypeArgument(CharacterIterator it, final StringBuilder buf) throws SignatureParsingException { - if (it.current() == '*') { - parseWildcardIndicator(it, buf); - } - else { - if (it.current() == '+' || it.current() == '-') { - parseWildcardIndicator(it, buf); - } - parseFieldTypeSignature(it, buf); - } - } - - public void parseWildcardIndicator(CharacterIterator it, final StringBuilder buf) { - buf.append(it.current()); - it.next(); - } - - public void parseArrayTypeSignature(CharacterIterator it, final StringBuilder buf) throws SignatureParsingException { - buf.append(it.current()); - it.next(); // consume '[' - parseTypeSignature(it, buf); - } - - public void parseTypeSignature(CharacterIterator it, final StringBuilder buf) throws SignatureParsingException { - char current = it.current(); - if (current == 'B' || current == 'C' || current == 'D' || current == 'F' || current == 'I' || current == 'J' || current == 'S' || current == 'Z') { - buf.append(it.current()); - it.next(); // base type - } - else if (current == 'L' || current == '[' || current == 'T') { - parseFieldTypeSignature(it, buf); - } - else { - throw new SignatureParsingException(CompilerBundle.message("error.signature.parsing.unknown.type.signature")); - } - } - - public void parseReturnType(CharacterIterator it, final StringBuilder buf) throws SignatureParsingException { - if (it.current() == 'V') { - buf.append(it.current()); - it.next(); - } - else { - parseTypeSignature(it, buf); - } - } - - public void parseThrowsSignature(CharacterIterator it, final StringBuilder buf) throws SignatureParsingException { - if (it.current() != '^') { - throw new SignatureParsingException(CompilerBundle.message("error.signature.parsing.expected.other.symbol", "^", buf.toString())); - } - buf.append(it.current()); - it.next(); - if (it.current() == 'T') { - parseTypeVariableSignature(it, buf); - } - else { - parseClassTypeSignature(it, buf); - } - } - - public void parseMethodSignature(CharacterIterator it, final StringBuilder buf) throws SignatureParsingException { - if (it.current() == '<') { - parseFormalTypeParameters(it, buf); - } - - if (it.current() != '(') { - throw new SignatureParsingException(CompilerBundle.message("error.signature.parsing.expected.other.symbol", "(", buf.toString())); - } - - buf.append(it.current()); - it.next(); // skip '(' - - while (it.current() != ')') { - parseTypeSignature(it, buf); - } - - buf.append(it.current()); - it.next(); // skip ')' - - parseReturnType(it, buf); - - if (it.current() != CharacterIterator.DONE) { - parseThrowsSignature(it, buf); - } - } - - public void parseClassSignature(CharacterIterator it, final StringBuilder buf) throws SignatureParsingException { - if (it.current() == '<') { - buf.append(it.current()); - it.next(); - while (it.current() != '>') { - parseFormalTypeParameter(it, buf); - } - buf.append(it.current()); - it.next(); - } - - parseClassTypeSignature(it, buf); - - while (it.current() != CharacterIterator.DONE) { - parseClassTypeSignature(it, buf); - } - } -} diff --git a/java/compiler/impl/src/com/intellij/compiler/classParsing/SignatureParsingException.java b/java/compiler/impl/src/com/intellij/compiler/classParsing/SignatureParsingException.java deleted file mode 100644 index 7246b1981d37..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/classParsing/SignatureParsingException.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.compiler.classParsing; - -/** - * @author Eugene Zhuravlev - * Date: Mar 4, 2004 - */ -public class SignatureParsingException extends Exception{ - public SignatureParsingException(String message) { - super(message); - } -} diff --git a/java/compiler/impl/src/com/intellij/compiler/classParsing/StringConstantValue.java b/java/compiler/impl/src/com/intellij/compiler/classParsing/StringConstantValue.java deleted file mode 100644 index faf560fdda69..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/classParsing/StringConstantValue.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * created at Feb 24, 2002 - * @author Jeka - */ -package com.intellij.compiler.classParsing; - -import java.io.DataInput; -import java.io.DataOutput; -import java.io.IOException; - -public class StringConstantValue extends ConstantValue{ - private final String myValue; - - public StringConstantValue(String value) { - myValue = value; - } - - public StringConstantValue(DataInput in) throws IOException{ - myValue = in.readUTF(); - } - - public String getValue() { - return myValue; - } - - public void save(DataOutput out) throws IOException { - super.save(out); - out.writeUTF(myValue); - } - - public boolean equals(Object obj) { - return - (obj instanceof StringConstantValue) && - ((myValue == null)? ((StringConstantValue)obj).myValue == null : myValue.equals(((StringConstantValue)obj).myValue)); - } -} diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/AdditionalCompileScopeProvider.java b/java/compiler/impl/src/com/intellij/compiler/impl/AdditionalCompileScopeProvider.java deleted file mode 100644 index 0b9ed31d0a59..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/impl/AdditionalCompileScopeProvider.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.intellij.compiler.impl; - -import com.intellij.openapi.compiler.CompilerFilter; -import com.intellij.openapi.extensions.ExtensionPointName; -import com.intellij.openapi.compiler.CompileScope; -import com.intellij.openapi.project.Project; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * @author nik - */ -public abstract class AdditionalCompileScopeProvider { - public static final ExtensionPointName EXTENSION_POINT_NAME = ExtensionPointName.create("com.intellij.compiler.additionalCompileScopeProvider"); - - @Nullable - public abstract CompileScope getAdditionalScope(@NotNull CompileScope baseScope, @NotNull CompilerFilter filter, @NotNull Project project); -} diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/CompileContextExProxy.java b/java/compiler/impl/src/com/intellij/compiler/impl/CompileContextExProxy.java deleted file mode 100644 index a8bad56c08fe..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/impl/CompileContextExProxy.java +++ /dev/null @@ -1,183 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.compiler.impl; - -import com.intellij.compiler.make.DependencyCache; -import com.intellij.openapi.compiler.CompileScope; -import com.intellij.openapi.compiler.CompilerMessage; -import com.intellij.openapi.compiler.CompilerMessageCategory; -import com.intellij.openapi.compiler.ex.CompileContextEx; -import com.intellij.openapi.module.Module; -import com.intellij.openapi.progress.ProgressIndicator; -import com.intellij.openapi.project.Project; -import com.intellij.openapi.util.Key; -import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.pom.Navigatable; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.util.Collection; -import java.util.Set; - -/** - * @author Eugene Zhuravlev - * Date: Dec 4, 2007 - */ -public class CompileContextExProxy implements CompileContextEx { - private final CompileContextEx myDelegate; - - public CompileContextExProxy(CompileContextEx delegate) { - myDelegate = delegate; - } - - public Project getProject() { - return myDelegate.getProject(); - } - - public DependencyCache getDependencyCache() { - return myDelegate.getDependencyCache(); - } - - public VirtualFile getSourceFileByOutputFile(final VirtualFile outputFile) { - return myDelegate.getSourceFileByOutputFile(outputFile); - } - - public void addMessage(final CompilerMessage message) { - myDelegate.addMessage(message); - } - - @NotNull - public Set getTestOutputDirectories() { - return myDelegate.getTestOutputDirectories(); - } - - public boolean isInTestSourceContent(@NotNull final VirtualFile fileOrDir) { - return myDelegate.isInTestSourceContent(fileOrDir); - } - - public boolean isInSourceContent(@NotNull final VirtualFile fileOrDir) { - return myDelegate.isInSourceContent(fileOrDir); - } - - public void addScope(final CompileScope additionalScope) { - myDelegate.addScope(additionalScope); - } - - public void addMessage(final CompilerMessageCategory category, - final String message, @Nullable final String url, final int lineNum, final int columnNum) { - myDelegate.addMessage(category, message, url, lineNum, columnNum); - } - - public void addMessage(final CompilerMessageCategory category, final String message, @Nullable final String url, - final int lineNum, - final int columnNum, - final Navigatable navigatable) { - myDelegate.addMessage(category, message, url, lineNum, columnNum, navigatable); - } - - public CompilerMessage[] getMessages(final CompilerMessageCategory category) { - return myDelegate.getMessages(category); - } - - public int getMessageCount(final CompilerMessageCategory category) { - return myDelegate.getMessageCount(category); - } - - public ProgressIndicator getProgressIndicator() { - return myDelegate.getProgressIndicator(); - } - - public CompileScope getCompileScope() { - return myDelegate.getCompileScope(); - } - - public CompileScope getProjectCompileScope() { - return myDelegate.getProjectCompileScope(); - } - - public void requestRebuildNextTime(final String message) { - myDelegate.requestRebuildNextTime(message); - } - - public boolean isRebuildRequested() { - return myDelegate.isRebuildRequested(); - } - - @Nullable - public String getRebuildReason() { - return myDelegate.getRebuildReason(); - } - - public Module getModuleByFile(final VirtualFile file) { - return myDelegate.getModuleByFile(file); - } - - public VirtualFile[] getSourceRoots(final Module module) { - return myDelegate.getSourceRoots(module); - } - - public VirtualFile[] getAllOutputDirectories() { - return myDelegate.getAllOutputDirectories(); - } - - public VirtualFile getModuleOutputDirectory(final Module module) { - return myDelegate.getModuleOutputDirectory(module); - } - - public VirtualFile getModuleOutputDirectoryForTests(final Module module) { - return myDelegate.getModuleOutputDirectoryForTests(module); - } - - public boolean isMake() { - return myDelegate.isMake(); - } - - public boolean isAnnotationProcessorsEnabled() { - return myDelegate.isAnnotationProcessorsEnabled(); - } - - public boolean isRebuild() { - return myDelegate.isRebuild(); - } - - public T getUserData(@NotNull final Key key) { - return myDelegate.getUserData(key); - } - - public void putUserData(@NotNull final Key key, final T value) { - myDelegate.putUserData(key, value); - } - - public void recalculateOutputDirs() { - myDelegate.recalculateOutputDirs(); - } - - public void markGenerated(Collection files) { - myDelegate.markGenerated(files); - } - - public boolean isGenerated(VirtualFile file) { - return myDelegate.isGenerated(file); - } - - public long getStartCompilationStamp() { - return myDelegate.getStartCompilationStamp(); - } - - public void assignModule(@NotNull VirtualFile root, @NotNull Module module, boolean isTestSource, com.intellij.openapi.compiler.Compiler compiler) { - myDelegate.assignModule(root, module, isTestSource, compiler); - } -} diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/CompileContextImpl.java b/java/compiler/impl/src/com/intellij/compiler/impl/CompileContextImpl.java index 764bf1dbc042..17e2dfed1dee 100644 --- a/java/compiler/impl/src/com/intellij/compiler/impl/CompileContextImpl.java +++ b/java/compiler/impl/src/com/intellij/compiler/impl/CompileContextImpl.java @@ -24,24 +24,21 @@ package com.intellij.compiler.impl; import com.intellij.compiler.CompilerConfiguration; import com.intellij.compiler.CompilerMessageImpl; import com.intellij.compiler.CompilerWorkspaceConfiguration; -import com.intellij.compiler.make.DependencyCache; import com.intellij.compiler.progress.CompilerTask; import com.intellij.execution.impl.ExecutionManagerImpl; import com.intellij.openapi.application.ApplicationManager; -import com.intellij.openapi.compiler.*; -import com.intellij.openapi.compiler.Compiler; +import com.intellij.openapi.compiler.CompileScope; +import com.intellij.openapi.compiler.CompilerMessage; +import com.intellij.openapi.compiler.CompilerMessageCategory; +import com.intellij.openapi.compiler.CompilerPaths; import com.intellij.openapi.compiler.ex.CompileContextEx; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.module.Module; -import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.project.Project; -import com.intellij.openapi.roots.CompilerModuleExtension; import com.intellij.openapi.roots.ModuleRootManager; import com.intellij.openapi.roots.ProjectFileIndex; import com.intellij.openapi.roots.ProjectRootManager; -import com.intellij.openapi.util.Computable; -import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.UserDataHolderBase; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VfsUtilCore; @@ -49,14 +46,9 @@ import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileManager; import com.intellij.pom.Navigatable; import com.intellij.util.containers.HashMap; -import com.intellij.util.containers.HashSet; -import com.intellij.util.containers.OrderedSet; -import com.intellij.util.indexing.FileBasedIndex; -import gnu.trove.TIntHashSet; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.io.File; import java.util.*; public class CompileContextImpl extends UserDataHolderBase implements CompileContextEx { @@ -66,7 +58,6 @@ public class CompileContextImpl extends UserDataHolderBase implements CompileCon private final Map> myMessages = new EnumMap>(CompilerMessageCategory.class); private final boolean myShouldUpdateProblemsView; private CompileScope myCompileScope; - private final DependencyCache myDependencyCache; private final boolean myMake; private final boolean myIsRebuild; private final boolean myIsAnnotationProcessorsEnabled; @@ -74,11 +65,7 @@ public class CompileContextImpl extends UserDataHolderBase implements CompileCon private String myRebuildReason; private final Map myRootToModuleMap = new HashMap(); private final Map> myModuleToRootsMap = new HashMap>(); - private final Map> myOutputRootToSourceGeneratorMap = new HashMap>(); private final Set myGeneratedTestRoots = new java.util.HashSet(); - private VirtualFile[] myOutputDirectories; - private Set myTestOutputDirectories; - private final TIntHashSet myGeneratedSources = new TIntHashSet(); private final ProjectFileIndex myProjectFileIndex; // cached for performance reasons private final ProjectCompileScope myProjectCompileScope; private final long myStartCompilationStamp; @@ -87,11 +74,10 @@ public class CompileContextImpl extends UserDataHolderBase implements CompileCon public CompileContextImpl(final Project project, final CompilerTask compilerSession, CompileScope compileScope, - DependencyCache dependencyCache, boolean isMake, boolean isRebuild) { + boolean isMake, boolean isRebuild) { myProject = project; myTask = compilerSession; myCompileScope = compileScope; - myDependencyCache = dependencyCache; myMake = isMake; myIsRebuild = isRebuild; myStartCompilationStamp = System.currentTimeMillis(); @@ -108,110 +94,22 @@ public class CompileContextImpl extends UserDataHolderBase implements CompileCon compilerSession.setSessionId(sessionId); } } - recalculateOutputDirs(); final CompilerWorkspaceConfiguration workspaceConfig = CompilerWorkspaceConfiguration.getInstance(myProject); - myShouldUpdateProblemsView = workspaceConfig.useOutOfProcessBuild() && workspaceConfig.MAKE_PROJECT_ON_SAVE; + myShouldUpdateProblemsView = workspaceConfig.MAKE_PROJECT_ON_SAVE; } public boolean shouldUpdateProblemsView() { return myShouldUpdateProblemsView; } - public void recalculateOutputDirs() { - final Module[] allModules = ModuleManager.getInstance(myProject).getModules(); - - final Set allDirs = new OrderedSet(); - final Set testOutputDirs = new java.util.HashSet(); - final Set productionOutputDirs = new java.util.HashSet(); - - for (Module module : allModules) { - final CompilerModuleExtension manager = CompilerModuleExtension.getInstance(module); - final VirtualFile output = manager.getCompilerOutputPath(); - if (output != null && output.isValid()) { - allDirs.add(output); - productionOutputDirs.add(output); - } - final VirtualFile testsOutput = manager.getCompilerOutputPathForTests(); - if (testsOutput != null && testsOutput.isValid()) { - allDirs.add(testsOutput); - testOutputDirs.add(testsOutput); - } - } - myOutputDirectories = VfsUtil.toVirtualFileArray(allDirs); - // need this to ensure that the sent contains only _dedicated_ test output dirs - // Directories that are configured for both test and production classes must not be added in the resulting set - testOutputDirs.removeAll(productionOutputDirs); - myTestOutputDirectories = Collections.unmodifiableSet(testOutputDirs); - } - - public void markGenerated(Collection files) { - for (final VirtualFile file : files) { - myGeneratedSources.add(FileBasedIndex.getFileId(file)); - } - } - public long getStartCompilationStamp() { return myStartCompilationStamp; } - public boolean isGenerated(VirtualFile file) { - if (myGeneratedSources.contains(FileBasedIndex.getFileId(file))) { - return true; - } - if (VfsUtilCore.isUnder(file, myRootToModuleMap.keySet())) { - return true; - } - final Module module = getModuleByFile(file); - if (module != null) { - final String procGenRoot = CompilerPaths.getAnnotationProcessorsGenerationPath(module); - if (procGenRoot != null && VfsUtil.isAncestor(new File(procGenRoot), new File(file.getPath()), true)) { - return true; - } - } - return false; - } - - /* - private JBZipFile lookupZip(String outputDir) { - synchronized (myOpenZipFiles) { - JBZipFile zip = myOpenZipFiles.get(outputDir); - if (zip == null) { - final File zipFile = CompilerPathsEx.getZippedOutputPath(myProject, outputDir); - try { - try { - zip = new JBZipFile(zipFile); - } - catch (FileNotFoundException e) { - try { - zipFile.createNewFile(); - zip = new JBZipFile(zipFile); - } - catch (IOException e1) { - zipFile.getParentFile().mkdirs(); - zipFile.createNewFile(); - zip = new JBZipFile(zipFile); - } - } - myOpenZipFiles.put(outputDir, zip); - } - catch (IOException e) { - LOG.info(e); - addMessage(CompilerMessageCategory.ERROR, "Cannot create zip file " + zipFile.getPath() + ": " + e.getMessage(), null, -1, -1); - } - } - return zip; - } - } - */ - public Project getProject() { return myProject; } - public DependencyCache getDependencyCache() { - return myDependencyCache; - } - public CompilerMessage[] getMessages(CompilerMessageCategory category) { Collection collection = myMessages.get(category); if (collection == null) { @@ -221,40 +119,16 @@ public class CompileContextImpl extends UserDataHolderBase implements CompileCon } public void addMessage(CompilerMessageCategory category, String message, String url, int lineNum, int columnNum) { - CompilerMessageImpl msg = new CompilerMessageImpl(myProject, category, message, findPresentableFileForMessage(url), lineNum, columnNum, null); + final CompilerMessageImpl msg = new CompilerMessageImpl(myProject, category, message, findFileByUrl(url), lineNum, columnNum, null); addMessage(msg); } public void addMessage(CompilerMessageCategory category, String message, String url, int lineNum, int columnNum, Navigatable navigatable) { - CompilerMessageImpl msg = new CompilerMessageImpl(myProject, category, message, findPresentableFileForMessage(url), lineNum, columnNum, navigatable); + final CompilerMessageImpl msg = new CompilerMessageImpl(myProject, category, message, findFileByUrl(url), lineNum, columnNum, navigatable); addMessage(msg); } - @Nullable - private VirtualFile findPresentableFileForMessage(@Nullable final String url) { - final VirtualFile file = findFileByUrl(url); - if (file == null) { - return null; - } - return ApplicationManager.getApplication().runReadAction(new Computable() { - @Override - public VirtualFile compute() { - if (file.isValid()) { - for (final Map.Entry> entry : myOutputRootToSourceGeneratorMap.entrySet()) { - final VirtualFile root = entry.getKey(); - if (VfsUtilCore.isAncestor(root, file, false)) { - final Pair pair = entry.getValue(); - final VirtualFile presentableFile = pair.getFirst().getPresentableFile(CompileContextImpl.this, pair.getSecond(), root, file); - return presentableFile != null ? presentableFile : file; - } - } - } - return file; - } - }); - } - @Nullable private static VirtualFile findFileByUrl(@Nullable String url) { if (url == null) { @@ -312,10 +186,6 @@ public class CompileContextImpl extends UserDataHolderBase implements CompileCon if (!myRebuildRequested) { myRebuildRequested = true; myRebuildReason = message; - final boolean isOutOfProcessBuild = myDependencyCache == null; - if (!isOutOfProcessBuild) { - addMessage(CompilerMessageCategory.ERROR, message, null, -1, -1); - } } } @@ -329,38 +199,9 @@ public class CompileContextImpl extends UserDataHolderBase implements CompileCon } public ProgressIndicator getProgressIndicator() { - //if (myProgressIndicatorProxy != null) { - // return myProgressIndicatorProxy; - //} return myTask.getIndicator(); } - public void assignModule(@NotNull VirtualFile root, @NotNull Module module, final boolean isTestSource, @Nullable Compiler compiler) { - try { - myRootToModuleMap.put(root, module); - Set set = myModuleToRootsMap.get(module); - if (set == null) { - set = new HashSet(); - myModuleToRootsMap.put(module, set); - } - set.add(root); - if (isTestSource) { - myGeneratedTestRoots.add(root); - } - if (compiler instanceof SourceGeneratingCompiler) { - myOutputRootToSourceGeneratorMap.put(root, Pair.create((SourceGeneratingCompiler)compiler, module)); - } - } - finally { - myModuleToRootsCache.remove(module); - } - } - - @Nullable - public VirtualFile getSourceFileByOutputFile(VirtualFile outputFile) { - return TranslatingCompilerFilesMonitor.getSourceFileByOutput(outputFile); - } - public Module getModuleByFile(VirtualFile file) { final Module module = myProjectFileIndex.getModuleForFile(file); if (module != null) { @@ -419,15 +260,6 @@ public class CompileContextImpl extends UserDataHolderBase implements CompileCon return true; } - public VirtualFile[] getAllOutputDirectories() { - return myOutputDirectories; - } - - @NotNull - public Set getTestOutputDirectories() { - return myTestOutputDirectories; - } - public VirtualFile getModuleOutputDirectory(Module module) { return CompilerPaths.getModuleOutputDirectory(module, false); } diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/CompileDriver.java b/java/compiler/impl/src/com/intellij/compiler/impl/CompileDriver.java index cc2b19b9cb66..f50fa0ad68bb 100644 --- a/java/compiler/impl/src/com/intellij/compiler/impl/CompileDriver.java +++ b/java/compiler/impl/src/com/intellij/compiler/impl/CompileDriver.java @@ -22,86 +22,54 @@ package com.intellij.compiler.impl; import com.intellij.CommonBundle; -import com.intellij.compiler.*; -import com.intellij.compiler.make.CacheCorruptedException; -import com.intellij.compiler.make.CacheUtils; -import com.intellij.compiler.make.ChangedConstantsDependencyProcessor; -import com.intellij.compiler.make.DependencyCache; -import com.intellij.compiler.options.CompilerConfigurable; +import com.intellij.compiler.CompilerConfiguration; +import com.intellij.compiler.CompilerWorkspaceConfiguration; +import com.intellij.compiler.ModuleCompilerUtil; +import com.intellij.compiler.ProblemsView; import com.intellij.compiler.progress.CompilerTask; import com.intellij.compiler.server.BuildManager; import com.intellij.compiler.server.CustomBuilderMessageHandler; import com.intellij.compiler.server.DefaultMessageHandler; -import com.intellij.diagnostic.IdeErrorsDialog; -import com.intellij.diagnostic.PluginException; -import com.intellij.notification.Notification; -import com.intellij.notification.NotificationListener; -import com.intellij.notification.NotificationType; -import com.intellij.notification.Notifications; -import com.intellij.openapi.application.*; +import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.compiler.*; -import com.intellij.openapi.compiler.Compiler; -import com.intellij.openapi.compiler.ex.CompileContextEx; import com.intellij.openapi.compiler.ex.CompilerPathsEx; -import com.intellij.openapi.compiler.generic.GenericCompiler; import com.intellij.openapi.deployment.DeploymentUtil; import com.intellij.openapi.diagnostic.Logger; -import com.intellij.openapi.extensions.Extensions; -import com.intellij.openapi.extensions.PluginId; import com.intellij.openapi.fileEditor.FileDocumentManager; -import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.module.LanguageLevelUtil; import com.intellij.openapi.module.Module; -import com.intellij.openapi.module.ModuleManager; -import com.intellij.openapi.options.ShowSettingsUtil; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressIndicator; -import com.intellij.openapi.progress.ProgressManager; -import com.intellij.openapi.project.DumbService; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectBundle; import com.intellij.openapi.projectRoots.Sdk; -import com.intellij.openapi.roots.CompilerModuleExtension; -import com.intellij.openapi.roots.CompilerProjectExtension; import com.intellij.openapi.roots.ModuleRootManager; -import com.intellij.openapi.roots.ProjectRootManager; -import com.intellij.openapi.roots.ex.ProjectRootManagerEx; import com.intellij.openapi.roots.ui.configuration.CommonContentEntriesEditor; import com.intellij.openapi.roots.ui.configuration.ProjectSettingsService; import com.intellij.openapi.ui.MessageType; import com.intellij.openapi.ui.Messages; -import com.intellij.openapi.util.*; +import com.intellij.openapi.util.Key; +import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.io.FileUtil; -import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.util.text.StringUtil; -import com.intellij.openapi.vfs.*; -import com.intellij.openapi.vfs.newvfs.ManagingFS; -import com.intellij.openapi.vfs.newvfs.RefreshQueue; +import com.intellij.openapi.vfs.LocalFileSystem; +import com.intellij.openapi.vfs.VirtualFileManager; import com.intellij.openapi.wm.StatusBar; import com.intellij.openapi.wm.ToolWindowId; import com.intellij.openapi.wm.ToolWindowManager; import com.intellij.openapi.wm.WindowManager; import com.intellij.packaging.artifacts.Artifact; -import com.intellij.packaging.artifacts.ArtifactManager; -import com.intellij.packaging.impl.artifacts.ArtifactImpl; -import com.intellij.packaging.impl.artifacts.ArtifactUtil; -import com.intellij.packaging.impl.compiler.ArtifactCompileScope; import com.intellij.packaging.impl.compiler.ArtifactCompilerUtil; import com.intellij.packaging.impl.compiler.ArtifactsCompiler; import com.intellij.pom.java.LanguageLevel; import com.intellij.psi.PsiDocumentManager; import com.intellij.util.Chunk; -import com.intellij.util.Function; import com.intellij.util.StringBuilderSpinAllocator; import com.intellij.util.ThrowableRunnable; -import com.intellij.util.concurrency.Semaphore; -import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.HashMap; import com.intellij.util.containers.MultiMap; -import com.intellij.util.containers.OrderedSet; import com.intellij.util.messages.MessageBus; import gnu.trove.THashSet; -import gnu.trove.TIntHashSet; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -112,8 +80,7 @@ import org.jetbrains.jps.api.RequestFuture; import org.jetbrains.jps.model.java.JavaSourceRootType; import javax.swing.*; -import javax.swing.event.HyperlinkEvent; -import java.io.*; +import java.io.File; import java.util.*; import java.util.concurrent.TimeUnit; @@ -122,78 +89,20 @@ import static org.jetbrains.jps.api.CmdlineRemoteProto.Message.ControllerMessage public class CompileDriver { private static final Logger LOG = Logger.getInstance("#com.intellij.compiler.impl.CompileDriver"); - // to be used in tests only for debug output - public static volatile boolean ourDebugMode = false; private final Project myProject; - private final Map, Couple> myGenerationCompilerModuleToOutputDirMap; // [IntermediateOutputCompiler, Module] -> [ProductionSources, TestSources] - private final String myCachesDirectoryPath; - private boolean myShouldClearOutputDirectory; private final Map myModuleOutputPaths = new HashMap(); private final Map myModuleTestOutputPaths = new HashMap(); - @NonNls private static final String VERSION_FILE_NAME = "version.dat"; - @NonNls private static final String LOCK_FILE_NAME = "in_progress.dat"; - - private static final boolean GENERATE_CLASSPATH_INDEX = "true".equals(System.getProperty("generate.classpath.index")); - private static final String PROP_PERFORM_INITIAL_REFRESH = "compiler.perform.outputs.refresh.on.start"; - private static final Key REFRESH_DONE_KEY = Key.create("_compiler.initial.refresh.done_"); private static final Key COMPILATION_STARTED_AUTOMATICALLY = Key.create("compilation_started_automatically"); - private static final FileProcessingCompilerAdapterFactory FILE_PROCESSING_COMPILER_ADAPTER_FACTORY = new FileProcessingCompilerAdapterFactory() { - public FileProcessingCompilerAdapter create(CompileContext context, FileProcessingCompiler compiler) { - return new FileProcessingCompilerAdapter(context, compiler); - } - }; - private static final FileProcessingCompilerAdapterFactory FILE_PACKAGING_COMPILER_ADAPTER_FACTORY = new FileProcessingCompilerAdapterFactory() { - public FileProcessingCompilerAdapter create(CompileContext context, FileProcessingCompiler compiler) { - return new PackagingCompilerAdapter(context, (PackagingCompiler)compiler); - } - }; private CompilerFilter myCompilerFilter = CompilerFilter.ALL; - private static final CompilerFilter SOURCE_PROCESSING_ONLY = new CompilerFilter() { - public boolean acceptCompiler(Compiler compiler) { - return compiler instanceof SourceProcessingCompiler; - } - }; - private static final CompilerFilter ALL_EXCEPT_SOURCE_PROCESSING = new CompilerFilter() { - public boolean acceptCompiler(Compiler compiler) { - return !SOURCE_PROCESSING_ONLY.acceptCompiler(compiler); - } - }; - private Set myAllOutputDirectories; private static final long ONE_MINUTE_MS = 60L /*sec*/ * 1000L /*millisec*/; public CompileDriver(Project project) { myProject = project; - myCachesDirectoryPath = CompilerPaths.getCacheStoreDirectory(myProject).getPath().replace('/', File.separatorChar); - myShouldClearOutputDirectory = CompilerWorkspaceConfiguration.getInstance(myProject).CLEAR_OUTPUT_DIRECTORY; - - myGenerationCompilerModuleToOutputDirMap = new HashMap, Couple>(); - - if (!useOutOfProcessBuild()) { - final LocalFileSystem lfs = LocalFileSystem.getInstance(); - final IntermediateOutputCompiler[] generatingCompilers = CompilerManager.getInstance(myProject).getCompilers(IntermediateOutputCompiler.class, myCompilerFilter); - final Module[] allModules = ModuleManager.getInstance(myProject).getModules(); - final CompilerConfiguration config = CompilerConfiguration.getInstance(project); - for (Module module : allModules) { - for (IntermediateOutputCompiler compiler : generatingCompilers) { - final VirtualFile productionOutput = lookupVFile(lfs, CompilerPaths.getGenerationOutputPath(compiler, module, false)); - final VirtualFile testOutput = lookupVFile(lfs, CompilerPaths.getGenerationOutputPath(compiler, module, true)); - final Pair pair = Pair.create(compiler, module); - final Couple outputs = Couple.newOne(productionOutput, testOutput); - myGenerationCompilerModuleToOutputDirMap.put(pair, outputs); - } - if (config.getAnnotationProcessingConfiguration(module).isEnabled()) { - final String path = CompilerPaths.getAnnotationProcessorsGenerationPath(module); - if (path != null) { - lookupVFile(lfs, path); // ensure the file is created and added to VFS - } - } - } - } } public void setCompilerFilter(CompilerFilter compilerFilter) { @@ -201,24 +110,12 @@ public class CompileDriver { } public void rebuild(CompileStatusNotification callback) { - final CompileScope compileScope; - ProjectCompileScope projectScope = new ProjectCompileScope(myProject); - if (useOutOfProcessBuild()) { - compileScope = projectScope; - } - else { - CompileScope scopeWithArtifacts = ArtifactCompileScope.createScopeWithArtifacts(projectScope, ArtifactUtil.getArtifactWithOutputPaths(myProject)); - compileScope = addAdditionalRoots(scopeWithArtifacts, ALL_EXCEPT_SOURCE_PROCESSING); - } - doRebuild(callback, null, true, compileScope); + doRebuild(callback, null, new ProjectCompileScope(myProject)); } public void make(CompileScope scope, CompileStatusNotification callback) { - if (!useOutOfProcessBuild()) { - scope = addAdditionalRoots(scope, ALL_EXCEPT_SOURCE_PROCESSING); - } - if (validateCompilerConfiguration(scope, false)) { - startup(scope, false, false, callback, null, true); + if (validateCompilerConfiguration(scope)) { + startup(scope, false, false, callback, null); } else { callback.finished(true, 0, 0, DummyCompileContext.getInstance()); @@ -229,80 +126,39 @@ public class CompileDriver { if (LOG.isDebugEnabled()) { LOG.debug("isUpToDate operation started"); } - if (!useOutOfProcessBuild()) { - scope = addAdditionalRoots(scope, ALL_EXCEPT_SOURCE_PROCESSING); - } final CompilerTask task = new CompilerTask(myProject, "Classes up-to-date check", true, false, false, isCompilationStartedAutomatically(scope)); - final DependencyCache cache = useOutOfProcessBuild()? null : createDependencyCache(); - final CompileContextImpl compileContext = new CompileContextImpl(myProject, task, scope, cache, true, false); - - if (!useOutOfProcessBuild()) { - checkCachesVersion(compileContext, ManagingFS.getInstance().getCreationTimestamp()); - if (compileContext.isRebuildRequested()) { - if (LOG.isDebugEnabled()) { - LOG.debug("Rebuild requested, up-to-date=false"); - } - return false; - } - - for (Map.Entry, Couple> entry : myGenerationCompilerModuleToOutputDirMap.entrySet()) { - final Couple outputs = entry.getValue(); - final Pair key = entry.getKey(); - final Module module = key.getSecond(); - compileContext.assignModule(outputs.getFirst(), module, false, key.getFirst()); - compileContext.assignModule(outputs.getSecond(), module, true, key.getFirst()); - } - } + final CompileContextImpl compileContext = new CompileContextImpl(myProject, task, scope, true, false); final Ref result = new Ref(); - final Runnable compileWork; - if (useOutOfProcessBuild()) { - compileWork = new Runnable() { - public void run() { - final ProgressIndicator indicator = compileContext.getProgressIndicator(); - if (indicator.isCanceled() || myProject.isDisposed()) { - return; - } - try { - final RequestFuture future = compileInExternalProcess(compileContext, true); - if (future != null) { - while (!future.waitFor(200L , TimeUnit.MILLISECONDS)) { - if (indicator.isCanceled()) { - future.cancel(false); - } + task.start(new Runnable() { + public void run() { + final ProgressIndicator indicator = compileContext.getProgressIndicator(); + if (indicator.isCanceled() || myProject.isDisposed()) { + return; + } + try { + final RequestFuture future = compileInExternalProcess(compileContext, true); + if (future != null) { + while (!future.waitFor(200L, TimeUnit.MILLISECONDS)) { + if (indicator.isCanceled()) { + future.cancel(false); } } } - catch (Throwable e) { - LOG.error(e); - } - finally { - result.set(COMPILE_SERVER_BUILD_STATUS.get(compileContext)); - if (!myProject.isDisposed()) { - CompilerCacheManager.getInstance(myProject).flushCaches(); - } - } } - }; - } - else { - compileWork = new Runnable() { - public void run() { - try { - myAllOutputDirectories = getAllOutputDirectories(compileContext); - // need this for updating zip archives experiment, uncomment if the feature is turned on - //myOutputFinder = new OutputPathFinder(myAllOutputDirectories); - result.set(doCompile(compileContext, false, false, true)); - } - finally { + catch (Throwable e) { + LOG.error(e); + } + finally { + result.set(COMPILE_SERVER_BUILD_STATUS.get(compileContext)); + if (!myProject.isDisposed()) { CompilerCacheManager.getInstance(myProject).flushCaches(); } } - }; - } - task.start(compileWork, null); + } + }, null); if (LOG.isDebugEnabled()) { LOG.debug("isUpToDate operation finished"); @@ -311,17 +167,9 @@ public class CompileDriver { return ExitStatus.UP_TO_DATE.equals(result.get()); } - private DependencyCache createDependencyCache() { - return new DependencyCache(myCachesDirectoryPath + File.separator + ".dependency-info"); - } - - public void compile(CompileScope scope, CompileStatusNotification callback, boolean clearingOutputDirsPossible) { - myShouldClearOutputDirectory &= clearingOutputDirsPossible; - if (containsFileIndexScopes(scope)) { - scope = addAdditionalRoots(scope, ALL_EXCEPT_SOURCE_PROCESSING); - } - if (validateCompilerConfiguration(scope, false)) { - startup(scope, false, true, callback, null, true); + public void compile(CompileScope scope, CompileStatusNotification callback) { + if (validateCompilerConfiguration(scope)) { + startup(scope, false, true, callback, null); } else { callback.finished(true, 0, 0, DummyCompileContext.getInstance()); @@ -339,116 +187,15 @@ public class CompileDriver { return scope instanceof FileIndexCompileScope; } - private static class CompileStatus { - final int CACHE_FORMAT_VERSION; - final boolean COMPILATION_IN_PROGRESS; - final long VFS_CREATION_STAMP; - - private CompileStatus(int cacheVersion, boolean isCompilationInProgress, long vfsStamp) { - CACHE_FORMAT_VERSION = cacheVersion; - COMPILATION_IN_PROGRESS = isCompilationInProgress; - VFS_CREATION_STAMP = vfsStamp; - } - } - - private CompileStatus readStatus() { - final boolean isInProgress = getLockFile().exists(); - int version = -1; - long vfsStamp = -1L; - try { - final File versionFile = new File(myCachesDirectoryPath, VERSION_FILE_NAME); - DataInputStream in = new DataInputStream(new FileInputStream(versionFile)); - try { - version = in.readInt(); - try { - vfsStamp = in.readLong(); - } - catch (IOException ignored) { - } - } - finally { - in.close(); - } - } - catch (FileNotFoundException e) { - // ignore - } - catch (IOException e) { - LOG.info(e); // may happen in case of IDEA crashed and the file is not written properly - return null; - } - return new CompileStatus(version, isInProgress, vfsStamp); - } - - private void writeStatus(CompileStatus status, CompileContext context) { - final File statusFile = new File(myCachesDirectoryPath, VERSION_FILE_NAME); - - final File lockFile = getLockFile(); - try { - FileUtil.createIfDoesntExist(statusFile); - DataOutputStream out = new DataOutputStream(new FileOutputStream(statusFile)); - try { - out.writeInt(status.CACHE_FORMAT_VERSION); - out.writeLong(status.VFS_CREATION_STAMP); - } - finally { - out.close(); - } - if (status.COMPILATION_IN_PROGRESS) { - FileUtil.createIfDoesntExist(lockFile); - } - else { - deleteFile(lockFile); - } - } - catch (IOException e) { - context.addMessage(CompilerMessageCategory.ERROR, CompilerBundle.message("compiler.error.exception", e.getMessage()), null, -1, -1); - } - } - - private File getLockFile() { - return new File(CompilerPaths.getCompilerSystemDirectory(myProject), LOCK_FILE_NAME); - } - - private void doRebuild(CompileStatusNotification callback, - CompilerMessage message, - final boolean checkCachesVersion, - final CompileScope compileScope) { - if (validateCompilerConfiguration(compileScope, !useOutOfProcessBuild())) { - startup(compileScope, true, false, callback, message, checkCachesVersion); + private void doRebuild(CompileStatusNotification callback, CompilerMessage message, final CompileScope compileScope) { + if (validateCompilerConfiguration(compileScope)) { + startup(compileScope, true, false, callback, message); } else { callback.finished(true, 0, 0, DummyCompileContext.getInstance()); } } - private CompileScope addAdditionalRoots(CompileScope originalScope, final CompilerFilter filter) { - CompileScope scope = attachIntermediateOutputDirectories(originalScope, filter); - - final AdditionalCompileScopeProvider[] scopeProviders = Extensions.getExtensions(AdditionalCompileScopeProvider.EXTENSION_POINT_NAME); - CompileScope baseScope = scope; - for (AdditionalCompileScopeProvider scopeProvider : scopeProviders) { - final CompileScope additionalScope = scopeProvider.getAdditionalScope(baseScope, filter, myProject); - if (additionalScope != null) { - scope = new CompositeScope(scope, additionalScope); - } - } - return scope; - } - - private CompileScope attachIntermediateOutputDirectories(CompileScope originalScope, CompilerFilter filter) { - CompileScope scope = originalScope; - final Set affected = new HashSet(Arrays.asList(originalScope.getAffectedModules())); - for (Map.Entry, Couple> entry : myGenerationCompilerModuleToOutputDirMap.entrySet()) { - final Module module = entry.getKey().getSecond(); - if (affected.contains(module) && filter.acceptCompiler(entry.getKey().getFirst())) { - final Couple outputs = entry.getValue(); - scope = new CompositeScope(scope, new FileSetCompileScope(Arrays.asList(outputs.getFirst(), outputs.getSecond()), new Module[]{module})); - } - } - return scope; - } - public static void setCompilationStartedAutomatically(CompileScope scope) { //todo[nik] pass this option as a parameter to compile/make methods instead scope.putUserData(COMPILATION_STARTED_AUTOMATICALLY, Boolean.TRUE); @@ -458,31 +205,6 @@ public class CompileDriver { return Boolean.TRUE.equals(scope.getUserData(COMPILATION_STARTED_AUTOMATICALLY)); } - private void attachAnnotationProcessorsOutputDirectories(CompileContextEx context) { - final LocalFileSystem lfs = LocalFileSystem.getInstance(); - final CompilerConfiguration config = CompilerConfiguration.getInstance(myProject); - final Set affected = new HashSet(Arrays.asList(context.getCompileScope().getAffectedModules())); - for (Module module : affected) { - if (!config.getAnnotationProcessingConfiguration(module).isEnabled()) { - continue; - } - final String path = CompilerPaths.getAnnotationProcessorsGenerationPath(module); - if (path == null) { - continue; - } - final VirtualFile vFile = lfs.findFileByPath(path); - if (vFile == null) { - continue; - } - if (ModuleRootManager.getInstance(module).getFileIndex().isInSourceContent(vFile)) { - // no need to add, is already marked as source - continue; - } - context.addScope(new FileSetCompileScope(Collections.singletonList(vFile), new Module[]{module})); - context.assignModule(vFile, module, false, null); - } - } - @Nullable private RequestFuture compileInExternalProcess(final @NotNull CompileContextImpl compileContext, final boolean onlyCheckUpToDate) throws Exception { @@ -648,140 +370,87 @@ public class CompileDriver { final boolean isRebuild, final boolean forceCompile, final CompileStatusNotification callback, - final CompilerMessage message, - final boolean checkCachesVersion) { + final CompilerMessage message) { ApplicationManager.getApplication().assertIsDispatchThread(); - final boolean useExtProcessBuild = useOutOfProcessBuild(); - final String contentName = forceCompile ? CompilerBundle.message("compiler.content.name.compile") : CompilerBundle.message("compiler.content.name.make"); final boolean isUnitTestMode = ApplicationManager.getApplication().isUnitTestMode(); final CompilerTask compileTask = new CompilerTask(myProject, contentName, isUnitTestMode, true, true, isCompilationStartedAutomatically(scope)); StatusBar.Info.set("", myProject, "Compiler"); - if (useExtProcessBuild) { - // ensure the project model seen by build process is up-to-date - myProject.save(); - if (!isUnitTestMode) { - ApplicationManager.getApplication().saveSettings(); - } + // ensure the project model seen by build process is up-to-date + myProject.save(); + if (!isUnitTestMode) { + ApplicationManager.getApplication().saveSettings(); } PsiDocumentManager.getInstance(myProject).commitAllDocuments(); FileDocumentManager.getInstance().saveAllDocuments(); - final DependencyCache dependencyCache = useExtProcessBuild ? null: createDependencyCache(); - final CompileContextImpl compileContext = - new CompileContextImpl(myProject, compileTask, scope, dependencyCache, !isRebuild && !forceCompile, isRebuild); + final CompileContextImpl compileContext = new CompileContextImpl(myProject, compileTask, scope, !isRebuild && !forceCompile, isRebuild); - if (!useExtProcessBuild) { - for (Map.Entry, Couple> entry : myGenerationCompilerModuleToOutputDirMap.entrySet()) { - final Couple outputs = entry.getValue(); - final Pair key = entry.getKey(); - final Module module = key.getSecond(); - compileContext.assignModule(outputs.getFirst(), module, false, key.getFirst()); - compileContext.assignModule(outputs.getSecond(), module, true, key.getFirst()); - } - attachAnnotationProcessorsOutputDirectories(compileContext); - } + final Runnable compileWork = new Runnable() { + public void run() { + final ProgressIndicator indicator = compileContext.getProgressIndicator(); + if (indicator.isCanceled() || myProject.isDisposed()) { + if (callback != null) { + callback.finished(true, 0, 0, compileContext); + } + return; + } + try { + LOG.info("COMPILATION STARTED (BUILD PROCESS)"); + if (message != null) { + compileContext.addMessage(message); + } + if (isRebuild) { + CompilerUtil.runInContext(compileContext, "Clearing build system data...", new ThrowableRunnable() { + @Override + public void run() throws Throwable { + CompilerCacheManager.getInstance(myProject).clearCaches(compileContext); + } + }); + } + final boolean beforeTasksOk = executeCompileTasks(compileContext, true); - final Runnable compileWork; - if (useExtProcessBuild) { - compileWork = new Runnable() { - public void run() { - final ProgressIndicator indicator = compileContext.getProgressIndicator(); - if (indicator.isCanceled() || myProject.isDisposed()) { - if (callback != null) { - callback.finished(true, 0, 0, compileContext); - } + final int errorCount = compileContext.getMessageCount(CompilerMessageCategory.ERROR); + if (!beforeTasksOk || errorCount > 0) { + COMPILE_SERVER_BUILD_STATUS.set(compileContext, errorCount > 0 ? ExitStatus.ERRORS : ExitStatus.CANCELLED); return; } - try { - LOG.info("COMPILATION STARTED (BUILD PROCESS)"); - if (message != null) { - compileContext.addMessage(message); - } - if (isRebuild) { - CompilerUtil.runInContext(compileContext, "Clearing build system data...", new ThrowableRunnable() { - @Override - public void run() throws Throwable { - CompilerCacheManager.getInstance(myProject).clearCaches(compileContext); - } - }); - } - final boolean beforeTasksOk = executeCompileTasks(compileContext, true); - final int errorCount = compileContext.getMessageCount(CompilerMessageCategory.ERROR); - if (!beforeTasksOk || errorCount > 0) { - COMPILE_SERVER_BUILD_STATUS.set(compileContext, errorCount > 0? ExitStatus.ERRORS : ExitStatus.CANCELLED); - return; + final RequestFuture future = compileInExternalProcess(compileContext, false); + if (future != null) { + while (!future.waitFor(200L, TimeUnit.MILLISECONDS)) { + if (indicator.isCanceled()) { + future.cancel(false); + } } - - final RequestFuture future = compileInExternalProcess(compileContext, false); - if (future != null) { - while (!future.waitFor(200L , TimeUnit.MILLISECONDS)) { - if (indicator.isCanceled()) { - future.cancel(false); - } - } - if (!executeCompileTasks(compileContext, false)) { - COMPILE_SERVER_BUILD_STATUS.set(compileContext, ExitStatus.CANCELLED); - } - if (compileContext.getMessageCount(CompilerMessageCategory.ERROR) > 0) { - COMPILE_SERVER_BUILD_STATUS.set(compileContext, ExitStatus.ERRORS); - } + if (!executeCompileTasks(compileContext, false)) { + COMPILE_SERVER_BUILD_STATUS.set(compileContext, ExitStatus.CANCELLED); + } + if (compileContext.getMessageCount(CompilerMessageCategory.ERROR) > 0) { + COMPILE_SERVER_BUILD_STATUS.set(compileContext, ExitStatus.ERRORS); } } - catch (Throwable e) { - LOG.error(e); // todo - } - finally { - CompilerCacheManager.getInstance(myProject).flushCaches(); + } + catch (Throwable e) { + LOG.error(e); // todo + } + finally { + CompilerCacheManager.getInstance(myProject).flushCaches(); - final long duration = notifyCompilationCompleted(compileContext, callback, COMPILE_SERVER_BUILD_STATUS.get(compileContext), true); - CompilerUtil.logDuration( - "\tCOMPILATION FINISHED (BUILD PROCESS); Errors: " + + final long duration = notifyCompilationCompleted(compileContext, callback, COMPILE_SERVER_BUILD_STATUS.get(compileContext)); + CompilerUtil.logDuration( + "\tCOMPILATION FINISHED (BUILD PROCESS); Errors: " + compileContext.getMessageCount(CompilerMessageCategory.ERROR) + "; warnings: " + compileContext.getMessageCount(CompilerMessageCategory.WARNING), - duration - ); - } + duration + ); } - }; - } - else { - compileWork = new Runnable() { - public void run() { - if (compileContext.getProgressIndicator().isCanceled()) { - if (callback != null) { - callback.finished(true, 0, 0, compileContext); - } - return; - } - try { - if (myProject.isDisposed()) { - return; - } - LOG.info("COMPILATION STARTED"); - if (message != null) { - compileContext.addMessage(message); - } - else { - if (!isUnitTestMode) { - notifyDeprecatedImplementation(); - } - } - - TranslatingCompilerFilesMonitor.getInstance().ensureInitializationCompleted(myProject, compileContext.getProgressIndicator()); - doCompile(compileContext, isRebuild, forceCompile, callback, checkCachesVersion); - } - finally { - FileUtil.delete(CompilerPaths.getRebuildMarkerFile(myProject)); - } - } - }; - } + } + }; compileTask.start(compileWork, new Runnable() { public void run() { @@ -791,121 +460,24 @@ public class CompileDriver { "Make", "Rebuild", Messages.getQuestionIcon() ); if (rv == Messages.OK /*yes, please, do run make*/) { - startup(scope, false, false, callback, null, checkCachesVersion); + startup(scope, false, false, callback, null); return; } } - startup(scope, isRebuild, forceCompile, callback, message, checkCachesVersion); + startup(scope, isRebuild, forceCompile, callback, message); } }); } - private static final Key OLD_IMPLEMENTATION_WARNING_SHOWN = Key.create("_old_make_implementation_warning_shown_"); - private void notifyDeprecatedImplementation() { - if (OLD_IMPLEMENTATION_WARNING_SHOWN.get(myProject, Boolean.FALSE).booleanValue()) { - return; - } - OLD_IMPLEMENTATION_WARNING_SHOWN.set(myProject, Boolean.TRUE); - final NotificationListener hyperlinkHandler = new NotificationListener.Adapter() { - @Override - protected void hyperlinkActivated(@NotNull Notification notification, @NotNull HyperlinkEvent e) { - notification.expire(); - if (!myProject.isDisposed()) { - ShowSettingsUtil.getInstance().editConfigurable(myProject, new CompilerConfigurable(myProject)); - } - } - }; - final Notification notification = new Notification( - "Compile", "Deprecated make implementation", - "Old implementation of \"Make\" feature is enabled for this project.
It has been deprecated and will be removed soon.
Please enable newer 'external build' feature in Settings | Compiler.", - NotificationType.WARNING, - hyperlinkHandler - ); - Notifications.Bus.notify(notification, myProject); - } - @Nullable @TestOnly public static ExitStatus getExternalBuildExitStatus(CompileContext context) { return context.getUserData(COMPILE_SERVER_BUILD_STATUS); } - private void doCompile(final CompileContextImpl compileContext, - final boolean isRebuild, - final boolean forceCompile, - final CompileStatusNotification callback, - final boolean checkCachesVersion) { - ExitStatus status = ExitStatus.ERRORS; - boolean wereExceptions = false; - final long vfsTimestamp = (ManagingFS.getInstance()).getCreationTimestamp(); - try { - if (checkCachesVersion) { - checkCachesVersion(compileContext, vfsTimestamp); - if (compileContext.isRebuildRequested()) { - return; - } - } - writeStatus(new CompileStatus(CompilerConfigurationImpl.DEPENDENCY_FORMAT_VERSION, true, vfsTimestamp), compileContext); - if (compileContext.getMessageCount(CompilerMessageCategory.ERROR) > 0) { - return; - } - - myAllOutputDirectories = getAllOutputDirectories(compileContext); - status = doCompile(compileContext, isRebuild, forceCompile, false); - } - catch (Throwable ex) { - if (ApplicationManager.getApplication().isUnitTestMode()) { - throw new RuntimeException(ex); - } - wereExceptions = true; - final PluginId pluginId = IdeErrorsDialog.findPluginId(ex); - - final StringBuilder message = new StringBuilder(); - message.append("Internal error"); - if (pluginId != null) { - message.append(" (Plugin: ").append(pluginId).append(")"); - } - message.append(": ").append(ex.getMessage()); - compileContext.addMessage(CompilerMessageCategory.ERROR, message.toString(), null, -1, -1); - - if (pluginId != null) { - throw new PluginException(ex, pluginId); - } - throw new RuntimeException(ex); - } - finally { - dropDependencyCache(compileContext); - CompilerCacheManager.getInstance(myProject).flushCaches(); - if (compileContext.isRebuildRequested()) { - ApplicationManager.getApplication().invokeLater(new Runnable() { - public void run() { - final CompilerMessageImpl msg = new CompilerMessageImpl(myProject, CompilerMessageCategory.INFORMATION, compileContext.getRebuildReason()); - doRebuild(callback, msg, false, compileContext.getCompileScope()); - } - }, ModalityState.NON_MODAL); - } - else { - if (!myProject.isDisposed()) { - writeStatus(new CompileStatus(CompilerConfigurationImpl.DEPENDENCY_FORMAT_VERSION, wereExceptions, vfsTimestamp), compileContext); - } - final long duration = notifyCompilationCompleted(compileContext, callback, status, false); - CompilerUtil.logDuration( - "\tCOMPILATION FINISHED; Errors: " + - compileContext.getMessageCount(CompilerMessageCategory.ERROR) + - "; warnings: " + - compileContext.getMessageCount(CompilerMessageCategory.WARNING), - duration - ); - } - } - } - /** @noinspection SSBasedInspection*/ - private long notifyCompilationCompleted(final CompileContextImpl compileContext, - final CompileStatusNotification callback, - final ExitStatus _status, - final boolean refreshOutputRoots) { + private long notifyCompilationCompleted(final CompileContextImpl compileContext, final CompileStatusNotification callback, final ExitStatus _status) { final long duration = System.currentTimeMillis() - compileContext.getStartCompilationStamp(); - if (refreshOutputRoots && !myProject.isDisposed()) { + if (!myProject.isDisposed()) { // refresh on output roots is required in order for the order enumerator to see all roots via VFS final Set outputs = new HashSet(); final Module[] affectedModules = compileContext.getCompileScope().getAffectedModules(); @@ -965,29 +537,6 @@ public class CompileDriver { return duration; } - private void checkCachesVersion(final CompileContextImpl compileContext, final long currentVFSTimestamp) { - if (CompilerPaths.getRebuildMarkerFile(compileContext.getProject()).exists()) { - compileContext.requestRebuildNextTime("Compiler caches are out of date, project rebuild is required"); - return; - } - final CompileStatus compileStatus = readStatus(); - if (compileStatus == null) { - compileContext.requestRebuildNextTime(CompilerBundle.message("error.compiler.caches.corrupted")); - } - else if (compileStatus.CACHE_FORMAT_VERSION != -1 && - compileStatus.CACHE_FORMAT_VERSION != CompilerConfigurationImpl.DEPENDENCY_FORMAT_VERSION) { - compileContext.requestRebuildNextTime(CompilerBundle.message("error.caches.old.format")); - } - else if (compileStatus.COMPILATION_IN_PROGRESS) { - compileContext.requestRebuildNextTime(CompilerBundle.message("error.previous.compilation.failed")); - } - else if (compileStatus.VFS_CREATION_STAMP >= 0L){ - if (currentVFSTimestamp != compileStatus.VFS_CREATION_STAMP) { - compileContext.requestRebuildNextTime(CompilerBundle.message("error.vfs.was.rebuilt")); - } - } - } - private static String createStatusMessage(final ExitStatus status, final int warningCount, final int errorCount, long duration) { String message; if (status == ExitStatus.CANCELLED) { @@ -1010,751 +559,7 @@ public class CompileDriver { return message; } - private ExitStatus doCompile(final CompileContextEx context, boolean isRebuild, final boolean forceCompile, final boolean onlyCheckStatus) { - try { - if (isRebuild) { - deleteAll(context); - } - else if (forceCompile) { - if (myShouldClearOutputDirectory) { - clearAffectedOutputPathsIfPossible(context); - } - } - if (context.getMessageCount(CompilerMessageCategory.ERROR) > 0) { - if (LOG.isDebugEnabled()) { - logErrorMessages(context); - } - return ExitStatus.ERRORS; - } - - if (!onlyCheckStatus) { - if (!executeCompileTasks(context, true)) { - if (LOG.isDebugEnabled()) { - LOG.debug("Compilation cancelled"); - } - return ExitStatus.CANCELLED; - } - } - - if (context.getMessageCount(CompilerMessageCategory.ERROR) > 0) { - if (LOG.isDebugEnabled()) { - logErrorMessages(context); - } - return ExitStatus.ERRORS; - } - - boolean needRecalcOutputDirs = false; - if (Registry.is(PROP_PERFORM_INITIAL_REFRESH) || !Boolean.valueOf(REFRESH_DONE_KEY.get(myProject, Boolean.FALSE))) { - REFRESH_DONE_KEY.set(myProject, Boolean.TRUE); - final long refreshStart = System.currentTimeMillis(); - - //need this to make sure the VFS is built - final List outputsToRefresh = new ArrayList(); - - final VirtualFile[] all = context.getAllOutputDirectories(); - - final ProgressIndicator progressIndicator = context.getProgressIndicator(); - - //final int totalCount = all.length + myGenerationCompilerModuleToOutputDirMap.size() * 2; - progressIndicator.pushState(); - progressIndicator.setText("Inspecting output directories..."); - try { - for (VirtualFile output : all) { - if (output.isValid()) { - walkChildren(output, context); - } - else { - needRecalcOutputDirs = true; - final File file = new File(output.getPath()); - if (!file.exists()) { - final boolean created = file.mkdirs(); - if (!created) { - context.addMessage(CompilerMessageCategory.ERROR, "Failed to create output directory " + file.getPath(), null, 0, 0); - return ExitStatus.ERRORS; - } - } - output = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file); - if (output == null) { - context.addMessage(CompilerMessageCategory.ERROR, "Failed to locate output directory " + file.getPath(), null, 0, 0); - return ExitStatus.ERRORS; - } - } - outputsToRefresh.add(output); - } - for (Pair pair : myGenerationCompilerModuleToOutputDirMap.keySet()) { - final Couple generated = myGenerationCompilerModuleToOutputDirMap.get(pair); - walkChildren(generated.getFirst(), context); - outputsToRefresh.add(generated.getFirst()); - walkChildren(generated.getSecond(), context); - outputsToRefresh.add(generated.getSecond()); - } - - RefreshQueue.getInstance().refresh(false, true, null, outputsToRefresh); - if (progressIndicator.isCanceled()) { - return ExitStatus.CANCELLED; - } - } - finally { - progressIndicator.popState(); - } - - final long initialRefreshTime = System.currentTimeMillis() - refreshStart; - CompilerUtil.logDuration("Initial VFS refresh", initialRefreshTime); - } - - //DumbService.getInstance(myProject).waitForSmartMode(); - final Semaphore semaphore = new Semaphore(); - semaphore.down(); - DumbService.getInstance(myProject).runWhenSmart(new Runnable() { - public void run() { - semaphore.up(); - } - }); - while (!semaphore.waitFor(500)) { - if (context.getProgressIndicator().isCanceled()) { - return ExitStatus.CANCELLED; - } - } - - if (needRecalcOutputDirs) { - context.recalculateOutputDirs(); - } - - boolean didSomething = false; - - final CompilerManager compilerManager = CompilerManager.getInstance(myProject); - GenericCompilerRunner runner = new GenericCompilerRunner(context, isRebuild, onlyCheckStatus, - compilerManager.getCompilers(GenericCompiler.class, myCompilerFilter)); - try { - didSomething |= generateSources(compilerManager, context, forceCompile, onlyCheckStatus); - - didSomething |= invokeFileProcessingCompilers(compilerManager, context, SourceInstrumentingCompiler.class, - FILE_PROCESSING_COMPILER_ADAPTER_FACTORY, forceCompile, true, onlyCheckStatus); - - didSomething |= invokeFileProcessingCompilers(compilerManager, context, SourceProcessingCompiler.class, - FILE_PROCESSING_COMPILER_ADAPTER_FACTORY, forceCompile, true, onlyCheckStatus); - - final CompileScope intermediateSources = attachIntermediateOutputDirectories(new CompositeScope(CompileScope.EMPTY_ARRAY) { - @NotNull - public Module[] getAffectedModules() { - return context.getCompileScope().getAffectedModules(); - } - }, SOURCE_PROCESSING_ONLY); - context.addScope(intermediateSources); - - didSomething |= translate(context, compilerManager, forceCompile, isRebuild, onlyCheckStatus); - - didSomething |= invokeFileProcessingCompilers(compilerManager, context, ClassInstrumentingCompiler.class, - FILE_PROCESSING_COMPILER_ADAPTER_FACTORY, isRebuild, false, onlyCheckStatus); - didSomething |= runner.invokeCompilers(GenericCompiler.CompileOrderPlace.CLASS_INSTRUMENTING); - - // explicitly passing forceCompile = false because in scopes that is narrower than ProjectScope it is impossible - // to understand whether the class to be processed is in scope or not. Otherwise compiler may process its items even if - // there were changes in completely independent files. - didSomething |= invokeFileProcessingCompilers(compilerManager, context, ClassPostProcessingCompiler.class, - FILE_PROCESSING_COMPILER_ADAPTER_FACTORY, isRebuild, false, onlyCheckStatus); - didSomething |= runner.invokeCompilers(GenericCompiler.CompileOrderPlace.CLASS_POST_PROCESSING); - - didSomething |= invokeFileProcessingCompilers(compilerManager, context, PackagingCompiler.class, - FILE_PACKAGING_COMPILER_ADAPTER_FACTORY, - isRebuild, false, onlyCheckStatus); - didSomething |= runner.invokeCompilers(GenericCompiler.CompileOrderPlace.PACKAGING); - - didSomething |= invokeFileProcessingCompilers(compilerManager, context, Validator.class, FILE_PROCESSING_COMPILER_ADAPTER_FACTORY, - forceCompile, true, onlyCheckStatus); - didSomething |= runner.invokeCompilers(GenericCompiler.CompileOrderPlace.VALIDATING); - } - catch (ExitException e) { - if (LOG.isDebugEnabled()) { - LOG.debug(e); - logErrorMessages(context); - } - return e.getExitStatus(); - } - finally { - // drop in case it has not been dropped yet. - dropDependencyCache(context); - final VirtualFile[] allOutputDirs = context.getAllOutputDirectories(); - - if (didSomething && GENERATE_CLASSPATH_INDEX) { - CompilerUtil.runInContext(context, "Generating classpath index...", new ThrowableRunnable(){ - public void run() { - int count = 0; - for (VirtualFile file : allOutputDirs) { - context.getProgressIndicator().setFraction((double)++count / allOutputDirs.length); - createClasspathIndex(file); - } - } - }); - } - - } - - if (!onlyCheckStatus) { - if (!executeCompileTasks(context, false)) { - return ExitStatus.CANCELLED; - } - final int constantSearchesCount = ChangedConstantsDependencyProcessor.getConstantSearchesCount(context); - LOG.debug("Constants searches: " + constantSearchesCount); - } - - if (context.getMessageCount(CompilerMessageCategory.ERROR) > 0) { - if (LOG.isDebugEnabled()) { - logErrorMessages(context); - } - return ExitStatus.ERRORS; - } - if (!didSomething) { - return ExitStatus.UP_TO_DATE; - } - return ExitStatus.SUCCESS; - } - catch (ProcessCanceledException e) { - return ExitStatus.CANCELLED; - } - } - - private void clearAffectedOutputPathsIfPossible(final CompileContextEx context) { - final List scopeOutputs = new ReadAction>() { - protected void run(@NotNull final Result> result) { - final MultiMap outputToModulesMap = new MultiMap(); - for (Module module : ModuleManager.getInstance(myProject).getModules()) { - final CompilerModuleExtension compilerModuleExtension = CompilerModuleExtension.getInstance(module); - if (compilerModuleExtension == null) { - continue; - } - final String outputPathUrl = compilerModuleExtension.getCompilerOutputUrl(); - if (outputPathUrl != null) { - final String path = VirtualFileManager.extractPath(outputPathUrl); - outputToModulesMap.putValue(new File(path), module); - } - - final String outputPathForTestsUrl = compilerModuleExtension.getCompilerOutputUrlForTests(); - if (outputPathForTestsUrl != null) { - final String path = VirtualFileManager.extractPath(outputPathForTestsUrl); - outputToModulesMap.putValue(new File(path), module); - } - } - final Set affectedModules = new HashSet(Arrays.asList(context.getCompileScope().getAffectedModules())); - List scopeOutputs = new ArrayList(affectedModules.size() * 2); - for (File output : outputToModulesMap.keySet()) { - if (affectedModules.containsAll(outputToModulesMap.get(output))) { - scopeOutputs.add(output); - } - } - - final Set artifactsToBuild = ArtifactCompileScope.getArtifactsToBuild(myProject, context.getCompileScope(), true); - for (Artifact artifact : artifactsToBuild) { - final String outputFilePath = ((ArtifactImpl)artifact).getOutputDirectoryPathToCleanOnRebuild(); - if (outputFilePath != null) { - scopeOutputs.add(new File(FileUtil.toSystemDependentName(outputFilePath))); - } - } - result.setResult(scopeOutputs); - } - }.execute().getResultObject(); - if (scopeOutputs.size() > 0) { - CompilerUtil.runInContext(context, CompilerBundle.message("progress.clearing.output"), new ThrowableRunnable() { - public void run() { - CompilerUtil.clearOutputDirectories(scopeOutputs); - } - }); - } - } - - private static void logErrorMessages(final CompileContext context) { - final CompilerMessage[] errors = context.getMessages(CompilerMessageCategory.ERROR); - if (errors.length > 0) { - LOG.debug("Errors reported: "); - for (CompilerMessage error : errors) { - LOG.debug("\t" + error.getMessage()); - } - } - } - - private static void walkChildren(VirtualFile from, final CompileContext context) { - VfsUtilCore.visitChildrenRecursively(from, new VirtualFileVisitor() { - @Override - public boolean visitFile(@NotNull VirtualFile file) { - if (file.isDirectory()) { - context.getProgressIndicator().checkCanceled(); - context.getProgressIndicator().setText2(file.getPresentableUrl()); - } - return true; - } - }); - } - - private static void createClasspathIndex(final VirtualFile file) { - try { - BufferedWriter writer = new BufferedWriter(new FileWriter(new File(VfsUtilCore.virtualToIoFile(file), "classpath.index"))); - try { - writeIndex(writer, file, file); - } - finally { - writer.close(); - } - } - catch (IOException e) { - // Ignore. Failed to create optional classpath index - } - } - - private static void writeIndex(final BufferedWriter writer, final VirtualFile root, final VirtualFile file) throws IOException { - VfsUtilCore.visitChildrenRecursively(file, new VirtualFileVisitor() { - @Override - public boolean visitFile(@NotNull VirtualFile file) { - try { - writer.write(VfsUtilCore.getRelativePath(file, root, '/')); - writer.write('\n'); - return true; - } - catch (IOException e) { - throw new VisitorException(e); - } - } - }, IOException.class); - } - - private static void dropDependencyCache(final CompileContextEx context) { - CompilerUtil.runInContext(context, CompilerBundle.message("progress.saving.caches"), new ThrowableRunnable(){ - public void run() { - context.getDependencyCache().resetState(); - } - }); - } - - private boolean generateSources(final CompilerManager compilerManager, - CompileContextEx context, - final boolean forceCompile, - final boolean onlyCheckStatus) throws ExitException { - boolean didSomething = false; - - final SourceGeneratingCompiler[] sourceGenerators = compilerManager.getCompilers(SourceGeneratingCompiler.class, myCompilerFilter); - for (final SourceGeneratingCompiler sourceGenerator : sourceGenerators) { - if (context.getProgressIndicator().isCanceled()) { - throw new ExitException(ExitStatus.CANCELLED); - } - - final boolean generatedSomething = generateOutput(context, sourceGenerator, forceCompile, onlyCheckStatus); - - if (context.getMessageCount(CompilerMessageCategory.ERROR) > 0) { - throw new ExitException(ExitStatus.ERRORS); - } - didSomething |= generatedSomething; - } - return didSomething; - } - - private boolean translate(final CompileContextEx context, - final CompilerManager compilerManager, - final boolean forceCompile, - boolean isRebuild, - final boolean onlyCheckStatus) throws ExitException { - - boolean didSomething = false; - - final TranslatingCompiler[] translators = compilerManager.getCompilers(TranslatingCompiler.class, myCompilerFilter); - - - final List> sortedChunks = Collections.unmodifiableList(ApplicationManager.getApplication().runReadAction(new Computable>>() { - public List> compute() { - final ModuleManager moduleManager = ModuleManager.getInstance(myProject); - return ModuleCompilerUtil.getSortedModuleChunks(myProject, Arrays.asList(moduleManager.getModules())); - } - })); - - final DumbService dumbService = DumbService.getInstance(myProject); - try { - final Set processedModules = new HashSet(); - VirtualFile[] snapshot = null; - final Map, Collection> chunkMap = new HashMap, Collection>(); - int total = 0; - int processed = 0; - for (final Chunk currentChunk : sortedChunks) { - final TranslatorsOutputSink sink = new TranslatorsOutputSink(context, translators); - final Set generatedTypes = new HashSet(); - Collection chunkFiles = chunkMap.get(currentChunk); - final Set filesToRecompile = new HashSet(); - final Set allDependent = new HashSet(); - try { - int round = 0; - boolean compiledSomethingForThisChunk = false; - Collection dependentFiles = Collections.emptyList(); - final Function>, Pair>> dependencyFilter = new DependentClassesCumulativeFilter(); - - do { - for (int currentCompiler = 0, translatorsLength = translators.length; currentCompiler < translatorsLength; currentCompiler++) { - sink.setCurrentCompilerIndex(currentCompiler); - final TranslatingCompiler compiler = translators[currentCompiler]; - if (context.getProgressIndicator().isCanceled()) { - throw new ExitException(ExitStatus.CANCELLED); - } - - dumbService.waitForSmartMode(); - - if (snapshot == null || ContainerUtil.intersects(generatedTypes, compilerManager.getRegisteredInputTypes(compiler))) { - // rescan snapshot if previously generated files may influence the input of this compiler - final Set prevSnapshot = round > 0 && snapshot != null? new HashSet(Arrays.asList(snapshot)) : Collections.emptySet(); - snapshot = ApplicationManager.getApplication().runReadAction(new Computable() { - public VirtualFile[] compute() { - return context.getCompileScope().getFiles(null, true); - } - }); - recalculateChunkToFilesMap(context, sortedChunks, snapshot, chunkMap); - if (round == 0) { - chunkFiles = chunkMap.get(currentChunk); - } - else { - final Set newFiles = new HashSet(chunkMap.get(currentChunk)); - newFiles.removeAll(prevSnapshot); - newFiles.removeAll(chunkFiles); - if (!newFiles.isEmpty()) { - final ArrayList merged = new ArrayList(chunkFiles.size() + newFiles.size()); - merged.addAll(chunkFiles); - merged.addAll(newFiles); - chunkFiles = merged; - } - } - total = snapshot.length * translatorsLength; - } - - final CompileContextEx _context; - if (compiler instanceof IntermediateOutputCompiler) { - // wrap compile context so that output goes into intermediate directories - final IntermediateOutputCompiler _compiler = (IntermediateOutputCompiler)compiler; - _context = new CompileContextExProxy(context) { - public VirtualFile getModuleOutputDirectory(final Module module) { - return getGenerationOutputDir(_compiler, module, false); - } - - public VirtualFile getModuleOutputDirectoryForTests(final Module module) { - return getGenerationOutputDir(_compiler, module, true); - } - }; - } - else { - _context = context; - } - final boolean compiledSomething = - compileSources(_context, currentChunk, compiler, chunkFiles, round == 0? forceCompile : true, isRebuild, onlyCheckStatus, sink); - - processed += chunkFiles.size(); - _context.getProgressIndicator().setFraction(((double)processed) / total); - - if (compiledSomething) { - generatedTypes.addAll(compilerManager.getRegisteredOutputTypes(compiler)); - } - - didSomething |= compiledSomething; - compiledSomethingForThisChunk |= didSomething; - - if (_context.getMessageCount(CompilerMessageCategory.ERROR) > 0) { - break; // break the loop over compilers - } - } - - final boolean hasUnprocessedTraverseRoots = context.getDependencyCache().hasUnprocessedTraverseRoots(); - if (!isRebuild && (compiledSomethingForThisChunk || hasUnprocessedTraverseRoots)) { - final Set compiledWithErrors = CacheUtils.getFilesCompiledWithErrors(context); - filesToRecompile.removeAll(sink.getCompiledSources()); - filesToRecompile.addAll(compiledWithErrors); - - dependentFiles = CacheUtils.findDependentFiles(context, compiledWithErrors, dependencyFilter); - if (!processedModules.isEmpty()) { - for (Iterator it = dependentFiles.iterator(); it.hasNext();) { - final VirtualFile next = it.next(); - final Module module = context.getModuleByFile(next); - if (module != null && processedModules.contains(module)) { - it.remove(); - } - } - } - - if (ourDebugMode) { - if (!dependentFiles.isEmpty()) { - for (VirtualFile dependentFile : dependentFiles) { - System.out.println("FOUND TO RECOMPILE: " + dependentFile.getPresentableUrl()); - } - } - else { - System.out.println("NO FILES TO RECOMPILE"); - } - } - - if (!dependentFiles.isEmpty()) { - filesToRecompile.addAll(dependentFiles); - allDependent.addAll(dependentFiles); - if (context.getProgressIndicator().isCanceled() || context.getMessageCount(CompilerMessageCategory.ERROR) > 0) { - break; - } - final List filesInScope = getFilesInScope(context, currentChunk, dependentFiles); - if (filesInScope.isEmpty()) { - break; - } - context.getDependencyCache().clearTraverseRoots(); - chunkFiles = filesInScope; - total += chunkFiles.size() * translators.length; - } - - didSomething |= (hasUnprocessedTraverseRoots != context.getDependencyCache().hasUnprocessedTraverseRoots()); - } - - round++; - } - while (!dependentFiles.isEmpty() && context.getMessageCount(CompilerMessageCategory.ERROR) == 0); - - if (CompilerConfiguration.MAKE_ENABLED) { - if (!context.getProgressIndicator().isCanceled()) { - // when cancelled pretend nothing was compiled and next compile will compile everything from the scratch - final ProgressIndicator indicator = context.getProgressIndicator(); - final DependencyCache cache = context.getDependencyCache(); - - indicator.pushState(); - indicator.setText(CompilerBundle.message("progress.updating.caches")); - indicator.setText2(""); - - cache.update(); - - indicator.setText(CompilerBundle.message("progress.saving.caches")); - cache.resetState(); - processedModules.addAll(currentChunk.getNodes()); - indicator.popState(); - } - } - - if (context.getMessageCount(CompilerMessageCategory.ERROR) > 0) { - throw new ExitException(ExitStatus.ERRORS); - } - - } - catch (CacheCorruptedException e) { - LOG.info(e); - context.requestRebuildNextTime(e.getMessage()); - } - finally { - final int errorCount = context.getMessageCount(CompilerMessageCategory.ERROR); - if (errorCount != 0) { - filesToRecompile.addAll(allDependent); - } - if (filesToRecompile.size() > 0) { - sink.add(null, Collections.emptyList(), VfsUtilCore.toVirtualFileArray(filesToRecompile)); - } - if (errorCount == 0) { - // perform update only if there were no errors, so it is guaranteed that the file was processd by all neccesary compilers - sink.flushPostponedItems(); - } - } - } - } - catch (ProcessCanceledException e) { - ProgressManager.getInstance().executeNonCancelableSection(new Runnable() { - public void run() { - try { - final Collection deps = CacheUtils.findDependentFiles(context, Collections.emptySet(), null); - if (deps.size() > 0) { - TranslatingCompilerFilesMonitor.getInstance().update(context, null, Collections.emptyList(), - VfsUtilCore.toVirtualFileArray(deps)); - } - } - catch (IOException ignored) { - LOG.info(ignored); - } - catch (CacheCorruptedException ignored) { - LOG.info(ignored); - } - catch (ExitException e1) { - LOG.info(e1); - } - } - }); - throw e; - } - finally { - dropDependencyCache(context); - if (didSomething) { - TranslatingCompilerFilesMonitor.getInstance().updateOutputRootsLayout(myProject); - } - } - return didSomething; - } - - private static List getFilesInScope(final CompileContextEx context, final Chunk chunk, final Collection files) { - final List filesInScope = new ArrayList(files.size()); - ApplicationManager.getApplication().runReadAction(new Runnable() { - public void run() { - for (VirtualFile file : files) { - if (context.getCompileScope().belongs(file.getUrl())) { - final Module module = context.getModuleByFile(file); - if (chunk.getNodes().contains(module)) { - filesInScope.add(file); - } - } - } - } - }); - return filesInScope; - } - - private static void recalculateChunkToFilesMap(CompileContextEx context, List> allChunks, VirtualFile[] snapshot, Map, Collection> chunkMap) { - final Map> moduleToFilesMap = CompilerUtil.buildModuleToFilesMap(context, snapshot); - for (Chunk moduleChunk : allChunks) { - List files = Collections.emptyList(); - for (Module module : moduleChunk.getNodes()) { - final List moduleFiles = moduleToFilesMap.get(module); - if (moduleFiles != null) { - files = ContainerUtil.concat(files, moduleFiles); - } - } - chunkMap.put(moduleChunk, files); - } - } - - private interface FileProcessingCompilerAdapterFactory { - FileProcessingCompilerAdapter create(CompileContext context, FileProcessingCompiler compiler); - } - - private boolean invokeFileProcessingCompilers(final CompilerManager compilerManager, - CompileContextEx context, - Class fileProcessingCompilerClass, - FileProcessingCompilerAdapterFactory factory, - boolean forceCompile, - final boolean checkScope, - final boolean onlyCheckStatus) throws ExitException { - boolean didSomething = false; - final FileProcessingCompiler[] compilers = compilerManager.getCompilers(fileProcessingCompilerClass, myCompilerFilter); - if (compilers.length > 0) { - try { - CacheDeferredUpdater cacheUpdater = new CacheDeferredUpdater(); - try { - for (final FileProcessingCompiler compiler : compilers) { - if (context.getProgressIndicator().isCanceled()) { - throw new ExitException(ExitStatus.CANCELLED); - } - - CompileContextEx _context = context; - if (compiler instanceof IntermediateOutputCompiler) { - final IntermediateOutputCompiler _compiler = (IntermediateOutputCompiler)compiler; - _context = new CompileContextExProxy(context) { - public VirtualFile getModuleOutputDirectory(final Module module) { - return getGenerationOutputDir(_compiler, module, false); - } - - public VirtualFile getModuleOutputDirectoryForTests(final Module module) { - return getGenerationOutputDir(_compiler, module, true); - } - }; - } - - final boolean processedSomething = processFiles(factory.create(_context, compiler), forceCompile, checkScope, onlyCheckStatus, cacheUpdater); - - if (context.getMessageCount(CompilerMessageCategory.ERROR) > 0) { - throw new ExitException(ExitStatus.ERRORS); - } - - didSomething |= processedSomething; - } - } - finally { - cacheUpdater.doUpdate(); - } - } - catch (IOException e) { - LOG.info(e); - context.requestRebuildNextTime(e.getMessage()); - throw new ExitException(ExitStatus.ERRORS); - } - catch (ProcessCanceledException e) { - throw e; - } - catch (ExitException e) { - throw e; - } - catch (Exception e) { - context.addMessage(CompilerMessageCategory.ERROR, CompilerBundle.message("compiler.error.exception", e.getMessage()), null, -1, -1); - LOG.error(e); - } - } - - return didSomething; - } - - private static Map> buildModuleToGenerationItemMap(GeneratingCompiler.GenerationItem[] items) { - final Map> map = new HashMap>(); - for (GeneratingCompiler.GenerationItem item : items) { - Module module = item.getModule(); - LOG.assertTrue(module != null); - Set itemSet = map.get(module); - if (itemSet == null) { - itemSet = new HashSet(); - map.put(module, itemSet); - } - itemSet.add(item); - } - return map; - } - - private void deleteAll(final CompileContextEx context) { - CompilerUtil.runInContext(context, CompilerBundle.message("progress.clearing.output"), new ThrowableRunnable() { - public void run() { - final boolean isTestMode = ApplicationManager.getApplication().isUnitTestMode(); - final VirtualFile[] allSources = context.getProjectCompileScope().getFiles(null, true); - if (myShouldClearOutputDirectory) { - CompilerUtil.clearOutputDirectories(myAllOutputDirectories); - } - else { // refresh is still required - try { - for (final Compiler compiler : CompilerManager.getInstance(myProject).getCompilers(Compiler.class)) { - try { - if (compiler instanceof GeneratingCompiler) { - final StateCache cache = getGeneratingCompilerCache((GeneratingCompiler)compiler); - final Iterator urlIterator = cache.getUrlsIterator(); - while (urlIterator.hasNext()) { - context.getProgressIndicator().checkCanceled(); - deleteFile(new File(VirtualFileManager.extractPath(urlIterator.next()))); - } - } - else if (compiler instanceof TranslatingCompiler) { - final ArrayList> toDelete = new ArrayList>(); - ApplicationManager.getApplication().runReadAction(new Runnable() { - public void run() { - TranslatingCompilerFilesMonitor.getInstance().collectFiles( - context, - (TranslatingCompiler)compiler, Arrays.asList(allSources).iterator(), - true /*pass true to make sure that every source in scope file is processed*/, - false /*important! should pass false to enable collection of files to delete*/, - new ArrayList(), - toDelete - ); - } - }); - for (Trinity trinity : toDelete) { - context.getProgressIndicator().checkCanceled(); - final File file = trinity.getFirst(); - deleteFile(file); - if (isTestMode) { - CompilerManagerImpl.addDeletedPath(file.getPath()); - } - } - } - } - catch (IOException e) { - LOG.info(e); - } - } - pruneEmptyDirectories(context.getProgressIndicator(), myAllOutputDirectories); // to avoid too much files deleted events - } - finally { - CompilerUtil.refreshIODirectories(myAllOutputDirectories); - } - } - dropScopesCaches(); - - clearCompilerSystemDirectory(context); - } - }); - } - + /* private void dropScopesCaches() { // hack to be sure the classpath will include the output directories ApplicationManager.getApplication().runReadAction(new Runnable() { @@ -1763,421 +568,7 @@ public class CompileDriver { } }); } - - private static void pruneEmptyDirectories(ProgressIndicator progress, final Set directories) { - for (File directory : directories) { - doPrune(progress, directory, directories); - } - } - - private static boolean doPrune(ProgressIndicator progress, final File directory, final Set outPutDirectories) { - progress.checkCanceled(); - final File[] files = directory.listFiles(); - boolean isEmpty = true; - if (files != null) { - for (File file : files) { - if (!outPutDirectories.contains(file)) { - if (doPrune(progress, file, outPutDirectories)) { - deleteFile(file); - } - else { - isEmpty = false; - } - } - else { - isEmpty = false; - } - } - } - else { - isEmpty = false; - } - - return isEmpty; - } - - private Set getAllOutputDirectories(CompileContext context) { - final Set outputDirs = new OrderedSet(); - final Module[] modules = ModuleManager.getInstance(myProject).getModules(); - for (final String path : CompilerPathsEx.getOutputPaths(modules)) { - outputDirs.add(new File(path)); - } - for (Pair pair : myGenerationCompilerModuleToOutputDirMap.keySet()) { - outputDirs.add(new File(CompilerPaths.getGenerationOutputPath(pair.getFirst(), pair.getSecond(), false))); - outputDirs.add(new File(CompilerPaths.getGenerationOutputPath(pair.getFirst(), pair.getSecond(), true))); - } - final CompilerConfiguration config = CompilerConfiguration.getInstance(myProject); - if (context.isAnnotationProcessorsEnabled()) { - for (Module module : modules) { - if (config.getAnnotationProcessingConfiguration(module).isEnabled()) { - final String path = CompilerPaths.getAnnotationProcessorsGenerationPath(module); - if (path != null) { - outputDirs.add(new File(path)); - } - } - } - } - for (Artifact artifact : ArtifactManager.getInstance(myProject).getArtifacts()) { - final String path = ((ArtifactImpl)artifact).getOutputDirectoryPathToCleanOnRebuild(); - if (path != null) { - outputDirs.add(new File(FileUtil.toSystemDependentName(path))); - } - } - return outputDirs; - } - - private void clearCompilerSystemDirectory(final CompileContextEx context) { - CompilerCacheManager.getInstance(myProject).clearCaches(context); - FileUtil.delete(CompilerPathsEx.getZipStoreDirectory(myProject)); - dropDependencyCache(context); - - for (Pair pair : myGenerationCompilerModuleToOutputDirMap.keySet()) { - final File[] outputs = { - new File(CompilerPaths.getGenerationOutputPath(pair.getFirst(), pair.getSecond(), false)), - new File(CompilerPaths.getGenerationOutputPath(pair.getFirst(), pair.getSecond(), true)) - }; - for (File output : outputs) { - final File[] files = output.listFiles(); - if (files != null) { - for (final File file : files) { - final boolean deleteOk = deleteFile(file); - if (!deleteOk) { - context.addMessage(CompilerMessageCategory.ERROR, CompilerBundle.message("compiler.error.failed.to.delete", file.getPath()), - null, -1, -1); - } - } - } - } - } - } - - /** - * @param file a file to delete - * @return true if and only if the file existed and was successfully deleted - * Note: the behaviour is different from FileUtil.delete() which returns true if the file absent on the disk - */ - private static boolean deleteFile(final File file) { - File[] files = file.listFiles(); - if (files != null) { - for (File file1 : files) { - deleteFile(file1); - } - } - - for (int i = 0; i < 10; i++){ - if (file.delete()) { - return true; - } - if (!file.exists()) { - return false; - } - try { - Thread.sleep(50); - } - catch (InterruptedException ignored) { - } - } - return false; - } - - private VirtualFile getGenerationOutputDir(final IntermediateOutputCompiler compiler, final Module module, final boolean forTestSources) { - final Couple outputs = - myGenerationCompilerModuleToOutputDirMap.get(Pair.create(compiler, module)); - return forTestSources? outputs.getSecond() : outputs.getFirst(); - } - - private boolean generateOutput(final CompileContextEx context, - final GeneratingCompiler compiler, - final boolean forceGenerate, - final boolean onlyCheckStatus) throws ExitException { - final GeneratingCompiler.GenerationItem[] allItems = compiler.getGenerationItems(context); - final List toGenerate = new ArrayList(); - final List filesToRefresh = new ArrayList(); - final List generatedFiles = new ArrayList(); - final List affectedModules = new ArrayList(); - try { - final StateCache cache = getGeneratingCompilerCache(compiler); - final Set pathsToRemove = new HashSet(cache.getUrls()); - - final Map itemToOutputPathMap = new HashMap(); - ApplicationManager.getApplication().runReadAction(new ThrowableComputable() { - @Override - public Void compute() throws IOException { - for (final GeneratingCompiler.GenerationItem item : allItems) { - - final Module itemModule = item.getModule(); - final String outputDirPath = CompilerPaths.getGenerationOutputPath(compiler, itemModule, item.isTestSource()); - final String outputPath = outputDirPath + "/" + item.getPath(); - itemToOutputPathMap.put(item, outputPath); - final ValidityState savedState = cache.getState(outputPath); - - if (forceGenerate || savedState == null || !savedState.equalsTo(item.getValidityState())) { - final String outputPathUrl = VirtualFileManager.constructUrl(LocalFileSystem.PROTOCOL, outputPath); - if (context.getCompileScope().belongs(outputPathUrl)) { - toGenerate.add(item); - } - else { - pathsToRemove.remove(outputPath); - } - } - else { - pathsToRemove.remove(outputPath); - } - } - return null; - } - }); - - if (onlyCheckStatus) { - if (toGenerate.isEmpty() && pathsToRemove.isEmpty()) { - return false; - } - if (LOG.isDebugEnabled()) { - if (!toGenerate.isEmpty()) { - LOG.debug("Found items to generate, compiler " + compiler.getDescription()); - } - if (!pathsToRemove.isEmpty()) { - LOG.debug("Found paths to remove, compiler " + compiler.getDescription()); - } - } - throw new ExitException(ExitStatus.CANCELLED); - } - - if (!pathsToRemove.isEmpty()) { - CompilerUtil.runInContext(context, CompilerBundle.message("progress.synchronizing.output.directory"), new ThrowableRunnable(){ - public void run() throws IOException { - for (final String path : pathsToRemove) { - final File file = new File(path); - final boolean deleted = deleteFile(file); - if (deleted) { - cache.remove(path); - filesToRefresh.add(file); - } - } - } - }); - } - - final Map> moduleToItemMap = - buildModuleToGenerationItemMap(toGenerate.toArray(new GeneratingCompiler.GenerationItem[toGenerate.size()])); - List modules = new ArrayList(moduleToItemMap.size()); - for (final Module module : moduleToItemMap.keySet()) { - modules.add(module); - } - ModuleCompilerUtil.sortModules(myProject, modules); - - for (final Module module : modules) { - CompilerUtil.runInContext(context, "Generating output from "+compiler.getDescription(),new ThrowableRunnable(){ - public void run() throws IOException { - final Set items = moduleToItemMap.get(module); - if (items != null && !items.isEmpty()) { - final GeneratingCompiler.GenerationItem[][] productionAndTestItems = splitGenerationItems(items); - for (GeneratingCompiler.GenerationItem[] _items : productionAndTestItems) { - if (_items.length == 0) continue; - final VirtualFile outputDir = getGenerationOutputDir(compiler, module, _items[0].isTestSource()); - final GeneratingCompiler.GenerationItem[] successfullyGenerated = compiler.generate(context, _items, outputDir); - - CompilerUtil.runInContext(context, CompilerBundle.message("progress.updating.caches"), new ThrowableRunnable() { - public void run() throws IOException { - if (successfullyGenerated.length > 0) { - affectedModules.add(module); - } - for (final GeneratingCompiler.GenerationItem item : successfullyGenerated) { - final String fullOutputPath = itemToOutputPathMap.get(item); - cache.update(fullOutputPath, item.getValidityState()); - final File file = new File(fullOutputPath); - filesToRefresh.add(file); - generatedFiles.add(file); - context.getProgressIndicator().setText2(file.getPath()); - } - } - }); - } - } - } - }); - } - } - catch (IOException e) { - LOG.info(e); - context.requestRebuildNextTime(e.getMessage()); - throw new ExitException(ExitStatus.ERRORS); - } - finally { - CompilerUtil.refreshIOFiles(filesToRefresh); - if (!generatedFiles.isEmpty()) { - List vFiles = DumbService.getInstance(myProject).runReadActionInSmartMode(new Computable>() { - public List compute() { - final ArrayList vFiles = new ArrayList(generatedFiles.size()); - for (File generatedFile : generatedFiles) { - final VirtualFile vFile = LocalFileSystem.getInstance().findFileByIoFile(generatedFile); - if (vFile != null) { - vFiles.add(vFile); - } - } - return vFiles; - } - }); - if (forceGenerate) { - context.addScope(new FileSetCompileScope(vFiles, affectedModules.toArray(new Module[affectedModules.size()]))); - } - context.markGenerated(vFiles); - } - } - return !toGenerate.isEmpty() || !filesToRefresh.isEmpty(); - } - - private static GeneratingCompiler.GenerationItem[][] splitGenerationItems(final Set items) { - final List production = new ArrayList(); - final List tests = new ArrayList(); - for (GeneratingCompiler.GenerationItem item : items) { - if (item.isTestSource()) { - tests.add(item); - } - else { - production.add(item); - } - } - return new GeneratingCompiler.GenerationItem[][]{ - production.toArray(new GeneratingCompiler.GenerationItem[production.size()]), - tests.toArray(new GeneratingCompiler.GenerationItem[tests.size()]) - }; - } - - private boolean compileSources(final CompileContextEx context, - final Chunk moduleChunk, - final TranslatingCompiler compiler, - final Collection srcSnapshot, - final boolean forceCompile, - final boolean isRebuild, - final boolean onlyCheckStatus, - TranslatingCompiler.OutputSink sink) throws ExitException { - - final Set toCompile = new HashSet(); - final List> toDelete = new ArrayList>(); - context.getProgressIndicator().pushState(); - - final boolean[] wereFilesDeleted = {false}; - try { - ApplicationManager.getApplication().runReadAction(new Runnable() { - public void run() { - TranslatingCompilerFilesMonitor.getInstance().collectFiles( - context, compiler, srcSnapshot.iterator(), forceCompile, isRebuild, toCompile, toDelete - ); - } - }); - - if (onlyCheckStatus) { - if (toDelete.isEmpty() && toCompile.isEmpty()) { - return false; - } - if (LOG.isDebugEnabled() || ourDebugMode) { - if (!toDelete.isEmpty()) { - final StringBuilder message = new StringBuilder(); - message.append("Found items to delete, compiler ").append(compiler.getDescription()); - for (Trinity trinity : toDelete) { - message.append("\n").append(trinity.getFirst()); - } - LOG.debug(message.toString()); - if (ourDebugMode) { - System.out.println(message); - } - } - if (!toCompile.isEmpty()) { - final String message = "Found items to compile, compiler " + compiler.getDescription(); - LOG.debug(message); - if (ourDebugMode) { - System.out.println(message); - } - } - } - throw new ExitException(ExitStatus.CANCELLED); - } - - if (!toDelete.isEmpty()) { - try { - wereFilesDeleted[0] = syncOutputDir(context, toDelete); - } - catch (CacheCorruptedException e) { - LOG.info(e); - context.requestRebuildNextTime(e.getMessage()); - } - } - - if ((wereFilesDeleted[0] || !toCompile.isEmpty()) && context.getMessageCount(CompilerMessageCategory.ERROR) == 0) { - compiler.compile(context, moduleChunk, VfsUtilCore.toVirtualFileArray(toCompile), sink); - } - } - finally { - context.getProgressIndicator().popState(); - } - return !toCompile.isEmpty() || wereFilesDeleted[0]; - } - - private static boolean syncOutputDir(final CompileContextEx context, final Collection> toDelete) throws CacheCorruptedException { - final DependencyCache dependencyCache = context.getDependencyCache(); - final boolean isTestMode = ApplicationManager.getApplication().isUnitTestMode(); - - final List filesToRefresh = new ArrayList(); - final boolean[] wereFilesDeleted = {false}; - CompilerUtil.runInContext(context, CompilerBundle.message("progress.synchronizing.output.directory"), new ThrowableRunnable(){ - public void run() throws CacheCorruptedException { - final long start = System.currentTimeMillis(); - try { - for (final Trinity trinity : toDelete) { - final File outputPath = trinity.getFirst(); - context.getProgressIndicator().checkCanceled(); - context.getProgressIndicator().setText2(outputPath.getPath()); - filesToRefresh.add(outputPath); - if (isTestMode) { - LOG.assertTrue(outputPath.exists()); - } - if (!deleteFile(outputPath)) { - if (isTestMode) { - if (outputPath.exists()) { - LOG.error("Was not able to delete output file: " + outputPath.getPath()); - } - else { - CompilerManagerImpl.addDeletedPath(outputPath.getPath()); - } - } - continue; - } - wereFilesDeleted[0] = true; - - // update zip here - //final String outputDir = myOutputFinder.lookupOutputPath(outputPath); - //if (outputDir != null) { - // try { - // context.updateZippedOuput(outputDir, FileUtil.toSystemIndependentName(outputPath.getPath()).substring(outputDir.length() + 1)); - // } - // catch (IOException e) { - // LOG.info(e); - // } - //} - - final String className = trinity.getSecond(); - if (className != null) { - final int id = dependencyCache.getSymbolTable().getId(className); - dependencyCache.addTraverseRoot(id); - final boolean sourcePresent = trinity.getThird().booleanValue(); - if (!sourcePresent) { - dependencyCache.markSourceRemoved(id); - } - } - if (isTestMode) { - CompilerManagerImpl.addDeletedPath(outputPath.getPath()); - } - } - } - finally { - CompilerUtil.logDuration("Sync output directory", System.currentTimeMillis() - start); - CompilerUtil.refreshIOFiles(filesToRefresh); - } - } - }); - return wereFilesDeleted[0]; - } + */ // [mike] performance optimization - this method is accessed > 15,000 times in Aurora private String getModuleOutputPath(final Module module, boolean inTestSourceContent) { @@ -2191,152 +582,9 @@ public class CompileDriver { return path; } - private boolean processFiles(final FileProcessingCompilerAdapter adapter, - final boolean forceCompile, - final boolean checkScope, - final boolean onlyCheckStatus, final CacheDeferredUpdater cacheUpdater) throws ExitException, IOException { - final CompileContextEx context = (CompileContextEx)adapter.getCompileContext(); - final FileProcessingCompilerStateCache cache = getFileProcessingCompilerCache(adapter.getCompiler()); - final FileProcessingCompiler.ProcessingItem[] items = adapter.getProcessingItems(); - if (context.getMessageCount(CompilerMessageCategory.ERROR) > 0) { - return false; - } - if (LOG.isDebugEnabled() && items.length > 0) { - LOG.debug("Start processing files by " + adapter.getCompiler().getDescription()); - } - final CompileScope scope = context.getCompileScope(); - final List toProcess = new ArrayList(); - final Set allUrls = new HashSet(); - final IOException[] ex = {null}; - DumbService.getInstance(myProject).runReadActionInSmartMode(new Runnable() { - public void run() { - try { - for (FileProcessingCompiler.ProcessingItem item : items) { - final VirtualFile file = item.getFile(); - final String url = file.getUrl(); - allUrls.add(url); - if (!forceCompile && 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; - } - } - if (LOG.isDebugEnabled()) { - LOG.debug("Adding item to process: " + url + "; saved ts= " + cache.getTimestamp(url) + "; VFS ts=" + file.getTimeStamp()); - } - toProcess.add(item); - } - } - catch (IOException e) { - ex[0] = e; - } - } - }); - - if (ex[0] != null) { - throw ex[0]; - } - - final Collection urls = cache.getUrls(); - final List urlsToRemove = new ArrayList(); - if (!urls.isEmpty()) { - CompilerUtil.runInContext(context, CompilerBundle.message("progress.processing.outdated.files"), new ThrowableRunnable(){ - public void run() throws IOException { - ApplicationManager.getApplication().runReadAction(new Runnable() { - public void run() { - for (final String url : urls) { - if (!allUrls.contains(url)) { - if (!checkScope || scope.belongs(url)) { - urlsToRemove.add(url); - } - } - } - } - }); - if (!onlyCheckStatus && !urlsToRemove.isEmpty()) { - for (final String url : urlsToRemove) { - adapter.processOutdatedItem(context, url, cache.getExtState(url)); - cache.remove(url); - } - } - } - }); - } - - if (onlyCheckStatus) { - if (urlsToRemove.isEmpty() && toProcess.isEmpty()) { - return false; - } - if (LOG.isDebugEnabled()) { - if (!urlsToRemove.isEmpty()) { - LOG.debug("Found urls to remove, compiler " + adapter.getCompiler().getDescription()); - for (String url : urlsToRemove) { - LOG.debug("\t" + url); - } - } - if (!toProcess.isEmpty()) { - LOG.debug("Found items to compile, compiler " + adapter.getCompiler().getDescription()); - for (FileProcessingCompiler.ProcessingItem item : toProcess) { - LOG.debug("\t" + item.getFile().getPresentableUrl()); - } - } - } - throw new ExitException(ExitStatus.CANCELLED); - } - - if (toProcess.isEmpty()) { - return false; - } - - final FileProcessingCompiler.ProcessingItem[] processed = - adapter.process(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() { - final List vFiles = new ArrayList(processed.length); - for (FileProcessingCompiler.ProcessingItem aProcessed : processed) { - final VirtualFile file = aProcessed.getFile(); - vFiles.add(file); - if (LOG.isDebugEnabled()) { - LOG.debug("\tFile processed " + file.getPresentableUrl() + "; ts=" + file.getTimeStamp()); - } - - //final String path = file.getPath(); - //final String outputDir = myOutputFinder.lookupOutputPath(path); - //if (outputDir != null) { - // context.updateZippedOuput(outputDir, path.substring(outputDir.length() + 1)); - //} - } - LocalFileSystem.getInstance().refreshFiles(vFiles); - if (LOG.isDebugEnabled()) { - LOG.debug("Files after VFS refresh:"); - for (VirtualFile file : vFiles) { - LOG.debug("\t" + file.getPresentableUrl() + "; ts=" + file.getTimeStamp()); - } - } - for (FileProcessingCompiler.ProcessingItem item : processed) { - cacheUpdater.addFileForUpdate(item, cache); - } - } - }); - return true; - } - - private FileProcessingCompilerStateCache getFileProcessingCompilerCache(FileProcessingCompiler compiler) throws IOException { - return CompilerCacheManager.getInstance(myProject).getFileProcessingCompilerCache(compiler); - } - - private StateCache getGeneratingCompilerCache(final GeneratingCompiler compiler) throws IOException { - return CompilerCacheManager.getInstance(myProject).getGeneratingCompilerCache(compiler); - } - public void executeCompileTask(final CompileTask task, final CompileScope scope, final String contentName, final Runnable onTaskFinished) { final CompilerTask progressManagerTask = new CompilerTask(myProject, contentName, false, false, true, isCompilationStartedAutomatically(scope)); - final CompileContextImpl compileContext = new CompileContextImpl(myProject, progressManagerTask, scope, null, false, false); + final CompileContextImpl compileContext = new CompileContextImpl(myProject, progressManagerTask, scope, false, false); FileDocumentManager.getInstance().saveAllDocuments(); @@ -2391,16 +639,13 @@ public class CompileDriver { return true; } - private boolean validateCompilerConfiguration(final CompileScope scope, boolean checkOutputAndSourceIntersection) { + private boolean validateCompilerConfiguration(final CompileScope scope) { try { - final Module[] scopeModules = scope.getAffectedModules()/*ModuleManager.getInstance(myProject).getModules()*/; + final Module[] scopeModules = scope.getAffectedModules(); final List modulesWithoutOutputPathSpecified = new ArrayList(); - boolean isProjectCompilePathSpecified = true; final List modulesWithoutJdkAssigned = new ArrayList(); - final Set nonExistingOutputPaths = new HashSet(); final CompilerConfiguration config = CompilerConfiguration.getInstance(myProject); final CompilerManager compilerManager = CompilerManager.getInstance(myProject); - final boolean useOutOfProcessBuild = useOutOfProcessBuild(); for (final Module module : scopeModules) { if (!compilerManager.isValidationEnabled(module)) { continue; @@ -2422,52 +667,16 @@ public class CompileDriver { modulesWithoutOutputPathSpecified.add(module.getName()); } else { - if (outputPath != null) { - if (!useOutOfProcessBuild) { - final File file = new File(outputPath.replace('/', File.separatorChar)); - if (!file.exists()) { - nonExistingOutputPaths.add(file); - } - } - } - else { + if (outputPath == null) { if (hasSources) { modulesWithoutOutputPathSpecified.add(module.getName()); } } - if (testsOutputPath != null) { - if (!useOutOfProcessBuild) { - final File f = new File(testsOutputPath.replace('/', File.separatorChar)); - if (!f.exists()) { - nonExistingOutputPaths.add(f); - } - } - } - else { + if (testsOutputPath == null) { if (hasTestSources) { modulesWithoutOutputPathSpecified.add(module.getName()); } } - if (!useOutOfProcessBuild) { - if (config.getAnnotationProcessingConfiguration(module).isEnabled()) { - final String path = CompilerPaths.getAnnotationProcessorsGenerationPath(module); - if (path == null) { - final CompilerProjectExtension extension = CompilerProjectExtension.getInstance(module.getProject()); - if (extension == null || extension.getCompilerOutputUrl() == null) { - isProjectCompilePathSpecified = false; - } - else { - modulesWithoutOutputPathSpecified.add(module.getName()); - } - } - else { - final File file = new File(path); - if (!file.exists()) { - nonExistingOutputPaths.add(file); - } - } - } - } } } if (!modulesWithoutJdkAssigned.isEmpty()) { @@ -2475,79 +684,17 @@ public class CompileDriver { return false; } - if (!isProjectCompilePathSpecified) { - final String message = CompilerBundle.message("error.project.output.not.specified"); - if (ApplicationManager.getApplication().isUnitTestMode()) { - LOG.error(message); - } - - Messages.showMessageDialog(myProject, message, CommonBundle.getErrorTitle(), Messages.getErrorIcon()); - ProjectSettingsService.getInstance(myProject).openProjectSettings(); - return false; - } - if (!modulesWithoutOutputPathSpecified.isEmpty()) { showNotSpecifiedError("error.output.not.specified", modulesWithoutOutputPathSpecified, CommonContentEntriesEditor.NAME); return false; } - if (!nonExistingOutputPaths.isEmpty()) { - for (File file : nonExistingOutputPaths) { - final boolean succeeded = file.mkdirs(); - if (!succeeded) { - if (file.exists()) { - // for overlapping paths, this one might have been created as an intermediate path on a previous iteration - continue; - } - Messages.showMessageDialog(myProject, CompilerBundle.message("error.failed.to.create.directory", file.getPath()), - CommonBundle.getErrorTitle(), Messages.getErrorIcon()); - return false; - } - } - final Boolean refreshSuccess = - new WriteAction() { - @Override - protected void run(@NotNull Result result) throws Throwable { - LocalFileSystem.getInstance().refreshIoFiles(nonExistingOutputPaths); - Boolean res = Boolean.TRUE; - for (File file : nonExistingOutputPaths) { - if (LocalFileSystem.getInstance().findFileByIoFile(file) == null) { - res = Boolean.FALSE; - break; - } - } - result.setResult(res); - } - }.execute().getResultObject(); - - if (!refreshSuccess.booleanValue()) { - return false; - } - dropScopesCaches(); - } - - if (checkOutputAndSourceIntersection && myShouldClearOutputDirectory) { - if (!validateOutputAndSourcePathsIntersection()) { - return false; - } - // myShouldClearOutputDirectory may change in validateOutputAndSourcePathsIntersection() - CompilerPathsEx.CLEAR_ALL_OUTPUTS_KEY.set(scope, myShouldClearOutputDirectory); - } - else { - CompilerPathsEx.CLEAR_ALL_OUTPUTS_KEY.set(scope, false); - } final List> chunks = ModuleCompilerUtil.getSortedModuleChunks(myProject, Arrays.asList(scopeModules)); for (final Chunk chunk : chunks) { final Set chunkModules = chunk.getNodes(); if (chunkModules.size() <= 1) { continue; // no need to check one-module chunks } - for (Module chunkModule : chunkModules) { - if (config.getAnnotationProcessingConfiguration(chunkModule).isEnabled()) { - showCyclesNotSupportedForAnnotationProcessors(chunkModules.toArray(new Module[chunkModules.size()])); - return false; - } - } Sdk jdk = null; LanguageLevel languageLevel = null; for (final Module module : chunkModules) { @@ -2574,14 +721,6 @@ public class CompileDriver { } } } - if (!useOutOfProcessBuild) { - final Compiler[] allCompilers = compilerManager.getCompilers(Compiler.class); - for (Compiler compiler : allCompilers) { - if (!compiler.validateConfiguration(scope)) { - return false; - } - } - } return true; } catch (Throwable e) { @@ -2590,10 +729,6 @@ public class CompileDriver { } } - private boolean useOutOfProcessBuild() { - return CompilerWorkspaceConfiguration.getInstance(myProject).useOutOfProcessBuild(); - } - private void showCyclicModulesHaveDifferentLanguageLevel(Module[] modulesInChunk) { LOG.assertTrue(modulesInChunk.length > 0); String moduleNameToSelect = modulesInChunk[0].getName(); @@ -2612,15 +747,6 @@ public class CompileDriver { showConfigurationDialog(moduleNameToSelect, null); } - private void showCyclesNotSupportedForAnnotationProcessors(Module[] modulesInChunk) { - LOG.assertTrue(modulesInChunk.length > 0); - String moduleNameToSelect = modulesInChunk[0].getName(); - final String moduleNames = getModulesString(modulesInChunk); - Messages.showMessageDialog(myProject, CompilerBundle.message("error.annotation.processing.not.supported.for.module.cycles", moduleNames), - CommonBundle.getErrorTitle(), Messages.getErrorIcon()); - showConfigurationDialog(moduleNameToSelect, null); - } - private static String getModulesString(Module[] modulesInChunk) { final StringBuilder moduleNames = StringBuilderSpinAllocator.alloc(); try { @@ -2675,228 +801,7 @@ public class CompileDriver { showConfigurationDialog(nameToSelect, editorNameToSelect); } - private boolean validateOutputAndSourcePathsIntersection() { - final Module[] allModules = ModuleManager.getInstance(myProject).getModules(); - List allOutputs = new ArrayList(); - ContainerUtil.addAll(allOutputs, CompilerPathsEx.getOutputDirectories(allModules)); - for (Artifact artifact : ArtifactManager.getInstance(myProject).getArtifacts()) { - ContainerUtil.addIfNotNull(artifact.getOutputFile(), allOutputs); - } - final Set affectedOutputPaths = new HashSet(); - CompilerUtil.computeIntersectingPaths(myProject, allOutputs, affectedOutputPaths); - affectedOutputPaths.addAll(ArtifactCompilerUtil.getArtifactOutputsContainingSourceFiles(myProject)); - - if (!affectedOutputPaths.isEmpty()) { - if (CompilerUtil.askUserToContinueWithNoClearing(myProject, affectedOutputPaths)) { - myShouldClearOutputDirectory = false; - return true; - } - else { - return false; - } - } - return true; - } - private void showConfigurationDialog(String moduleNameToSelect, String tabNameToSelect) { ProjectSettingsService.getInstance(myProject).showModuleConfigurationDialog(moduleNameToSelect, tabNameToSelect); } - - private static VirtualFile lookupVFile(final LocalFileSystem lfs, final String path) { - final File file = new File(path); - - VirtualFile vFile = lfs.findFileByIoFile(file); - if (vFile != null) { - return vFile; - } - - final boolean justCreated = file.mkdirs(); - vFile = lfs.refreshAndFindFileByIoFile(file); - - if (vFile == null) { - assert false: "Virtual file not found for " + file.getPath() + "; mkdirs() exit code is " + justCreated + "; file exists()? " + file.exists(); - } - - return vFile; - } - - private static class CacheDeferredUpdater { - private final Map>> myData = new java.util.HashMap>>(); - - public void addFileForUpdate(final FileProcessingCompiler.ProcessingItem item, FileProcessingCompilerStateCache cache) { - final VirtualFile file = item.getFile(); - List> list = myData.get(file); - if (list == null) { - list = new ArrayList>(); - myData.put(file, list); - } - list.add(Pair.create(cache, item)); - } - - public void doUpdate() throws IOException { - ApplicationManager.getApplication().runReadAction(new ThrowableComputable() { - @Override - public Void compute() throws IOException { - for (Map.Entry>> entry : myData.entrySet()) { - for (Pair pair : entry.getValue()) { - final FileProcessingCompiler.ProcessingItem item = pair.getSecond(); - pair.getFirst().update(entry.getKey(), item.getValidityState()); - } - } - return null; - } - }); - } - } - - private static class TranslatorsOutputSink implements TranslatingCompiler.OutputSink { - final Map> myPostponedItems = new HashMap>(); - private final CompileContextEx myContext; - private final TranslatingCompiler[] myCompilers; - private int myCurrentCompilerIdx; - private final Set myCompiledSources = new HashSet(); - //private LinkedBlockingQueue myFutures = new LinkedBlockingQueue(); - - private TranslatorsOutputSink(CompileContextEx context, TranslatingCompiler[] compilers) { - myContext = context; - myCompilers = compilers; - } - - public void setCurrentCompilerIndex(int index) { - myCurrentCompilerIdx = index; - } - - public Set getCompiledSources() { - return Collections.unmodifiableSet(myCompiledSources); - } - - public void add(final String outputRoot, final Collection items, final VirtualFile[] filesToRecompile) { - for (TranslatingCompiler.OutputItem item : items) { - final VirtualFile file = item.getSourceFile(); - if (file != null) { - myCompiledSources.add(file); - } - } - final TranslatingCompiler compiler = myCompilers[myCurrentCompilerIdx]; - if (compiler instanceof IntermediateOutputCompiler) { - final LocalFileSystem lfs = LocalFileSystem.getInstance(); - final List outputs = new ArrayList(); - for (TranslatingCompiler.OutputItem item : items) { - final VirtualFile vFile = lfs.findFileByPath(item.getOutputPath()); - if (vFile != null) { - outputs.add(vFile); - } - } - myContext.markGenerated(outputs); - } - final int nextCompilerIdx = myCurrentCompilerIdx + 1; - try { - if (nextCompilerIdx < myCompilers.length ) { - final Map> updateNow = new java.util.HashMap>(); - // process postponed - for (Map.Entry> entry : myPostponedItems.entrySet()) { - final String outputDir = entry.getKey(); - final Collection postponed = entry.getValue(); - for (Iterator it = postponed.iterator(); it.hasNext();) { - TranslatingCompiler.OutputItem item = it.next(); - boolean shouldPostpone = false; - for (int idx = nextCompilerIdx; idx < myCompilers.length; idx++) { - shouldPostpone = myCompilers[idx].isCompilableFile(item.getSourceFile(), myContext); - if (shouldPostpone) { - break; - } - } - if (!shouldPostpone) { - // the file is not compilable by the rest of compilers, so it is safe to update it now - it.remove(); - addItemToMap(updateNow, outputDir, item); - } - } - } - // process items from current compilation - for (TranslatingCompiler.OutputItem item : items) { - boolean shouldPostpone = false; - for (int idx = nextCompilerIdx; idx < myCompilers.length; idx++) { - shouldPostpone = myCompilers[idx].isCompilableFile(item.getSourceFile(), myContext); - if (shouldPostpone) { - break; - } - } - if (shouldPostpone) { - // the file is compilable by the next compiler in row, update should be postponed - addItemToMap(myPostponedItems, outputRoot, item); - } - else { - addItemToMap(updateNow, outputRoot, item); - } - } - - if (updateNow.size() == 1) { - final Map.Entry> entry = updateNow.entrySet().iterator().next(); - final String outputDir = entry.getKey(); - final Collection itemsToUpdate = entry.getValue(); - TranslatingCompilerFilesMonitor.getInstance().update(myContext, outputDir, itemsToUpdate, filesToRecompile); - } - else { - for (Map.Entry> entry : updateNow.entrySet()) { - final String outputDir = entry.getKey(); - final Collection itemsToUpdate = entry.getValue(); - TranslatingCompilerFilesMonitor.getInstance().update(myContext, outputDir, itemsToUpdate, VirtualFile.EMPTY_ARRAY); - } - if (filesToRecompile.length > 0) { - TranslatingCompilerFilesMonitor.getInstance().update(myContext, null, Collections.emptyList(), filesToRecompile); - } - } - } - else { - TranslatingCompilerFilesMonitor.getInstance().update(myContext, outputRoot, items, filesToRecompile); - } - } - catch (IOException e) { - LOG.info(e); - myContext.requestRebuildNextTime(e.getMessage()); - } - } - - private static void addItemToMap(Map> map, String outputDir, TranslatingCompiler.OutputItem item) { - Collection collection = map.get(outputDir); - if (collection == null) { - collection = new ArrayList(); - map.put(outputDir, collection); - } - collection.add(item); - } - - public void flushPostponedItems() { - final TranslatingCompilerFilesMonitor filesMonitor = TranslatingCompilerFilesMonitor.getInstance(); - try { - for (Map.Entry> entry : myPostponedItems.entrySet()) { - final String outputDir = entry.getKey(); - final Collection items = entry.getValue(); - filesMonitor.update(myContext, outputDir, items, VirtualFile.EMPTY_ARRAY); - } - } - catch (IOException e) { - LOG.info(e); - myContext.requestRebuildNextTime(e.getMessage()); - } - } - } - - private static class DependentClassesCumulativeFilter implements Function>, Pair>> { - - private final TIntHashSet myProcessedNames = new TIntHashSet(); - private final Set myProcessedFiles = new HashSet(); - - public Pair> fun(Pair> deps) { - final TIntHashSet currentDeps = new TIntHashSet(deps.getFirst()); - currentDeps.removeAll(myProcessedNames.toArray()); - myProcessedNames.addAll(deps.getFirst()); - - final Set depFiles = new HashSet(deps.getSecond()); - depFiles.removeAll(myProcessedFiles); - myProcessedFiles.addAll(deps.getSecond()); - return Pair.create(currentDeps.toArray(), depFiles); - } - } } diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/CompilerCacheManager.java b/java/compiler/impl/src/com/intellij/compiler/impl/CompilerCacheManager.java index 5c147ee644a1..c30eb739e9a2 100644 --- a/java/compiler/impl/src/com/intellij/compiler/impl/CompilerCacheManager.java +++ b/java/compiler/impl/src/com/intellij/compiler/impl/CompilerCacheManager.java @@ -27,8 +27,6 @@ import com.intellij.openapi.util.io.FileUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; -import java.io.DataInput; -import java.io.DataOutput; import java.io.File; import java.io.IOException; import java.util.ArrayList; @@ -124,35 +122,6 @@ public class CompilerCacheManager implements ProjectComponent { return (FileProcessingCompilerStateCache)cache; } - public synchronized StateCache getGeneratingCompilerCache(final GeneratingCompiler compiler) throws IOException { - Object cache = myCompilerToCacheMap.get(compiler); - if (cache == null) { - final File cacheDir = getCompilerRootDir(compiler); - final StateCache stateCache = new StateCache(new File(cacheDir, "timestamps")) { - public ValidityState read(DataInput stream) throws IOException { - return compiler.createValidityState(stream); - } - - public void write(ValidityState validityState, DataOutput out) throws IOException { - validityState.save(out); - } - }; - myCompilerToCacheMap.put(compiler, stateCache); - myCacheDisposables.add(new Disposable() { - public void dispose() { - try { - stateCache.close(); - } - catch (IOException e) { - LOG.info(e); - } - } - }); - cache = stateCache; - } - return (StateCache)cache; - } - public static String getCompilerIdString(Compiler compiler) { @NonNls String description = compiler.getDescription(); return description.replaceAll("\\s+", "_").replaceAll("[\\.\\?]", "_").toLowerCase(); diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/FileProcessingCompilerAdapterTask.java b/java/compiler/impl/src/com/intellij/compiler/impl/FileProcessingCompilerAdapterTask.java index 8848a40d6e06..514eb3cd03ef 100644 --- a/java/compiler/impl/src/com/intellij/compiler/impl/FileProcessingCompilerAdapterTask.java +++ b/java/compiler/impl/src/com/intellij/compiler/impl/FileProcessingCompilerAdapterTask.java @@ -15,7 +15,6 @@ */ package com.intellij.compiler.impl; -import com.intellij.compiler.CompilerWorkspaceConfiguration; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.compiler.*; import com.intellij.openapi.diagnostic.Logger; @@ -53,9 +52,6 @@ public class FileProcessingCompilerAdapterTask implements CompileTask { @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); diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/SourceUrlClassNamePair.java b/java/compiler/impl/src/com/intellij/compiler/impl/SourceUrlClassNamePair.java deleted file mode 100644 index 6d9a60da5d9b..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/impl/SourceUrlClassNamePair.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.compiler.impl; - -import org.jetbrains.annotations.Nullable; - -/** - * @author Eugene Zhuravlev - * Date: Jun 21, 2006 - */ -public class SourceUrlClassNamePair { - private final String mySourceUrl; - private final @Nullable String myClassName; - - public SourceUrlClassNamePair(String url, @Nullable String className) { - mySourceUrl = url; - myClassName = className; - } - - public String getSourceUrl() { - return mySourceUrl; - } - - public @Nullable String getClassName() { - return myClassName; - } -} diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/TranslatingCompilerFilesMonitor.java b/java/compiler/impl/src/com/intellij/compiler/impl/TranslatingCompilerFilesMonitor.java index f9d2fbecaca7..6d2d798807c9 100644 --- a/java/compiler/impl/src/com/intellij/compiler/impl/TranslatingCompilerFilesMonitor.java +++ b/java/compiler/impl/src/com/intellij/compiler/impl/TranslatingCompilerFilesMonitor.java @@ -15,55 +15,27 @@ */ package com.intellij.compiler.impl; -import com.intellij.ProjectTopics; -import com.intellij.compiler.CompilerConfiguration; -import com.intellij.compiler.CompilerIOUtil; -import com.intellij.compiler.CompilerWorkspaceConfiguration; -import com.intellij.compiler.make.MakeUtil; import com.intellij.compiler.server.BuildManager; -import com.intellij.openapi.Disposable; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; -import com.intellij.openapi.application.ModalityState; -import com.intellij.openapi.compiler.*; -import com.intellij.openapi.compiler.ex.CompileContextEx; import com.intellij.openapi.components.ApplicationComponent; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileTypes.FileTypeManager; -import com.intellij.openapi.module.Module; -import com.intellij.openapi.module.ModuleManager; -import com.intellij.openapi.progress.ProgressIndicator; -import com.intellij.openapi.progress.ProgressManager; -import com.intellij.openapi.progress.Task; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectManager; -import com.intellij.openapi.project.ProjectManagerAdapter; -import com.intellij.openapi.roots.*; -import com.intellij.openapi.startup.StartupManager; -import com.intellij.openapi.util.*; +import com.intellij.openapi.roots.ProjectRootManager; +import com.intellij.openapi.util.Comparing; +import com.intellij.openapi.util.Computable; import com.intellij.openapi.util.io.FileUtil; -import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.*; -import com.intellij.openapi.vfs.newvfs.FileAttribute; -import com.intellij.openapi.vfs.newvfs.ManagingFS; import com.intellij.openapi.vfs.newvfs.NewVirtualFile; -import com.intellij.openapi.vfs.newvfs.persistent.FSRecords; -import com.intellij.openapi.vfs.newvfs.persistent.PersistentFS; -import com.intellij.util.Alarm; -import com.intellij.util.containers.ContainerUtil; -import com.intellij.util.containers.SLRUCache; -import com.intellij.util.indexing.FileBasedIndex; -import com.intellij.util.indexing.IndexInfrastructure; -import com.intellij.util.io.*; -import com.intellij.util.io.DataOutputStream; -import com.intellij.util.messages.MessageBusConnection; -import gnu.trove.*; +import gnu.trove.THashSet; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.io.*; -import java.util.*; -import java.util.concurrent.atomic.AtomicInteger; +import java.io.File; +import java.util.Collection; +import java.util.Set; /** * @author Eugene Zhuravlev @@ -82,104 +54,7 @@ public class TranslatingCompilerFilesMonitor implements ApplicationComponent { private static final Logger LOG = Logger.getInstance("#com.intellij.compiler.impl.TranslatingCompilerFilesMonitor"); public static boolean ourDebugMode = false; - private static final FileAttribute ourSourceFileAttribute = new FileAttribute("_make_source_file_info_", 3); - private static final FileAttribute ourOutputFileAttribute = new FileAttribute("_make_output_file_info_", 3); - private static final Key> SOURCE_FILES_CACHE = Key.create("_source_url_to_vfile_cache_"); - - private final Object myDataLock = new Object(); - - private final TIntHashSet mySuspendedProjects = new TIntHashSet(); // projectId for all projects that should not be monitored - - private final TIntObjectHashMap mySourcesToRecompile = new TIntObjectHashMap(); // ProjectId->set of source file paths - private PersistentHashMap>> myOutputRootsStorage; // ProjectId->map[moduleId->Pair(outputDirId, testOutputDirId)] - - // Map: projectId -> Map{output path -> [sourceUrl; className]} - private final SLRUCache myOutputsToDelete = new SLRUCache(3, 3) { - @Override - public Outputs getIfCached(Integer key) { - final Outputs value = super.getIfCached(key); - if (value != null) { - value.allocate(); - } - return value; - } - - @NotNull - @Override - public Outputs get(Integer key) { - final Outputs value = super.get(key); - value.allocate(); - return value; - } - - @NotNull - @Override - public Outputs createValue(Integer key) { - try { - final String dirName = FSRecords.getNames().valueOf(key); - final File storeFile; - if (StringUtil.isEmpty(dirName)) { - storeFile = null; - } - else { - final File compilerCacheDir = CompilerPaths.getCacheStoreDirectory(dirName); - storeFile = compilerCacheDir.exists()? new File(compilerCacheDir, "paths_to_delete.dat") : null; - } - return new Outputs(storeFile, loadPathsToDelete(storeFile)); - } - catch (IOException e) { - LOG.info(e); - return new Outputs(null, new HashMap()); - } - } - - @Override - protected void onDropFromCache(Integer key, Outputs value) { - value.release(); - } - }; - private final SLRUCache myGeneratedDataPaths = new SLRUCache(8, 8) { - @NotNull - public File createValue(final Project project) { - Disposer.register(project, new Disposable() { - public void dispose() { - myGeneratedDataPaths.remove(project); - } - }); - return CompilerPaths.getGeneratedDataDirectory(project); - } - }; - private final SLRUCache>> myProjectOutputRoots = new SLRUCache>>(2, 2) { - protected void onDropFromCache(Integer key, TIntObjectHashMap> value) { - try { - myOutputRootsStorage.put(key, value); - } - catch (IOException e) { - LOG.info(e); - } - } - - @NotNull - public TIntObjectHashMap> createValue(Integer key) { - TIntObjectHashMap> map = null; - try { - ensureOutputStorageInitialized(); - map = myOutputRootsStorage.get(key); - } - catch (IOException e) { - LOG.info(e); - } - return map != null? map : new TIntObjectHashMap>(); - } - }; - private final ProjectManager myProjectManager; - private final TIntIntHashMap myInitInProgress = new TIntIntHashMap(); // projectId for successfully initialized projects - private final Object myAsyncScanLock = new Object(); - - public TranslatingCompilerFilesMonitor(VirtualFileManager vfsManager, ProjectManager projectManager, Application application) { - myProjectManager = projectManager; - - projectManager.addProjectManagerListener(new MyProjectManagerListener()); + public TranslatingCompilerFilesMonitor(VirtualFileManager vfsManager, Application application) { vfsManager.addVirtualFileListener(new MyVfsListener(), application); } @@ -187,843 +62,18 @@ public class TranslatingCompilerFilesMonitor implements ApplicationComponent { return ApplicationManager.getApplication().getComponent(TranslatingCompilerFilesMonitor.class); } - public void suspendProject(Project project) { - final int projectId = getProjectId(project); - - synchronized (myDataLock) { - if (!mySuspendedProjects.add(projectId)) { - return; - } - FileUtil.createIfDoesntExist(CompilerPaths.getRebuildMarkerFile(project)); - // cleanup internal structures to free memory - mySourcesToRecompile.remove(projectId); - myOutputsToDelete.remove(projectId); - myGeneratedDataPaths.remove(project); - } - - synchronized (myProjectOutputRoots) { - ensureOutputStorageInitialized(); - myProjectOutputRoots.remove(projectId); - try { - myOutputRootsStorage.remove(projectId); - } - catch (IOException e) { - LOG.info(e); - } - } - } - - public void watchProject(Project project) { - synchronized (myDataLock) { - int projectId = getProjectId(project); - mySuspendedProjects.remove(projectId); - } - } - - public boolean isSuspended(Project project) { - return isSuspended(getProjectId(project)); - } - - public boolean isSuspended(int projectId) { - synchronized (myDataLock) { - return mySuspendedProjects.contains(projectId); - } - } - - @Nullable - public static VirtualFile getSourceFileByOutput(VirtualFile outputFile) { - final OutputFileInfo outputFileInfo = loadOutputInfo(outputFile); - if (outputFileInfo != null) { - final String path = outputFileInfo.getSourceFilePath(); - if (path != null) { - return LocalFileSystem.getInstance().findFileByPath(path); - } - } - return null; - } - - public void collectFiles(CompileContext context, final TranslatingCompiler compiler, Iterator scopeSrcIterator, boolean forceCompile, - final boolean isRebuild, - Collection toCompile, - Collection> toDelete) { - final Project project = context.getProject(); - final int projectId = getProjectId(project); - final CompilerConfiguration configuration = CompilerConfiguration.getInstance(project); - final boolean _forceCompile = forceCompile || isRebuild; - final Set selectedForRecompilation = new HashSet(); - synchronized (myDataLock) { - final TIntHashSet pathsToRecompile = mySourcesToRecompile.get(projectId); - if (_forceCompile || pathsToRecompile != null && !pathsToRecompile.isEmpty()) { - if (ourDebugMode) { - System.out.println("Analysing potentially recompilable files for " + compiler.getDescription()); - } - while (scopeSrcIterator.hasNext()) { - final VirtualFile file = scopeSrcIterator.next(); - if (!file.isValid()) { - if (LOG.isDebugEnabled() || ourDebugMode) { - LOG.debug("Skipping invalid file " + file.getPresentableUrl()); - if (ourDebugMode) { - System.out.println("\t SKIPPED(INVALID) " + file.getPresentableUrl()); - } - } - continue; - } - final int fileId = getFileId(file); - if (_forceCompile) { - if (compiler.isCompilableFile(file, context) && !configuration.isExcludedFromCompilation(file)) { - toCompile.add(file); - if (ourDebugMode) { - System.out.println("\t INCLUDED " + file.getPresentableUrl()); - } - selectedForRecompilation.add(file); - if (pathsToRecompile == null || !pathsToRecompile.contains(fileId)) { - loadInfoAndAddSourceForRecompilation(projectId, file); - } - } - else { - if (ourDebugMode) { - System.out.println("\t NOT COMPILABLE OR EXCLUDED " + file.getPresentableUrl()); - } - } - } - else if (pathsToRecompile.contains(fileId)) { - if (compiler.isCompilableFile(file, context) && !configuration.isExcludedFromCompilation(file)) { - toCompile.add(file); - if (ourDebugMode) { - System.out.println("\t INCLUDED " + file.getPresentableUrl()); - } - selectedForRecompilation.add(file); - } - else { - if (ourDebugMode) { - System.out.println("\t NOT COMPILABLE OR EXCLUDED " + file.getPresentableUrl()); - } - } - } - else { - if (ourDebugMode) { - System.out.println("\t NOT INCLUDED " + file.getPresentableUrl()); - } - } - } - } - // it is important that files to delete are collected after the files to compile (see what happens if forceCompile == true) - if (!isRebuild) { - final Outputs outputs = myOutputsToDelete.get(projectId); - try { - final VirtualFileManager vfm = VirtualFileManager.getInstance(); - final LocalFileSystem lfs = LocalFileSystem.getInstance(); - final List zombieEntries = new ArrayList(); - final Map srcFileCache = getFileCache(context); - for (Map.Entry entry : outputs.getEntries()) { - final String outputPath = entry.getKey(); - final SourceUrlClassNamePair classNamePair = entry.getValue(); - final String sourceUrl = classNamePair.getSourceUrl(); - - final VirtualFile srcFile; - if (srcFileCache.containsKey(sourceUrl)) { - srcFile = srcFileCache.get(sourceUrl); - } - else { - srcFile = vfm.findFileByUrl(sourceUrl); - srcFileCache.put(sourceUrl, srcFile); - } - - final boolean sourcePresent = srcFile != null; - if (sourcePresent) { - if (!compiler.isCompilableFile(srcFile, context)) { - continue; // do not collect files that were compiled by another compiler - } - if (!selectedForRecompilation.contains(srcFile)) { - if (!isMarkedForRecompilation(projectId, getFileId(srcFile))) { - if (LOG.isDebugEnabled() || ourDebugMode) { - final String message = "Found zombie entry (output is marked, but source is present and up-to-date): " + outputPath; - LOG.debug(message); - if (ourDebugMode) { - System.out.println(message); - } - } - zombieEntries.add(outputPath); - } - continue; - } - } - if (lfs.findFileByPath(outputPath) != null) { - //noinspection UnnecessaryBoxing - final File file = new File(outputPath); - toDelete.add(new Trinity(file, classNamePair.getClassName(), Boolean.valueOf(sourcePresent))); - if (LOG.isDebugEnabled() || ourDebugMode) { - final String message = "Found file to delete: " + file; - LOG.debug(message); - if (ourDebugMode) { - System.out.println(message); - } - } - } - else { - if (LOG.isDebugEnabled() || ourDebugMode) { - final String message = "Found zombie entry marked for deletion: " + outputPath; - LOG.debug(message); - if (ourDebugMode) { - System.out.println(message); - } - } - // must be gagbage entry, should cleanup - zombieEntries.add(outputPath); - } - } - for (String path : zombieEntries) { - unmarkOutputPathForDeletion(projectId, path); - } - } - finally { - outputs.release(); - } - } - } - } - - private static Map getFileCache(CompileContext context) { - Map cache = context.getUserData(SOURCE_FILES_CACHE); - if (cache == null) { - context.putUserData(SOURCE_FILES_CACHE, cache = new HashMap()); - } - return cache; - } - - private static int getFileId(final VirtualFile file) { - return FileBasedIndex.getFileId(file); - } - - private static VirtualFile findFileById(int id) { - return IndexInfrastructure.findFileById((PersistentFS)ManagingFS.getInstance(), id); - } - - public void update(final CompileContext context, @Nullable final String outputRoot, final Collection successfullyCompiled, final VirtualFile[] filesToRecompile) - throws IOException { - final Project project = context.getProject(); - final int projectId = getProjectId(project); - if (!successfullyCompiled.isEmpty()) { - final LocalFileSystem lfs = LocalFileSystem.getInstance(); - // need read action here to ensure that no modifications were made to VFS while updating file attributes - ApplicationManager.getApplication().runReadAction(new ThrowableComputable() { - @Override - public Void compute() throws IOException { - final Map compiledSources = new HashMap(); - final Set forceRecompile = new HashSet(); - - for (TranslatingCompiler.OutputItem item : successfullyCompiled) { - final VirtualFile sourceFile = item.getSourceFile(); - final boolean isSourceValid = sourceFile.isValid(); - SourceFileInfo srcInfo = compiledSources.get(sourceFile); - if (isSourceValid && srcInfo == null) { - srcInfo = loadSourceInfo(sourceFile); - if (srcInfo != null) { - srcInfo.clearPaths(projectId); - } - else { - srcInfo = new SourceFileInfo(); - } - compiledSources.put(sourceFile, srcInfo); - } - - final String outputPath = item.getOutputPath(); - if (outputPath != null) { // can be null for packageinfo - final VirtualFile outputFile = lfs.findFileByPath(outputPath); - - //assert outputFile != null : "Virtual file was not found for \"" + outputPath + "\""; - - if (outputFile != null) { - if (!sourceFile.equals(outputFile)) { - final String className = outputRoot == null? null : MakeUtil.relativeClassPathToQName(outputPath.substring(outputRoot.length()), '/'); - if (isSourceValid) { - srcInfo.addOutputPath(projectId, outputPath); - saveOutputInfo(outputFile, new OutputFileInfo(sourceFile.getPath(), className)); - } - else { - markOutputPathForDeletion(projectId, outputPath, className, sourceFile.getUrl()); - } - } - } - else { // output file was not found - LOG.warn("TranslatingCompilerFilesMonitor.update(): Virtual file was not found for \"" + outputPath + "\""); - if (isSourceValid) { - forceRecompile.add(sourceFile); - } - } - } - } - final long compilationStartStamp = ((CompileContextEx)context).getStartCompilationStamp(); - for (Map.Entry entry : compiledSources.entrySet()) { - final SourceFileInfo info = entry.getValue(); - final VirtualFile file = entry.getKey(); - - final long fileStamp = file.getTimeStamp(); - info.updateTimestamp(projectId, fileStamp); - saveSourceInfo(file, info); - if (LOG.isDebugEnabled() || ourDebugMode) { - final String message = "Unschedule recompilation (successfully compiled) " + file.getPresentableUrl(); - LOG.debug(message); - if (ourDebugMode) { - System.out.println(message); - } - } - removeSourceForRecompilation(projectId, Math.abs(getFileId(file))); - if (fileStamp > compilationStartStamp && !((CompileContextEx)context).isGenerated(file) || forceRecompile.contains(file)) { - // changes were made during compilation, need to re-schedule compilation - // it is important to invoke removeSourceForRecompilation() before this call to make sure - // the corresponding output paths will be scheduled for deletion - addSourceForRecompilation(projectId, file, info); - } - } - return null; - } - }); - } - - if (filesToRecompile.length > 0) { - ApplicationManager.getApplication().runReadAction(new Runnable() { - public void run() { - for (VirtualFile file : filesToRecompile) { - if (file.isValid()) { - loadInfoAndAddSourceForRecompilation(projectId, file); - } - } - } - }); - } - } - - public void updateOutputRootsLayout(Project project) { - final TIntObjectHashMap> map = buildOutputRootsLayout(new ProjectRef(project)); - final int projectId = getProjectId(project); - synchronized (myProjectOutputRoots) { - myProjectOutputRoots.put(projectId, map); - } - } - @NotNull public String getComponentName() { return "TranslatingCompilerFilesMonitor"; } public void initComponent() { - ensureOutputStorageInitialized(); } - private static File getOutputRootsFile() { - return new File(CompilerPaths.getCompilerSystemDirectory(), "output_roots.dat"); - } - - private static void deleteStorageFiles(File tableFile) { - final File[] files = tableFile.getParentFile().listFiles(); - if (files != null) { - final String name = tableFile.getName(); - for (File file : files) { - if (file.getName().startsWith(name)) { - FileUtil.delete(file); - } - } - } - } - - private static Map loadPathsToDelete(@Nullable final File file) { - final Map map = new HashMap(); - try { - if (file != null && file.length() > 0) { - final DataInputStream is = new DataInputStream(new BufferedInputStream(new FileInputStream(file))); - try { - final int size = is.readInt(); - for (int i = 0; i < size; i++) { - final String _outputPath = CompilerIOUtil.readString(is); - final String srcUrl = CompilerIOUtil.readString(is); - final String className = CompilerIOUtil.readString(is); - map.put(FileUtil.toSystemIndependentName(_outputPath), new SourceUrlClassNamePair(srcUrl, className)); - } - } - finally { - is.close(); - } - } - } - catch (FileNotFoundException ignored) { - } - catch (IOException e) { - LOG.info(e); - } - return map; - } - - private void ensureOutputStorageInitialized() { - if (myOutputRootsStorage != null) { - return; - } - final File rootsFile = getOutputRootsFile(); - try { - initOutputRootsFile(rootsFile); - } - catch (IOException e) { - LOG.info(e); - deleteStorageFiles(rootsFile); - try { - initOutputRootsFile(rootsFile); - } - catch (IOException e1) { - LOG.error(e1); - } - } - } - - private TIntObjectHashMap> buildOutputRootsLayout(ProjectRef projRef) { - final TIntObjectHashMap> map = new TIntObjectHashMap>(); - for (Module module : ModuleManager.getInstance(projRef.get()).getModules()) { - final CompilerModuleExtension manager = CompilerModuleExtension.getInstance(module); - if (manager != null) { - final VirtualFile output = manager.getCompilerOutputPath(); - final int first = output != null? Math.abs(getFileId(output)) : -1; - final VirtualFile testsOutput = manager.getCompilerOutputPathForTests(); - final int second = testsOutput != null? Math.abs(getFileId(testsOutput)) : -1; - map.put(getModuleId(module), Couple.newOne(first, second)); - } - } - return map; - } - - private void initOutputRootsFile(File rootsFile) throws IOException { - myOutputRootsStorage = new PersistentHashMap>>(rootsFile, EnumeratorIntegerDescriptor.INSTANCE, new DataExternalizer>>() { - public void save(@NotNull DataOutput out, TIntObjectHashMap> value) throws IOException { - for (final TIntObjectIterator> it = value.iterator(); it.hasNext();) { - it.advance(); - DataInputOutputUtil.writeINT(out, it.key()); - final Couple pair = it.value(); - DataInputOutputUtil.writeINT(out, pair.first); - DataInputOutputUtil.writeINT(out, pair.second); - } - } - - public TIntObjectHashMap> read(@NotNull DataInput in) throws IOException { - final DataInputStream _in = (DataInputStream)in; - final TIntObjectHashMap> map = new TIntObjectHashMap>(); - while (_in.available() > 0) { - final int key = DataInputOutputUtil.readINT(_in); - final int first = DataInputOutputUtil.readINT(_in); - final int second = DataInputOutputUtil.readINT(_in); - map.put(key, Couple.newOne(first, second)); - } - return map; - } - }); - } public void disposeComponent() { - try { - synchronized (myProjectOutputRoots) { - myProjectOutputRoots.clear(); - } - } - finally { - synchronized (myDataLock) { - myOutputsToDelete.clear(); - } - } - - try { - final PersistentHashMap>> storage = myOutputRootsStorage; - if (storage != null) { - storage.close(); - } - } - catch (IOException e) { - LOG.info(e); - deleteStorageFiles(getOutputRootsFile()); - } } - private static void savePathsToDelete(final File file, final Map outputs) { - try { - FileUtil.createParentDirs(file); - final DataOutputStream os = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file))); - try { - if (outputs != null) { - os.writeInt(outputs.size()); - for (Map.Entry entry : outputs.entrySet()) { - CompilerIOUtil.writeString(entry.getKey(), os); - final SourceUrlClassNamePair pair = entry.getValue(); - CompilerIOUtil.writeString(pair.getSourceUrl(), os); - CompilerIOUtil.writeString(pair.getClassName(), os); - } - } - else { - os.writeInt(0); - } - } - finally { - os.close(); - } - } - catch (IOException e) { - LOG.error(e); - } - } - - @Nullable - private static SourceFileInfo loadSourceInfo(final VirtualFile file) { - try { - final DataInputStream is = ourSourceFileAttribute.readAttribute(file); - if (is != null) { - try { - return new SourceFileInfo(is); - } - finally { - is.close(); - } - } - } - catch (RuntimeException e) { - final Throwable cause = e.getCause(); - if (cause instanceof IOException) { - LOG.info(e); // ignore IOExceptions - } - else { - throw e; - } - } - catch (IOException ignored) { - LOG.info(ignored); - } - return null; - } - - public static void removeSourceInfo(VirtualFile file) { - saveSourceInfo(file, new SourceFileInfo()); - } - - private static void saveSourceInfo(VirtualFile file, SourceFileInfo descriptor) { - final java.io.DataOutputStream out = ourSourceFileAttribute.writeAttribute(file); - try { - try { - descriptor.save(out); - } - finally { - out.close(); - } - } - catch (IOException ignored) { - LOG.info(ignored); - } - } - - @Nullable - private static OutputFileInfo loadOutputInfo(final VirtualFile file) { - try { - final DataInputStream is = ourOutputFileAttribute.readAttribute(file); - if (is != null) { - try { - return new OutputFileInfo(is); - } - finally { - is.close(); - } - } - } - catch (RuntimeException e) { - final Throwable cause = e.getCause(); - if (cause instanceof IOException) { - LOG.info(e); // ignore IO exceptions - } - else { - throw e; - } - } - catch (IOException ignored) { - LOG.info(ignored); - } - return null; - } - - private static void saveOutputInfo(VirtualFile file, OutputFileInfo descriptor) { - final java.io.DataOutputStream out = ourOutputFileAttribute.writeAttribute(file); - try { - try { - descriptor.save(out); - } - finally { - out.close(); - } - } - catch (IOException ignored) { - LOG.info(ignored); - } - } - - private static int getProjectId(Project project) { - try { - return FSRecords.getNames().enumerate(CompilerPaths.getCompilerSystemDirectoryName(project)); - } - catch (IOException e) { - LOG.info(e); - } - return -1; - } - - private static int getModuleId(Module module) { - try { - return FSRecords.getNames().enumerate(module.getName().toLowerCase(Locale.US)); - } - catch (IOException e) { - LOG.info(e); - } - return -1; - } - - private static class OutputFileInfo { - private final int mySourcePath; - - private final int myClassName; - - OutputFileInfo(final String sourcePath, @Nullable String className) throws IOException { - final PersistentStringEnumerator symtable = FSRecords.getNames(); - mySourcePath = symtable.enumerate(sourcePath); - myClassName = className != null? symtable.enumerate(className) : -1; - } - - OutputFileInfo(final DataInput in) throws IOException { - mySourcePath = in.readInt(); - myClassName = in.readInt(); - } - - String getSourceFilePath() { - try { - return FSRecords.getNames().valueOf(mySourcePath); - } - catch (IOException e) { - LOG.info(e); - } - return null; - } - - @Nullable - public String getClassName() { - try { - return myClassName < 0? null : FSRecords.getNames().valueOf(myClassName); - } - catch (IOException e) { - LOG.info(e); - } - return null; - } - - public void save(final DataOutput out) throws IOException { - out.writeInt(mySourcePath); - out.writeInt(myClassName); - } - } - - private static class SourceFileInfo { - private TIntLongHashMap myTimestamps; // ProjectId -> last compiled stamp - private TIntObjectHashMap myProjectToOutputPathMap; // ProjectId -> either a single output path or a set of output paths - - private SourceFileInfo() { - } - - private SourceFileInfo(@NotNull DataInput in) throws IOException { - final int projCount = DataInputOutputUtil.readINT(in); - for (int idx = 0; idx < projCount; idx++) { - final int projectId = DataInputOutputUtil.readINT(in); - final long stamp = DataInputOutputUtil.readTIME(in); - updateTimestamp(projectId, stamp); - - final int pathsCount = DataInputOutputUtil.readINT(in); - for (int i = 0; i < pathsCount; i++) { - final int path = in.readInt(); - addOutputPath(projectId, path); - } - } - } - - public void save(@NotNull final DataOutput out) throws IOException { - final int[] projects = getProjectIds().toArray(); - DataInputOutputUtil.writeINT(out, projects.length); - for (int projectId : projects) { - DataInputOutputUtil.writeINT(out, projectId); - DataInputOutputUtil.writeTIME(out, getTimestamp(projectId)); - final Object value = myProjectToOutputPathMap != null? myProjectToOutputPathMap.get(projectId) : null; - if (value instanceof Integer) { - DataInputOutputUtil.writeINT(out, 1); - out.writeInt(((Integer)value).intValue()); - } - else if (value instanceof TIntHashSet) { - final TIntHashSet set = (TIntHashSet)value; - DataInputOutputUtil.writeINT(out, set.size()); - final IOException[] ex = new IOException[] {null}; - set.forEach(new TIntProcedure() { - public boolean execute(final int value) { - try { - out.writeInt(value); - return true; - } - catch (IOException e) { - ex[0] = e; - return false; - } - } - }); - if (ex[0] != null) { - throw ex[0]; - } - } - else { - DataInputOutputUtil.writeINT(out, 0); - } - } - } - - private void updateTimestamp(final int projectId, final long stamp) { - if (stamp > 0L) { - if (myTimestamps == null) { - myTimestamps = new TIntLongHashMap(1, 0.98f); - } - myTimestamps.put(projectId, stamp); - } - else { - if (myTimestamps != null) { - myTimestamps.remove(projectId); - } - } - } - - TIntHashSet getProjectIds() { - final TIntHashSet result = new TIntHashSet(); - if (myTimestamps != null) { - result.addAll(myTimestamps.keys()); - } - if (myProjectToOutputPathMap != null) { - result.addAll(myProjectToOutputPathMap.keys()); - } - return result; - } - - private void addOutputPath(final int projectId, String outputPath) { - try { - addOutputPath(projectId, FSRecords.getNames().enumerate(outputPath)); - } - catch (IOException e) { - LOG.info(e); - } - } - - private void addOutputPath(final int projectId, final int outputPath) { - if (myProjectToOutputPathMap == null) { - myProjectToOutputPathMap = new TIntObjectHashMap(1, 0.98f); - myProjectToOutputPathMap.put(projectId, outputPath); - } - else { - final Object val = myProjectToOutputPathMap.get(projectId); - if (val == null) { - myProjectToOutputPathMap.put(projectId, outputPath); - } - else { - TIntHashSet set; - if (val instanceof Integer) { - set = new TIntHashSet(); - set.add(((Integer)val).intValue()); - myProjectToOutputPathMap.put(projectId, set); - } - else { - assert val instanceof TIntHashSet; - set = (TIntHashSet)val; - } - set.add(outputPath); - } - } - } - - public boolean clearPaths(final int projectId){ - if (myProjectToOutputPathMap != null) { - final Serializable removed = myProjectToOutputPathMap.remove(projectId); - return removed != null; - } - return false; - } - - long getTimestamp(final int projectId) { - return myTimestamps == null? -1L : myTimestamps.get(projectId); - } - - void processOutputPaths(final int projectId, final Proc proc){ - if (myProjectToOutputPathMap != null) { - try { - final PersistentStringEnumerator symtable = FSRecords.getNames(); - final Object val = myProjectToOutputPathMap.get(projectId); - if (val instanceof Integer) { - proc.execute(projectId, symtable.valueOf(((Integer)val).intValue())); - } - else if (val instanceof TIntHashSet) { - ((TIntHashSet)val).forEach(new TIntProcedure() { - public boolean execute(final int value) { - try { - proc.execute(projectId, symtable.valueOf(value)); - return true; - } - catch (IOException e) { - LOG.info(e); - return false; - } - } - }); - } - } - catch (IOException e) { - LOG.info(e); - } - } - } - - boolean isAssociated(int projectId, String outputPath) { - if (myProjectToOutputPathMap != null) { - try { - final Object val = myProjectToOutputPathMap.get(projectId); - if (val instanceof Integer) { - return FileUtil.pathsEqual(outputPath, FSRecords.getNames().valueOf(((Integer)val).intValue())); - } - if (val instanceof TIntHashSet) { - final int _outputPath = FSRecords.getNames().enumerate(outputPath); - return ((TIntHashSet)val).contains(_outputPath); - } - } - catch (IOException e) { - LOG.info(e); - } - } - return false; - } - } - - public List getCompiledClassNames(VirtualFile srcFile, Project project) { - final SourceFileInfo info = loadSourceInfo(srcFile); - if (info == null) { - return Collections.emptyList(); - } - - final ArrayList result = new ArrayList(); - - info.processOutputPaths(getProjectId(project), new Proc() { - @Override - public boolean execute(int projectId, String outputPath) { - VirtualFile clsFile = LocalFileSystem.getInstance().findFileByPath(outputPath); - if (clsFile != null) { - OutputFileInfo outputInfo = loadOutputInfo(clsFile); - if (outputInfo != null) { - ContainerUtil.addIfNotNull(result, outputInfo.getClassName()); - } - } - return true; - } - }); - return result; - } - - private interface FileProcessor { void execute(VirtualFile file); } @@ -1080,354 +130,6 @@ public class TranslatingCompilerFilesMonitor implements ApplicationComponent { return needReadAction? ApplicationManager.getApplication().runReadAction(computation) : computation.compute(); } - // made public for tests - public void scanSourceContent(final ProjectRef projRef, final Collection roots, final int totalRootCount, final boolean isNewRoots) { - if (roots.isEmpty()) { - return; - } - final int projectId = getProjectId(projRef.get()); - if (LOG.isDebugEnabled()) { - LOG.debug("Scanning source content for project projectId=" + projectId + "; url=" + projRef.get().getPresentableUrl()); - } - - final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(projRef.get()).getFileIndex(); - final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator(); - int processed = 0; - for (VirtualFile srcRoot : roots) { - if (indicator != null) { - projRef.get(); - indicator.setText2(srcRoot.getPresentableUrl()); - indicator.setFraction(++processed / (double)totalRootCount); - } - if (isNewRoots) { - fileIndex.iterateContentUnderDirectory(srcRoot, new ContentIterator() { - public boolean processFile(final VirtualFile file) { - if (!file.isDirectory()) { - if (!isMarkedForRecompilation(projectId, Math.abs(getFileId(file)))) { - final SourceFileInfo srcInfo = loadSourceInfo(file); - if (srcInfo == null || srcInfo.getTimestamp(projectId) != file.getTimeStamp()) { - addSourceForRecompilation(projectId, file, srcInfo); - } - } - } - else { - projRef.get(); - } - return true; - } - }); - } - else { - final FileTypeManager fileTypeManager = FileTypeManager.getInstance(); - VfsUtilCore.visitChildrenRecursively(srcRoot, new VirtualFileVisitor() { - @Override - public boolean visitFile(@NotNull VirtualFile file) { - if (fileTypeManager.isFileIgnored(file)) { - return false; - } - final int fileId = getFileId(file); - if (fileId > 0 /*file is valid*/) { - if (file.isDirectory()) { - projRef.get(); - } - else if (!isMarkedForRecompilation(projectId, fileId)) { - final SourceFileInfo srcInfo = loadSourceInfo(file); - if (srcInfo != null) { - addSourceForRecompilation(projectId, file, srcInfo); - } - } - } - return true; - } - }); - } - } - } - - public void ensureInitializationCompleted(Project project, ProgressIndicator indicator) { - final int id = getProjectId(project); - synchronized (myAsyncScanLock) { - while (myInitInProgress.containsKey(id)) { - if (!project.isOpen() || project.isDisposed() || (indicator != null && indicator.isCanceled())) { - // makes no sense to continue waiting - break; - } - try { - myAsyncScanLock.wait(500); - } - catch (InterruptedException ignored) { - break; - } - } - } - } - - private void markOldOutputRoots(final ProjectRef projRef, final TIntObjectHashMap> currentLayout) { - final int projectId = getProjectId(projRef.get()); - - final TIntHashSet rootsToMark = new TIntHashSet(); - synchronized (myProjectOutputRoots) { - final TIntObjectHashMap> oldLayout = myProjectOutputRoots.get(projectId); - for (final TIntObjectIterator> it = oldLayout.iterator(); it.hasNext();) { - it.advance(); - final Couple currentRoots = currentLayout.get(it.key()); - final Couple oldRoots = it.value(); - if (shouldMark(oldRoots.first, currentRoots != null? currentRoots.first : -1)) { - rootsToMark.add(oldRoots.first); - } - if (shouldMark(oldRoots.second, currentRoots != null? currentRoots.second : -1)) { - rootsToMark.add(oldRoots.second); - } - } - } - - for (TIntIterator it = rootsToMark.iterator(); it.hasNext();) { - final int id = it.next(); - final VirtualFile outputRoot = findFileById(id); - if (outputRoot != null) { - processOldOutputRoot(projectId, outputRoot); - } - } - } - - private static boolean shouldMark(Integer oldOutputRoot, Integer currentOutputRoot) { - return oldOutputRoot != null && oldOutputRoot.intValue() > 0 && !Comparing.equal(oldOutputRoot, currentOutputRoot); - } - - private void processOldOutputRoot(final int projectId, VirtualFile outputRoot) { - // recursively mark all corresponding sources for recompilation - VfsUtilCore.visitChildrenRecursively(outputRoot, new VirtualFileVisitor() { - @Override - public boolean visitFile(@NotNull VirtualFile file) { - if (!file.isDirectory()) { - // todo: possible optimization - process only those outputs that are not marked for deletion yet - final OutputFileInfo outputInfo = loadOutputInfo(file); - if (outputInfo != null) { - final String srcPath = outputInfo.getSourceFilePath(); - final VirtualFile srcFile = srcPath != null? LocalFileSystem.getInstance().findFileByPath(srcPath) : null; - if (srcFile != null) { - loadInfoAndAddSourceForRecompilation(projectId, srcFile); - } - } - } - return true; - } - }); - } - - public void scanSourcesForCompilableFiles(final Project project) { - final int projectId = getProjectId(project); - if (isSuspended(projectId)) { - return; - } - startAsyncScan(projectId); - StartupManager.getInstance(project).runWhenProjectIsInitialized(new Runnable() { - public void run() { - new Task.Backgroundable(project, CompilerBundle.message("compiler.initial.scanning.progress.text"), false) { - public void run(@NotNull final ProgressIndicator indicator) { - final ProjectRef projRef = new ProjectRef(project); - if (LOG.isDebugEnabled()) { - LOG.debug("Initial sources scan for project hash=" + projectId + "; url="+ projRef.get().getPresentableUrl()); - } - try { - final IntermediateOutputCompiler[] compilers = - CompilerManager.getInstance(projRef.get()).getCompilers(IntermediateOutputCompiler.class); - - final Set intermediateRoots = new HashSet(); - if (compilers.length > 0) { - final Module[] modules = ModuleManager.getInstance(projRef.get()).getModules(); - for (IntermediateOutputCompiler compiler : compilers) { - for (Module module : modules) { - if (module.isDisposed()) { - continue; - } - final VirtualFile outputRoot = LocalFileSystem.getInstance().refreshAndFindFileByPath(CompilerPaths.getGenerationOutputPath(compiler, module, false)); - if (outputRoot != null) { - intermediateRoots.add(outputRoot); - } - final VirtualFile testsOutputRoot = LocalFileSystem.getInstance().refreshAndFindFileByPath(CompilerPaths.getGenerationOutputPath(compiler, module, true)); - if (testsOutputRoot != null) { - intermediateRoots.add(testsOutputRoot); - } - } - } - } - - final List projectRoots = Arrays.asList(ProjectRootManager.getInstance(projRef.get()).getContentSourceRoots()); - final int totalRootsCount = projectRoots.size() + intermediateRoots.size(); - scanSourceContent(projRef, projectRoots, totalRootsCount, true); - - if (!intermediateRoots.isEmpty()) { - final FileProcessor processor = new FileProcessor() { - public void execute(final VirtualFile file) { - if (!isMarkedForRecompilation(projectId, Math.abs(getFileId(file)))) { - final SourceFileInfo srcInfo = loadSourceInfo(file); - if (srcInfo == null || srcInfo.getTimestamp(projectId) != file.getTimeStamp()) { - addSourceForRecompilation(projectId, file, srcInfo); - } - } - } - }; - int processed = projectRoots.size(); - for (VirtualFile root : intermediateRoots) { - projRef.get(); - indicator.setText2(root.getPresentableUrl()); - indicator.setFraction(++processed / (double)totalRootsCount); - processRecursively(root, false, true, processor); - } - } - - markOldOutputRoots(projRef, buildOutputRootsLayout(projRef)); - } - catch (ProjectRef.ProjectClosedException swallowed) { - } - finally { - terminateAsyncScan(projectId, false); - } - } - }.queue(); - } - }); - } - - private void terminateAsyncScan(int projectId, final boolean clearCounter) { - synchronized (myAsyncScanLock) { - int counter = myInitInProgress.remove(projectId); - if (clearCounter) { - myAsyncScanLock.notifyAll(); - } - else { - if (--counter > 0) { - myInitInProgress.put(projectId, counter); - } - else { - myAsyncScanLock.notifyAll(); - } - } - } - } - - private void startAsyncScan(final int projectId) { - synchronized (myAsyncScanLock) { - int counter = myInitInProgress.get(projectId); - counter = (counter > 0)? counter + 1 : 1; - myInitInProgress.put(projectId, counter); - myAsyncScanLock.notifyAll(); - } - } - - private class MyProjectManagerListener extends ProjectManagerAdapter { - - final Map myConnections = new HashMap(); - - public void projectOpened(final Project project) { - final MessageBusConnection conn = project.getMessageBus().connect(); - myConnections.put(project, conn); - final ProjectRef projRef = new ProjectRef(project); - final int projectId = getProjectId(project); - - if (CompilerWorkspaceConfiguration.getInstance(project).useOutOfProcessBuild()) { - suspendProject(project); - } - else { - watchProject(project); - } - - conn.subscribe(ProjectTopics.PROJECT_ROOTS, new ModuleRootListener() { - private VirtualFile[] myRootsBefore; - private Alarm myAlarm = new Alarm(Alarm.ThreadToUse.SWING_THREAD, project); - - public void beforeRootsChange(final ModuleRootEvent event) { - if (isSuspended(projectId)) { - return; - } - try { - myRootsBefore = ProjectRootManager.getInstance(projRef.get()).getContentSourceRoots(); - } - catch (ProjectRef.ProjectClosedException e) { - myRootsBefore = null; - } - } - - public void rootsChanged(final ModuleRootEvent event) { - if (isSuspended(projectId)) { - return; - } - if (LOG.isDebugEnabled()) { - LOG.debug("Before roots changed for projectId=" + projectId + "; url="+ project.getPresentableUrl()); - } - try { - final VirtualFile[] rootsBefore = myRootsBefore; - myRootsBefore = null; - final VirtualFile[] rootsAfter = ProjectRootManager.getInstance(projRef.get()).getContentSourceRoots(); - final Set newRoots = new HashSet(); - final Set oldRoots = new HashSet(); - { - if (rootsAfter.length > 0) { - ContainerUtil.addAll(newRoots, rootsAfter); - } - if (rootsBefore != null) { - newRoots.removeAll(Arrays.asList(rootsBefore)); - } - } - { - if (rootsBefore != null) { - ContainerUtil.addAll(oldRoots, rootsBefore); - } - if (!oldRoots.isEmpty() && rootsAfter.length > 0) { - oldRoots.removeAll(Arrays.asList(rootsAfter)); - } - } - - myAlarm.cancelAllRequests(); // need alarm to deal with multiple rootsChanged events - myAlarm.addRequest(new Runnable() { - public void run() { - startAsyncScan(projectId); - new Task.Backgroundable(project, CompilerBundle.message("compiler.initial.scanning.progress.text"), false) { - public void run(@NotNull final ProgressIndicator indicator) { - try { - if (newRoots.size() > 0) { - scanSourceContent(projRef, newRoots, newRoots.size(), true); - } - if (oldRoots.size() > 0) { - scanSourceContent(projRef, oldRoots, oldRoots.size(), false); - } - markOldOutputRoots(projRef, buildOutputRootsLayout(projRef)); - } - catch (ProjectRef.ProjectClosedException swallowed) { - // ignored - } - finally { - terminateAsyncScan(projectId, false); - } - } - }.queue(); - } - }, 500, ModalityState.NON_MODAL); - } - catch (ProjectRef.ProjectClosedException e) { - LOG.info(e); - } - } - }); - - scanSourcesForCompilableFiles(project); - } - - public void projectClosed(final Project project) { - final int projectId = getProjectId(project); - terminateAsyncScan(projectId, true); - final MessageBusConnection connection = myConnections.remove(project); - if (connection != null) { - connection.disconnect(); - } - synchronized (myDataLock) { - mySourcesToRecompile.remove(projectId); - myOutputsToDelete.remove(projectId); // drop cache to save memory - } - } - } - private class MyVfsListener extends VirtualFileAdapter { public void propertyChanged(@NotNull final VirtualFilePropertyEvent event) { if (VirtualFile.PROP_NAME.equals(event.getPropertyName())) { @@ -1480,15 +182,15 @@ public class TranslatingCompilerFilesMonitor implements ApplicationComponent { } public void fileCreated(@NotNull final VirtualFileEvent event) { - processNewFile(event.getFile(), true); + processNewFile(event.getFile()); } public void fileCopied(@NotNull final VirtualFileCopyEvent event) { - processNewFile(event.getFile(), true); + processNewFile(event.getFile()); } public void fileMoved(@NotNull VirtualFileMoveEvent event) { - processNewFile(event.getFile(), true); + processNewFile(event.getFile()); } public void beforeFileDeletion(@NotNull final VirtualFileEvent event) { @@ -1504,84 +206,8 @@ public class TranslatingCompilerFilesMonitor implements ApplicationComponent { final Set pathsToMark = new THashSet(FileUtil.FILE_HASHING_STRATEGY); processRecursively(eventFile, true, false, new FileProcessor() { - private final TIntArrayList myAssociatedProjectIds = new TIntArrayList(); - public void execute(final VirtualFile file) { - final String filePath = file.getPath(); - pathsToMark.add(new File(filePath)); - myAssociatedProjectIds.clear(); - try { - final OutputFileInfo outputInfo = loadOutputInfo(file); - if (outputInfo != null) { - final String srcPath = outputInfo.getSourceFilePath(); - final VirtualFile srcFile = srcPath != null? LocalFileSystem.getInstance().findFileByPath(srcPath) : null; - if (srcFile != null) { - final SourceFileInfo srcInfo = loadSourceInfo(srcFile); - if (srcInfo != null) { - final boolean srcWillBeDeleted = VfsUtil.isAncestor(eventFile, srcFile, false); - for (int projectId : srcInfo.getProjectIds().toArray()) { - if (isSuspended(projectId)) { - continue; - } - if (srcInfo.isAssociated(projectId, filePath)) { - myAssociatedProjectIds.add(projectId); - if (srcWillBeDeleted) { - if (LOG.isDebugEnabled() || ourDebugMode) { - final String message = "Unschedule recompilation because of deletion " + srcFile.getPresentableUrl(); - LOG.debug(message); - if (ourDebugMode) { - System.out.println(message); - } - } - removeSourceForRecompilation(projectId, Math.abs(getFileId(srcFile))); - } - else { - addSourceForRecompilation(projectId, srcFile, srcInfo); - } - } - } - } - } - } - - final SourceFileInfo srcInfo = loadSourceInfo(file); - if (srcInfo != null) { - final TIntHashSet projects = srcInfo.getProjectIds(); - if (!projects.isEmpty()) { - final ScheduleOutputsForDeletionProc deletionProc = new ScheduleOutputsForDeletionProc(file.getUrl()); - deletionProc.setRootBeingDeleted(eventFile); - final int sourceFileId = Math.abs(getFileId(file)); - for (int projectId : projects.toArray()) { - if (isSuspended(projectId)) { - continue; - } - if (srcInfo.isAssociated(projectId, filePath)) { - myAssociatedProjectIds.add(projectId); - } - // mark associated outputs for deletion - srcInfo.processOutputPaths(projectId, deletionProc); - if (LOG.isDebugEnabled() || ourDebugMode) { - final String message = "Unschedule recompilation because of deletion " + file.getPresentableUrl(); - LOG.debug(message); - if (ourDebugMode) { - System.out.println(message); - } - } - removeSourceForRecompilation(projectId, sourceFileId); - } - } - } - } - finally { - // it is important that update of myOutputsToDelete is done at the end - // otherwise the filePath of the file that is about to be deleted may be re-scheduled for deletion in addSourceForRecompilation() - myAssociatedProjectIds.forEach(new TIntProcedure() { - public boolean execute(int projectId) { - unmarkOutputPathForDeletion(projectId, filePath); - return true; - } - }); - } + pathsToMark.add(new File(file.getPath())); } }); @@ -1597,29 +223,6 @@ public class TranslatingCompilerFilesMonitor implements ApplicationComponent { processRecursively(file, false, false, new FileProcessor() { public void execute(final VirtualFile file) { pathsToMark.add(new File(file.getPath())); - final SourceFileInfo srcInfo = file.isValid()? loadSourceInfo(file) : null; - if (srcInfo != null) { - for (int projectId : srcInfo.getProjectIds().toArray()) { - if (isSuspended(projectId)) { - if (srcInfo.clearPaths(projectId)) { - srcInfo.updateTimestamp(projectId, -1L); - saveSourceInfo(file, srcInfo); - } - } - else { - addSourceForRecompilation(projectId, file, srcInfo); - // when the file is moved to a new location, we should 'forget' previous associations - if (fromMove) { - if (srcInfo.clearPaths(projectId)) { - saveSourceInfo(file, srcInfo); - } - } - } - } - } - else { - processNewFile(file, false); - } } }); if (fromMove) { @@ -1630,52 +233,10 @@ public class TranslatingCompilerFilesMonitor implements ApplicationComponent { } } - private void processNewFile(final VirtualFile file, final boolean notifyServer) { - boolean isInContent = false; - for (final Project project : myProjectManager.getOpenProjects()) { - if (!project.isInitialized()) { - continue; // the content of this project will be scanned during its post-startup activities - } - final int projectId = getProjectId(project); - final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex(); - if (fileIndex.isInContent(file)) { - isInContent = true; - } - if (isSuspended(projectId)) { - continue; - } - if (fileIndex.isInSourceContent(file)) { - final TranslatingCompiler[] translators = CompilerManager.getInstance(project).getCompilers(TranslatingCompiler.class); - processRecursively(file, false, false, new FileProcessor() { - public void execute(final VirtualFile file) { - if (isCompilable(file)) { - loadInfoAndAddSourceForRecompilation(projectId, file); - } - } - - boolean isCompilable(VirtualFile file) { - for (TranslatingCompiler translator : translators) { - if (translator.isCompilableFile(file, DummyCompileContext.getInstance())) { - return true; - } - } - return false; - } - }); - } - else { - if (belongsToIntermediateSources(file, project)) { - processRecursively(file, false, false, new FileProcessor() { - public void execute(final VirtualFile file) { - loadInfoAndAddSourceForRecompilation(projectId, file); - } - }); - } - } - } - if (notifyServer && !isIgnoredOrUnderIgnoredDirectory(file)) { + private void processNewFile(final VirtualFile file) { + if (!isIgnoredOrUnderIgnoredDirectory(file)) { // todo: avoid duplicated isInContent check final Set pathsToMark = new THashSet(FileUtil.FILE_HASHING_STRATEGY); - boolean dbOnly = !isInContent; + boolean dbOnly = !isInContentOfOpenedProject(file, false); processRecursively(file, dbOnly, false, new FileProcessor() { @Override public void execute(VirtualFile file) { @@ -1687,25 +248,14 @@ public class TranslatingCompilerFilesMonitor implements ApplicationComponent { } } - private boolean isIgnoredOrUnderIgnoredDirectory(final VirtualFile file) { - FileTypeManager fileTypeManager = FileTypeManager.getInstance(); + private static boolean isIgnoredOrUnderIgnoredDirectory(final VirtualFile file) { + final FileTypeManager fileTypeManager = FileTypeManager.getInstance(); if (fileTypeManager.isFileIgnored(file)) { return true; } //optimization: if file is in content of some project it's definitely not ignored - boolean isInContent = ApplicationManager.getApplication().runReadAction(new Computable() { - @Override - public Boolean compute() { - for (Project project : myProjectManager.getOpenProjects()) { - if (project.isInitialized() && ProjectRootManager.getInstance(project).getFileIndex().isInContent(file)) { - return true; - } - } - return false; - } - }); - if (isInContent) { + if (isInContentOfOpenedProject(file, true)) { return false; } @@ -1731,207 +281,4 @@ public class TranslatingCompilerFilesMonitor implements ApplicationComponent { } } - private boolean belongsToIntermediateSources(VirtualFile file, Project project) { - return FileUtil.isAncestor(myGeneratedDataPaths.get(project), new File(file.getPath()), true); - } - - private void loadInfoAndAddSourceForRecompilation(final int projectId, final VirtualFile srcFile) { - addSourceForRecompilation(projectId, srcFile, loadSourceInfo(srcFile)); - } - private void addSourceForRecompilation(final int projectId, final VirtualFile srcFile, @Nullable final SourceFileInfo srcInfo) { - final boolean alreadyMarked; - synchronized (myDataLock) { - TIntHashSet set = mySourcesToRecompile.get(projectId); - if (set == null) { - set = new TIntHashSet(); - mySourcesToRecompile.put(projectId, set); - } - alreadyMarked = !set.add(Math.abs(getFileId(srcFile))); - if (!alreadyMarked && (LOG.isDebugEnabled() || ourDebugMode)) { - final String message = "Scheduled recompilation " + srcFile.getPresentableUrl(); - LOG.debug(message); - if (ourDebugMode) { - System.out.println(message); - } - } - } - - if (!alreadyMarked && srcInfo != null) { - srcInfo.updateTimestamp(projectId, -1L); - srcInfo.processOutputPaths(projectId, new ScheduleOutputsForDeletionProc(srcFile.getUrl())); - saveSourceInfo(srcFile, srcInfo); - } - } - - private void removeSourceForRecompilation(final int projectId, final int srcId) { - synchronized (myDataLock) { - TIntHashSet set = mySourcesToRecompile.get(projectId); - if (set != null) { - set.remove(srcId); - if (set.isEmpty()) { - mySourcesToRecompile.remove(projectId); - } - } - } - } - - public boolean isMarkedForCompilation(Project project, VirtualFile file) { - if (CompilerWorkspaceConfiguration.getInstance(project).useOutOfProcessBuild()) { - final CompilerManager compilerManager = CompilerManager.getInstance(project); - return !compilerManager.isUpToDate(compilerManager.createFilesCompileScope(new VirtualFile[]{file})); - } - return isMarkedForRecompilation(getProjectId(project), getFileId(file)); - } - - private boolean isMarkedForRecompilation(int projectId, final int srcId) { - synchronized (myDataLock) { - final TIntHashSet set = mySourcesToRecompile.get(projectId); - return set != null && set.contains(srcId); - } - } - - private interface Proc { - boolean execute(final int projectId, String outputPath); - } - - private class ScheduleOutputsForDeletionProc implements Proc { - private final String mySrcUrl; - private final LocalFileSystem myFileSystem; - @Nullable - private VirtualFile myRootBeingDeleted; - - private ScheduleOutputsForDeletionProc(final String srcUrl) { - mySrcUrl = srcUrl; - myFileSystem = LocalFileSystem.getInstance(); - } - - public void setRootBeingDeleted(@Nullable VirtualFile rootBeingDeleted) { - myRootBeingDeleted = rootBeingDeleted; - } - - public boolean execute(final int projectId, String outputPath) { - final VirtualFile outFile = myFileSystem.findFileByPath(outputPath); - if (outFile != null) { // not deleted yet - if (myRootBeingDeleted != null && VfsUtil.isAncestor(myRootBeingDeleted, outFile, false)) { - unmarkOutputPathForDeletion(projectId, outputPath); - } - else { - final OutputFileInfo outputInfo = loadOutputInfo(outFile); - final String classname = outputInfo != null? outputInfo.getClassName() : null; - markOutputPathForDeletion(projectId, outputPath, classname, mySrcUrl); - } - } - return true; - } - } - - private void markOutputPathForDeletion(final int projectId, final String outputPath, final String classname, final String srcUrl) { - final SourceUrlClassNamePair pair = new SourceUrlClassNamePair(srcUrl, classname); - synchronized (myDataLock) { - final Outputs outputs = myOutputsToDelete.get(projectId); - try { - outputs.put(outputPath, pair); - if (LOG.isDebugEnabled() || ourDebugMode) { - final String message = "ADD path to delete: " + outputPath + "; source: " + srcUrl; - LOG.debug(message); - if (ourDebugMode) { - System.out.println(message); - } - } - } - finally { - outputs.release(); - } - } - } - - private void unmarkOutputPathForDeletion(final int projectId, String outputPath) { - synchronized (myDataLock) { - final Outputs outputs = myOutputsToDelete.get(projectId); - try { - final SourceUrlClassNamePair val = outputs.remove(outputPath); - if (val != null) { - if (LOG.isDebugEnabled() || ourDebugMode) { - final String message = "REMOVE path to delete: " + outputPath; - LOG.debug(message); - if (ourDebugMode) { - System.out.println(message); - } - } - } - } - finally { - outputs.release(); - } - } - } - - public static final class ProjectRef extends Ref { - static class ProjectClosedException extends RuntimeException { - } - - public ProjectRef(Project project) { - super(project); - } - - public Project get() { - final Project project = super.get(); - if (project != null && project.isDisposed()) { - throw new ProjectClosedException(); - } - return project; - } - } - - private static class Outputs { - private boolean myIsDirty = false; - @Nullable - private final File myStoreFile; - private final Map myMap; - private final AtomicInteger myRefCount = new AtomicInteger(1); - - Outputs(@Nullable File storeFile, Map map) { - myStoreFile = storeFile; - myMap = map; - } - - public Set> getEntries() { - return Collections.unmodifiableSet(myMap.entrySet()); - } - - public void put(String outputPath, SourceUrlClassNamePair pair) { - if (myStoreFile == null) { - return; - } - if (pair == null) { - remove(outputPath); - } - else { - myMap.put(outputPath, pair); - myIsDirty = true; - } - } - - public SourceUrlClassNamePair remove(String outputPath) { - if (myStoreFile == null) { - return null; - } - final SourceUrlClassNamePair removed = myMap.remove(outputPath); - myIsDirty |= removed != null; - return removed; - } - - void allocate() { - myRefCount.incrementAndGet(); - } - - public void release() { - if (myRefCount.decrementAndGet() == 0) { - if (myIsDirty && myStoreFile != null) { - savePathsToDelete(myStoreFile, myMap); - } - } - } - } - } diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/AnnotationProcessingCompiler.java b/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/AnnotationProcessingCompiler.java deleted file mode 100644 index c7269a47eec1..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/AnnotationProcessingCompiler.java +++ /dev/null @@ -1,151 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * @author: Eugene Zhuravlev - * Date: Jan 17, 2003 - * Time: 3:22:59 PM - */ -package com.intellij.compiler.impl.javaCompiler; - -import com.intellij.compiler.CompilerConfiguration; -import com.intellij.compiler.CompilerConfigurationImpl; -import com.intellij.compiler.CompilerException; -import com.intellij.compiler.impl.CompileContextExProxy; -import com.intellij.compiler.impl.javaCompiler.javac.JavacCompiler; -import com.intellij.compiler.make.CacheCorruptedException; -import com.intellij.openapi.application.ApplicationManager; -import com.intellij.openapi.compiler.*; -import com.intellij.openapi.compiler.ex.CompileContextEx; -import com.intellij.openapi.diagnostic.Logger; -import com.intellij.openapi.fileTypes.StdFileTypes; -import com.intellij.openapi.module.Module; -import com.intellij.openapi.project.Project; -import com.intellij.openapi.vfs.LocalFileSystem; -import com.intellij.openapi.vfs.VfsUtil; -import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.util.Chunk; -import org.jetbrains.annotations.NotNull; - -import java.util.Arrays; -import java.util.HashSet; -import java.util.Set; - -public class AnnotationProcessingCompiler implements TranslatingCompiler{ - private static final Logger LOG = Logger.getInstance("#com.intellij.compiler.impl.javaCompiler.JavaCompiler"); - private final Project myProject; - private final CompilerConfiguration myConfig; - - public AnnotationProcessingCompiler(Project project) { - myProject = project; - myConfig = CompilerConfiguration.getInstance(project); - } - - @NotNull - public String getDescription() { - return CompilerBundle.message("annotation.processing.compiler.description"); - } - - public boolean isCompilableFile(VirtualFile file, CompileContext context) { - if (!context.isAnnotationProcessorsEnabled()) { - return false; - } - return file.getFileType() == StdFileTypes.JAVA && !isExcludedFromAnnotationProcessing(file, context); - } - - public void compile(final CompileContext context, final Chunk moduleChunk, final VirtualFile[] files, OutputSink sink) { - if (!context.isAnnotationProcessorsEnabled()) { - return; - } - final LocalFileSystem lfs = LocalFileSystem.getInstance(); - final CompileContextEx _context = new CompileContextExProxy((CompileContextEx)context) { - public VirtualFile getModuleOutputDirectory(Module module) { - final String path = CompilerPaths.getAnnotationProcessorsGenerationPath(module); - return path != null? lfs.findFileByPath(path) : null; - } - - public VirtualFile getModuleOutputDirectoryForTests(Module module) { - return getModuleOutputDirectory(module); - } - }; - final JavacCompiler javacCompiler = getBackEndCompiler(); - final boolean processorMode = javacCompiler.setAnnotationProcessorMode(true); - final BackendCompilerWrapper wrapper = new BackendCompilerWrapper(moduleChunk, myProject, Arrays.asList(files), _context, javacCompiler, sink); - wrapper.setForceCompileTestsSeparately(true); - try { - wrapper.compile(); - } - catch (CompilerException e) { - _context.addMessage(CompilerMessageCategory.ERROR, e.getMessage(), null, -1, -1); - } - catch (CacheCorruptedException e) { - LOG.info(e); - _context.requestRebuildNextTime(e.getMessage()); - } - finally { - javacCompiler.setAnnotationProcessorMode(processorMode); - final Set dirsToRefresh = new HashSet(); - ApplicationManager.getApplication().runReadAction(new Runnable() { - public void run() { - for (Module module : moduleChunk.getNodes()) { - final VirtualFile out = _context.getModuleOutputDirectory(module); - if (out != null) { - dirsToRefresh.add(out); - } - } - } - }); - for (VirtualFile root : dirsToRefresh) { - root.refresh(false, true); - } - } - } - - private boolean isExcludedFromAnnotationProcessing(VirtualFile file, CompileContext context) { - if (!context.isAnnotationProcessorsEnabled()) { - return true; - } - final Module module = context.getModuleByFile(file); - if (module != null) { - if (!myConfig.getAnnotationProcessingConfiguration(module).isEnabled()) { - return true; - } - final String path = CompilerPaths.getAnnotationProcessorsGenerationPath(module); - final VirtualFile generationDir = path != null? LocalFileSystem.getInstance().findFileByPath(path) : null; - if (generationDir != null && VfsUtil.isAncestor(generationDir, file, false)) { - return true; - } - } - return myConfig.isExcludedFromCompilation(file); - } - - public boolean validateConfiguration(CompileScope scope) { - final JavacCompiler compiler = getBackEndCompiler(); - final boolean previousValue = compiler.setAnnotationProcessorMode(true); - try { - return compiler.checkCompiler(scope); - } - finally { - compiler.setAnnotationProcessorMode(previousValue); - } - } - - private JavacCompiler getBackEndCompiler() { - CompilerConfigurationImpl configuration = (CompilerConfigurationImpl)myConfig; - return configuration.getJavacCompiler(); - } - -} diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/BackendCompiler.java b/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/BackendCompiler.java index 9da4a3952baf..5c20791837ad 100644 --- a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/BackendCompiler.java +++ b/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/BackendCompiler.java @@ -15,36 +15,26 @@ */ package com.intellij.compiler.impl.javaCompiler; -import com.intellij.compiler.OutputParser; -import com.intellij.openapi.compiler.CompileContext; -import com.intellij.openapi.compiler.CompileScope; import com.intellij.openapi.extensions.ExtensionPointName; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.options.Configurable; -import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import java.io.IOException; import java.util.Set; public interface BackendCompiler { ExtensionPointName EP_NAME = ExtensionPointName.create("com.intellij.java.compiler"); - @NotNull @NonNls String getId(); // used for externalization - @NotNull String getPresentableName(); - @NotNull Configurable createConfigurable(); - @NotNull Set getCompilableFileTypes(); - @Nullable OutputParser createErrorParser(@NotNull String outputDir, Process process); - @Nullable OutputParser createOutputParser(@NotNull String outputDir); - - boolean checkCompiler(final CompileScope scope); - - @NotNull Process launchProcess( - @NotNull ModuleChunk chunk, - @NotNull String outputDir, - @NotNull CompileContext compileContext) throws IOException; - - void compileFinished(); - + @NotNull + String getId(); // used for externalization + + @NotNull + String getPresentableName(); + + @NotNull + Configurable createConfigurable(); + + @NotNull + Set getCompilableFileTypes(); + } diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/BackendCompilerWrapper.java b/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/BackendCompilerWrapper.java deleted file mode 100644 index e845d03ac837..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/BackendCompilerWrapper.java +++ /dev/null @@ -1,1015 +0,0 @@ -/* - * Copyright 2000-2014 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.compiler.impl.javaCompiler; - -import com.intellij.codeInsight.NullableNotNullManager; -import com.intellij.compiler.*; -import com.intellij.compiler.classParsing.AnnotationConstantValue; -import com.intellij.compiler.classParsing.MethodInfo; -import com.intellij.compiler.impl.CompileDriver; -import com.intellij.compiler.impl.CompilerUtil; -import com.intellij.compiler.make.Cache; -import com.intellij.compiler.make.CacheCorruptedException; -import com.intellij.compiler.make.DependencyCache; -import com.intellij.compiler.make.MakeUtil; -import com.intellij.compiler.notNullVerification.NotNullVerifyingInstrumenter; -import com.intellij.ide.util.projectWizard.JavaModuleBuilder; -import com.intellij.openapi.application.Application; -import com.intellij.openapi.application.ApplicationManager; -import com.intellij.openapi.compiler.*; -import com.intellij.openapi.compiler.ex.CompileContextEx; -import com.intellij.openapi.diagnostic.Logger; -import com.intellij.openapi.fileTypes.FileTypeManager; -import com.intellij.openapi.module.JavaModuleType; -import com.intellij.openapi.module.Module; -import com.intellij.openapi.module.ModuleType; -import com.intellij.openapi.project.Project; -import com.intellij.openapi.projectRoots.JavaSdk; -import com.intellij.openapi.projectRoots.JavaSdkType; -import com.intellij.openapi.projectRoots.JavaSdkVersion; -import com.intellij.openapi.projectRoots.Sdk; -import com.intellij.openapi.roots.*; -import com.intellij.openapi.util.*; -import com.intellij.openapi.util.io.FileUtil; -import com.intellij.openapi.util.text.StringUtil; -import com.intellij.openapi.vfs.LocalFileSystem; -import com.intellij.openapi.vfs.VfsUtilCore; -import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.openapi.vfs.VirtualFileVisitor; -import com.intellij.psi.JavaPsiFacade; -import com.intellij.psi.PsiClass; -import com.intellij.psi.search.GlobalSearchScope; -import com.intellij.psi.search.GlobalSearchScopes; -import com.intellij.util.Chunk; -import com.intellij.util.cls.ClsFormatException; -import gnu.trove.THashMap; -import org.jetbrains.annotations.NonNls; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import org.jetbrains.asm4.ClassReader; -import org.jetbrains.asm4.ClassWriter; - -import java.io.File; -import java.io.IOException; -import java.nio.charset.Charset; -import java.util.*; -import java.util.concurrent.ArrayBlockingQueue; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Future; - -/** - * @author Eugene Zhuravlev - * @since Jan 24, 2003 - */ -public class BackendCompilerWrapper { - private static final Logger LOG = Logger.getInstance("#com.intellij.compiler.impl.javaCompiler.BackendCompilerWrapper"); - - private final BackendCompiler myCompiler; - - private final CompileContextEx myCompileContext; - private final List myFilesToCompile; - private final TranslatingCompiler.OutputSink mySink; - private final Chunk myChunk; - private final Project myProject; - private final Map myModuleToTempDirMap = new THashMap(); - private final ProjectFileIndex myProjectFileIndex; - @NonNls private static final String PACKAGE_ANNOTATION_FILE_NAME = "package-info.java"; - private static final FileObject myStopThreadToken = new FileObject(new File(""), new byte[0]); - public final Map> myFileNameToSourceMap= new THashMap>(); - private final Set myProcessedPackageInfos = new HashSet(); - private final CompileStatistics myStatistics; - private volatile String myModuleName = null; - private boolean myForceCompileTestsSeparately = false; - - public BackendCompilerWrapper(Chunk chunk, @NotNull final Project project, - @NotNull List filesToCompile, - @NotNull CompileContextEx compileContext, - @NotNull BackendCompiler compiler, TranslatingCompiler.OutputSink sink) { - myChunk = chunk; - myProject = project; - myCompiler = compiler; - myCompileContext = compileContext; - myFilesToCompile = filesToCompile; - mySink = sink; - myProjectFileIndex = ProjectRootManager.getInstance(myProject).getFileIndex(); - CompileStatistics stat = compileContext.getUserData(CompileStatistics.KEY); - if (stat == null) { - stat = new CompileStatistics(); - compileContext.putUserData(CompileStatistics.KEY, stat); - } - myStatistics = stat; - } - - public void compile() throws CompilerException, CacheCorruptedException { - Application application = ApplicationManager.getApplication(); - try { - if (!myFilesToCompile.isEmpty()) { - if (application.isUnitTestMode()) { - saveTestData(); - } - compileModules(buildModuleToFilesMap(myFilesToCompile)); - } - } - catch (SecurityException e) { - throw new CompilerException(CompilerBundle.message("error.compiler.process.not.started", e.getMessage()), e); - } - catch (IllegalArgumentException e) { - throw new CompilerException(e.getMessage(), e); - } - finally { - for (final VirtualFile file : myModuleToTempDirMap.values()) { - if (file != null) { - final File ioFile = new File(file.getPath()); - FileUtil.asyncDelete(ioFile); - } - } - myModuleToTempDirMap.clear(); - } - - if (!myFilesToCompile.isEmpty() && myCompileContext.getMessageCount(CompilerMessageCategory.ERROR) == 0) { - // package-info.java hack - final List outputs = new ArrayList(); - ApplicationManager.getApplication().runReadAction(new Runnable() { - public void run() { - for (final VirtualFile file : myFilesToCompile) { - if (PACKAGE_ANNOTATION_FILE_NAME.equals(file.getName()) && !myProcessedPackageInfos.contains(file)) { - outputs.add(new OutputItemImpl(file)); - } - } - } - }); - if (!outputs.isEmpty()) { - mySink.add(null, outputs, VirtualFile.EMPTY_ARRAY); - } - } - } - - public boolean isForceCompileTestsSeparately() { - return myForceCompileTestsSeparately; - } - - public void setForceCompileTestsSeparately(boolean forceCompileTestsSeparately) { - myForceCompileTestsSeparately = forceCompileTestsSeparately; - } - - private Map> buildModuleToFilesMap(final List filesToCompile) { - if (myChunk.getNodes().size() == 1) { - return Collections.singletonMap(myChunk.getNodes().iterator().next(), Collections.unmodifiableList(filesToCompile)); - } - return CompilerUtil.buildModuleToFilesMap(myCompileContext, filesToCompile); - } - - private void compileModules(final Map> moduleToFilesMap) throws CompilerException { - try { - compileChunk(new ModuleChunk(myCompileContext, myChunk, moduleToFilesMap)); - } - catch (IOException e) { - throw new CompilerException(e.getMessage(), e); - } - } - - private void compileChunk(ModuleChunk chunk) throws IOException { - final String chunkPresentableName = getPresentableNameFor(chunk); - myModuleName = chunkPresentableName; - - // validate encodings - if (chunk.getModuleCount() > 1) { - validateEncoding(chunk, chunkPresentableName); - // todo: validation for bytecode target? - } - - runTransformingCompilers(chunk); - - - final List outs = new ArrayList(); - File fileToDelete = getOutputDirsToCompileTo(chunk, outs); - - try { - for (final OutputDir outputDir : outs) { - chunk.setSourcesFilter(outputDir.getKind()); - doCompile(chunk, outputDir.getPath()); - } - } - finally { - if (fileToDelete != null) { - FileUtil.asyncDelete(fileToDelete); - } - } - } - - private void validateEncoding(ModuleChunk chunk, String chunkPresentableName) { - final CompilerEncodingService es = CompilerEncodingService.getInstance(myProject); - Charset charset = null; - for (Module module : chunk.getModules()) { - final Charset moduleCharset = es.getPreferredModuleEncoding(module); - if (charset == null) { - charset = moduleCharset; - } - else { - if (!Comparing.equal(charset, moduleCharset)) { - // warn user - final Charset chunkEncoding = CompilerEncodingService.getPreferredModuleEncoding(chunk); - final StringBuilder message = new StringBuilder(); - message.append("Modules in chunk ["); - message.append(chunkPresentableName); - message.append("] configured to use different encodings.\n"); - if (chunkEncoding != null) { - message.append("\"").append(chunkEncoding.name()).append("\" encoding will be used to compile the chunk"); - } - else { - message.append("Default compiler encoding will be used to compile the chunk"); - } - myCompileContext.addMessage(CompilerMessageCategory.INFORMATION, message.toString(), null, -1, -1); - break; - } - } - } - } - - - private static String getPresentableNameFor(final ModuleChunk chunk) { - return ApplicationManager.getApplication().runReadAction(new Computable() { - public String compute() { - final Module[] modules = chunk.getModules(); - StringBuilder moduleName = new StringBuilder(Math.min(128, modules.length * 8)); - for (int idx = 0; idx < modules.length; idx++) { - final Module module = modules[idx]; - if (idx > 0) { - moduleName.append(", "); - } - moduleName.append(module.getName()); - if (moduleName.length() > 128 && idx + 1 < modules.length /*name is already too long and seems to grow longer*/) { - moduleName.append("..."); - break; - } - } - return moduleName.toString(); - } - }); - } - - @Nullable - private File getOutputDirsToCompileTo(ModuleChunk chunk, final List dirs) throws IOException { - File fileToDelete = null; - if (chunk.getModuleCount() == 1) { // optimization - final Module module = chunk.getModules()[0]; - ApplicationManager.getApplication().runReadAction(new Runnable() { - public void run() { - final String sourcesOutputDir = getOutputDir(module); - if (shouldCompileTestsSeparately(module)) { - if (sourcesOutputDir != null) { - dirs.add(new OutputDir(sourcesOutputDir, ModuleChunk.SOURCES)); - } - final String testsOutputDir = getTestsOutputDir(module); - if (testsOutputDir == null) { - LOG.error("Tests output dir is null for module \"" + module.getName() + "\""); - } - else { - dirs.add(new OutputDir(testsOutputDir, ModuleChunk.TEST_SOURCES)); - } - } - else { // both sources and test sources go into the same output - if (sourcesOutputDir == null) { - LOG.error("Sources output dir is null for module \"" + module.getName() + "\""); - } - else { - dirs.add(new OutputDir(sourcesOutputDir, ModuleChunk.ALL_SOURCES)); - } - } - } - }); - } - else { // chunk has several modules - final File outputDir = FileUtil.createTempDirectory("compile", "output"); - fileToDelete = outputDir; - dirs.add(new OutputDir(outputDir.getPath(), ModuleChunk.ALL_SOURCES)); - } - return fileToDelete; - } - - - private boolean shouldCompileTestsSeparately(Module module) { - if (myForceCompileTestsSeparately) { - return true; - } - final String moduleTestOutputDirectory = getTestsOutputDir(module); - if (moduleTestOutputDirectory == null) { - return false; - } - // here we have test output specified - final String moduleOutputDirectory = getOutputDir(module); - if (moduleOutputDirectory == null) { - // only test output is specified, so should return true - return true; - } - return !FileUtil.pathsEqual(moduleTestOutputDirectory, moduleOutputDirectory); - } - - private void saveTestData() { - ApplicationManager.getApplication().runReadAction(new Runnable() { - public void run() { - for (VirtualFile file : myFilesToCompile) { - CompilerManagerImpl.addCompiledPath(file.getPath()); - } - } - }); - } - - private final Object lock = new Object(); - - private class SynchedCompilerParsing extends CompilerParsingThread { - private final ClassParsingThread myClassParsingThread; - - private SynchedCompilerParsing(Process process, - final CompileContext context, - OutputParser outputParser, - ClassParsingThread classParsingThread, - boolean readErrorStream, - boolean trimLines) { - super(process, outputParser, readErrorStream, trimLines,context); - myClassParsingThread = classParsingThread; - } - - public void setProgressText(String text) { - synchronized (lock) { - super.setProgressText(text); - } - } - - public void message(CompilerMessageCategory category, String message, String url, int lineNum, int columnNum) { - synchronized (lock) { - super.message(category, message, url, lineNum, columnNum); - } - } - - public void fileProcessed(String path) { - synchronized (lock) { - sourceFileProcessed(); - } - } - - protected void processCompiledClass(final FileObject classFileToProcess) throws CacheCorruptedException { - synchronized (lock) { - myClassParsingThread.addPath(classFileToProcess); - } - } - } - - private void doCompile(@NotNull final ModuleChunk chunk, @NotNull String outputDir) throws IOException { - myCompileContext.getProgressIndicator().checkCanceled(); - - if (ApplicationManager.getApplication().runReadAction(new Computable() { - public Boolean compute() { - return chunk.getFilesToCompile().isEmpty() ? Boolean.TRUE : Boolean.FALSE; - } - }).booleanValue()) { - return; // should not invoke javac with empty sources list - } - - ModuleType moduleType = ModuleType.get(chunk.getModules()[0]); - if ((chunk.getJdk() == null || !(chunk.getJdk().getSdkType() instanceof JavaSdkType)) && - !(moduleType instanceof JavaModuleType || moduleType.createModuleBuilder() instanceof JavaModuleBuilder)) { - // TODO - // don't try to compile non-java type module - return; - } - - int exitValue = 0; - try { - final Process process = myCompiler.launchProcess(chunk, outputDir, myCompileContext); - final long compilationStart = System.currentTimeMillis(); - final ClassParsingThread classParsingThread = new ClassParsingThread(isJdk6(chunk.getJdk()), outputDir); - final Future classParsingThreadFuture = ApplicationManager.getApplication().executeOnPooledThread(classParsingThread); - - OutputParser errorParser = myCompiler.createErrorParser(outputDir, process); - CompilerParsingThread errorParsingThread = errorParser == null - ? null - : new SynchedCompilerParsing(process, myCompileContext, errorParser, classParsingThread, - true, errorParser.isTrimLines()); - Future errorParsingThreadFuture = null; - if (errorParsingThread != null) { - errorParsingThreadFuture = ApplicationManager.getApplication().executeOnPooledThread(errorParsingThread); - } - - OutputParser outputParser = myCompiler.createOutputParser(outputDir); - CompilerParsingThread outputParsingThread = outputParser == null - ? null - : new SynchedCompilerParsing(process, myCompileContext, outputParser, classParsingThread, - false, outputParser.isTrimLines()); - Future outputParsingThreadFuture = null; - if (outputParsingThread != null) { - outputParsingThreadFuture = ApplicationManager.getApplication().executeOnPooledThread(outputParsingThread); - } - - try { - exitValue = process.waitFor(); - } - catch (InterruptedException e) { - process.destroy(); - exitValue = process.exitValue(); - } - catch (Error e) { - process.destroy(); - exitValue = process.exitValue(); - throw e; - } - finally { - if (CompileDriver.ourDebugMode) { - System.out.println("Compiler exit code is " + exitValue); - } - if (errorParsingThread != null) { - errorParsingThread.setProcessTerminated(true); - } - if (outputParsingThread != null) { - outputParsingThread.setProcessTerminated(true); - } - joinThread(errorParsingThreadFuture); - joinThread(outputParsingThreadFuture); - classParsingThread.stopParsing(); - joinThread(classParsingThreadFuture); - - registerParsingException(outputParsingThread); - registerParsingException(errorParsingThread); - assert outputParsingThread == null || !outputParsingThread.processing; - assert errorParsingThread == null || !errorParsingThread.processing; - assert classParsingThread == null || !classParsingThread.processing; - } - } - finally { - compileFinished(exitValue, chunk, outputDir); - myModuleName = null; - } - } - - private static void joinThread(final Future threadFuture) { - if (threadFuture != null) { - try { - threadFuture.get(); - } - catch (InterruptedException ignored) { - LOG.info("Thread interrupted", ignored); - } - catch (ExecutionException ignored) { - LOG.info("Thread interrupted", ignored); - } - } - } - - private void registerParsingException(final CompilerParsingThread outputParsingThread) { - Throwable error = outputParsingThread == null ? null : outputParsingThread.getError(); - if (error != null) { - String message = error.getMessage(); - if (error instanceof CacheCorruptedException) { - myCompileContext.requestRebuildNextTime(message); - } - else { - myCompileContext.addMessage(CompilerMessageCategory.ERROR, message, null, -1, -1); - } - } - } - - private void runTransformingCompilers(final ModuleChunk chunk) { - final JavaSourceTransformingCompiler[] transformers = - CompilerManager.getInstance(myProject).getCompilers(JavaSourceTransformingCompiler.class); - if (transformers.length == 0) { - return; - } - if (LOG.isDebugEnabled()) { - LOG.debug("Running transforming compilers..."); - } - final Module[] modules = chunk.getModules(); - for (final JavaSourceTransformingCompiler transformer : transformers) { - final Map originalToCopyFileMap = new HashMap(); - final Application application = ApplicationManager.getApplication(); - application.invokeAndWait(new Runnable() { - public void run() { - for (final Module module : modules) { - for (final VirtualFile file : chunk.getFilesToCompile(module)) { - final VirtualFile untransformed = chunk.getOriginalFile(file); - if (transformer.isTransformable(untransformed)) { - application.runWriteAction(new Runnable() { - public void run() { - try { - // if untransformed != file, the file is already a (possibly transformed) copy of the original 'untransformed' file. - // If this is the case, just use already created copy and do not copy file content once again - final VirtualFile fileCopy = untransformed.equals(file)? createFileCopy(getTempDir(module), file) : file; - originalToCopyFileMap.put(file, fileCopy); - } - catch (IOException e) { - // skip it - } - } - }); - } - } - } - } - }, myCompileContext.getProgressIndicator().getModalityState()); - - // do actual transform - for (final Module module : modules) { - final List filesToCompile = chunk.getFilesToCompile(module); - for (int j = 0; j < filesToCompile.size(); j++) { - final VirtualFile file = filesToCompile.get(j); - final VirtualFile fileCopy = originalToCopyFileMap.get(file); - if (fileCopy != null) { - final boolean ok = transformer.transform(myCompileContext, fileCopy, chunk.getOriginalFile(file)); - if (ok) { - chunk.substituteWithTransformedVersion(module, j, fileCopy); - } - } - } - } - } - } - - private VirtualFile createFileCopy(VirtualFile tempDir, final VirtualFile file) throws IOException { - final String fileName = file.getName(); - if (tempDir.findChild(fileName) != null) { - int idx = 0; - while (true) { - //noinspection HardCodedStringLiteral - final String dirName = "dir" + idx++; - final VirtualFile dir = tempDir.findChild(dirName); - if (dir == null) { - tempDir = tempDir.createChildDirectory(this, dirName); - break; - } - if (dir.findChild(fileName) == null) { - tempDir = dir; - break; - } - } - } - return VfsUtilCore.copyFile(this, file, tempDir); - } - - private VirtualFile getTempDir(Module module) throws IOException { - VirtualFile tempDir = myModuleToTempDirMap.get(module); - if (tempDir == null) { - final String projectName = myProject.getName(); - final String moduleName = module.getName(); - File tempDirectory = FileUtil.createTempDirectory(projectName, moduleName); - tempDir = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(tempDirectory); - if (tempDir == null) { - LOG.error("Cannot locate temp directory " + tempDirectory.getPath()); - } - myModuleToTempDirMap.put(module, tempDir); - } - return tempDir; - } - - private void compileFinished(int exitValue, final ModuleChunk chunk, final String outputDir) { - if (exitValue != 0 && !myCompileContext.getProgressIndicator().isCanceled() && myCompileContext.getMessageCount(CompilerMessageCategory.ERROR) == 0) { - myCompileContext.addMessage(CompilerMessageCategory.ERROR, CompilerBundle.message("error.compiler.internal.error", exitValue), null, -1, -1); - } - - myCompiler.compileFinished(); - final List toRefresh = new ArrayList(); - final Map> results = new HashMap>(); - try { - final FileTypeManager typeManager = FileTypeManager.getInstance(); - final String outputDirPath = outputDir.replace(File.separatorChar, '/'); - try { - for (final Module module : chunk.getModules()) { - for (final VirtualFile root : chunk.getSourceRoots(module)) { - final String packagePrefix = myProjectFileIndex.getPackageNameByDirectory(root); - if (LOG.isDebugEnabled()) { - LOG.debug("Building output items for " + root.getPresentableUrl() + "; output dir = " + outputDirPath + "; packagePrefix = \"" + packagePrefix + "\""); - } - buildOutputItemsList(outputDirPath, module, root, typeManager, root, packagePrefix, toRefresh, results); - } - } - } - catch (CacheCorruptedException e) { - myCompileContext.requestRebuildNextTime(CompilerBundle.message("error.compiler.caches.corrupted")); - if (LOG.isDebugEnabled()) { - LOG.debug(e); - } - } - } - finally { - CompilerUtil.refreshIOFiles(toRefresh); - for (Iterator>> it = results.entrySet().iterator(); it.hasNext();) { - Map.Entry> entry = it.next(); - mySink.add(entry.getKey(), entry.getValue(), VirtualFile.EMPTY_ARRAY); - it.remove(); // to free memory - } - } - myFileNameToSourceMap.clear(); // clear the map before the next use - } - - private void buildOutputItemsList(final String outputDir, final Module module, VirtualFile from, - final FileTypeManager typeManager, - final VirtualFile sourceRoot, - final String packagePrefix, final List filesToRefresh, final Map> results) throws CacheCorruptedException { - final Ref exRef = new Ref(null); - final ModuleFileIndex fileIndex = ModuleRootManager.getInstance(module).getFileIndex(); - final GlobalSearchScope srcRootScope = GlobalSearchScope.moduleScope(module).intersectWith( - GlobalSearchScopes.directoryScope(myProject, sourceRoot, true)); - - final ContentIterator contentIterator = new ContentIterator() { - public boolean processFile(final VirtualFile child) { - try { - if (child.isValid()) { - if (!child.isDirectory() && myCompiler.getCompilableFileTypes().contains(child.getFileType())) { - updateOutputItemsList(outputDir, child, sourceRoot, packagePrefix, filesToRefresh, results, srcRootScope); - } - } - return true; - } - catch (CacheCorruptedException e) { - exRef.set(e); - return false; - } - } - }; - if (fileIndex.isInContent(from)) { - // use file index for iteration to handle 'inner modules' and excludes properly - fileIndex.iterateContentUnderDirectory(from, contentIterator); - } - else { - // seems to be a root for generated sources - VfsUtilCore.visitChildrenRecursively(from, new VirtualFileVisitor() { - @Override - public boolean visitFile(@NotNull VirtualFile file) { - if (!file.isDirectory()) { - contentIterator.processFile(file); - } - return true; - } - }); - } - final CacheCorruptedException exc = exRef.get(); - if (exc != null) { - throw exc; - } - } - - private void putName(String sourceFileName, int classQName, String relativePathToSource, String pathToClass) { - if (LOG.isDebugEnabled()) { - LOG.debug("Registering [sourceFileName, relativePathToSource, pathToClass] = [" + sourceFileName + "; " + relativePathToSource + - "; " + pathToClass + "]"); - } - Set paths = myFileNameToSourceMap.get(sourceFileName); - - if (paths == null) { - paths = new HashSet(); - myFileNameToSourceMap.put(sourceFileName, paths); - } - paths.add(new CompiledClass(classQName, relativePathToSource, pathToClass)); - } - - private void updateOutputItemsList(final String outputDir, final VirtualFile srcFile, - VirtualFile sourceRoot, - final String packagePrefix, final List filesToRefresh, - Map> results, - final GlobalSearchScope srcRootScope) throws CacheCorruptedException { - final Cache newCache = myCompileContext.getDependencyCache().getNewClassesCache(); - final Set paths = myFileNameToSourceMap.get(srcFile.getName()); - if (paths == null || paths.isEmpty()) { - return; - } - final String filePath = "/" + calcPackagePath(srcFile, sourceRoot, packagePrefix); - for (final CompiledClass cc : paths) { - myCompileContext.getProgressIndicator().checkCanceled(); - if (LOG.isDebugEnabled()) { - LOG.debug("Checking [pathToClass; relPathToSource] = " + cc); - } - - boolean pathsEquals = FileUtil.pathsEqual(filePath, cc.relativePathToSource); - if (!pathsEquals) { - final String qName = myCompileContext.getDependencyCache().resolve(cc.qName); - if (qName != null) { - pathsEquals = ApplicationManager.getApplication().runReadAction(new Computable() { - public Boolean compute() { - final JavaPsiFacade facade = JavaPsiFacade.getInstance(myProject); - PsiClass psiClass = facade.findClass(qName, srcRootScope); - if (psiClass == null) { - final int dollarIndex = qName.indexOf("$"); - if (dollarIndex >= 0) { - final String topLevelClassName = qName.substring(0, dollarIndex); - psiClass = facade.findClass(topLevelClassName, srcRootScope); - } - } - if (psiClass != null) { - final VirtualFile vFile = psiClass.getContainingFile().getVirtualFile(); - return vFile != null && vFile.equals(srcFile); - } - return false; - } - }); - } - } - - if (pathsEquals) { - final String outputPath = cc.pathToClass.replace(File.separatorChar, '/'); - final Couple realLocation = moveToRealLocation(outputDir, outputPath, srcFile, filesToRefresh); - if (realLocation != null) { - Collection outputs = results.get(realLocation.getFirst()); - if (outputs == null) { - outputs = new ArrayList(); - results.put(realLocation.getFirst(), outputs); - } - outputs.add(new OutputItemImpl(realLocation.getSecond(), srcFile)); - if (PACKAGE_ANNOTATION_FILE_NAME.equals(srcFile.getName())) { - myProcessedPackageInfos.add(srcFile); - } - if (CompilerConfiguration.MAKE_ENABLED) { - newCache.setPath(cc.qName, realLocation.getSecond()); - } - if (LOG.isDebugEnabled()) { - LOG.debug("Added output item: [outputDir; outputPath; sourceFile] = [" + realLocation.getFirst() + "; " + - realLocation.getSecond() + "; " + srcFile.getPresentableUrl() + "]"); - } - } - else { - myCompileContext.addMessage(CompilerMessageCategory.ERROR, "Failed to copy from temporary location to output directory: " + outputPath + " (see idea.log for details)", null, -1, -1); - if (LOG.isDebugEnabled()) { - LOG.debug("Failed to move to real location: " + outputPath + "; from " + outputDir); - } - } - } - } - } - - /** - * - * @param srcFile - * @param sourceRoot - * @param packagePrefix - * @return A 'package'-path to a given src file relative to a specified root. "/" slashes must be used - */ - protected static String calcPackagePath(VirtualFile srcFile, VirtualFile sourceRoot, String packagePrefix) { - final String prefix = packagePrefix != null && packagePrefix.length() > 0 ? packagePrefix.replace('.', '/') + "/" : ""; - return prefix + VfsUtilCore.getRelativePath(srcFile, sourceRoot, '/'); - } - - @Nullable - private Couple moveToRealLocation(String tempOutputDir, - String pathToClass, - VirtualFile sourceFile, - final List filesToRefresh) { - final Module module = myCompileContext.getModuleByFile(sourceFile); - if (module == null) { - final String message = - "Cannot determine module for source file: " + sourceFile.getPresentableUrl() + ";\nCorresponding output file: " + pathToClass; - LOG.info(message); - myCompileContext.addMessage(CompilerMessageCategory.WARNING, message, sourceFile.getUrl(), -1, -1); - // do not move: looks like source file has been invalidated, need recompilation - return Couple.newOne(tempOutputDir, pathToClass); - } - final String realOutputDir; - if (myCompileContext.isInTestSourceContent(sourceFile)) { - realOutputDir = getTestsOutputDir(module); - LOG.assertTrue(realOutputDir != null); - } - else { - realOutputDir = getOutputDir(module); - LOG.assertTrue(realOutputDir != null); - } - - if (FileUtil.pathsEqual(tempOutputDir, realOutputDir)) { // no need to move - filesToRefresh.add(new File(pathToClass)); - return Couple.newOne(realOutputDir, pathToClass); - } - - final String realPathToClass = realOutputDir + pathToClass.substring(tempOutputDir.length()); - final File fromFile = new File(pathToClass); - final File toFile = new File(realPathToClass); - - boolean success = fromFile.renameTo(toFile); - if (!success) { - // assuming cause of the fail: intermediate dirs do not exist - FileUtil.createParentDirs(toFile); - // retry after making non-existent dirs - success = fromFile.renameTo(toFile); - } - if (!success) { // failed to move the file: e.g. because source and destination reside on different mountpoints. - try { - FileUtil.copy(fromFile, toFile); - FileUtil.delete(fromFile); - success = true; - } - catch (IOException e) { - LOG.info(e); - success = false; - } - } - if (success) { - filesToRefresh.add(toFile); - return Couple.newOne(realOutputDir, realPathToClass); - } - return null; - } - - private final Map myModuleToTestsOutput = new HashMap(); - - private String getTestsOutputDir(final Module module) { - if (myModuleToTestsOutput.containsKey(module)) { - return myModuleToTestsOutput.get(module); - } - final VirtualFile outputDirectory = myCompileContext.getModuleOutputDirectoryForTests(module); - final String out = outputDirectory != null? outputDirectory.getPath() : null; - myModuleToTestsOutput.put(module, out); - return out; - } - - private final Map myModuleToOutput = new HashMap(); - - private String getOutputDir(final Module module) { - if (myModuleToOutput.containsKey(module)) { - return myModuleToOutput.get(module); - } - final VirtualFile outputDirectory = myCompileContext.getModuleOutputDirectory(module); - final String out = outputDirectory != null? outputDirectory.getPath() : null; - myModuleToOutput.put(module, out); - return out; - } - - private void sourceFileProcessed() { - myStatistics.incFilesCount(); - updateStatistics(); - } - - private void updateStatistics() { - final String msg; - String moduleName = myModuleName; - if (moduleName != null) { - msg = CompilerBundle.message("statistics.files.classes.module", myStatistics.getFilesCount(), myStatistics.getClassesCount(), moduleName); - } - else { - msg = CompilerBundle.message("statistics.files.classes", myStatistics.getFilesCount(), myStatistics.getClassesCount()); - } - myCompileContext.getProgressIndicator().setText2(msg); - //myCompileContext.getProgressIndicator().setFraction(1.0* myProcessedFilesCount /myTotalFilesToCompile); - } - - private class ClassParsingThread implements Runnable { - private final BlockingQueue myPaths = new ArrayBlockingQueue(50000); - private CacheCorruptedException myError = null; - private final boolean myAddNotNullAssertions; - private final boolean myIsJdk16; - private final String myOutputDir; - - private ClassParsingThread(final boolean isJdk16, String outputDir) { - myIsJdk16 = isJdk16; - myOutputDir = FileUtil.toSystemIndependentName(outputDir); - myAddNotNullAssertions = CompilerConfiguration.getInstance(myProject).isAddNotNullAssertions(); - } - - private volatile boolean processing; - public void run() { - processing = true; - try { - while (true) { - FileObject path = myPaths.take(); - - if (path == myStopThreadToken) { - break; - } - processPath(path, myProject); - } - } - catch (InterruptedException e) { - LOG.error(e); - } - catch (CacheCorruptedException e) { - myError = e; - } - finally { - processing = false; - } - } - - public void addPath(FileObject path) throws CacheCorruptedException { - if (myError != null) { - throw myError; - } - myPaths.offer(path); - } - - public void stopParsing() { - myPaths.offer(myStopThreadToken); - } - - private void processPath(FileObject fileObject, Project project) throws CacheCorruptedException { - File file = fileObject.getFile(); - final String path = file.getPath(); - try { - if (CompilerConfiguration.MAKE_ENABLED) { - byte[] fileContent = fileObject.getContent(); - // the file is assumed to exist! - final DependencyCache dependencyCache = myCompileContext.getDependencyCache(); - final int newClassQName = dependencyCache.reparseClassFile(file, fileContent); - final Cache newClassesCache = dependencyCache.getNewClassesCache(); - final String sourceFileName = newClassesCache.getSourceFileName(newClassQName); - final String qName = dependencyCache.resolve(newClassQName); - String relativePathToSource = "/" + MakeUtil.createRelativePathToSource(qName, sourceFileName); - putName(sourceFileName, newClassQName, relativePathToSource, path); - boolean haveToInstrument = myAddNotNullAssertions && hasNotNullAnnotations(newClassesCache, dependencyCache.getSymbolTable(), newClassQName, project); - - if (haveToInstrument) { - try { - ClassReader reader = new ClassReader(fileContent, 0, fileContent.length); - ClassWriter writer = new PsiClassWriter(myProject, myIsJdk16); - - if (NotNullVerifyingInstrumenter.processClassFile(reader, writer)) { - fileObject = new FileObject(file, writer.toByteArray()); - } - } - catch (Exception ignored) { - LOG.info(ignored); - } - } - - fileObject.save(); - } - else { - final String _path = FileUtil.toSystemIndependentName(path); - final int dollarIndex = _path.indexOf('$'); - final int tailIndex = dollarIndex >=0 ? dollarIndex : _path.length() - ".class".length(); - final int slashIndex = _path.lastIndexOf('/'); - final String sourceFileName = _path.substring(slashIndex + 1, tailIndex) + ".java"; - String relativePathToSource = _path.substring(myOutputDir.length(), tailIndex) + ".java"; - putName(sourceFileName, 0 /*doesn't matter here*/ , relativePathToSource.startsWith("/")? relativePathToSource : "/" + relativePathToSource, path); - } - } - catch (ClsFormatException e) { - final String m = e.getMessage(); - String message = CompilerBundle.message("error.bad.class.file.format", StringUtil.isEmpty(m) ? path : m + "\n" + path); - myCompileContext.addMessage(CompilerMessageCategory.ERROR, message, null, -1, -1); - LOG.info(e); - } - catch (IOException e) { - myCompileContext.addMessage(CompilerMessageCategory.ERROR, e.getMessage(), null, -1, -1); - LOG.info(e); - } - finally { - myStatistics.incClassesCount(); - updateStatistics(); - } - } - } - - private static boolean hasNotNullAnnotations(final Cache cache, final SymbolTable symbolTable, final int className, Project project) throws CacheCorruptedException { - final NullableNotNullManager manager = NullableNotNullManager.getInstance(project); - final List notNulls = manager.getNotNulls(); - for (MethodInfo methodId : cache.getMethods(className)) { - for (AnnotationConstantValue annotation : methodId.getRuntimeInvisibleAnnotations()) { - if (notNulls.contains(symbolTable.getSymbol(annotation.getAnnotationQName()))) { - return true; - } - } - final AnnotationConstantValue[][] paramAnnotations = methodId.getRuntimeInvisibleParameterAnnotations(); - for (AnnotationConstantValue[] _singleParamAnnotations : paramAnnotations) { - for (AnnotationConstantValue annotation : _singleParamAnnotations) { - if (notNulls.contains(symbolTable.getSymbol(annotation.getAnnotationQName()))) { - return true; - } - } - } - } - return false; - } - - private static boolean isJdk6(final Sdk jdk) { - return jdk != null && JavaSdk.getInstance().isOfVersionOrHigher(jdk, JavaSdkVersion.JDK_1_6); - } - - private static final class CompileStatistics { - private static final Key KEY = Key.create("_Compile_Statistics_"); - private int myClassesCount; - private int myFilesCount; - - public int getClassesCount() { - return myClassesCount; - } - - public int incClassesCount() { - return ++myClassesCount; - } - - public int getFilesCount() { - return myFilesCount; - } - - public int incFilesCount() { - return ++myFilesCount; - } - } -} diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/CompiledClass.java b/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/CompiledClass.java deleted file mode 100644 index 4bfa51988945..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/CompiledClass.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.compiler.impl.javaCompiler; - -/** -* @author cdr -*/ -final class CompiledClass { - public final int qName; - public final String relativePathToSource; - public final String pathToClass; - - CompiledClass(final int qName, final String relativePathToSource, final String pathToClass) { - this.qName = qName; - this.relativePathToSource = relativePathToSource; - this.pathToClass = pathToClass; - } - - public boolean equals(final Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - final CompiledClass that = (CompiledClass)o; - - if (qName != that.qName) return false; - if (!pathToClass.equals(that.pathToClass)) return false; - if (!relativePathToSource.equals(that.relativePathToSource)) return false; - - return true; - } - - public int hashCode() { - int result; - result = qName; - result = 31 * result + relativePathToSource.hashCode(); - result = 31 * result + pathToClass.hashCode(); - return result; - } - - public String toString() { - return "[" + pathToClass + ";" + relativePathToSource + "]"; - } -} diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/CompilerParsingThread.java b/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/CompilerParsingThread.java deleted file mode 100644 index 38b6b2f8e39d..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/CompilerParsingThread.java +++ /dev/null @@ -1,263 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.compiler.impl.javaCompiler; - -import com.intellij.compiler.OutputParser; -import com.intellij.compiler.impl.CompileDriver; -import com.intellij.compiler.make.CacheCorruptedException; -import com.intellij.openapi.application.ApplicationManager; -import com.intellij.openapi.compiler.CompileContext; -import com.intellij.openapi.compiler.CompilerMessageCategory; -import com.intellij.openapi.diagnostic.Logger; -import com.intellij.util.SpinAllocator; -import com.intellij.util.StringBuilderSpinAllocator; -import org.jetbrains.annotations.NonNls; - -import java.io.*; - -/** - * @author Eugene Zhuravlev - * Date: Mar 30, 2004 - */ -public class CompilerParsingThread implements Runnable, OutputParser.Callback { - private static final Logger LOG = Logger.getInstance("#com.intellij.compiler.impl.javaCompiler.JavaCompilerParsingThread"); - @NonNls public static final String TERMINATION_STRING = "__terminate_read__"; - private final Reader myCompilerOutStreamReader; - private Process myProcess; - private final OutputParser myOutputParser; - private final boolean myTrimLines; - private boolean mySkipLF = false; - private Throwable myError = null; - private final boolean myIsUnitTestMode; - private FileObject myClassFileToProcess = null; - private String myLastReadLine = null; - private String myPushBackLine = null; - private volatile boolean myProcessExited = false; - private final CompileContext myContext; - - public CompilerParsingThread(Process process, OutputParser outputParser, final boolean readErrorStream, boolean trimLines, CompileContext context) { - myProcess = process; - myOutputParser = outputParser; - myTrimLines = trimLines; - InputStream stream = readErrorStream ? process.getErrorStream() : process.getInputStream(); - myCompilerOutStreamReader = stream == null ? null : new BufferedReader(new InputStreamReader(stream), 16384); - myIsUnitTestMode = ApplicationManager.getApplication().isUnitTestMode(); - myContext = context; - } - - volatile boolean processing; - public void run() { - processing = true; - try { - while (true) { - if (!myIsUnitTestMode && myProcess == null) { - break; - } - if (isCanceled()) { - break; - } - if (!myOutputParser.processMessageLine(this)) { - break; - } - } - if (myClassFileToProcess != null) { - processCompiledClass(myClassFileToProcess); - myClassFileToProcess = null; - } - } - catch (Throwable e) { - e.printStackTrace(); - myError = e; - LOG.info(e); - } - finally { - killProcess(); - processing = false; - } - } - - private void killProcess() { - if (myProcess != null) { - myProcess.destroy(); - myProcess = null; - } - } - - public Throwable getError() { - return myError; - } - - public String getCurrentLine() { - return myLastReadLine; - } - - public final String getNextLine() { - final String pushBack = myPushBackLine; - if (pushBack != null) { - myPushBackLine = null; - myLastReadLine = pushBack; - return pushBack; - } - final String line = readLine(myCompilerOutStreamReader); - if (LOG.isDebugEnabled()) { - LOG.debug("LIne read: #" + line + "#"); - } - if (CompileDriver.ourDebugMode) { - System.out.println("LIne read: #" + line + "#"); - } - if (TERMINATION_STRING.equals(line)) { - myLastReadLine = null; - } - else { - myLastReadLine = line == null ? null : myTrimLines ? line.trim() : line; - } - return myLastReadLine; - } - - @Override - public void pushBack(String line) { - myLastReadLine = null; - myPushBackLine = line; - } - - public final void fileGenerated(FileObject path) { - // javac first logs file generated, then starts to write the file to disk, - // so this thread sometimes can stumble on not yet existing file, - // hence this complex logic - FileObject previousPath = myClassFileToProcess; - myClassFileToProcess = path; - if (previousPath != null) { - try { - processCompiledClass(previousPath); - } - catch (CacheCorruptedException e) { - if (CompileDriver.ourDebugMode) { - e.printStackTrace(); - } - myError = e; - LOG.info(e); - killProcess(); - } - } - } - - protected boolean isCanceled() { - return myContext.getProgressIndicator().isCanceled(); - } - - public void setProgressText(String text) { - myContext.getProgressIndicator().setText(text); - } - - public void fileProcessed(String path) { - } - - public void message(CompilerMessageCategory category, String message, String url, int lineNum, int columnNum) { - myContext.addMessage(category, message, url, lineNum, columnNum); - } - - protected void processCompiledClass(final FileObject classFileToProcess) throws CacheCorruptedException { - } - - - private String readLine(final Reader reader) { - StringBuilder buffer; - boolean releaseBuffer = true; - try { - buffer = StringBuilderSpinAllocator.alloc(); - } - catch (SpinAllocator.AllocatorExhaustedException e) { - if (CompileDriver.ourDebugMode) { - e.printStackTrace(); - } - LOG.info(e); - buffer = new StringBuilder(); - releaseBuffer = false; - } - - try { - boolean first = true; - while (true) { - int c = readNextByte(reader); - if (c == -1) break; - first = false; - if (c == '\n') { - if (mySkipLF) { - mySkipLF = false; - continue; - } - break; - } - else if (c == '\r') { - mySkipLF = true; - break; - } - else { - mySkipLF = false; - buffer.append((char)c); - } - } - if (first) { - return null; - } - return buffer.toString(); - } - finally { - if (releaseBuffer) { - StringBuilderSpinAllocator.dispose(buffer); - } - } - } - - private int readNextByte(final Reader reader) { - try { - while(!reader.ready()) { - if (isProcessTerminated()) { - if (reader.ready()) { - break; - } - return -1; - } - try { - Thread.sleep(1L); - } - catch (InterruptedException ignore) { - } - } - return reader.read(); - } - catch (IOException e) { - if (CompileDriver.ourDebugMode) { - e.printStackTrace(); - } - return -1; // When process terminated Process.getInputStream()'s underlying stream becomes closed on Linux. - } - catch (Throwable t) { - if (CompileDriver.ourDebugMode) { - t.printStackTrace(); - } - return -1; - } - } - - private boolean isProcessTerminated() { - return myProcessExited; - } - - public void setProcessTerminated(final boolean procesExited) { - myProcessExited = procesExited; - } -} diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/DummySourceGeneratingCompiler.java b/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/DummySourceGeneratingCompiler.java deleted file mode 100644 index 5fd91b01196f..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/DummySourceGeneratingCompiler.java +++ /dev/null @@ -1,137 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.compiler.impl.javaCompiler; - -import com.intellij.openapi.application.ApplicationManager; -import com.intellij.openapi.compiler.CompileContext; -import com.intellij.openapi.compiler.CompileScope; -import com.intellij.openapi.compiler.SourceGeneratingCompiler; -import com.intellij.openapi.compiler.ValidityState; -import com.intellij.openapi.module.Module; -import com.intellij.openapi.module.ModuleManager; -import com.intellij.openapi.project.Project; -import com.intellij.openapi.util.Computable; -import com.intellij.openapi.util.io.FileUtil; -import com.intellij.openapi.vfs.VirtualFile; -import org.jetbrains.annotations.NotNull; - -import java.io.DataInput; -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -/** - * @author Eugene Zhuravlev - * Date: Oct 9, 2004 - */ -@SuppressWarnings({"HardCodedStringLiteral"}) -public class DummySourceGeneratingCompiler implements SourceGeneratingCompiler{ - public static final String MODULE_NAME = "generated"; - private final Project myProject; - - public DummySourceGeneratingCompiler(Project project) { - myProject = project; - } - - @Override - public VirtualFile getPresentableFile(CompileContext context, Module module, VirtualFile outputRoot, VirtualFile generatedFile) { - return null; - } - - public GenerationItem[] getGenerationItems(CompileContext context) { - final Module module = findMyModule(); - return new GenerationItem[] { - new MyGenerationItem("aaa/p1.properties", module, false), - new MyGenerationItem("bbb/p2.properties", module, false), - new MyGenerationItem("bbb/ccc/p3.properties", module, false), - new MyGenerationItem("aaa/p1.properties", module, true), - new MyGenerationItem("bbb/p2-t.properties", module, true), - new MyGenerationItem("bbb/ccc/p3.properties", module, true) - }; - } - - private Module findMyModule() { - return ApplicationManager.getApplication().runReadAction(new Computable() { - public Module compute() { - Module[] modules = ModuleManager.getInstance(myProject).getModules(); - for (Module module : modules) { - if (MODULE_NAME.equals(module.getName())) { - return module; - } - } - return null; - } - }); - } - - public GenerationItem[] generate(CompileContext context, GenerationItem[] items, final VirtualFile outputRootDirectory) { - final String rootPath = ApplicationManager.getApplication().runReadAction(new Computable() { - public String compute() { - return outputRootDirectory.getPath(); - } - }); - final List success = new ArrayList(); - for (GenerationItem item1 : items) { - GenerationItem item = item1; - File file = new File(rootPath + File.separator + item.getPath()); - FileUtil.createIfDoesntExist(file); - success.add(item); - } - return success.toArray(new GenerationItem[success.size()]); - } - - @NotNull - public String getDescription() { - return "Dummy Source Generator"; - } - - public boolean validateConfiguration(CompileScope scope) { - return findMyModule() != null; - } - - public ValidityState createValidityState(DataInput in) throws IOException { - return null; - } - - private static class MyGenerationItem implements GenerationItem { - private final String myRelPath; - private final Module myModule; - private final boolean myIsTestSource; - - public MyGenerationItem(String relPath, Module module, final boolean isTestSource) { - myRelPath = relPath; - myModule = module; - myIsTestSource = isTestSource; - } - - public String getPath() { - return myRelPath; - } - - public ValidityState getValidityState() { - return null; - } - - public Module getModule() { - return myModule; - } - - public boolean isTestSource() { - return myIsTestSource; - } - } -} diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/DummyTransformingCompiler.java b/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/DummyTransformingCompiler.java deleted file mode 100644 index 29311901883d..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/DummyTransformingCompiler.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.compiler.impl.javaCompiler; - -import com.intellij.openapi.application.ApplicationManager; -import com.intellij.openapi.compiler.CompileContext; -import com.intellij.openapi.compiler.CompileScope; -import com.intellij.openapi.compiler.CompilerMessageCategory; -import com.intellij.openapi.compiler.JavaSourceTransformingCompiler; -import com.intellij.openapi.util.Computable; -import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.util.ui.UIUtil; -import org.jetbrains.annotations.NotNull; - -import java.io.*; - -/** - * @author Eugene Zhuravlev - * Date: Jul 10, 2004 - */ -@SuppressWarnings({"HardCodedStringLiteral"}) -public class DummyTransformingCompiler implements JavaSourceTransformingCompiler{ - public boolean isTransformable(VirtualFile file) { - return "A.java".equals(file.getName()); - } - - public boolean transform(CompileContext context, final VirtualFile file, VirtualFile originalFile) { - System.out.println("DummyTransformingCompiler.transform"); - final String url = ApplicationManager.getApplication().runReadAction(new Computable() { - public String compute() { - return file.getPresentableUrl(); - } - }); - context.getProgressIndicator().setText("Transforming file: " + url); - try { - OutputStream os = new BufferedOutputStream(new FileOutputStream(new File(url))); - DataOutput out = new DataOutputStream(os); - out.writeBytes("package a; "); - out.writeBytes("public class A { public static void main(String[] args) { System.out.println(\"Hello from modified class\");} }"); - os.close(); - UIUtil.invokeAndWaitIfNeeded(new Runnable() { - public void run() { - file.refresh(false, false); - } - }); - return true; - } - catch (FileNotFoundException e) { - context.addMessage(CompilerMessageCategory.ERROR, e.getMessage(), null, -1, -1); - } - catch (IOException e) { - context.addMessage(CompilerMessageCategory.ERROR, e.getMessage(), null, -1, -1); - } - return false; - } - - @NotNull - public String getDescription() { - return "a dummy compiler for testing"; - } - - public boolean validateConfiguration(CompileScope scope) { - return true; - } -} diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/DummyTranslatingCompiler.java b/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/DummyTranslatingCompiler.java deleted file mode 100644 index 573b7e02323d..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/DummyTranslatingCompiler.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.compiler.impl.javaCompiler; - -import com.intellij.compiler.impl.CompilerUtil; -import com.intellij.openapi.application.ApplicationManager; -import com.intellij.openapi.compiler.*; -import com.intellij.openapi.module.Module; -import com.intellij.openapi.util.io.FileUtil; -import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.util.Chunk; -import org.jetbrains.annotations.NonNls; -import org.jetbrains.annotations.NotNull; - -import java.io.File; -import java.io.IOException; -import java.util.*; - -/** - * @author Eugene Zhuravlev - * Date: Dec 4, 2007 - */ -public class DummyTranslatingCompiler implements TranslatingCompiler, IntermediateOutputCompiler{ - @NonNls private static final String DESCRIPTION = "DUMMY TRANSLATOR"; - @NonNls private static final String FILETYPE_EXTENSION = ".dummy"; - - public boolean isCompilableFile(final VirtualFile file, final CompileContext context) { - return file.getName().endsWith(FILETYPE_EXTENSION); - } - - public void compile(final CompileContext context, Chunk moduleChunk, final VirtualFile[] files, OutputSink sink) { - final List filesToRefresh = new ArrayList(); - final Map> outputs = new HashMap>(); - ApplicationManager.getApplication().runReadAction(new Runnable() { - public void run() { - for (final VirtualFile file : files) { - final Module module = context.getModuleByFile(file); - try { - final VirtualFile outputDir = context.getModuleOutputDirectory(module); - if (outputDir != null) { - final String outputDirPath = outputDir.getPath(); - final File compiledFile = doCompile(outputDir, file); - filesToRefresh.add(compiledFile); - Collection collection = outputs.get(outputDirPath); - if (collection == null) { - collection = new ArrayList(); - outputs.put(outputDirPath, collection); - } - collection.add(new OutputItemImpl(FileUtil.toSystemIndependentName(compiledFile.getPath()), file)); - } - } - catch (IOException e) { - context.addMessage(CompilerMessageCategory.ERROR, e.getMessage(), null, 0, 0); - } - } - } - }); - CompilerUtil.refreshIOFiles(filesToRefresh); - for (Map.Entry> entry : outputs.entrySet()) { - sink.add(entry.getKey(), entry.getValue(), VirtualFile.EMPTY_ARRAY); - } - } - - private static File doCompile(VirtualFile out, VirtualFile src) throws IOException { - final String originalName = src.getName(); - String compiledName = originalName.substring(0, originalName.length() - FILETYPE_EXTENSION.length()); - final File destFile = new File(out.getPath(), compiledName + ".java"); - FileUtil.copy(new File(src.getPath()), destFile); - return destFile; - } - - @NotNull - public String getDescription() { - return DESCRIPTION; - } - - public boolean validateConfiguration(final CompileScope scope) { - return true; - } -} diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/ExternalCompiler.java b/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/ExternalCompiler.java deleted file mode 100644 index 9223cbd95a35..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/ExternalCompiler.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.compiler.impl.javaCompiler; - -import com.intellij.openapi.compiler.CompileContext; -import com.intellij.openapi.diagnostic.Logger; -import com.intellij.openapi.fileTypes.FileType; -import com.intellij.openapi.fileTypes.StdFileTypes; -import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.util.EnvironmentUtil; -import com.intellij.util.StringBuilderSpinAllocator; -import org.jetbrains.annotations.NonNls; -import org.jetbrains.annotations.NotNull; - -import java.io.IOException; -import java.util.Collections; -import java.util.Set; - -public abstract class ExternalCompiler implements BackendCompiler { - private static final Logger LOG = Logger.getInstance("#com.intellij.compiler.impl.javaCompiler.ExternalCompiler"); - private static final Set COMPILABLE_TYPES = Collections.singleton(StdFileTypes.JAVA); - - @NotNull - public abstract String[] createStartupCommand(ModuleChunk chunk, CompileContext context, String outputPath) - throws IOException, IllegalArgumentException; - - @NotNull - public Set getCompilableFileTypes() { - return COMPILABLE_TYPES; - } - - /** - * Checks if the compiler can compile the specified file. - * - * @param file the file to check. - * @param context the context for the current compile operation. - * @return true if can compile the file, false otherwise. If the method returns false, file - * will not be included in the list of files passed to {@link #compile(CompileContext, com.intellij.util.Chunk < com.intellij.openapi.module.Module >,com.intellij.openapi.vfs.VirtualFile[], com.intellij.openapi.compiler.TranslatingCompiler.OutputSink)}. - */ - public boolean isCompilableFile(VirtualFile file, CompileContext context) { - return getCompilableFileTypes().contains(file.getFileType()); - } - - @NotNull - public Process launchProcess(@NotNull final ModuleChunk chunk, @NotNull final String outputDir, @NotNull final CompileContext compileContext) throws IOException { - final String[] commands = createStartupCommand(chunk, compileContext, outputDir); - - if (LOG.isDebugEnabled()) { - @NonNls final StringBuilder buf = StringBuilderSpinAllocator.alloc(); - try { - buf.append("\n===================================Environment:===========================\n"); - for (String pair : EnvironmentUtil.getEnvironment()) { - buf.append("\t").append(pair).append("\n"); - } - buf.append("=============================================================================\n"); - buf.append("Running compiler: "); - for (final String command : commands) { - buf.append(" ").append(command); - } - - LOG.debug(buf.toString()); - } - finally { - StringBuilderSpinAllocator.dispose(buf); - } - } - - return Runtime.getRuntime().exec(commands); - } -} diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/FileObject.java b/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/FileObject.java deleted file mode 100644 index 4ce53a50ec1f..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/FileObject.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.compiler.impl.javaCompiler; - -import com.intellij.openapi.util.io.FileUtil; -import com.intellij.util.ArrayUtil; -import org.jetbrains.annotations.NotNull; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; - -/** - * @author cdr - */ -public class FileObject { - private static final byte[] NOT_LOADED = ArrayUtil.EMPTY_BYTE_ARRAY; - - private final File myFile; - private final byte[] myContent; - - public FileObject(@NotNull File file, @NotNull byte[] content) { - myFile = file; - myContent = content; - } - - public FileObject(File file) { - myFile = file; - myContent = NOT_LOADED; - } - - public File getFile() { - return myFile; - } - - public byte[] getContent() throws IOException { - if (myContent == NOT_LOADED) { - return FileUtil.loadFileBytes(myFile); - } - return myContent; - } - - public void save() throws IOException { - if (myContent == NOT_LOADED) { - return; // already on disk - } - try { - FileUtil.writeToFile(myFile, myContent); - } - catch (FileNotFoundException e) { - FileUtil.createParentDirs(myFile); - FileUtil.writeToFile(myFile, myContent); - } - } - - @Override - public String toString() { - return getFile().toString(); - } -} diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/JavaCompiler.java b/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/JavaCompiler.java deleted file mode 100644 index 827c8135b622..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/JavaCompiler.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * @author: Eugene Zhuravlev - * Date: Jan 17, 2003 - * Time: 3:22:59 PM - */ -package com.intellij.compiler.impl.javaCompiler; - -import com.intellij.compiler.CompilerConfiguration; -import com.intellij.compiler.CompilerConfigurationImpl; -import com.intellij.compiler.CompilerException; -import com.intellij.compiler.impl.CompileDriver; -import com.intellij.compiler.make.CacheCorruptedException; -import com.intellij.openapi.compiler.*; -import com.intellij.openapi.compiler.ex.CompileContextEx; -import com.intellij.openapi.diagnostic.Logger; -import com.intellij.openapi.module.Module; -import com.intellij.openapi.project.Project; -import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.util.Chunk; -import org.jetbrains.annotations.NotNull; - -import java.util.Arrays; - -public class JavaCompiler implements TranslatingCompiler { - private static final Logger LOG = Logger.getInstance("#com.intellij.compiler.impl.javaCompiler.JavaCompiler"); - private final Project myProject; - - public JavaCompiler(Project project) { - myProject = project; - } - - @NotNull - public String getDescription() { - return CompilerBundle.message("java.compiler.description"); - } - - public boolean isCompilableFile(VirtualFile file, CompileContext context) { - final BackendCompiler backEndCompiler = getBackEndCompiler(); - if (backEndCompiler instanceof ExternalCompiler) { - return ((ExternalCompiler)backEndCompiler).isCompilableFile(file, context); - } - return backEndCompiler.getCompilableFileTypes().contains(file.getFileType()); - } - - public void compile(CompileContext context, Chunk moduleChunk, VirtualFile[] files, OutputSink sink) { - final BackendCompiler backEndCompiler = getBackEndCompiler(); - final BackendCompilerWrapper wrapper = new BackendCompilerWrapper(moduleChunk, myProject, Arrays.asList(files), (CompileContextEx)context, backEndCompiler, sink); - try { - if (CompileDriver.ourDebugMode) { - System.out.println("Starting java compiler; with backend compiler: " + backEndCompiler.getClass().getName()); - } - wrapper.compile(); - } - catch (CompilerException e) { - if (CompileDriver.ourDebugMode) { - e.printStackTrace(); - } - context.addMessage(CompilerMessageCategory.ERROR, e.getMessage(), null, -1, -1); - LOG.info(e); - } - catch (CacheCorruptedException e) { - if (CompileDriver.ourDebugMode) { - e.printStackTrace(); - } - LOG.info(e); - context.requestRebuildNextTime(e.getMessage()); - } - } - - public boolean validateConfiguration(CompileScope scope) { - return getBackEndCompiler().checkCompiler(scope); - } - - private BackendCompiler getBackEndCompiler() { - CompilerConfigurationImpl configuration = (CompilerConfigurationImpl)CompilerConfiguration.getInstance(myProject); - return configuration.getDefaultCompiler(); - } -} diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/OutputDir.java b/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/OutputDir.java deleted file mode 100644 index 7d7b12d7d689..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/OutputDir.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.compiler.impl.javaCompiler; - -import org.jetbrains.annotations.NotNull; - -/** -* @author cdr -*/ -class OutputDir { - private final String myPath; - private final int myKind; - - OutputDir(@NotNull String path, int kind) { - myPath = path; - myKind = kind; - } - - @NotNull - public String getPath() { - return myPath; - } - - public int getKind() { - return myKind; - } - - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (!(o instanceof OutputDir)) { - return false; - } - - final OutputDir outputDir = (OutputDir)o; - - return myKind == outputDir.myKind && myPath.equals(outputDir.myPath); - - } - - public int hashCode() { - int result = myPath.hashCode(); - result = 29 * result + myKind; - return result; - } -} diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/OutputItemImpl.java b/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/OutputItemImpl.java deleted file mode 100644 index eb5720c1c636..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/OutputItemImpl.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * @author: Eugene Zhuravlev - * Date: Apr 1, 2003 - * Time: 5:58:41 PM - */ -package com.intellij.compiler.impl.javaCompiler; - -import com.intellij.openapi.compiler.TranslatingCompiler; -import com.intellij.openapi.vfs.VirtualFile; -import org.jetbrains.annotations.Nullable; - -public class OutputItemImpl implements TranslatingCompiler.OutputItem{ - - private final String myOutputPath; - private final VirtualFile mySourceFile; - - public OutputItemImpl(VirtualFile packageInfoFile) { - this(null, packageInfoFile); - } - - /** - * @param outputPath absolute path of the output file ('/' slashes used) - * @param sourceFile corresponding source file - */ - public OutputItemImpl(@Nullable String outputPath, VirtualFile sourceFile) { - myOutputPath = outputPath; - mySourceFile = sourceFile; - } - - public String getOutputPath() { - return myOutputPath; - } - - public VirtualFile getSourceFile() { - return mySourceFile; - } -} diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/api/CompAPIDriver.java b/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/api/CompAPIDriver.java deleted file mode 100644 index d75fe63843d0..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/api/CompAPIDriver.java +++ /dev/null @@ -1,180 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.compiler.impl.javaCompiler.api; - -import com.intellij.compiler.OutputParser; -import com.intellij.openapi.compiler.CompilerMessageCategory; -import com.sun.source.util.JavacTask; -import com.sun.source.util.TaskEvent; -import com.sun.source.util.TaskListener; -import com.sun.tools.javac.api.JavacTool; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import javax.tools.*; -import java.io.File; -import java.io.IOException; -import java.io.PrintWriter; -import java.lang.reflect.Field; -import java.net.URI; -import java.util.List; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.LinkedBlockingQueue; - -/** - * @author cdr - */ -@SuppressWarnings({"Since15"}) -class CompAPIDriver { - private final BlockingQueue myCompilationResults = new LinkedBlockingQueue(); - private static final CompilationEvent GUARD = new CompilationEvent() { - @Override - protected void process(OutputParser.Callback callback) { - } - - @Override - public String toString() { - return "FINISH"; - } - }; - private String myOutputDir; - - private volatile boolean compiling; - private static final PrintWriter COMPILER_ERRORS = new PrintWriter(System.err); - @Nullable - private final String mySourcesEncoding; - - CompAPIDriver(@Nullable String sourcesEncoding) { - mySourcesEncoding = sourcesEncoding; - } - - public void compile(List commandLine, List paths, final String outputDir) { - myOutputDir = outputDir; - compiling = true; - - assert myCompilationResults.isEmpty(); - JavaCompiler compiler = JavacTool.create(); //use current classloader - StandardJavaFileManager standardFileManager = compiler.getStandardFileManager(null, null, null); - MyFileManager manager = new MyFileManager(this, outputDir, standardFileManager, mySourcesEncoding); - - Iterable input = manager.getJavaFileObjectsFromFiles(paths); - - DiagnosticListener listener = new DiagnosticListener() { - public void report(Diagnostic diagnostic) { - CompilationEvent event = CompilationEvent.diagnostic(diagnostic); - myCompilationResults.offer(event); - } - }; - try { - JavaCompiler.CompilationTask task = compiler.getTask(COMPILER_ERRORS, manager, listener, commandLine, null, input); - ((JavacTask)task).setTaskListener(new TaskListener() { - public void started(TaskEvent taskEvent) { - JavaFileObject sourceFile = taskEvent.getSourceFile(); - CompilationEvent event; - switch (taskEvent.getKind()) { - case ANALYZE: - event = CompilationEvent.progress("Analyzing ",sourceFile); - break; - case PARSE: - event = CompilationEvent.progress("Parsing ", sourceFile); - break; - default: - event = null; - } - if (event != null) { - myCompilationResults.offer(event); - } - } - public void finished(TaskEvent taskEvent) { - CompilationEvent event; - switch (taskEvent.getKind()) { - case ENTER: - event = CompilationEvent.fileProcessed(); - break; - default: - event = null; - } - if (event != null) { - myCompilationResults.offer(event); - } - } - }); - task.call(); - } - catch (IllegalArgumentException e) { - final String message = "Javac in-process compiler error: " + e.getMessage(); - myCompilationResults.offer(new CompilationEvent() { - @Override - protected void process(OutputParser.Callback callback) { - callback.message(CompilerMessageCategory.ERROR, message, null, -1, -1); - } - }); - } - finally { - compiling = false; - myCompilationResults.offer(GUARD); - try { - manager.close(); - } - catch (IOException ignored) { - } - } - } - - private volatile boolean processing; - public void processAll(@NotNull OutputParser.Callback callback) { - try { - processing = true; - while (true) { - CompilationEvent event = myCompilationResults.take(); - if (event == GUARD) break; - event.process(callback); - } - } - catch (InterruptedException ignored) { - } - finally { - processing = false; - } - } - - public void finish() { - assert !compiling : "still compiling to "+myOutputDir; - assert !processing; - //assert myCompilationResults.isEmpty() : myCompilationResults; - myCompilationResults.clear(); - cleanupInternalFields(); - } - - private static void cleanupInternalFields() { - try { - Field freelist = Class.forName("com.sun.tools.javac.util.SharedNameTable").getDeclaredField("freelist"); - freelist.setAccessible(true); - freelist.set(null, com.sun.tools.javac.util.List.nil()); - } - catch (Exception ignored) { - - } - } - - public void offerClassFile(URI uri, byte[] bytes) { - CompilationEvent event = CompilationEvent.generateClass(uri, bytes); - myCompilationResults.offer(event); - } - -} - - diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/api/CompilationEvent.java b/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/api/CompilationEvent.java deleted file mode 100644 index 0ca1e2b3729e..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/api/CompilationEvent.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.compiler.impl.javaCompiler.api; - -import com.intellij.compiler.OutputParser; -import com.intellij.compiler.impl.javaCompiler.FileObject; -import com.intellij.openapi.compiler.CompilerMessageCategory; -import com.intellij.openapi.util.io.FileUtil; -import com.intellij.openapi.util.text.StringUtil; -import com.intellij.openapi.vfs.VfsUtil; -import org.jetbrains.annotations.NonNls; - -import javax.tools.*; -import java.io.File; -import java.net.URI; - -/** - * @author cdr - */ -abstract class CompilationEvent { - protected abstract void process(OutputParser.Callback callback); - static CompilationEvent progress(final String title, final JavaFileObject fileObject) { - return new CompilationEvent() { - @Override - protected void process(OutputParser.Callback callback) { - showProgressFor(title, fileObject.toUri(), callback); - } - - @NonNls - @Override - public String toString() { - return "Progress: "+title+" "+fileObject.toUri(); - } - }; - } - - private static void showProgressFor(String title, URI uri, OutputParser.Callback callback) { - String normalizedPath; - try { - normalizedPath = new File(uri).getPath(); - } - catch (IllegalArgumentException e) { - normalizedPath = uri.toString(); - } - callback.setProgressText(title + StringUtil.last(normalizedPath, 100, true)); - } - - static CompilationEvent generateClass(final URI uri, final byte[] bytes) { - return new CompilationEvent() { - @Override - protected void process(OutputParser.Callback callback) { - showProgressFor("Writing ", uri, callback); - File file = new File(uri); - callback.fileGenerated(new FileObject(file,bytes)); - } - @NonNls - @Override - public String toString() { - return "Write: "+uri; - } - }; - } - static CompilationEvent diagnostic(final Diagnostic diagnostic) { - return new CompilationEvent() { - @Override - protected void process(OutputParser.Callback callback) { - JavaFileObject fileObject = diagnostic.getSource(); - String message = diagnostic.getMessage(null); - String url; - if (fileObject == null) { - url = null; - } - else { - URI uri = fileObject.toUri(); - if (uri.getScheme().equals("file")) { - url = VfsUtil.pathToUrl(FileUtil.toSystemIndependentName(uri.getPath())); - } - else { - url = fileObject.toString(); - } - } - - CompilerMessageCategory category = diagnostic.getKind() == Diagnostic.Kind.ERROR - ? CompilerMessageCategory.ERROR - : diagnostic.getKind() == Diagnostic.Kind.WARNING || - diagnostic.getKind() == Diagnostic.Kind.MANDATORY_WARNING - ? CompilerMessageCategory.WARNING - : CompilerMessageCategory.INFORMATION; - callback.message(category, message, url, (int)diagnostic.getLineNumber(), (int)diagnostic.getColumnNumber()); - } - @NonNls - @Override - public String toString() { - return "Diagnostic: "+diagnostic; - } - }; - } - - public static CompilationEvent fileProcessed() { - return FILE_PROCESSED; - } - private static final CompilationEvent FILE_PROCESSED = new CompilationEvent() { - @Override - protected void process(OutputParser.Callback callback) { - callback.fileProcessed(null); - } - - @NonNls - @Override - public String toString() { - return "Processed"; - } - }; -} diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/api/CompilerAPICompiler.java b/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/api/CompilerAPICompiler.java deleted file mode 100644 index 19e2a0bf6fbf..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/api/CompilerAPICompiler.java +++ /dev/null @@ -1,199 +0,0 @@ -/* - * Copyright 2000-2014 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.compiler.impl.javaCompiler.api; - -import com.intellij.compiler.OutputParser; -import com.intellij.compiler.impl.javaCompiler.BackendCompiler; -import com.intellij.compiler.impl.javaCompiler.ModuleChunk; -import com.intellij.compiler.impl.javaCompiler.javac.JavacCompiler; -import com.intellij.compiler.impl.javaCompiler.javac.JavacConfigurable; -import com.intellij.openapi.application.ApplicationManager; -import com.intellij.openapi.compiler.CompileContext; -import com.intellij.openapi.compiler.CompileScope; -import com.intellij.openapi.compiler.CompilerMessageCategory; -import com.intellij.openapi.diagnostic.Logger; -import com.intellij.openapi.fileTypes.FileType; -import com.intellij.openapi.fileTypes.StdFileTypes; -import com.intellij.openapi.options.Configurable; -import com.intellij.openapi.project.Project; -import com.intellij.openapi.projectRoots.JavaSdkVersion; -import com.intellij.openapi.util.ThrowableComputable; -import com.intellij.openapi.vfs.VirtualFile; -import org.jetbrains.annotations.NonNls; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import org.jetbrains.jps.model.java.compiler.JavaCompilers; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Set; - - -public class CompilerAPICompiler implements BackendCompiler { - private static final Logger LOG = Logger.getInstance("#com.intellij.compiler.impl.javaCompiler.api.CompilerAPICompiler"); - private final Project myProject; - private static final Set COMPILABLE_TYPES = Collections.singleton(StdFileTypes.JAVA); - - public CompilerAPICompiler(Project project) { - myProject = project; - } - - public boolean checkCompiler(final CompileScope scope) { - return true; - } - - @NotNull - @NonNls - public String getId() { // used for externalization - return JavaCompilers.JAVAC_API_ID; - } - - @NotNull - public String getPresentableName() { - return "Javac in-process (Java6+ only)"; - } - - @NotNull - public Configurable createConfigurable() { - return new JavacConfigurable(CompilerAPIConfiguration.getOptions(myProject, CompilerAPIConfiguration.class)); - } - - @NotNull - public Set getCompilableFileTypes() { - return COMPILABLE_TYPES; - } - - @Nullable - public OutputParser createErrorParser(@NotNull final String outputDir, final Process process) { - return new OutputParser() { - public boolean processMessageLine(Callback callback) { - ((MyProcess)process).myCompAPIDriver.processAll(callback); - return false; - } - }; - } - - @Nullable - public OutputParser createOutputParser(@NotNull final String outputDir) { - return null; - } - - public void compileFinished() { - } - - @NotNull - public Process launchProcess(@NotNull final ModuleChunk chunk, @NotNull final String outputDir, @NotNull final CompileContext compileContext) throws IOException { - @NonNls final List commandLine = - ApplicationManager.getApplication().runReadAction(new ThrowableComputable, IOException>() { - @Override - public List compute() throws IOException { - List commandLine = new ArrayList(); - final List additionalOptions = - JavacCompiler.addAdditionalSettings(commandLine, CompilerAPIConfiguration .getOptions(myProject, CompilerAPIConfiguration.class), false, - JavaSdkVersion.JDK_1_6, chunk, compileContext.isAnnotationProcessorsEnabled()); - - JavacCompiler.addCommandLineOptions(chunk, commandLine, outputDir, chunk.getJdk(), false, false, null, false, false, false); - commandLine.addAll(additionalOptions); - return commandLine; - } - }); - return new MyProcess(commandLine, chunk, outputDir, compileContext); - } - - private static void compile(List commandLine, ModuleChunk chunk, String outputDir, CompAPIDriver myCompAPIDriver) { - List filesToCompile = chunk.getFilesToCompile(); - List paths = new ArrayList(filesToCompile.size()); - for (VirtualFile file : filesToCompile) { - paths.add(new File(file.getPresentableUrl())); - } - myCompAPIDriver.compile(commandLine, paths, outputDir); - } - - private static class MyProcess extends Process { - private final List myCommandLine; - private final ModuleChunk myChunk; - private final String myOutputDir; - private final CompileContext myCompileContext; - private final CompAPIDriver myCompAPIDriver; - - private MyProcess(List commandLine, ModuleChunk chunk, String outputDir, CompileContext compileContext) { - myCommandLine = commandLine; - myChunk = chunk; - myOutputDir = outputDir; - myCompileContext = compileContext; - myCompAPIDriver = new CompAPIDriver(findEncodingValue(commandLine)); - } - - private static String findEncodingValue(List commandLine) { - boolean found = false; - for (String param : commandLine) { - if (found) { - return param; - } - if ("-encoding".equalsIgnoreCase(param)) { - found = true; - } - } - return null; - } - - public OutputStream getOutputStream() { - throw new UnsupportedOperationException(); - } - - public InputStream getInputStream() { - return null; - } - - public InputStream getErrorStream() { - return null; - } - - public void destroy() { - myCompAPIDriver.finish(); - } - - private int myExitCode; - public int waitFor() { - try { - myCommandLine.remove("-verbose"); - compile(myCommandLine, myChunk, myOutputDir, myCompAPIDriver); - myExitCode = 0; - return myExitCode; - } - catch (Exception e) { - myCompileContext.addMessage(CompilerMessageCategory.ERROR, e.getMessage(), null, -1, -1); - LOG.info(e); - myExitCode = -1; - return -1; - } - } - - public int exitValue() { - return myExitCode; - } - - @Override - public String toString() { - return myChunk.toString(); - } - } -} diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/api/CompilerAPIConfiguration.java b/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/api/CompilerAPIConfiguration.java deleted file mode 100755 index 3a695410922e..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/api/CompilerAPIConfiguration.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright 2000-2012 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.compiler.impl.javaCompiler.api; - -import com.intellij.compiler.impl.javaCompiler.javac.JavacConfiguration; -import com.intellij.openapi.components.State; -import com.intellij.openapi.components.Storage; -import com.intellij.openapi.components.StoragePathMacros; -import com.intellij.openapi.components.StorageScheme; -import com.intellij.openapi.project.Project; - -@State( - name = "CompilerAPISettings", - storages = { - @Storage(file = StoragePathMacros.PROJECT_FILE), - @Storage(file = StoragePathMacros.PROJECT_CONFIG_DIR + "/compiler.xml", scheme = StorageScheme.DIRECTORY_BASED) - } -) -public class CompilerAPIConfiguration extends JavacConfiguration { - public CompilerAPIConfiguration(Project project) { - super(project); - } -} \ No newline at end of file diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/api/CompilerPerfTestAction.java b/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/api/CompilerPerfTestAction.java deleted file mode 100644 index ad587875157f..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/api/CompilerPerfTestAction.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.compiler.impl.javaCompiler.api; - -import com.intellij.compiler.CompilerConfiguration; -import com.intellij.compiler.CompilerConfigurationImpl; -import com.intellij.compiler.impl.javaCompiler.BackendCompiler; -import com.intellij.openapi.actionSystem.AnAction; -import com.intellij.openapi.actionSystem.AnActionEvent; -import com.intellij.openapi.actionSystem.CommonDataKeys; -import com.intellij.openapi.actionSystem.PlatformDataKeys; -import com.intellij.openapi.compiler.CompileContext; -import com.intellij.openapi.compiler.CompileStatusNotification; -import com.intellij.openapi.compiler.CompilerManager; -import com.intellij.openapi.project.Project; -import com.intellij.util.containers.ContainerUtil; - -import java.util.List; -import java.util.concurrent.TimeUnit; - -/** - * @author cdr - */ -public class CompilerPerfTestAction extends AnAction { - @Override - public void update(AnActionEvent e) { - Project project = e.getData(CommonDataKeys.PROJECT); - e.getPresentation().setEnabled(project != null); - } - - public void actionPerformed(AnActionEvent e) { - final Project project = e.getData(CommonDataKeys.PROJECT); - - final CompilerManager compilerManager = CompilerManager.getInstance(project); - - final CompilerConfigurationImpl configuration = (CompilerConfigurationImpl)CompilerConfiguration.getInstance(project); - List compilers = (List)configuration.getRegisteredJavaCompilers(); - final List allCompilers = ContainerUtil.concat(compilers, compilers, compilers, compilers, compilers, compilers, compilers); - final int[] i = new int[1]; - - CompileStatusNotification callback = new CompileStatusNotification() { - volatile long start; - BackendCompiler compiler; - - public void finished(boolean aborted, int errors, int warnings, CompileContext compileContext) { - if (compiler == null) { - next(); - return; - } - final long finish = System.currentTimeMillis(); - System.out.println("Compiled with '" + - compiler.getPresentableName() + "' " + - " in " + - TimeUnit.MILLISECONDS.toMinutes(finish - start) + "m" + - TimeUnit.MILLISECONDS.toSeconds((finish - start)%60000) + "s" + - " with " + - errors + - " errors, " + - warnings + - " warnings, aborted=" + - aborted+"; free memory="+Runtime.getRuntime().freeMemory()+" bytes"); - //ProfilingUtil.forceCaptureMemorySnapshot(); - next(); - } - - void next() { - if (i[0] >= allCompilers.size()) return; - compiler = allCompilers.get(i[0]++); - if (compiler.getId().equals("Jikes")|| compiler.getId().contains("Eclipse")) { - next(); - return; - } - boolean success = compiler.checkCompiler(compilerManager.createProjectCompileScope(project)); - if (!success) { - next(); - return; - } - configuration.setDefaultCompiler(compiler); - start = System.currentTimeMillis(); - compilerManager.rebuild(this); - } - }; - - callback.finished(false,0,0,null); - } -} diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/api/FileVirtualObject.java b/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/api/FileVirtualObject.java deleted file mode 100644 index b6866f003c86..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/api/FileVirtualObject.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.compiler.impl.javaCompiler.api; - -import com.intellij.openapi.fileEditor.impl.LoadTextUtil; -import com.intellij.openapi.vfs.VirtualFile; - -import javax.tools.*; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.URI; - -/** - * @author cdr - */ -@SuppressWarnings({"Since15"}) -public abstract class FileVirtualObject extends SimpleJavaFileObject { - public FileVirtualObject(URI uri, Kind kind) { - super(uri, kind); - } - - protected abstract VirtualFile getVirtualFile(); - @Override - public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException { - VirtualFile virtualFile = getVirtualFile(); - if (virtualFile == null) return null; - return LoadTextUtil.loadText(virtualFile); - } - - @Override - public InputStream openInputStream() throws IOException { - // in-process compiler does not work well with zipped stream - byte[] bytes = getVirtualFile().contentsToByteArray(); - return new ByteArrayInputStream(bytes); - } - - @Override - public OutputStream openOutputStream() throws IOException { - return getVirtualFile().getOutputStream(this); - } - - @Override - public String toString() { - return toUri().toString(); - } - @Override - public int hashCode() { - return toUri().hashCode(); - } - - @Override - public boolean equals(Object obj) { - return obj instanceof JavaFileObject && toUri().equals(((JavaFileObject)obj).toUri()); - } -} diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/api/JavaIoFile.java b/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/api/JavaIoFile.java deleted file mode 100644 index 801fc75aace4..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/api/JavaIoFile.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright 2000-2010 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.compiler.impl.javaCompiler.api; - -import com.intellij.openapi.util.io.FileUtil; -import com.intellij.openapi.util.text.StringUtil; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import javax.tools.JavaFileObject; -import javax.tools.SimpleJavaFileObject; -import java.io.*; -import java.net.URI; -import java.net.URISyntaxException; - -/** -* User: cdr -*/ -@SuppressWarnings({"Since15"}) -class JavaIoFile extends SimpleJavaFileObject { - private final File myFile; - @Nullable - private final String myEncoding; - - JavaIoFile(@NotNull File file, @NotNull Kind kind, @Nullable String encoding) { - super(convertToURI(file.getPath()), kind); - myFile = file; - myEncoding = encoding; - } - - // File.toURI() asks for File.isDirectory which is too expensive - @NotNull - private static URI convertToURI(@NotNull String path) { - if (File.separatorChar != '/') { - path = path.replace(File.separatorChar, '/'); - } - if (!StringUtil.startsWithChar(path, '/')) { - path = "/" + path; - } - - if (path.startsWith("//")) { - path = "//" + path; - } - try { - return new URI("file", null, path, null); - } - catch (URISyntaxException e) { - throw new RuntimeException(e); - } - } - - @Override - public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException { - return FileUtil.loadFile(myFile, myEncoding); - } - - @Override - public InputStream openInputStream() throws IOException { - return new BufferedInputStream(new FileInputStream(myFile)); - } - - @Override - public OutputStream openOutputStream() throws IOException { - return new BufferedOutputStream(new FileOutputStream(myFile)); - } - - @Override - public String toString() { - return toUri().toString(); - } - - @Override - public int hashCode() { - return toUri().hashCode(); - } - - @Override - public boolean equals(Object obj) { - return obj instanceof JavaFileObject && toUri().equals(((JavaFileObject)obj).toUri()); - } -} diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/api/JavaVirtualByIoFile.java b/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/api/JavaVirtualByIoFile.java deleted file mode 100644 index 6fd106528aab..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/api/JavaVirtualByIoFile.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright 2000-2010 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.compiler.impl.javaCompiler.api; - -import com.intellij.openapi.vfs.LocalFileSystem; -import com.intellij.openapi.vfs.VirtualFile; - -import java.io.File; - -/** - * User: cdr - */ -@SuppressWarnings({"Since15"}) -class JavaVirtualByIoFile extends FileVirtualObject { - private final File myFile; - - protected JavaVirtualByIoFile(File file, Kind kind) { - super(file.toURI(), kind); - myFile = file; - } - - protected VirtualFile getVirtualFile() { - return LocalFileSystem.getInstance().findFileByIoFile(myFile); - } -} \ No newline at end of file diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/api/JavaVirtualFile.java b/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/api/JavaVirtualFile.java deleted file mode 100644 index abe8f24cda58..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/api/JavaVirtualFile.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright 2000-2010 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.compiler.impl.javaCompiler.api; - -import com.intellij.openapi.vfs.VirtualFile; - -/** -* User: cdr -*/ -@SuppressWarnings({"Since15"}) -class JavaVirtualFile extends FileVirtualObject { - private final VirtualFile myFile; - - JavaVirtualFile(VirtualFile file, Kind kind) { - super(MyFileManager.createUri(file.getUrl()), kind); - myFile = file; - } - - protected VirtualFile getVirtualFile() { - return myFile; - } -} diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/api/MyFileManager.java b/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/api/MyFileManager.java deleted file mode 100644 index d46d5042e6bf..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/api/MyFileManager.java +++ /dev/null @@ -1,260 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.compiler.impl.javaCompiler.api; - -import com.intellij.openapi.diagnostic.Logger; -import com.intellij.openapi.util.io.FileUtil; -import com.intellij.openapi.util.text.StringUtil; -import com.intellij.openapi.vfs.JarFileSystem; -import com.intellij.openapi.vfs.LocalFileSystem; -import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.util.SmartList; -import com.sun.tools.javac.util.ListBuffer; -import gnu.trove.THashSet; -import gnu.trove.TObjectHashingStrategy; - -import javax.tools.FileObject; -import javax.tools.JavaFileObject; -import javax.tools.StandardJavaFileManager; -import java.io.File; -import java.io.IOException; -import java.net.URI; -import java.util.*; - -/** -* @author cdr -*/ -class MyFileManager implements StandardJavaFileManager { - private static final Logger LOG = Logger.getInstance("#com.intellij.compiler.impl.javaCompiler.api.MyFileManager"); - - private final String myOutputDir; - private final StandardJavaFileManager myStandardFileManager; - private final String myEncoding; - private final CompAPIDriver myCompAPIDriver; - - MyFileManager(CompAPIDriver compAPIDriver, String outputDir, StandardJavaFileManager standardFileManager, String encoding) { - myCompAPIDriver = compAPIDriver; - myOutputDir = outputDir; - myStandardFileManager = standardFileManager; - myEncoding = encoding; - } - - @Override - public Iterable getJavaFileObjectsFromFiles(Iterable files) { - int size = ((Collection)files).size(); - List result = new ArrayList(size); - - for (File file : files) { - JavaFileObject fileObject = new JavaIoFile(file, JavaFileObject.Kind.SOURCE, myEncoding); - result.add(fileObject); - } - - return result; - } - - @Override - public JavaFileObject getJavaFileForOutput(Location location, String name, JavaFileObject.Kind kind, FileObject fileObject) { - URI uri = toURI(myOutputDir, name, kind); - return new Output(uri, myCompAPIDriver, kind); - } - - static URI createUri(String url) { - return URI.create(url.replaceAll(" ","%20")); - } - - private static URI toURI(String outputDir, String name, JavaFileObject.Kind kind) { - return createUri("file:///" + outputDir.replace('\\','/') + "/" + name.replace('.', '/') + kind.extension); - } - - - @Override - public Iterable list(Location location, String packageName, Set kinds, boolean recurse) throws IOException { - if (recurse) { - throw new IllegalArgumentException(); - } - return findInside(location, packageName, kinds, false); - } - - private List findInside(Location location, String packageName, Set kinds, boolean lookForFile) - throws IOException { - Iterable path = getLocation(location); - if (path == null) return Collections.emptyList(); - - String subdirectory = packageName.replace('.', '/'); - List results = null; - - for (File directory : path) { - VirtualFile dir = LocalFileSystem.getInstance().findFileByIoFile(directory); - if (dir == null) continue; - if (!dir.isDirectory()) { - dir = JarFileSystem.getInstance().getJarRootForLocalFile(dir); - if (dir == null) continue; - } - VirtualFile virtualFile = StringUtil.isEmptyOrSpaces(subdirectory) ? dir : dir.findFileByRelativePath(subdirectory); - if (virtualFile == null) continue; - - VirtualFile[] children; - if (lookForFile) { - if (!virtualFile.isDirectory()) { - children = new VirtualFile[]{virtualFile}; - } - else continue; - } - else { - children = virtualFile.getChildren(); - } - for (VirtualFile child : children) { - JavaFileObject.Kind kind = getKind("." + child.getExtension()); - if (kinds == null || kinds.contains(kind)) { - if (results == null) results = new SmartList(); - if (kind == JavaFileObject.Kind.SOURCE && child.getFileSystem() instanceof JarFileSystem) continue; //for some reasdon javac looks for java files inside jar - - // use VFS to read content inside .jar - String childPath = child.getPath(); - JavaFileObject fileObject = !childPath.contains("!/") ? new JavaIoFile(new File(childPath), kind, myEncoding) : new JavaVirtualFile(child, kind); - results.add(fileObject); - } - } - } - - List ret = results == null ? Collections.emptyList() : results; - - if (LOG.isDebugEnabled()) { - // for testing consistency - Collection c = (Collection)myStandardFileManager.list(location, packageName, kinds, false); - Collection sup = new HashSet(c); - assert sup.size() == c.size(); - assert new HashSet(c).equals(sup); - - THashSet s = new THashSet(new TObjectHashingStrategy() { - public int computeHashCode(JavaFileObject object) { - return object.getName().hashCode(); - } - - public boolean equals(JavaFileObject o1, JavaFileObject o2) { - return o1.getKind() == o2.getKind() && o1.toUri().equals(o2.toUri()); - } - }); - s.addAll(ret); - - s.removeAll(sup); - if (ret.size() != sup.size()) { - assert false : "our implementation differs from javac'"; - } - } - - return ret; - } - - private static JavaFileObject.Kind getKind(String name) { - if (name.endsWith(JavaFileObject.Kind.CLASS.extension)) - return JavaFileObject.Kind.CLASS; - else if (name.endsWith(JavaFileObject.Kind.SOURCE.extension)) - return JavaFileObject.Kind.SOURCE; - else if (name.endsWith(JavaFileObject.Kind.HTML.extension)) - return JavaFileObject.Kind.HTML; - else - return JavaFileObject.Kind.OTHER; - } - - - @Override - public String inferBinaryName(Location location, JavaFileObject file) { - return FileUtil.getNameWithoutExtension(new File(file.getName()).getName()); - } - - ////////// delegates - @Override - public int isSupportedOption(String option) { - return myStandardFileManager.isSupportedOption(option); - } - - @Override - public void close() throws IOException { - myStandardFileManager.close(); - } - - @Override - public void flush() throws IOException { - myStandardFileManager.flush(); - } - - @Override - public boolean handleOption(String current, Iterator remaining) { - return myStandardFileManager.handleOption(current, remaining); - } - - @Override - public ClassLoader getClassLoader(Location location) { - return myStandardFileManager.getClassLoader(location); - } - - @Override - public boolean isSameFile(FileObject a, FileObject b) { - if (a instanceof FileVirtualObject && b instanceof FileVirtualObject || a instanceof Output && b instanceof Output) { - return a.equals(b); - } - return myStandardFileManager.isSameFile(a, b); - } - - public Iterable getJavaFileObjects(File... files) { - return getJavaFileObjectsFromFiles(Arrays.asList(files)); - } - - public Iterable getJavaFileObjects(String... names) { - return getJavaFileObjectsFromStrings(Arrays.asList(names)); - } - public Iterable getJavaFileObjectsFromStrings(Iterable names) { - ListBuffer files = new ListBuffer(); - for (String name : names) { - files.append(new File(name)); - } - return getJavaFileObjectsFromFiles(files.toList()); - } - - public JavaFileObject getJavaFileForInput(Location location, String className, JavaFileObject.Kind kind) throws IOException { - List result = findInside(location, className, kind == null ? null : Collections.singleton(kind), true); - if (!result.isEmpty()) { - return result.get(0); - } - return null; - } - - @Override - public FileObject getFileForInput(Location location, String packageName, String relativeName) throws IOException { - return getJavaFileForInput(location, packageName + "/" + relativeName, getKind(relativeName)); - } - - @Override - public FileObject getFileForOutput(Location location, String packageName, String relativeName, FileObject sibling) throws IOException { - return getJavaFileForOutput(location, packageName + "/" + relativeName, getKind(relativeName), null); - } - - @Override - public Iterable getLocation(Location location) { - return myStandardFileManager.getLocation(location); - } - - @Override - public void setLocation(Location location, Iterable path) throws IOException { - myStandardFileManager.setLocation(location, path); - } - - @Override - public boolean hasLocation(Location location) { - return myStandardFileManager.hasLocation(location); - } -} diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/api/Output.java b/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/api/Output.java deleted file mode 100644 index 8cdf09c7dbfa..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/api/Output.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright 2000-2010 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.compiler.impl.javaCompiler.api; - -import org.jetbrains.annotations.Nullable; - -import javax.tools.*; -import java.io.*; -import java.net.URI; - -/** -* User: cdr -*/ -@SuppressWarnings({"ALL"}) -class Output extends SimpleJavaFileObject { - private final CompAPIDriver myCompAPIDriver; - @Nullable - private volatile byte[] myFileBytes; - - Output(URI uri, CompAPIDriver compAPIDriver, final Kind kind) { - super(uri, kind); - myCompAPIDriver = compAPIDriver; - } - - @Override - public ByteArrayOutputStream openOutputStream() { - return new ByteArrayOutputStream() { - @Override - public void close() throws IOException { - super.close(); - final byte[] bytes = toByteArray(); - myFileBytes = bytes; - if (Kind.CLASS.equals(kind)) { - myCompAPIDriver.offerClassFile(toUri(), bytes); - } - } - }; - } - - @Override - public InputStream openInputStream() throws IOException { - final byte[] bytes = myFileBytes; - if (bytes == null) { - throw new FileNotFoundException(toUri().getPath()); - } - return new ByteArrayInputStream(bytes); - } - - @Override - public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException { - final byte[] bytes = myFileBytes; - if (bytes == null) { - throw null; - } - return new String(bytes); - } - - @Override - public int hashCode() { - return toUri().hashCode(); - } - - @Override - public boolean equals(Object obj) { - return obj instanceof JavaFileObject && toUri().equals(((JavaFileObject)obj).toUri()); - } -} diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/eclipse/EclipseCompiler.java b/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/eclipse/EclipseCompiler.java index d9a7c303494f..874fb51a5625 100644 --- a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/eclipse/EclipseCompiler.java +++ b/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/eclipse/EclipseCompiler.java @@ -15,43 +15,24 @@ */ package com.intellij.compiler.impl.javaCompiler.eclipse; -import com.intellij.compiler.OutputParser; -import com.intellij.compiler.impl.CompilerUtil; -import com.intellij.compiler.impl.javaCompiler.ExternalCompiler; -import com.intellij.compiler.impl.javaCompiler.ModuleChunk; -import com.intellij.openapi.application.ApplicationManager; +import com.intellij.compiler.impl.javaCompiler.BackendCompiler; import com.intellij.openapi.application.PathManager; -import com.intellij.openapi.compiler.CompileContext; -import com.intellij.openapi.compiler.CompileScope; import com.intellij.openapi.compiler.CompilerBundle; -import com.intellij.openapi.diagnostic.Logger; +import com.intellij.openapi.fileTypes.FileType; +import com.intellij.openapi.fileTypes.StdFileTypes; import com.intellij.openapi.options.Configurable; import com.intellij.openapi.project.Project; -import com.intellij.openapi.projectRoots.JavaSdkType; -import com.intellij.openapi.projectRoots.Sdk; -import com.intellij.openapi.projectRoots.impl.JavaAwareProjectJdkTableImpl; -import com.intellij.openapi.ui.Messages; -import com.intellij.openapi.util.ThrowableComputable; -import com.intellij.openapi.util.io.FileUtil; -import com.intellij.openapi.util.text.StringUtil; -import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.util.ArrayUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import org.jetbrains.jps.model.java.compiler.EclipseCompilerOptions; import org.jetbrains.jps.model.java.compiler.JavaCompilers; -import java.io.*; -import java.util.ArrayList; -import java.util.List; -import java.util.StringTokenizer; - -public class EclipseCompiler extends ExternalCompiler { - private static final Logger LOG = Logger.getInstance("#com.intellij.compiler.impl.javaCompiler.eclipse.EclipseCompiler"); +import java.io.File; +import java.io.FilenameFilter; +import java.util.Collections; +import java.util.Set; +public class EclipseCompiler implements BackendCompiler { private final Project myProject; - private final List myTempFiles = new ArrayList(); private static final String COMPILER_CLASS_NAME = "org.eclipse.jdt.core.compiler.batch.BatchCompiler"; @NonNls private static final String PATH_TO_COMPILER_JAR = findJarPah(); @@ -84,24 +65,6 @@ public class EclipseCompiler extends ExternalCompiler { return file.exists(); } - public boolean checkCompiler(final CompileScope scope) { - if (!isInitialized()) { - Messages.showMessageDialog( - myProject, - CompilerBundle.message("eclipse.compiler.error.jar.not.found", PATH_TO_COMPILER_JAR), - CompilerBundle.message("compiler.eclipse.name"), - Messages.getErrorIcon() - ); - return false; - } - return true; - } - - @NonNls - public static String getCompilerClass() { - return "org.eclipse.jdt.internal.compiler.batch.Main"; - } - @NotNull public String getId() { // used for externalization return JavaCompilers.ECLIPSE_ID; @@ -117,116 +80,9 @@ public class EclipseCompiler extends ExternalCompiler { return new EclipseCompilerConfigurable(EclipseCompilerConfiguration.getOptions(myProject, EclipseCompilerConfiguration.class)); } - public OutputParser createErrorParser(@NotNull final String outputDir, Process process) { - return new EclipseCompilerErrorParser(); - } - - @Nullable - public OutputParser createOutputParser(@NotNull final String outputDir) { - return new EclipseCompilerOutputParser(outputDir); - } - @NotNull - public String[] createStartupCommand(final ModuleChunk chunk, final CompileContext context, final String outputPath) - throws IOException { - - final ArrayList commandLine = new ArrayList(); - ApplicationManager.getApplication().runReadAction(new ThrowableComputable() { - @Override - public Void compute() throws IOException { - createStartupCommand(chunk, commandLine, outputPath, true); - return null; - } - }); - return ArrayUtil.toStringArray(commandLine); - } - - private void createStartupCommand(final ModuleChunk chunk, - @NonNls final ArrayList commandLine, - final String outputPath, - final boolean useTempFile) throws IOException { - final EclipseCompilerOptions options = EclipseCompilerConfiguration.getOptions(myProject, EclipseCompilerConfiguration.class); - - final Sdk projectJdk = JavaAwareProjectJdkTableImpl.getInstanceEx().getInternalJdk(); - final String vmExePath = ((JavaSdkType)projectJdk.getSdkType()).getVMExecutablePath(projectJdk); - commandLine.add(vmExePath); - commandLine.add("-Xmx" + options.MAXIMUM_HEAP_SIZE + "m"); - - CompilerUtil.addLocaleOptions(commandLine, false); - - commandLine.add("-classpath"); - commandLine.add(PATH_TO_COMPILER_JAR); - commandLine.add(getCompilerClass()); - - addCommandLineOptions(commandLine, chunk, outputPath, options, useTempFile, true); - } - - public void addCommandLineOptions(@NotNull @NonNls final List commandLine, - @NotNull final ModuleChunk chunk, - @NotNull final String outputPath, - @NotNull final EclipseCompilerOptions options, - final boolean useTempFile, - boolean quoteBootClasspath) throws IOException { - final Sdk jdk = chunk.getJdk(); - CompilerUtil.addSourceCommandLineSwitch(jdk, chunk.getLanguageLevel(), commandLine); - CompilerUtil.addTargetCommandLineSwitch(chunk, commandLine); - - final String bootCp = chunk.getCompilationBootClasspath(); - - final String classPath = chunk.getCompilationClasspath(); - - if (!StringUtil.isEmpty(bootCp)) { - commandLine.add("-bootclasspath"); - // important: need to quote boot classpath if path to jdk contain spaces - commandLine.add(quoteBootClasspath ? CompilerUtil.quotePath(bootCp) : bootCp); - } - - if (!StringUtil.isEmpty(classPath)) { - commandLine.add("-classpath"); - commandLine.add(classPath); - } - - commandLine.add("-d"); - commandLine.add(outputPath.replace('/', File.separatorChar)); - - commandLine.add("-verbose"); - StringTokenizer tokenizer = new StringTokenizer(new EclipseSettingsBuilder(options).getOptionsString(chunk), " "); - while (tokenizer.hasMoreTokens()) { - commandLine.add(tokenizer.nextToken()); - } - - final List files = chunk.getFilesToCompile(); - - if (useTempFile) { - File sourcesFile = FileUtil.createTempFile("javac", ".tmp"); - sourcesFile.deleteOnExit(); - myTempFiles.add(sourcesFile); - final PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(sourcesFile))); - try { - for (final VirtualFile file : files) { - // Important: should use "/" slashes! - // but not for JDK 1.5 - see SCR 36673 - final String path = file.getPath().replace('/', File.separatorChar); - if (LOG.isDebugEnabled()) { - LOG.debug("Adding path for compilation " + path); - } - writer.println(CompilerUtil.quotePath(path)); - } - } - finally { - writer.close(); - } - commandLine.add("@" + sourcesFile.getAbsolutePath()); - } - else { - for (VirtualFile file : files) { - commandLine.add(file.getPath()); - } - } - } - - public void compileFinished() { - FileUtil.asyncDelete(myTempFiles); - myTempFiles.clear(); + @Override + public Set getCompilableFileTypes() { + return Collections.singleton(StdFileTypes.JAVA); } } diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/eclipse/EclipseCompilerDriver.java b/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/eclipse/EclipseCompilerDriver.java deleted file mode 100644 index 9538c1606b9f..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/eclipse/EclipseCompilerDriver.java +++ /dev/null @@ -1,255 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * @author Alexey - */ - -package com.intellij.compiler.impl.javaCompiler.eclipse; - -import com.intellij.compiler.OutputParser; -import com.intellij.compiler.impl.javaCompiler.FileObject; -import com.intellij.openapi.application.ApplicationManager; -import com.intellij.openapi.compiler.CompileContext; -import com.intellij.openapi.compiler.CompilerBundle; -import com.intellij.openapi.compiler.CompilerMessageCategory; -import com.intellij.openapi.diagnostic.Logger; -import com.intellij.openapi.editor.Document; -import com.intellij.openapi.fileEditor.FileDocumentManager; -import com.intellij.openapi.progress.ProcessCanceledException; -import com.intellij.openapi.progress.ProgressIndicator; -import com.intellij.openapi.progress.ProgressManager; -import com.intellij.openapi.project.Project; -import com.intellij.openapi.util.Computable; -import com.intellij.openapi.util.io.FileUtil; -import com.intellij.openapi.vfs.LocalFileSystem; -import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.openapi.vfs.VirtualFileManager; -import org.eclipse.jdt.core.compiler.IProblem; -import org.eclipse.jdt.core.compiler.InvalidInputException; -import org.eclipse.jdt.internal.compiler.*; -import org.eclipse.jdt.internal.compiler.Compiler; -import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration; -import org.eclipse.jdt.internal.compiler.batch.CompilationUnit; -import org.eclipse.jdt.internal.compiler.batch.FileSystem; -import org.eclipse.jdt.internal.compiler.batch.Main; -import org.eclipse.jdt.internal.compiler.env.INameEnvironment; -import org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory; - -import java.io.File; -import java.io.IOException; -import java.io.PrintWriter; -import java.io.StringWriter; -import java.util.Locale; -import java.util.Map; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.LinkedBlockingQueue; - -public class EclipseCompilerDriver { - private static final Logger LOG = Logger.getInstance("#com.intellij.compiler.impl.javaCompiler.eclipse.EclipseCompilerDriver"); - - private String[] sourceFilePaths; - private Map compilerOptions; - private final BlockingQueue myCompilationResults = new LinkedBlockingQueue(); - private FileSystem classPath; - - private void parseCommandLine(String[] args) throws InvalidInputException { - StringWriter err = new StringWriter(); - Main driver = new Main(null, new PrintWriter(err), false); - driver.configure(args); - StringBuffer buffer = err.getBuffer(); - if (buffer.length() != 0) { - throw new InvalidInputException(buffer.toString()); - } - sourceFilePaths = driver.filenames; - compilerOptions = driver.options; - classPath = driver.getLibraryAccess(); - } - - private CompilationUnit[] getCompilationUnits() { - int fileCount = sourceFilePaths.length; - CompilationUnit[] units = new CompilationUnit[fileCount]; - final String defaultEncoding = null; - - for (int i = 0; i < fileCount; i++) { - units[i] = new MyCompilationUnit(sourceFilePaths[i], defaultEncoding); - } - return units; - } - - private ICompilerRequestor getBatchRequestor(final CompileContext compileContext) { - return new ICompilerRequestor() { - public void acceptResult(CompilationResult compilationResult) { - ProgressIndicator progress = compileContext.getProgressIndicator(); - if (progress != null) { - progress.checkCanceled(); - } - myCompilationResults.offer(compilationResult); - } - }; - } - - private static final CompilationResult END_OF_STREAM = new CompilationResult(new char[0], 0, 0, 0); - - private INameEnvironment getEnvironment() { - return classPath; - } - - private static IProblemFactory getProblemFactory() { - return new DefaultProblemFactory(Locale.getDefault()); - } - - private static IErrorHandlingPolicy getHandlingPolicy() { - return new IErrorHandlingPolicy() { - public boolean proceedOnErrors() { - return false; // stop if there are some errors - } - - public boolean stopOnFirstError() { - return false; - } - }; - } - - private Map getCompilerOptions() { - return compilerOptions; - } - - - private void compile(final CompileContext compileContext) { - final INameEnvironment environment = getEnvironment(); - - Compiler compiler = - new Compiler( - environment, - getHandlingPolicy(), - getCompilerOptions(), - getBatchRequestor(compileContext), - getProblemFactory()){ - protected void handleInternalException(Throwable internalException, CompilationUnitDeclaration unit, CompilationResult result) { - if (internalException instanceof ProcessCanceledException) throw (ProcessCanceledException)internalException; - super.handleInternalException(internalException, unit, result); - } - }; - compiler.parseThreshold = 2500; - try { - compiler.compile(getCompilationUnits()); - } - catch (ProcessCanceledException e) { - //compileContext.addMessage(CompilerMessageCategory.ERROR, "Canceled",null,-1,-1); - } - catch (Exception e) { - ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator(); - if (indicator == null || !indicator.isCanceled()) { - compileContext.addMessage(CompilerMessageCategory.ERROR, "Internal Error: "+e.toString(),null,-1,-1); - } - } - finally { - myCompilationResults.offer(END_OF_STREAM); - environment.cleanup(); - } - } - - public boolean processMessageLine(final OutputParser.Callback callback, final String outputDir, Project project) { - ProgressManager.checkCanceled(); - CompilationResult result; - try { - result = myCompilationResults.take(); - } - catch (InterruptedException e) { - LOG.error(e); - return true; - } - if (result == END_OF_STREAM) { - return false; - } - - String file = String.valueOf(result.getFileName()); - callback.setProgressText(CompilerBundle.message("eclipse.compiler.parsing", file)); - callback.fileProcessed(file); - - ClassFile[] classFiles = result.getClassFiles(); - for (ClassFile classFile : classFiles) { - String filePath = String.valueOf(classFile.fileName()); - String relativePath = FileUtil.toSystemDependentName(filePath + ".class"); - String path = FileUtil.toSystemDependentName(outputDir) + File.separatorChar + relativePath; - - byte[] bytes = classFile.getBytes(); - File out = new File(path); - - callback.fileGenerated(new FileObject(out,bytes)); - } - IProblem[] problems = result.getProblems(); - if (problems != null) { - for (IProblem problem : problems) { - CompilerMessageCategory category = problem.isError() ? CompilerMessageCategory.ERROR - : problem.isWarning() ? CompilerMessageCategory.WARNING : - CompilerMessageCategory.INFORMATION; - String filePath = String.valueOf(problem.getOriginatingFileName()); - String url = VirtualFileManager.constructUrl(LocalFileSystem.PROTOCOL, FileUtil.toSystemIndependentName(filePath)); - int lineNumber = problem.getSourceLineNumber(); - int sourceStart = problem.getSourceStart(); - int column = getColumn(url, lineNumber, sourceStart, project); - callback.message(category, problem.getMessage(), url, lineNumber, column); - } - } - return true; - } - - private static int getColumn(final String url, final int lineNumber, final int sourceStart, final Project project) { - if (sourceStart == 0) return 0; - return ApplicationManager.getApplication().runReadAction(new Computable() { - public Integer compute() { - VirtualFile file = VirtualFileManager.getInstance().findFileByUrl(url); - if (file == null) return 0; - Document document = FileDocumentManager.getInstance().getDocument(file); - if (document == null) return 0; - int lineStartOffset = document.getLineStartOffset(lineNumber - 1); - - String lineSeparator = FileDocumentManager.getInstance().getLineSeparator(file, project); - int offsetInVirtualFile = sourceStart - (lineNumber - 1) * (lineSeparator.length() - 1); - return offsetInVirtualFile - lineStartOffset + 1; - } - }).intValue(); - } - - public void parseCommandLineAndCompile(final String[] finalCmds, final CompileContext compileContext) throws Exception { - parseCommandLine(finalCmds); - - compile(compileContext); - } - - private static class MyCompilationUnit extends CompilationUnit { - private final String myDefaultEncoding; - - private MyCompilationUnit(final String sourceFilePath, final String defaultEncoding) { - super(null, sourceFilePath, defaultEncoding); - myDefaultEncoding = defaultEncoding; - } - - public char[] getContents() { - final String fileName = String.valueOf(getFileName()); - try { - ProgressManager.checkCanceled(); - return FileUtil.loadFileText(new File(fileName), myDefaultEncoding); - } - catch (IOException e) { - LOG.error(e); - } - return null; - } - } -} diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/eclipse/EclipseCompilerErrorParser.java b/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/eclipse/EclipseCompilerErrorParser.java deleted file mode 100644 index aa87dcbe47b9..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/eclipse/EclipseCompilerErrorParser.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.compiler.impl.javaCompiler.eclipse; - -import com.intellij.compiler.OutputParser; -import com.intellij.openapi.application.ApplicationManager; -import com.intellij.openapi.compiler.CompilerMessageCategory; -import com.intellij.openapi.editor.Document; -import com.intellij.openapi.fileEditor.FileDocumentManager; -import com.intellij.openapi.util.Computable; -import com.intellij.openapi.util.io.FileUtil; -import com.intellij.openapi.vfs.LocalFileSystem; -import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.openapi.vfs.VirtualFileManager; -import org.jetbrains.annotations.NonNls; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public class EclipseCompilerErrorParser extends OutputParser { - - private final StringBuilder problemText = new StringBuilder(); - - public boolean processMessageLine(Callback callback) { - @NonNls String line = callback.getNextLine(); - if (line == null) { - spitOutProblem(callback); - return false; - } - if (line.trim().length() == 0) { - return true; - } - if (line.equals("----------")) { - spitOutProblem(callback); - problemText.setLength(0); - return true; - } - problemText.append(line); - problemText.append("\n"); - return true; - } - - private void spitOutProblem(final Callback callback) { - final String problem = problemText.toString(); - if (problem.trim().length() == 0) return; - - @NonNls final String problemTemplate = "(\\d*)\\. (\\w*) in (.*)" + - "\\s*\\(at line (\\d*)\\)\n" + - "\\s*(.*)\n" + - "(\\s*)\\^+\n" + - "(.*)\\s*"; - final Pattern PATTERN = Pattern.compile(problemTemplate, Pattern.DOTALL); - Matcher matcher = PATTERN.matcher(problem); - if (matcher.matches()) { - //String seqN = matcher.group(1); - @NonNls String problemType = matcher.group(2); - String path = matcher.group(3).trim(); - String lineNum = matcher.group(4); - String codeSnippet = matcher.group(5); - String indentWhiteSpace = matcher.group(6); - String message = matcher.group(7).trim(); - - CompilerMessageCategory messageCategory; - if ("WARNING".equals(problemType)) { - messageCategory = CompilerMessageCategory.WARNING; - } - else if ("ERROR".equals(problemType)) { - messageCategory = CompilerMessageCategory.ERROR; - } - else { - messageCategory = CompilerMessageCategory.INFORMATION; - } - final String url = VirtualFileManager.constructUrl(LocalFileSystem.PROTOCOL, FileUtil.toSystemIndependentName(path)); - final int line = Integer.parseInt(lineNum); - int col = indentWhiteSpace.length(); - final String offendingCode = codeSnippet.substring(col-1); - - // try to find similar text inside source file - int colFromFile = ApplicationManager.getApplication().runReadAction(new Computable() { - public Integer compute() { - int index = -1; - VirtualFile file = VirtualFileManager.getInstance().findFileByUrl(url); - Document document = file == null ? null : FileDocumentManager.getInstance().getDocument(file); - if (document != null) { - // line is one-based - int docLine = line == 0 ? 0 : line-1; - int startOffset = document.getLineStartOffset(docLine); - int endOffset = document.getLineEndOffset(docLine); - String lineText = document.getText().substring(startOffset, endOffset); - index = lineText.indexOf(offendingCode); - if (index == -1) { - for (index = 0; index < lineText.length(); index++) { - if (!Character.isWhitespace(lineText.charAt(index))) break; - } - if (index == lineText.length()) index = -1; - } - // to one-based - if (index != -1) { - index++; - } - } - return index; - } - }).intValue(); - if (colFromFile != -1) { - col = colFromFile; - } - callback.message(messageCategory, message, url, line, col); - } - else { - callback.message(CompilerMessageCategory.WARNING, problem, null, -1, -1); - } - } - - public boolean isTrimLines() { - return false; - } -} diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/eclipse/EclipseCompilerOutputParser.java b/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/eclipse/EclipseCompilerOutputParser.java deleted file mode 100644 index 12ceca333c50..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/eclipse/EclipseCompilerOutputParser.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.compiler.impl.javaCompiler.eclipse; - -import com.intellij.compiler.OutputParser; -import com.intellij.compiler.impl.javaCompiler.FileObject; -import com.intellij.openapi.compiler.CompilerBundle; -import com.intellij.openapi.compiler.CompilerMessageCategory; -import com.intellij.openapi.util.io.FileUtil; -import org.jetbrains.annotations.NonNls; - -import java.io.File; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public class EclipseCompilerOutputParser extends OutputParser { - private final String myOutputDir; - - public EclipseCompilerOutputParser(final String outputDir) { - myOutputDir = outputDir; - } - - @NonNls private static final Pattern PATH_PATTERN = Pattern.compile("\\s*(.*) - #.*"); - @NonNls private static final Pattern COMPILED_PATTERN = Pattern.compile("\\[\\d* unit(s)? compiled\\]"); - @NonNls private static final Pattern GENERATED_PATTERN = Pattern.compile("\\[\\d* \\.class file(s)? generated\\]"); - public boolean processMessageLine(Callback callback) { - @NonNls String line = callback.getNextLine(); - if (line == null) { - return false; - } - if (line.trim().length() == 0) { - return true; - } - if (line.startsWith("[parsing ")) { - Matcher matcher = PATH_PATTERN.matcher(line.substring("[parsing ".length())); - matcher.matches(); - String path = matcher.group(1); - callback.setProgressText(CompilerBundle.message("eclipse.compiler.parsing", path)); - callback.fileProcessed(path); - return true; - } - if (line.startsWith("[reading ")) { - //StringTokenizer tokenizer = new StringTokenizer(line.substring("[reading ".length()), " ]"); - //String fqn = tokenizer.nextToken(); - callback.setProgressText(CompilerBundle.message("eclipse.compiler.reading")); - return true; - } - if (line.startsWith("[analyzing ")) { - Matcher matcher = PATH_PATTERN.matcher(line.substring("[analyzing ".length())); - matcher.matches(); - String path = matcher.group(1); - callback.setProgressText(CompilerBundle.message("eclipse.compiler.analyzing", path)); - return true; - } - if (line.startsWith("[completed ")) { - //Matcher matcher = PATH_PATTERN.matcher(line.substring("[completed ".length())); - //matcher.matches(); - //String path = matcher.group(1); - //callback.setProgressText(CompilerBundle.message("eclipse.compiler.completed", path)); - return true; - } - if (line.startsWith("[writing ")) { - Matcher matcher = PATH_PATTERN.matcher(line.substring("[writing ".length())); - matcher.matches(); - String path = matcher.group(1); - String absPath = FileUtil.toSystemDependentName(myOutputDir + '/' + path); - //callback.setProgressText(CompilerBundle.message("eclipse.compiler.writing", absPath)); - callback.fileGenerated(new FileObject(new File(absPath))); - return true; - } - if (COMPILED_PATTERN.matcher(line).matches() || GENERATED_PATTERN.matcher(line).matches()) { - return true; - } - callback.message(CompilerMessageCategory.INFORMATION, line, null, -1, -1); - return true; - } -} diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/eclipse/EclipseEmbeddedCompiler.java b/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/eclipse/EclipseEmbeddedCompiler.java deleted file mode 100644 index ed6c03a451be..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/eclipse/EclipseEmbeddedCompiler.java +++ /dev/null @@ -1,155 +0,0 @@ -/* - * Copyright 2000-2014 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.compiler.impl.javaCompiler.eclipse; - -import com.intellij.compiler.OutputParser; -import com.intellij.compiler.impl.javaCompiler.BackendCompiler; -import com.intellij.compiler.impl.javaCompiler.ModuleChunk; -import com.intellij.openapi.application.ApplicationManager; -import com.intellij.openapi.compiler.CompileContext; -import com.intellij.openapi.compiler.CompileScope; -import com.intellij.openapi.compiler.CompilerBundle; -import com.intellij.openapi.compiler.CompilerMessageCategory; -import com.intellij.openapi.diagnostic.Logger; -import com.intellij.openapi.fileTypes.FileType; -import com.intellij.openapi.fileTypes.StdFileTypes; -import com.intellij.openapi.options.Configurable; -import com.intellij.openapi.project.Project; -import com.intellij.openapi.util.ThrowableComputable; -import com.intellij.util.ArrayUtil; -import org.jetbrains.annotations.NonNls; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import org.jetbrains.jps.model.java.compiler.EclipseCompilerOptions; -import org.jetbrains.jps.model.java.compiler.JavaCompilers; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Set; - - -public class EclipseEmbeddedCompiler implements BackendCompiler { - private static final Logger LOG = Logger.getInstance("#com.intellij.compiler.impl.javaCompiler.eclipse.EclipseEmbeddedCompiler"); - - private final Project myProject; - private final EclipseCompiler myEclipseExternalCompiler; - private int myExitCode; - private final EclipseCompilerDriver myEclipseCompilerDriver; - private static final Set COMPILABLE_TYPES = Collections.singleton(StdFileTypes.JAVA); - - public EclipseEmbeddedCompiler(Project project) { - myProject = project; - myEclipseExternalCompiler = new EclipseCompiler(project); - myEclipseCompilerDriver = new EclipseCompilerDriver(); - } - - public boolean checkCompiler(final CompileScope scope) { - return myEclipseCompilerDriver != null && myEclipseExternalCompiler.checkCompiler(scope); - } - - @NotNull - @NonNls - public String getId() { // used for externalization - return JavaCompilers.ECLIPSE_EMBEDDED_ID; - } - - @NotNull - public String getPresentableName() { - return CompilerBundle.message("compiler.eclipse.embedded.name"); - } - - @NotNull - public Configurable createConfigurable() { - return new EclipseCompilerConfigurable(EclipseEmbeddedCompilerConfiguration.getOptions(myProject, EclipseEmbeddedCompilerConfiguration.class)); - } - - @NotNull - public Set getCompilableFileTypes() { - return COMPILABLE_TYPES; - } - - @Nullable - public OutputParser createErrorParser(@NotNull final String outputDir, Process process) { - return new OutputParser() { - public boolean processMessageLine(Callback callback) { - return myEclipseCompilerDriver.processMessageLine(callback, outputDir, myProject); - } - }; - } - - @Nullable - public OutputParser createOutputParser(@NotNull final String outputDir) { - return null; - } - - public void compileFinished() { - } - - - @NotNull - public Process launchProcess(@NotNull final ModuleChunk chunk, @NotNull final String outputDir, @NotNull final CompileContext compileContext) throws IOException { - @NonNls final ArrayList commandLine = new ArrayList(); - ApplicationManager.getApplication().runReadAction(new ThrowableComputable() { - @Override - public Void compute() throws IOException { - final EclipseCompilerOptions options = - EclipseCompilerConfiguration.getOptions(myProject, EclipseEmbeddedCompilerConfiguration.class); - myEclipseExternalCompiler.addCommandLineOptions(commandLine, chunk, outputDir, options, false, false); - return null; - } - }); - - return new Process() { - public OutputStream getOutputStream() { - throw new UnsupportedOperationException(); - } - - public InputStream getInputStream() { - return null; - } - - public InputStream getErrorStream() { - return null; - } - - public void destroy() { - } - - public int waitFor() { - try { - commandLine.remove("-verbose"); - String[] finalCmds = ArrayUtil.toStringArray(commandLine); - myEclipseCompilerDriver.parseCommandLineAndCompile(finalCmds, compileContext); - myExitCode = 0; - return myExitCode; - } - catch (Exception e) { - compileContext.addMessage(CompilerMessageCategory.ERROR, e.getMessage(), null, -1, -1); - LOG.info(e); - myExitCode = -1; - return -1; - } - } - - public int exitValue() { - return myExitCode; - } - }; - } -} diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/eclipse/EclipseEmbeddedCompilerConfiguration.java b/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/eclipse/EclipseEmbeddedCompilerConfiguration.java deleted file mode 100755 index cb1652369c39..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/eclipse/EclipseEmbeddedCompilerConfiguration.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright 2000-2012 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.compiler.impl.javaCompiler.eclipse; - -import com.intellij.openapi.components.State; -import com.intellij.openapi.components.Storage; -import com.intellij.openapi.components.StoragePathMacros; -import com.intellij.openapi.components.StorageScheme; - -@State( - name = "EclipseEmbeddedCompilerSettings", - storages = { - @Storage(file = StoragePathMacros.PROJECT_FILE), - @Storage(file = StoragePathMacros.PROJECT_CONFIG_DIR + "/compiler.xml", scheme = StorageScheme.DIRECTORY_BASED) - } -) -public class EclipseEmbeddedCompilerConfiguration extends EclipseCompilerConfiguration { -} \ No newline at end of file diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/javac/FilePathActionJavac.java b/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/javac/FilePathActionJavac.java index fc32b08a7074..835c4fe2d662 100644 --- a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/javac/FilePathActionJavac.java +++ b/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/javac/FilePathActionJavac.java @@ -16,14 +16,12 @@ package com.intellij.compiler.impl.javaCompiler.javac; import com.intellij.compiler.OutputParser; -import com.intellij.compiler.impl.javaCompiler.FileObject; import com.intellij.openapi.compiler.CompilerBundle; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.fileTypes.FileTypeManager; import com.intellij.openapi.fileTypes.StdFileTypes; -import java.io.File; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -59,7 +57,7 @@ public class FilePathActionJavac extends JavacParserAction { callback.setProgressText(CompilerBundle.message("progress.parsing.file", name)); } else if (StdFileTypes.CLASS.equals(fileType)) { - callback.fileGenerated(new FileObject(new File(filePath))); + callback.fileGenerated(filePath); } } } 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 e962a9373913..feb04273b1f5 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 @@ -15,122 +15,26 @@ */ package com.intellij.compiler.impl.javaCompiler.javac; -import com.intellij.compiler.CompilerConfiguration; -import com.intellij.compiler.CompilerConfigurationImpl; -import com.intellij.compiler.CompilerIOUtil; -import com.intellij.compiler.OutputParser; -import com.intellij.compiler.impl.CompilerUtil; -import com.intellij.compiler.impl.javaCompiler.ExternalCompiler; -import com.intellij.compiler.impl.javaCompiler.ModuleChunk; -import com.intellij.openapi.application.ApplicationManager; -import com.intellij.openapi.compiler.CompileContext; -import com.intellij.openapi.compiler.CompileScope; +import com.intellij.compiler.impl.javaCompiler.BackendCompiler; import com.intellij.openapi.compiler.CompilerBundle; -import com.intellij.openapi.compiler.CompilerPaths; -import com.intellij.openapi.diagnostic.Logger; -import com.intellij.openapi.module.Module; +import com.intellij.openapi.fileTypes.FileType; +import com.intellij.openapi.fileTypes.StdFileTypes; import com.intellij.openapi.options.Configurable; import com.intellij.openapi.project.Project; -import com.intellij.openapi.projectRoots.*; -import com.intellij.openapi.projectRoots.ex.JavaSdkUtil; -import com.intellij.openapi.projectRoots.impl.MockJdkWrapper; -import com.intellij.openapi.roots.ModuleRootManager; -import com.intellij.openapi.ui.Messages; -import com.intellij.openapi.util.Computable; -import com.intellij.openapi.util.io.FileUtil; -import com.intellij.openapi.util.text.StringUtil; -import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.pom.java.LanguageLevel; -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 org.jetbrains.jps.model.java.compiler.JavaCompilers; -import org.jetbrains.jps.model.java.compiler.JpsJavaCompilerOptions; -import java.io.*; -import java.util.*; +import java.util.Collections; +import java.util.Set; -public class JavacCompiler extends ExternalCompiler { - private static final Logger LOG = Logger.getInstance("#com.intellij.compiler.impl.javaCompiler.javac.JavacCompiler"); +public class JavacCompiler implements BackendCompiler { private final Project myProject; - private final List myTempFiles = new ArrayList(); - @NonNls private static final String JAVAC_MAIN_CLASS_OLD = "sun.tools.javac.Main"; - @NonNls public static final String JAVAC_MAIN_CLASS = "com.sun.tools.javac.Main"; - private boolean myAnnotationProcessorMode = false; public JavacCompiler(Project project) { myProject = project; } - public boolean isAnnotationProcessorMode() { - return myAnnotationProcessorMode; - } - - /** - * @param annotationProcessorMode - * @return previous value - */ - public boolean setAnnotationProcessorMode(boolean annotationProcessorMode) { - final boolean oldValue = myAnnotationProcessorMode; - myAnnotationProcessorMode = annotationProcessorMode; - return oldValue; - } - - public boolean checkCompiler(final CompileScope scope) { - final Module[] modules = scope.getAffectedModules(); - final Set checkedJdks = new HashSet(); - for (final Module module : modules) { - final Sdk jdk = ModuleRootManager.getInstance(module).getSdk(); - if (jdk == null || checkedJdks.contains(jdk)) { - continue; - } - checkedJdks.add(jdk); - final SdkTypeId sdkType = jdk.getSdkType(); - if (!(sdkType instanceof JavaSdkType)) { - continue; - } - final VirtualFile homeDirectory = jdk.getHomeDirectory(); - if (homeDirectory == null) { - Messages.showMessageDialog( - myProject, CompilerBundle.jdkHomeNotFoundMessage(jdk), CompilerBundle.message("compiler.javac.name"), Messages.getErrorIcon() - ); - return false; - } - final String vmExecutablePath = ((JavaSdkType)sdkType).getVMExecutablePath(jdk); - if (vmExecutablePath == null) { - Messages.showMessageDialog( - myProject, CompilerBundle.message("javac.error.vm.executable.missing", jdk.getName()), CompilerBundle.message("compiler.javac.name"), Messages.getErrorIcon() - ); - return false; - } - final String toolsJarPath = ((JavaSdkType)sdkType).getToolsPath(jdk); - if (toolsJarPath == null) { - Messages.showMessageDialog( - myProject, CompilerBundle.message("javac.error.tools.jar.missing", jdk.getName()), CompilerBundle.message("compiler.javac.name"), Messages.getErrorIcon() - ); - return false; - } - final String versionString = jdk.getVersionString(); - if (versionString == null) { - Messages.showMessageDialog( - myProject, CompilerBundle.message("javac.error.unknown.jdk.version", jdk.getName()), CompilerBundle.message("compiler.javac.name"), Messages.getErrorIcon() - ); - return false; - } - - if (CompilerUtil.isOfVersion(versionString, "1.0")) { - Messages.showMessageDialog( - myProject, CompilerBundle.message("javac.error.1_0_compilation.not.supported"), CompilerBundle.message("compiler.javac.name"), Messages.getErrorIcon() - ); - return false; - } - } - - return true; - } - @NotNull @NonNls public String getId() { // used for externalization @@ -147,304 +51,8 @@ public class JavacCompiler extends ExternalCompiler { return new JavacConfigurable(JavacConfiguration.getOptions(myProject, JavacConfiguration.class)); } - public OutputParser createErrorParser(@NotNull final String outputDir, Process process) { - return new JavacOutputParser(myProject); - } - - public OutputParser createOutputParser(@NotNull final String outputDir) { - return null; - } - - private static class MyException extends RuntimeException { - private MyException(Throwable cause) { - super(cause); - } - } - - @NotNull - public String[] createStartupCommand(final ModuleChunk chunk, final CompileContext context, final String outputPath) - throws IOException, IllegalArgumentException { - - try { - return ApplicationManager.getApplication().runReadAction(new Computable() { - public String[] compute() { - try { - final List commandLine = new ArrayList(); - createStartupCommand(chunk, commandLine, outputPath, JavacConfiguration.getOptions(myProject, JavacConfiguration.class), context.isAnnotationProcessorsEnabled()); - return ArrayUtil.toStringArray(commandLine); - } - catch (IOException e) { - throw new MyException(e); - } - } - }); - } - catch (MyException e) { - Throwable cause = e.getCause(); - if (cause instanceof IOException) { - throw (IOException)cause; - } - throw e; - } - } - - private void createStartupCommand(final ModuleChunk chunk, @NonNls final List commandLine, final String outputPath, - JpsJavaCompilerOptions javacOptions, final boolean annotationProcessorsEnabled) throws IOException { - final Sdk jdk = getJdkForStartupCommand(chunk); - final String versionString = jdk.getVersionString(); - JavaSdkVersion version = JavaSdk.getInstance().getVersion(jdk); - if (versionString == null || version == null || !(jdk.getSdkType() instanceof JavaSdkType)) { - throw new IllegalArgumentException(CompilerBundle.message("javac.error.unknown.jdk.version", jdk.getName())); - } - final boolean isVersion1_0 = version == JavaSdkVersion.JDK_1_0; - final boolean isVersion1_1 = version == JavaSdkVersion.JDK_1_1; - - JavaSdkType sdkType = (JavaSdkType)jdk.getSdkType(); - - final String toolsJarPath = sdkType.getToolsPath(jdk); - if (toolsJarPath == null) { - throw new IllegalArgumentException(CompilerBundle.message("javac.error.tools.jar.missing", jdk.getName())); - } - - final String vmExePath = sdkType.getVMExecutablePath(jdk); - - commandLine.add(vmExePath); - - if (version.isAtLeast(JavaSdkVersion.JDK_1_2)) { - commandLine.add("-Xmx" + javacOptions.MAXIMUM_HEAP_SIZE + "m"); - } - else { - commandLine.add("-mx" + javacOptions.MAXIMUM_HEAP_SIZE + "m"); - } - - final List additionalOptions = - addAdditionalSettings(commandLine, javacOptions, myAnnotationProcessorMode, version, chunk, annotationProcessorsEnabled); - - CompilerUtil.addLocaleOptions(commandLine, false); - - commandLine.add("-classpath"); - - if (isVersion1_0) { - commandLine.add(sdkType.getToolsPath(jdk)); // do not use JavacRunner for jdk 1.0 - } - else { - commandLine.add(sdkType.getToolsPath(jdk) + File.pathSeparator + JavaSdkUtil.getIdeaRtJarPath()); - commandLine.add(JavacRunner.class.getName()); - commandLine.add("\"" + versionString + "\""); - } - - if (version.isAtLeast(JavaSdkVersion.JDK_1_3)) { - commandLine.add(JAVAC_MAIN_CLASS); - } - else { - commandLine.add(JAVAC_MAIN_CLASS_OLD); - } - - addCommandLineOptions(chunk, commandLine, outputPath, jdk, isVersion1_0, isVersion1_1, myTempFiles, true, true, myAnnotationProcessorMode); - - commandLine.addAll(additionalOptions); - - final List files = chunk.getFilesToCompile(); - - if (isVersion1_0) { - for (VirtualFile file : files) { - String path = file.getPath(); - if (LOG.isDebugEnabled()) { - LOG.debug("Adding path for compilation " + path); - } - commandLine.add(CompilerUtil.quotePath(path)); - } - } - else { - File sourcesFile = FileUtil.createTempFile("javac", ".tmp"); - sourcesFile.deleteOnExit(); - myTempFiles.add(sourcesFile); - final PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(sourcesFile))); - try { - for (final VirtualFile file : files) { - // Important: should use "/" slashes! - // but not for JDK 1.5 - see SCR 36673 - final String path = version.isAtLeast(JavaSdkVersion.JDK_1_5) ? file.getPath().replace('/', File.separatorChar) : file.getPath(); - if (LOG.isDebugEnabled()) { - LOG.debug("Adding path for compilation " + path); - } - writer.println(isVersion1_1 ? path : CompilerUtil.quotePath(path)); - } - } - finally { - writer.close(); - } - commandLine.add("@" + sourcesFile.getAbsolutePath()); - } - } - - public static List addAdditionalSettings(List commandLine, JpsJavaCompilerOptions javacOptions, boolean isAnnotationProcessing, - JavaSdkVersion version, ModuleChunk chunk, boolean annotationProcessorsEnabled) { - final List additionalOptions = new ArrayList(); - StringTokenizer tokenizer = new StringTokenizer(new JavacSettingsBuilder(javacOptions).getOptionsString(chunk), " "); - if (!version.isAtLeast(JavaSdkVersion.JDK_1_6)) { - isAnnotationProcessing = false; // makes no sense for these versions - annotationProcessorsEnabled = false; - } - if (isAnnotationProcessing) { - final AnnotationProcessingConfiguration config = CompilerConfiguration.getInstance(chunk.getProject()).getAnnotationProcessingConfiguration(chunk.getModules()[0]); - additionalOptions.add("-Xprefer:source"); - additionalOptions.add("-implicit:none"); - additionalOptions.add("-proc:only"); - if (!config.isObtainProcessorsFromClasspath()) { - final String processorPath = config.getProcessorPath(); - additionalOptions.add("-processorpath"); - additionalOptions.add(FileUtil.toSystemDependentName(processorPath)); - } - final Set processors = config.getProcessors(); - if (!processors.isEmpty()) { - additionalOptions.add("-processor"); - additionalOptions.add(StringUtil.join(processors, ",")); - } - for (Map.Entry entry : config.getProcessorOptions().entrySet()) { - additionalOptions.add("-A" + entry.getKey() + "=" +entry.getValue()); - } - } - else { - if (annotationProcessorsEnabled) { - // Unless explicitly specified by user, disable annotation processing by default for 'java compilation' mode - // This is needed to suppress unwanted side-effects from auto-discovered processors from compilation classpath - additionalOptions.add("-proc:none"); - } - } - - while (tokenizer.hasMoreTokens()) { - @NonNls String token = tokenizer.nextToken(); - if (version == JavaSdkVersion.JDK_1_0 && "-deprecation".equals(token)) { - continue; // not supported for this version - } - if (!version.isAtLeast(JavaSdkVersion.JDK_1_5) && "-Xlint".equals(token)) { - continue; // not supported in these versions - } - if (isAnnotationProcessing) { - if (token.startsWith("-proc:")) { - continue; - } - if (token.startsWith("-implicit:")) { - continue; - } - } - else { // compiling java - if (annotationProcessorsEnabled) { - // in this mode we have -proc:none already added above, so user's settings should be ignored - if (token.startsWith("-proc:")) { - continue; - } - } - } - if (token.startsWith("-J-")) { - commandLine.add(token.substring("-J".length())); - } - else { - additionalOptions.add(token); - } - } - - return additionalOptions; - } - - public static void addCommandLineOptions(ModuleChunk chunk, @NonNls List commandLine, String outputPath, Sdk jdk, - boolean version1_0, - boolean version1_1, - List tempFiles, boolean addSourcePath, boolean useTempFile, - boolean isAnnotationProcessingMode) throws IOException { - - LanguageLevel languageLevel = chunk.getLanguageLevel(); - CompilerUtil.addSourceCommandLineSwitch(jdk, languageLevel, commandLine); - CompilerUtil.addTargetCommandLineSwitch(chunk, commandLine); - - commandLine.add("-verbose"); - - final String cp = chunk.getCompilationClasspath(); - final String bootCp = chunk.getCompilationBootClasspath(); - - final String classPath; - if (version1_0 || version1_1) { - classPath = bootCp + File.pathSeparator + cp; - } - else { - classPath = cp; - commandLine.add("-bootclasspath"); - addClassPathValue(jdk, false, commandLine, bootCp, "javac_bootcp", tempFiles, useTempFile); - } - - commandLine.add("-classpath"); - addClassPathValue(jdk, version1_0, commandLine, classPath, "javac_cp", tempFiles, useTempFile); - - if (!version1_1 && !version1_0 && addSourcePath) { - commandLine.add("-sourcepath"); - // this way we tell the compiler that the sourcepath is "empty". However, javac thinks that sourcepath is 'new File("")' - // this may cause problems if we have java code in IDEA working directory - if (isAnnotationProcessingMode) { - final int currentSourcesMode = chunk.getSourcesFilter(); - commandLine.add(chunk.getSourcePath(currentSourcesMode == ModuleChunk.TEST_SOURCES? ModuleChunk.ALL_SOURCES : currentSourcesMode)); - } - else { - commandLine.add("\"\""); - } - } - - if (isAnnotationProcessingMode) { - commandLine.add("-s"); - commandLine.add(outputPath.replace('/', File.separatorChar)); - final String moduleOutputPath = CompilerPaths.getModuleOutputPath(chunk.getModules()[0], false); - if (moduleOutputPath != null) { - commandLine.add("-d"); - commandLine.add(moduleOutputPath.replace('/', File.separatorChar)); - } - } - else { - commandLine.add("-d"); - commandLine.add(outputPath.replace('/', File.separatorChar)); - } - } - - private static void addClassPathValue(final Sdk jdk, final boolean isVersion1_0, final List commandLine, final String cpString, @NonNls final String tempFileName, - List tempFiles, - boolean useTempFile) throws IOException { - if (!useTempFile) { - commandLine.add(cpString); - return; - } - // must include output path to classpath, otherwise javac will compile all dependent files no matter were they compiled before or not - if (isVersion1_0) { - commandLine.add(((JavaSdkType)jdk.getSdkType()).getToolsPath(jdk) + File.pathSeparator + cpString); - } - else { - File cpFile = FileUtil.createTempFile(tempFileName, ".tmp"); - cpFile.deleteOnExit(); - tempFiles.add(cpFile); - final DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(cpFile))); - try { - CompilerIOUtil.writeString(cpString, out); - } - finally { - out.close(); - } - commandLine.add("@" + cpFile.getAbsolutePath()); - } - } - - private Sdk getJdkForStartupCommand(final ModuleChunk chunk) { - final Sdk jdk = chunk.getJdk(); - if (ApplicationManager.getApplication().isUnitTestMode() && JavacConfiguration.getOptions(myProject, JavacConfiguration.class).isTestsUseExternalCompiler()) { - final String jdkHomePath = CompilerConfigurationImpl.getTestsExternalCompilerHome(); - if (jdkHomePath == null) { - throw new IllegalArgumentException("[TEST-MODE] Cannot determine home directory for JDK to use javac from"); - } - // when running under Mock JDK use VM executable from the JDK on which the tests run - return new MockJdkWrapper(jdkHomePath, jdk); - } - return jdk; - } - - public void compileFinished() { - FileUtil.asyncDelete(myTempFiles); - myTempFiles.clear(); + @NotNull + public Set getCompilableFileTypes() { + return Collections.singleton(StdFileTypes.JAVA); } } diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/javac/JavacOutputParser.java b/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/javac/JavacOutputParser.java index ba12e6931945..be7db2e355b5 100644 --- a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/javac/JavacOutputParser.java +++ b/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/javac/JavacOutputParser.java @@ -277,7 +277,4 @@ public class JavacOutputParser extends OutputParser { return Pattern.compile(regexp, Pattern.CASE_INSENSITIVE).matcher(""); } - public boolean isTrimLines() { - return false; - } } diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/javac/StatisticsActionJavac.java b/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/javac/StatisticsActionJavac.java deleted file mode 100644 index d969e40bdd75..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/javac/StatisticsActionJavac.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.compiler.impl.javaCompiler.javac; - -import com.intellij.compiler.OutputParser; -import com.intellij.openapi.compiler.CompilerBundle; -import org.jetbrains.annotations.Nullable; - -import java.util.regex.Matcher; - -/** - * @author Eugene Zhuravlev - * Date: Sep 24, 2005 - */ -public class StatisticsActionJavac extends JavacParserAction { - private final String myProgressMessageResourceKey; - - public StatisticsActionJavac(final Matcher matcher, String progressMessageResourceKey) { - super(matcher); - myProgressMessageResourceKey = progressMessageResourceKey; - } - - protected void doExecute(final String line, @Nullable String parsedData, final OutputParser.Callback callback) { - callback.setProgressText(CompilerBundle.message(myProgressMessageResourceKey)); - } -} diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/jikes/JikesCompiler.java b/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/jikes/JikesCompiler.java deleted file mode 100644 index fb0246fa0fa7..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/jikes/JikesCompiler.java +++ /dev/null @@ -1,231 +0,0 @@ -/* - * Copyright 2000-2014 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.compiler.impl.javaCompiler.jikes; - -import com.intellij.compiler.CompilerConfiguration; -import com.intellij.compiler.CompilerConfigurationImpl; -import com.intellij.compiler.OutputParser; -import com.intellij.compiler.impl.CompilerUtil; -import com.intellij.compiler.impl.javaCompiler.BackendCompiler; -import com.intellij.compiler.impl.javaCompiler.ExternalCompiler; -import com.intellij.compiler.impl.javaCompiler.ModuleChunk; -import com.intellij.compiler.options.JavaCompilersTab; -import com.intellij.openapi.application.ApplicationManager; -import com.intellij.openapi.compiler.CompileContext; -import com.intellij.openapi.compiler.CompileScope; -import com.intellij.openapi.compiler.CompilerBundle; -import com.intellij.openapi.diagnostic.Logger; -import com.intellij.openapi.options.Configurable; -import com.intellij.openapi.options.ShowSettingsUtil; -import com.intellij.openapi.project.Project; -import com.intellij.openapi.projectRoots.Sdk; -import com.intellij.openapi.ui.Messages; -import com.intellij.openapi.util.ThrowableComputable; -import com.intellij.openapi.util.io.FileUtil; -import com.intellij.openapi.util.text.StringUtil; -import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.pom.java.LanguageLevel; -import com.intellij.util.ArrayUtil; -import org.jetbrains.annotations.NonNls; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.io.PrintWriter; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.StringTokenizer; - -public class JikesCompiler extends ExternalCompiler { - private static final Logger LOG = Logger.getInstance("#com.intellij.compiler.impl.JikesHandler"); - private final Project myProject; - private File myTempFile; - - public JikesCompiler(Project project) { - myProject = project; - } - - public boolean checkCompiler(final CompileScope scope) { - String compilerPath = getCompilerPath(); - if (StringUtil.isEmpty(compilerPath)) { - Messages.showMessageDialog( - myProject, - CompilerBundle.message("jikes.error.path.to.compiler.unspecified"), CompilerBundle.message("compiler.jikes.name"), - Messages.getErrorIcon() - ); - openConfigurationDialog(); - compilerPath = getCompilerPath(); // update path - if (StringUtil.isEmpty(compilerPath)) { - return false; - } - } - - File file = new File(compilerPath); - if (!file.exists()) { - Messages.showMessageDialog( - myProject, - CompilerBundle.message("jikes.error.path.to.compiler.missing", compilerPath), - CompilerBundle.message("compiler.jikes.name"), - Messages.getErrorIcon() - ); - openConfigurationDialog(); - compilerPath = getCompilerPath(); // update path - if (StringUtil.isEmpty(compilerPath)) { - return false; - } - if (!new File(compilerPath).exists()) { - return false; - } - } - - return true; - } - - private void openConfigurationDialog() { - final CompilerConfigurationImpl configuration = (CompilerConfigurationImpl)CompilerConfiguration.getInstance(myProject); - final Collection compilers = configuration.getRegisteredJavaCompilers(); - final BackendCompiler defaultCompiler = configuration.getDefaultCompiler(); - final JavaCompilersTab compilersTab = new JavaCompilersTab(myProject, compilers, defaultCompiler); - - ShowSettingsUtil.getInstance().editConfigurable(myProject, compilersTab); - } - - private String getCompilerPath() { - return JikesConfiguration.getOptions(myProject).JIKES_PATH.replace('/', File.separatorChar); - } - - @NotNull - @NonNls - public String getId() // used for externalization - { - return "Jikes"; - } - - @NotNull - public String getPresentableName() { - return CompilerBundle.message("compiler.jikes.name"); - } - - @NotNull - public Configurable createConfigurable() { - return new JikesConfigurable(JikesConfiguration.getOptions(myProject)); - } - - public OutputParser createErrorParser(@NotNull final String outputDir, Process process) { - return new JikesOutputParser(myProject); - } - - @Nullable - public OutputParser createOutputParser(@NotNull final String outputDir) { - return null; - } - - @NotNull - public String[] createStartupCommand(final ModuleChunk chunk, final CompileContext context, final String outputPath) - throws IOException { - - final ArrayList commandLine = new ArrayList(); - ApplicationManager.getApplication().runReadAction(new ThrowableComputable() { - @Override - public Void compute() throws IOException { - _createStartupCommand(chunk, commandLine, outputPath); - return null; - } - }); - return ArrayUtil.toStringArray(commandLine); - } - - private void _createStartupCommand(final ModuleChunk chunk, final ArrayList commandLine, @NotNull final String outputPath) throws IOException { - - myTempFile = FileUtil.createTempFile("jikes", ".tmp"); - myTempFile.deleteOnExit(); - - final List files = chunk.getFilesToCompile(); - PrintWriter writer = new PrintWriter(new FileWriter(myTempFile)); - try { - for (VirtualFile file : files) { - writer.println(file.getPath()); - } - } - finally { - writer.close(); - } - - String compilerPath = getCompilerPath(); - LOG.assertTrue(compilerPath != null, "No path to compiler configured"); - - commandLine.add(compilerPath); - - //noinspection HardCodedStringLiteral - commandLine.add("-verbose"); - //noinspection HardCodedStringLiteral - commandLine.add("-classpath"); - - // must include output path to classpath, otherwise javac will compile all dependent files no matter were they compiled before or not - commandLine.add(chunk.getCompilationBootClasspath() + File.pathSeparator + chunk.getCompilationClasspath()); - - setupSourceVersion(chunk, commandLine); - //noinspection HardCodedStringLiteral - commandLine.add("-sourcepath"); - String sourcePath = chunk.getSourcePath(); - if (sourcePath.length() > 0) { - commandLine.add(sourcePath); - } - else { - commandLine.add("\"\""); - } - - //noinspection HardCodedStringLiteral - commandLine.add("-d"); - commandLine.add(outputPath.replace('/', File.separatorChar)); - - JikesSettingsBuilder jikesSettings = new JikesSettingsBuilder(JikesConfiguration.getOptions(myProject)); - StringTokenizer tokenizer = new StringTokenizer(jikesSettings.getOptionsString(chunk), " "); - while (tokenizer.hasMoreTokens()) { - commandLine.add(tokenizer.nextToken()); - } - commandLine.add("@" + myTempFile.getAbsolutePath()); - } - - @SuppressWarnings({"HardCodedStringLiteral"}) - private static void setupSourceVersion(final ModuleChunk chunk, final ArrayList commandLine) { - final Sdk jdk = chunk.getJdk(); - final String versionString = jdk.getVersionString(); - - final LanguageLevel applicableLanguageLevel = CompilerUtil.getApplicableLanguageLevel(versionString, chunk.getLanguageLevel()); - if (applicableLanguageLevel.equals(LanguageLevel.JDK_1_5)) { - commandLine.add("-source"); - commandLine.add("1.4"); // -source 1.5 not supported yet by jikes, so use the highest possible version - } - else if (applicableLanguageLevel.equals(LanguageLevel.JDK_1_4)) { - commandLine.add("-source"); - commandLine.add("1.4"); - } - } - - - public void compileFinished() { - if (myTempFile != null) { - FileUtil.delete(myTempFile); - myTempFile = null; - } - } - -} - diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/jikes/JikesConfigurable.java b/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/jikes/JikesConfigurable.java deleted file mode 100644 index 17316253dd56..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/jikes/JikesConfigurable.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright 2000-2012 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.compiler.impl.javaCompiler.jikes; - -import com.intellij.compiler.options.ComparingUtils; -import com.intellij.openapi.compiler.CompilerBundle; -import com.intellij.openapi.fileChooser.FileChooser; -import com.intellij.openapi.fileChooser.FileChooserDescriptor; -import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory; -import com.intellij.openapi.options.Configurable; -import com.intellij.openapi.options.ConfigurationException; -import com.intellij.openapi.ui.TextFieldWithBrowseButton; -import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.ui.RawCommandLineEditor; -import org.jetbrains.jps.model.java.compiler.JikesCompilerOptions; - -import javax.swing.*; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.io.File; - -/** - * @author Eugene Zhuravlev - * Date: Mar 30, 2004 - */ -public class JikesConfigurable implements Configurable { - private JPanel myPanel; - private JCheckBox myCbDebuggingInfo; - private JCheckBox myCbDeprecation; - private JCheckBox myCbGenerateNoWarnings; - private RawCommandLineEditor myAdditionalOptionsField; - private TextFieldWithBrowseButton myPathField; - private final JikesCompilerOptions myJikesSettings; - - public JikesConfigurable(JikesCompilerOptions jikesSettings) { - myJikesSettings = jikesSettings; - myPathField.getButton().addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - FileChooserDescriptor descriptor = FileChooserDescriptorFactory.createSingleFileNoJarsDescriptor(); - VirtualFile file = FileChooser.chooseFile(descriptor, myPathField, null, null); - if (file != null) { - myPathField.setText(file.getPath().replace('/', File.separatorChar)); - } - } - }); - myAdditionalOptionsField.setDialogCaption(CompilerBundle.message("java.compiler.option.additional.command.line.parameters")); - } - - public String getDisplayName() { - return null; - } - - public String getHelpTopic() { - return null; - } - - public JComponent createComponent() { - return myPanel; - } - - public boolean isModified() { - boolean isModified = false; - isModified |= ComparingUtils.isModified(myPathField, myJikesSettings.JIKES_PATH.replace('/', File.separatorChar)); - isModified |= ComparingUtils.isModified(myCbDeprecation, myJikesSettings.DEPRECATION); - isModified |= ComparingUtils.isModified(myCbDebuggingInfo, myJikesSettings.DEBUGGING_INFO); - isModified |= ComparingUtils.isModified(myCbGenerateNoWarnings, myJikesSettings.GENERATE_NO_WARNINGS); - isModified |= ComparingUtils.isModified(myAdditionalOptionsField, myJikesSettings.ADDITIONAL_OPTIONS_STRING); - return isModified; - } - - public void apply() throws ConfigurationException { - myJikesSettings.JIKES_PATH = myPathField.getText().trim().replace(File.separatorChar, '/'); - myJikesSettings.DEPRECATION = myCbDeprecation.isSelected(); - myJikesSettings.DEBUGGING_INFO = myCbDebuggingInfo.isSelected(); - myJikesSettings.GENERATE_NO_WARNINGS = myCbGenerateNoWarnings.isSelected(); - myJikesSettings.ADDITIONAL_OPTIONS_STRING = myAdditionalOptionsField.getText(); - } - - public void reset() { - myPathField.setText(myJikesSettings.JIKES_PATH.replace('/', File.separatorChar)); - myCbDeprecation.setSelected(myJikesSettings.DEPRECATION); - myCbDebuggingInfo.setSelected(myJikesSettings.DEBUGGING_INFO); - myCbGenerateNoWarnings.setSelected(myJikesSettings.GENERATE_NO_WARNINGS); - myAdditionalOptionsField.setText(myJikesSettings.ADDITIONAL_OPTIONS_STRING); - } - - public void disposeUIResources() { - } -} diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/jikes/JikesConfiguration.java b/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/jikes/JikesConfiguration.java deleted file mode 100755 index 28992466b72b..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/jikes/JikesConfiguration.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright 2000-2012 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.compiler.impl.javaCompiler.jikes; - -import com.intellij.openapi.components.*; -import com.intellij.openapi.project.Project; -import com.intellij.util.xmlb.XmlSerializerUtil; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.jps.model.java.compiler.JikesCompilerOptions; - -@State( - name = "JikesSettings", - storages = { - @Storage(file = StoragePathMacros.PROJECT_FILE), - @Storage(file = StoragePathMacros.PROJECT_CONFIG_DIR + "/compiler.xml", scheme = StorageScheme.DIRECTORY_BASED) - } -) -public class JikesConfiguration implements PersistentStateComponent { - private final JikesCompilerOptions mySettings = new JikesCompilerOptions(); - - @NotNull - public JikesCompilerOptions getState() { - return mySettings; - } - - public void loadState(JikesCompilerOptions state) { - XmlSerializerUtil.copyBean(state, mySettings); - } - - public static JikesCompilerOptions getOptions(Project project) { - return ServiceManager.getService(project, JikesConfiguration.class).getState(); - } -} \ No newline at end of file diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/jikes/JikesOptionsPanel.form b/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/jikes/JikesOptionsPanel.form deleted file mode 100644 index 23055ee7a80b..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/jikes/JikesOptionsPanel.form +++ /dev/null @@ -1,101 +0,0 @@ - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/jikes/JikesOutputParser.java b/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/jikes/JikesOutputParser.java deleted file mode 100644 index 1d5bb00288a7..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/jikes/JikesOutputParser.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.compiler.impl.javaCompiler.jikes; - -import com.intellij.compiler.OutputParser; -import com.intellij.openapi.compiler.CompilerMessageCategory; -import com.intellij.openapi.project.Project; -import com.intellij.openapi.vfs.LocalFileSystem; -import com.intellij.openapi.vfs.VirtualFileManager; -import org.jetbrains.annotations.NonNls; -import org.jetbrains.jps.model.java.compiler.JikesCompilerOptions; - -import java.io.File; -import java.util.ArrayList; -import java.util.StringTokenizer; - -public class JikesOutputParser extends OutputParser { - private final JikesCompilerOptions myJikesSettings; - @NonNls private static final String JAVA_FILE_MSG_TAIL = ".java:"; - @NonNls private static final String CAUTION = "Caution"; - @NonNls private static final String WARNING = "Warning"; - @NonNls private static final String ERROR = "Error"; - @NonNls private static final String SEMANTIC_WARNING = "Semantic Warning"; - @NonNls private static final String SEMANTIC_ERROR = "Semantic Error"; - @NonNls private static final String ENTER_TO_CONTINUE_REGEXP = ".*Enter\\s+to\\s+continue.*"; - - public JikesOutputParser(Project project) { - myJikesSettings = JikesConfiguration.getOptions(project); - myParserActions.add(new ParserActionJikes()); - } - - public boolean processMessageLine(Callback callback) { - if (super.processMessageLine(callback)) { - return true; - } - String line = callback.getCurrentLine(); - if (line == null) { - return false; - } - if (line.length() == 0) { - return false; - } -//sae - if (myJikesSettings.IS_EMACS_ERRORS_MODE) { - - String filePath = ""; - final int tailIndex = line.indexOf(JAVA_FILE_MSG_TAIL); - if (tailIndex > 5) filePath = line.substring(0, tailIndex + 5); - filePath = filePath.replace(File.separatorChar, '/'); - final String url = VirtualFileManager.constructUrl(LocalFileSystem.PROTOCOL, filePath); - if (tailIndex > 6) { - line = line.substring(tailIndex + 6); - int lineNum; - -//second token = start line - StringTokenizer tokenizer = new StringTokenizer(line, ":"); -//first token = filename - String token = tokenizer.nextToken(); - - try { - lineNum = Integer.parseInt(token); - } - catch (Exception e) { - addMessage(callback, CompilerMessageCategory.INFORMATION, line); - return true; - } -//thrd token = start column - token = tokenizer.nextToken(); - int colNum; - try { - colNum = Integer.parseInt(token); - } - catch (Exception e) { - addMessage(callback, CompilerMessageCategory.INFORMATION, line); - return true; - } -//4,5 token = end line/column tmp not used - tokenizer.nextToken(); - tokenizer.nextToken(); -// 6 error type - CompilerMessageCategory category = CompilerMessageCategory.INFORMATION; - token = tokenizer.nextToken().trim(); - if (CAUTION.equalsIgnoreCase(token)) { - category = CompilerMessageCategory.WARNING; - } - else if (WARNING.equalsIgnoreCase(token) || SEMANTIC_WARNING.equalsIgnoreCase(token)) { // Semantic errors/warnings were introduced in jikes 1.18 - category = CompilerMessageCategory.WARNING; - } - else if (ERROR.equalsIgnoreCase(token) || SEMANTIC_ERROR.equalsIgnoreCase(token)) { - category = CompilerMessageCategory.ERROR; - } - - String message = token; - message = message.concat(" "); - message = message.concat(tokenizer.nextToken("")); - ArrayList messages = new ArrayList(); - messages.add(message); - - if (colNum > 0 && messages.size() > 0) { - StringBuilder buf = new StringBuilder(); - for (String m : messages) { - if (buf.length() > 0) { - buf.append("\n"); - } - buf.append(m); - } - addMessage(callback, category, buf.toString(), url, lineNum, colNum); - return true; - } - } - } -//--sae - -//Enter to continue - if (!line.matches(ENTER_TO_CONTINUE_REGEXP)) { - addMessage(callback, CompilerMessageCategory.INFORMATION, line); - } - return true; - } -} diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/jikes/JikesSettingsBuilder.java b/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/jikes/JikesSettingsBuilder.java deleted file mode 100644 index 636db21e3e80..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/jikes/JikesSettingsBuilder.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright 2000-2012 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.compiler.impl.javaCompiler.jikes; - -import com.intellij.compiler.impl.javaCompiler.javac.JavacSettingsBuilder; -import com.intellij.openapi.module.Module; -import com.intellij.util.Chunk; -import org.jetbrains.jps.model.java.compiler.JikesCompilerOptions; - -import java.util.Collection; - -public class JikesSettingsBuilder extends JavacSettingsBuilder { - - public JikesSettingsBuilder(JikesCompilerOptions options) { - super(options); - } - - @Override - public JikesCompilerOptions getOptions() { - return (JikesCompilerOptions)super.getOptions(); - } - - public Collection getOptions(Chunk chunk) { - final Collection options = super.getOptions(chunk); - if(getOptions().IS_EMACS_ERRORS_MODE) { - options.add("+E"); - } - return options; - } - - protected boolean acceptUserOption(String token) { - if (!super.acceptUserOption(token)) { - return false; - } - return !("++".equals(token) || "+M".equals(token) || "+F".equals(token) || "+E".equals(token)); - } -} \ No newline at end of file diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/jikes/ParserActionJikes.java b/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/jikes/ParserActionJikes.java deleted file mode 100644 index ba1884f5e680..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/impl/javaCompiler/jikes/ParserActionJikes.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.compiler.impl.javaCompiler.jikes; - -import com.intellij.openapi.compiler.CompilerBundle; -import com.intellij.openapi.fileTypes.FileType; -import com.intellij.openapi.fileTypes.FileTypeManager; -import com.intellij.openapi.fileTypes.StdFileTypes; -import com.intellij.openapi.util.text.StringUtil; -import com.intellij.compiler.ParserAction; -import com.intellij.compiler.OutputParser; -import com.intellij.compiler.impl.javaCompiler.FileObject; -import org.jetbrains.annotations.NonNls; - -import java.io.File; - -/** - * This class provides compatibility with older javac(english locale) and jikes versions and - * implements parsing method from previous IDEA versions for jikes and javac compiler output. - * Used in order not to miss some compiler output messages when jikes is configured as a preferred compiler - * Also used in test mode in which javac is not run via JavacRunner - * - * @author Eugene Zhuravlev - * Date: Sep 24, 2005 - */ -public class ParserActionJikes extends ParserAction { - @NonNls private static final String JAVA_EXTENSION = ".java"; - - public boolean execute(@NonNls String line, final OutputParser.Callback callback) { - if (!StringUtil.startsWithChar(line, '[') || !StringUtil.endsWithChar(line, ']')) { - return false; - } - if (line.startsWith("[parsing started")){ // javac - String filePath = line.substring("[parsing started".length(), line.length() - 1).trim(); - processParsingMessage(callback, filePath.replace(File.separatorChar, '/')); - } - else if (line.startsWith("[parsed") && line.contains(JAVA_EXTENSION)) { // javac version 1.2.2 - int index = line.indexOf(JAVA_EXTENSION); - String filePath = line.substring("[parsed".length(), index + JAVA_EXTENSION.length()).trim(); - processParsingMessage(callback, filePath.replace(File.separatorChar, '/')); - } - else if (line.startsWith("[read") && line.endsWith(".java]")){ // jikes - String filePath = line.substring("[read".length(), line.length() - 1).trim(); - processParsingMessage(callback, filePath.replace(File.separatorChar, '/')); - } - else if (line.startsWith("[parsing completed")){ - } - else if (line.startsWith("[loading") || line.startsWith("[loaded") || line.startsWith("[read")){ - callback.setProgressText(CompilerBundle.message("progress.loading.classes")); - } - else if (line.startsWith("[checking")){ - String className = line.substring("[checking".length(), line.length() - 1).trim(); - callback.setProgressText(CompilerBundle.message("progress.compiling.class", className)); - } - else if (line.startsWith("[wrote") || line.startsWith("[write")){ - String filePath = line.substring("[wrote".length(), line.length() - 1).trim(); - processParsingMessage(callback, filePath.replace(File.separatorChar, '/')); - } - return true; - } - - private static void processParsingMessage(final OutputParser.Callback callback, @NonNls final String filePath) { - int index = filePath.lastIndexOf('/'); - final String name = index >= 0 ? filePath.substring(index + 1) : filePath; - - final FileType fileType = FileTypeManager.getInstance().getFileTypeByFileName(name); - if (StdFileTypes.JAVA.equals(fileType)) { - callback.fileProcessed(filePath); - callback.setProgressText(CompilerBundle.message("progress.parsing.file", name)); - } - else if (StdFileTypes.CLASS.equals(fileType)) { - callback.fileGenerated(new FileObject(new File(filePath))); - } - } -} diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/packagingCompiler/BuildRecipeImpl.java b/java/compiler/impl/src/com/intellij/compiler/impl/packagingCompiler/BuildRecipeImpl.java deleted file mode 100644 index 03e62a0907ab..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/impl/packagingCompiler/BuildRecipeImpl.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * @author cdr - */ -package com.intellij.compiler.impl.packagingCompiler; - -import com.intellij.openapi.compiler.make.BuildInstruction; -import com.intellij.openapi.compiler.make.BuildInstructionVisitor; -import com.intellij.openapi.compiler.make.BuildRecipe; -import com.intellij.openapi.deployment.DeploymentUtil; -import org.jetbrains.annotations.NotNull; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; - -@Deprecated -public class BuildRecipeImpl implements BuildRecipe { - private final List myInstructions = new ArrayList(); - - public void addInstruction(BuildInstruction instruction) { - if (!contains(instruction)) { - myInstructions.add(instruction); - } - } - - public boolean contains(final BuildInstruction instruction) { - return myInstructions.contains(instruction); - } - - public boolean visitInstructions(BuildInstructionVisitor visitor, boolean reverseOrder){ - try { - return visitInstructionsWithExceptions(visitor, reverseOrder); - } - catch (Exception e) { - if (e instanceof RuntimeException) { - throw (RuntimeException)e; - } - return false; - } - } - public boolean visitInstructionsWithExceptions(BuildInstructionVisitor visitor, boolean reverseOrder) throws Exception { - for (int i = reverseOrder ? myInstructions.size()-1 : 0; - reverseOrder ? i>=0 : i < myInstructions.size(); - i += reverseOrder ? -1 : 1) { - BuildInstruction instruction = myInstructions.get(i); - if (!instruction.accept(visitor)) { - return false; - } - } - return true; - } - - public void addFileCopyInstruction(@NotNull File file, boolean isDirectory, String outputRelativePath) { - addInstruction(new FileCopyInstructionImpl(file, isDirectory, DeploymentUtil.trimForwardSlashes(outputRelativePath))); - } - - public String toString() { - String s = "Build recipe:"; - for (BuildInstruction buildInstruction : myInstructions) { - s += "\n" + buildInstruction + "; "; - } - return s; - } -} \ No newline at end of file diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/resourceCompiler/ResourceCompiler.java b/java/compiler/impl/src/com/intellij/compiler/impl/resourceCompiler/ResourceCompiler.java deleted file mode 100644 index 3efbec2208df..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/impl/resourceCompiler/ResourceCompiler.java +++ /dev/null @@ -1,236 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * @author: Eugene Zhuravlev - * Date: Jan 17, 2003 - * Time: 3:48:26 PM - */ -package com.intellij.compiler.impl.resourceCompiler; - -import com.intellij.compiler.CompilerConfiguration; -import com.intellij.compiler.CompilerConfigurationImpl; -import com.intellij.compiler.impl.CompilerUtil; -import com.intellij.compiler.make.MakeUtil; -import com.intellij.openapi.application.ApplicationManager; -import com.intellij.openapi.compiler.*; -import com.intellij.openapi.compiler.ex.CompileContextEx; -import com.intellij.openapi.diagnostic.Logger; -import com.intellij.openapi.module.Module; -import com.intellij.openapi.project.Project; -import com.intellij.openapi.roots.ProjectFileIndex; -import com.intellij.openapi.roots.ProjectRootManager; -import com.intellij.openapi.util.io.FileUtil; -import com.intellij.openapi.vfs.VfsUtilCore; -import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.openapi.vfs.VirtualFileManager; -import com.intellij.util.Chunk; -import org.jetbrains.annotations.NotNull; - -import java.io.File; -import java.io.IOException; -import java.util.*; - -public class ResourceCompiler implements TranslatingCompiler { - private static final Logger LOG = Logger.getInstance("#com.intellij.compiler.impl.resourceCompiler.ResourceCompiler"); - private final Project myProject; - private final CompilerConfiguration myConfiguration; - private final ResourceCompilerExtension[] myResourceCompilerExtensions = ResourceCompilerExtension.EP_NAME.getExtensions(); - - public ResourceCompiler(Project project, CompilerConfiguration compilerConfiguration) { - myProject = project; - myConfiguration = compilerConfiguration; - } - - @NotNull - public String getDescription() { - return CompilerBundle.message("resource.compiler.description"); - } - - public boolean validateConfiguration(CompileScope scope) { - ((CompilerConfigurationImpl) CompilerConfiguration.getInstance(myProject)).convertPatterns(); - return true; - } - - public boolean isCompilableFile(VirtualFile file, CompileContext context) { - final Module module = context.getModuleByFile(file); - if (module != null && skipStandardResourceCompiler(module)) { - return false; - } - return myConfiguration.isResourceFile(file); - } - - public void compile(final CompileContext context, Chunk moduleChunk, final VirtualFile[] files, OutputSink sink) { - context.getProgressIndicator().pushState(); - context.getProgressIndicator().setText(CompilerBundle.message("progress.copying.resources")); - - final Map> processed = new HashMap>(); - final LinkedList copyCommands = new LinkedList(); - final Module singleChunkModule = moduleChunk.getNodes().size() == 1? moduleChunk.getNodes().iterator().next() : null; - ApplicationManager.getApplication().runReadAction(new Runnable() { - public void run() { - final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(myProject).getFileIndex(); - for (final VirtualFile file : files) { - if (context.getProgressIndicator().isCanceled()) { - break; - } - final Module module = singleChunkModule != null? singleChunkModule : context.getModuleByFile(file); - if (module == null) { - continue; // looks like file invalidated - } - final VirtualFile fileRoot = MakeUtil.getSourceRoot(context, module, file); - if (fileRoot == null) { - continue; - } - final String sourcePath = file.getPath(); - final String relativePath = VfsUtilCore.getRelativePath(file, fileRoot, '/'); - final boolean inTests = ((CompileContextEx)context).isInTestSourceContent(file); - final VirtualFile outputDir = inTests? context.getModuleOutputDirectoryForTests(module) : context.getModuleOutputDirectory(module); - if (outputDir == null) { - continue; - } - final String outputPath = outputDir.getPath(); - - final String packagePrefix = fileIndex.getPackageNameByDirectory(fileRoot); - final String targetPath; - if (packagePrefix != null && packagePrefix.length() > 0) { - targetPath = outputPath + "/" + packagePrefix.replace('.', '/') + "/" + relativePath; - } - else { - targetPath = outputPath + "/" + relativePath; - } - if (sourcePath.equals(targetPath)) { - addToMap(processed, outputPath, new MyOutputItem(targetPath, file)); - } - else { - copyCommands.add(new CopyCommand(outputPath, sourcePath, targetPath, file)); - } - } - } - }); - - final List filesToRefresh = new ArrayList(); - // do actual copy outside of read action to reduce the time the application is locked on it - while (!copyCommands.isEmpty()) { - final CopyCommand command = copyCommands.removeFirst(); - if (context.getProgressIndicator().isCanceled()) { - break; - } - //context.getProgressIndicator().setFraction((idx++) * 1.0 / total); - context.getProgressIndicator().setText2("Copying " + command.getFromPath() + "..."); - try { - final MyOutputItem outputItem = command.copy(filesToRefresh); - addToMap(processed, command.getOutputPath(), outputItem); - } - catch (IOException e) { - context.addMessage( - CompilerMessageCategory.ERROR, - CompilerBundle.message("error.copying", command.getFromPath(), command.getToPath(), e.getMessage()), - command.getSourceFileUrl(), -1, -1 - ); - } - } - - if (!filesToRefresh.isEmpty()) { - CompilerUtil.refreshIOFiles(filesToRefresh); - filesToRefresh.clear(); - } - - for (Iterator>> it = processed.entrySet().iterator(); it.hasNext();) { - Map.Entry> entry = it.next(); - sink.add(entry.getKey(), entry.getValue(), VirtualFile.EMPTY_ARRAY); - it.remove(); // to free memory - } - context.getProgressIndicator().popState(); - } - - private boolean skipStandardResourceCompiler(final Module module) { - for (ResourceCompilerExtension extension : myResourceCompilerExtensions) { - if (extension.skipStandardResourceCompiler(module)) { - return true; - } - } - return false; - } - - private static void addToMap(Map> map, String outputDir, OutputItem item) { - Collection list = map.get(outputDir); - if (list == null) { - list = new ArrayList(); - map.put(outputDir, list); - } - list.add(item); - } - - private static class CopyCommand { - private final String myOutputPath; - private final String myFromPath; - private final String myToPath; - private final VirtualFile mySourceFile; - - private CopyCommand(String outputPath, String fromPath, String toPath, VirtualFile sourceFile) { - myOutputPath = outputPath; - myFromPath = fromPath; - myToPath = toPath; - mySourceFile = sourceFile; - } - - public MyOutputItem copy(List filesToRefresh) throws IOException { - if (LOG.isDebugEnabled()) { - LOG.debug("Copying " + myFromPath + " to " + myToPath); - } - final File targetFile = new File(myToPath); - FileUtil.copyContent(new File(myFromPath), targetFile); - filesToRefresh.add(targetFile); - return new MyOutputItem(myToPath, mySourceFile); - } - - public String getOutputPath() { - return myOutputPath; - } - - public String getFromPath() { - return myFromPath; - } - - public String getToPath() { - return myToPath; - } - - public String getSourceFileUrl() { - // do not use mySourseFile.getUrl() directly as it requires read action - return VirtualFileManager.constructUrl(mySourceFile.getFileSystem().getProtocol(), myFromPath); - } - } - - private static class MyOutputItem implements OutputItem { - private final String myTargetPath; - private final VirtualFile myFile; - - private MyOutputItem(String targetPath, VirtualFile sourceFile) { - myTargetPath = targetPath; - myFile = sourceFile; - } - - public String getOutputPath() { - return myTargetPath; - } - - public VirtualFile getSourceFile() { - return myFile; - } - } -} diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/resourceCompiler/ResourceCompilerExtension.java b/java/compiler/impl/src/com/intellij/compiler/impl/resourceCompiler/ResourceCompilerExtension.java deleted file mode 100644 index 47d901c10987..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/impl/resourceCompiler/ResourceCompilerExtension.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.intellij.compiler.impl.resourceCompiler; - -import com.intellij.openapi.extensions.ExtensionPointName; -import com.intellij.openapi.module.Module; -import org.jetbrains.annotations.NotNull; - -public abstract class ResourceCompilerExtension { - public static final ExtensionPointName EP_NAME = - ExtensionPointName.create("com.intellij.compiler.resourceCompilerExtension"); - - public boolean skipStandardResourceCompiler(final @NotNull Module module) { - return false; - } -} diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/rmiCompiler/JavacOutputParserPool.java b/java/compiler/impl/src/com/intellij/compiler/impl/rmiCompiler/JavacOutputParserPool.java deleted file mode 100644 index cc99f2dce8d1..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/impl/rmiCompiler/JavacOutputParserPool.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.compiler.impl.rmiCompiler; - -import com.intellij.compiler.OutputParser; -import com.intellij.compiler.impl.CompilerUtil; -import com.intellij.compiler.impl.javaCompiler.CompilerParsingThread; -import com.intellij.compiler.impl.javaCompiler.javac.JavacOutputParser; -import com.intellij.openapi.application.ApplicationManager; -import com.intellij.openapi.compiler.CompileContext; -import com.intellij.openapi.compiler.CompilerBundle; -import com.intellij.openapi.project.Project; -import com.intellij.openapi.projectRoots.JavaSdkType; -import com.intellij.openapi.projectRoots.Sdk; -import com.intellij.openapi.projectRoots.ex.JavaSdkUtil; -import com.intellij.openapi.util.Computable; -import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.rt.compiler.JavacResourcesReader; -import com.intellij.util.ArrayUtil; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Future; - -/** - * @author Eugene Zhuravlev - * Date: Oct 10, 2005 - */ -public class JavacOutputParserPool { - protected final Project myProject; - private final CompileContext myContext; - private final Map myProjectToParserMap = new HashMap(); - - protected JavacOutputParserPool(Project project, final CompileContext context) { - myProject = project; - myContext = context; - } - - public OutputParser getJavacOutputParser(Sdk jdk) throws IOException { - OutputParser outputParser = myProjectToParserMap.get(jdk); - if (outputParser == null) { - outputParser = createJavacOutputParser(jdk); - myProjectToParserMap.put(jdk, outputParser); - } - return outputParser; - } - - private OutputParser createJavacOutputParser(final Sdk jdk) throws IOException { - final JavacOutputParser outputParser = new JavacOutputParser(myProject); - // first, need to setup the output parser - final String[] setupCmdLine = ApplicationManager.getApplication().runReadAction(new Computable() { - public String[] compute() { - return createParserSetupCommand(jdk); - } - }); - final Process setupProcess = Runtime.getRuntime().exec(setupCmdLine); - - final CompilerParsingThread setupProcessParsingThread = new CompilerParsingThread(setupProcess, outputParser, true, true,myContext); - final Future parsingThreadFuture = ApplicationManager.getApplication().executeOnPooledThread(setupProcessParsingThread); - try { - setupProcess.waitFor(); - } - catch (InterruptedException ignored) { - } - finally { - setupProcessParsingThread.setProcessTerminated(true); - } - try { - parsingThreadFuture.get(); - } - catch (InterruptedException e) { - } - catch (ExecutionException e) { - } - return outputParser; - } - - private static String[] createParserSetupCommand(final Sdk jdk) { - - final VirtualFile homeDirectory = jdk.getHomeDirectory(); - if (homeDirectory == null) { - throw new IllegalArgumentException(CompilerBundle.jdkHomeNotFoundMessage(jdk)); - } - - final List commandLine = new ArrayList(); - commandLine.add(((JavaSdkType)jdk.getSdkType()).getVMExecutablePath(jdk)); - - CompilerUtil.addLocaleOptions(commandLine, false); - - //noinspection HardCodedStringLiteral - commandLine.add("-classpath"); - commandLine.add(((JavaSdkType)jdk.getSdkType()).getToolsPath(jdk) + File.pathSeparator + JavaSdkUtil.getIdeaRtJarPath()); - - commandLine.add(JavacResourcesReader.class.getName()); - - return ArrayUtil.toStringArray(commandLine); - } - -} diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/rmiCompiler/RmicCompiler.java b/java/compiler/impl/src/com/intellij/compiler/impl/rmiCompiler/RmicCompiler.java deleted file mode 100644 index 142b6e694d0a..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/impl/rmiCompiler/RmicCompiler.java +++ /dev/null @@ -1,522 +0,0 @@ -/* - * Copyright 2000-2014 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.compiler.impl.rmiCompiler; - -import com.intellij.compiler.OutputParser; -import com.intellij.compiler.impl.CompilerUtil; -import com.intellij.compiler.impl.javaCompiler.CompilerParsingThread; -import com.intellij.compiler.impl.javaCompiler.FileObject; -import com.intellij.compiler.make.Cache; -import com.intellij.compiler.make.CacheCorruptedException; -import com.intellij.compiler.make.DependencyCache; -import com.intellij.compiler.make.MakeUtil; -import com.intellij.openapi.application.ApplicationManager; -import com.intellij.openapi.compiler.*; -import com.intellij.openapi.compiler.ex.CompileContextEx; -import com.intellij.openapi.diagnostic.Logger; -import com.intellij.openapi.module.Module; -import com.intellij.openapi.progress.ProgressIndicator; -import com.intellij.openapi.project.Project; -import com.intellij.openapi.projectRoots.Sdk; -import com.intellij.openapi.roots.ModuleRootManager; -import com.intellij.openapi.roots.OrderEnumerator; -import com.intellij.openapi.roots.ProjectFileIndex; -import com.intellij.openapi.roots.ProjectRootManager; -import com.intellij.openapi.util.Computable; -import com.intellij.openapi.util.Pair; -import com.intellij.openapi.util.io.FileUtil; -import com.intellij.openapi.vfs.LocalFileSystem; -import com.intellij.openapi.vfs.VfsUtil; -import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.util.ArrayUtil; -import com.intellij.util.Chunk; -import com.intellij.util.PathsList; -import com.intellij.util.containers.ContainerUtil; -import org.jetbrains.annotations.NonNls; -import org.jetbrains.annotations.NotNull; - -import java.io.DataInput; -import java.io.DataOutput; -import java.io.File; -import java.io.IOException; -import java.util.*; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Future; - -/** - * @author Eugene Zhuravlev - * Date: Mar 29, 2004 - */ - -public class RmicCompiler implements ClassPostProcessingCompiler{ - private static final Logger LOG = Logger.getInstance("#com.intellij.compiler.impl.rmiCompiler.RmicCompiler"); - //private static final FileFilter CLASSES_AND_DIRECTORIES_FILTER = new FileFilter() { - // public boolean accept(File pathname) { - // return pathname.isDirectory() || pathname.getName().endsWith(".class"); - // } - //}; - //private static final String REMOTE_INTERFACE_NAME = Remote.class.getName(); - - @NotNull - public ProcessingItem[] getProcessingItems(final CompileContext context) { - if (!RmicConfiguration.getOptions(context.getProject()).IS_EANABLED) { - return ProcessingItem.EMPTY_ARRAY; - } - final Project project = context.getProject(); - final List items = new ArrayList(); - ApplicationManager.getApplication().runReadAction(new Runnable() { - public void run() { - DependencyCache dependencyCache = ((CompileContextEx)context).getDependencyCache(); - try { - final Cache cache = dependencyCache.getCache(); - final int[] allClassNames = cache.getAllClassNames(); - final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex(); - final LocalFileSystem lfs = LocalFileSystem.getInstance(); - for (final int className : allClassNames) { - final boolean isRemoteObject = cache.isRemote(className) && !MakeUtil.isInterface(cache.getFlags(className)); - if (!isRemoteObject && !dependencyCache.wasRemote(className)) { - continue; - } - final String outputPath = cache.getPath(className); - if (outputPath == null) { - continue; - } - final VirtualFile outputClassFile = lfs.findFileByPath(outputPath.replace(File.separatorChar, '/')); - if (outputClassFile == null) { - continue; - } - final VirtualFile sourceFile = ((CompileContextEx)context).getSourceFileByOutputFile(outputClassFile); - if (sourceFile == null) { - continue; - } - final Module module = context.getModuleByFile(sourceFile); - if (module == null) { - continue; - } - final VirtualFile outputDir = fileIndex.isInTestSourceContent(sourceFile) - ? context.getModuleOutputDirectoryForTests(module) - : context.getModuleOutputDirectory(module); - if (outputDir == null) { - continue; - } - - if (!VfsUtil.isAncestor(outputDir, outputClassFile, true)) { - LOG.error(outputClassFile.getPath() + " should be located under the output root " + outputDir.getPath()); - } - - final ProcessingItem item = createProcessingItem(module, outputClassFile, outputDir, - isRemoteObject, dependencyCache.resolve(className)); - items.add(item); - } - } - catch (CacheCorruptedException e) { - context.addMessage(CompilerMessageCategory.ERROR, e.getMessage(), null, -1, -1); - LOG.info(e); - } - } - }); - - return items.toArray(new ProcessingItem[items.size()]); - } - - public static ProcessingItem createProcessingItem(final Module module, - final VirtualFile outputClassFile, - final VirtualFile outputDir, - final boolean remoteObject, String qName) { - final RmicProcessingItem item = new RmicProcessingItem( - module, outputClassFile, new File(outputDir.getPath()), qName - ); - item.setIsRemoteObject(remoteObject); - return item; - } - - public ProcessingItem[] process(CompileContext context, ProcessingItem[] items) { - final Project project = context.getProject(); - if (!RmicConfiguration.getOptions(project).IS_EANABLED) { - return ProcessingItem.EMPTY_ARRAY; - } - final ProgressIndicator progressIndicator = context.getProgressIndicator(); - progressIndicator.pushState(); - try { - progressIndicator.setText(CompilerBundle.message("progress.generating.rmi.stubs")); - final Map, List> sortedByModuleAndOutputPath = new HashMap, List>(); - for (ProcessingItem item1 : items) { - final RmicProcessingItem item = (RmicProcessingItem)item1; - final Pair moduleOutputPair = Pair.create(item.getModule(), item.getOutputDir()); - List dirItems = sortedByModuleAndOutputPath.get(moduleOutputPair); - if (dirItems == null) { - dirItems = new ArrayList(); - sortedByModuleAndOutputPath.put(moduleOutputPair, dirItems); - } - dirItems.add(item); - } - final List processed = new ArrayList(); - - final JavacOutputParserPool parserPool = new JavacOutputParserPool(project, context); - - for (final Pair pair : sortedByModuleAndOutputPath.keySet()) { - if (progressIndicator.isCanceled()) { - break; - } - final List dirItems = sortedByModuleAndOutputPath.get(pair); - try { - // should delete all previously generated files for the remote class if there are any - for (Iterator itemIterator = dirItems.iterator(); itemIterator.hasNext();) { - final RmicProcessingItem item = (RmicProcessingItem)itemIterator.next(); - item.deleteGeneratedFiles(); - if (!item.isRemoteObject()) { - itemIterator - .remove(); // the object was remote and currently is not, so remove it from the list and do not generate stubs for it - } - } - if (!dirItems.isEmpty()) { - final RmicProcessingItem[] successfullyProcessed = invokeRmic(context, parserPool, pair.getFirst(), dirItems, pair.getSecond()); - ContainerUtil.addAll(processed, successfullyProcessed); - } - progressIndicator.setFraction(((double)processed.size()) / ((double)items.length)); - } - catch (IOException e) { - context.addMessage(CompilerMessageCategory.ERROR, e.getMessage(), null, -1, -1); - LOG.info(e); - } - } - // update state so that the latest timestamps are recorded by make - final ProcessingItem[] processedItems = processed.toArray(new ProcessingItem[processed.size()]); - final List filesToRefresh = new ArrayList(processedItems.length * 3); - for (ProcessingItem processedItem : processedItems) { - RmicProcessingItem item = (RmicProcessingItem)processedItem; - item.updateState(); - filesToRefresh.add(item.myStub); - filesToRefresh.add(item.mySkel); - filesToRefresh.add(item.myTie); - } - CompilerUtil.refreshIOFiles(filesToRefresh); - return processedItems; - } - finally { - progressIndicator.popState(); - } - } - - private static RmicProcessingItem[] invokeRmic(final CompileContext context, - final JavacOutputParserPool parserPool, final Module module, - final List dirItems, - final File outputDir - ) throws IOException{ - - final Sdk jdk = ModuleRootManager.getInstance(module).getSdk(); - - final Map pathToItemMap = new HashMap(); - final String[] cmdLine = ApplicationManager.getApplication().runReadAction(new Computable() { - public String[] compute() { - for (final RmicProcessingItem item : dirItems) { - pathToItemMap.put(item.myStub.getPath().replace(File.separatorChar, '/'), item); - pathToItemMap.put(item.mySkel.getPath().replace(File.separatorChar, '/'), item); - pathToItemMap.put(item.myTie.getPath().replace(File.separatorChar, '/'), item); - } - return createStartupCommand(module, outputDir.getPath(), dirItems.toArray(new RmicProcessingItem[dirItems.size()])); - } - }); - - if (LOG.isDebugEnabled()) { - StringBuilder buf = new StringBuilder(); - for (int idx = 0; idx < cmdLine.length; idx++) { - if (idx > 0) { - buf.append(" "); - } - buf.append(cmdLine[idx]); - } - LOG.debug(buf.toString()); - } - - // obtain parser before running the process because configuring parser may involve starting another process - final OutputParser outputParser = parserPool.getJavacOutputParser(jdk); - - final Process process = Runtime.getRuntime().exec(cmdLine); - final Set successfullyCompiledItems = new HashSet(); - final CompilerParsingThread parsingThread = new CompilerParsingThread(process, outputParser, false, true,context) { - protected void processCompiledClass(FileObject classFileToProcess) { - String key = classFileToProcess.getFile().getPath().replace(File.separatorChar, '/'); - final RmicProcessingItem item = pathToItemMap.get(key); - if (item != null) { - successfullyCompiledItems.add(item); - } - } - }; - - final Future parsingThreadFuture = ApplicationManager.getApplication().executeOnPooledThread(parsingThread); - try { - process.waitFor(); - } - catch (InterruptedException ignored) { - } - finally { - parsingThread.setProcessTerminated(true); - } - - try { - parsingThreadFuture.get(); - } - catch (InterruptedException ignored) { - } - catch (ExecutionException ignored) { - } - return successfullyCompiledItems.toArray(new RmicProcessingItem[successfullyCompiledItems.size()]); - } - - private static String[] createStartupCommand(final Module module, final String outputPath, final RmicProcessingItem[] items) { - final Sdk jdk = ModuleRootManager.getInstance(module).getSdk(); - - final VirtualFile homeDirectory = jdk.getHomeDirectory(); - if (homeDirectory == null) { - throw new IllegalArgumentException(CompilerBundle.jdkHomeNotFoundMessage(jdk)); - } - final String jdkPath = homeDirectory.getPath().replace('/', File.separatorChar); - - @NonNls final String compilerPath = jdkPath + File.separator + "bin" + File.separator + "rmic"; - - @NonNls final List commandLine = new ArrayList(); - commandLine.add(compilerPath); - - CompilerUtil.addLocaleOptions(commandLine, true); - - commandLine.add("-verbose"); - - final Project project = module.getProject(); - ContainerUtil.addAll(commandLine, new RmicSettingsBuilder(RmicConfiguration.getOptions(project)).getOptions(new Chunk(module))); - - commandLine.add("-classpath"); - - commandLine.add(getCompilationClasspath(module)); - - commandLine.add("-d"); - - commandLine.add(outputPath); - - for (RmicProcessingItem item : items) { - commandLine.add(item.getClassQName()); - } - return ArrayUtil.toStringArray(commandLine); - } - - @NotNull - public String getDescription() { - return CompilerBundle.message("rmi.compiler.description"); - } - - public boolean validateConfiguration(CompileScope scope) { - return true; - } - - /* - private void addAllRemoteFilesFromModuleOutput(final CompileContext context, final Module module, final List items, final File outputDir, File fromDir, final JavaClass remoteInterface) { - final File[] children = fromDir.listFiles(CLASSES_AND_DIRECTORIES_FILTER); - for (int idx = 0; idx < children.length; idx++) { - final File child = children[idx]; - if (child.isDirectory()) { - addAllRemoteFilesFromModuleOutput(context, module, items, outputDir, child, remoteInterface); - } - else { - final String path = child.getPath(); - try { - final ClassParser classParser = new ClassParser(path); - final JavaClass javaClass = classParser.parse(); - // important! Need this in order to resolve other classes in the project (e.g. superclasses) - javaClass.setRepository(BcelUtils.getActiveRepository()); - if (isRmicCompilable(javaClass, remoteInterface)) { - ApplicationManager.getApplication().runReadAction(new Runnable() { - public void run() { - final VirtualFile outputClassFile = LocalFileSystem.getInstance().findFileByIoFile(child); - if (outputClassFile != null) { - items.add(new RmicProcessingItem(module, outputClassFile, outputDir, javaClass.getClassName())); - } - } - }); - } - } - catch (IOException e) { - context.addMessage(CompilerMessageCategory.ERROR, "Cannot parse class file " + path + ": " + e.toString(), null, -1, -1); - } - catch (ClassFormatException e) { - context.addMessage(CompilerMessageCategory.ERROR, "Class format exception: " + e.getMessage() + " File: " + path, null, -1, -1); - } - } - } - } - */ - - /* - private boolean isRmicCompilable(final JavaClass javaClass, final JavaClass remoteInterface) { - // stubs are needed for classes that _directly_ implement remote interfaces - if (javaClass.isInterface() || isGenerated(javaClass)) { - return false; - } - final JavaClass[] directlyImplementedInterfaces = javaClass.getInterfaces(); - if (directlyImplementedInterfaces != null) { - for (int i = 0; i < directlyImplementedInterfaces.length; i++) { - if (directlyImplementedInterfaces[i].instanceOf(remoteInterface)) { - return true; - } - } - } - return false; - } - */ - - /* - private boolean isGenerated(JavaClass javaClass) { - final String sourceFileName = javaClass.getSourceFileName(); - return sourceFileName == null || !sourceFileName.endsWith(".java"); - } - */ - - - public ValidityState createValidityState(DataInput in) throws IOException { - return new RemoteClassValidityState(in.readLong(), in.readLong(), in.readLong(), in.readLong()); - } - - private static String getCompilationClasspath(Module module) { - final OrderEnumerator enumerator = ModuleRootManager.getInstance(module).orderEntries().withoutSdk().compileOnly().recursively().exportedOnly(); - final PathsList pathsList = enumerator.getPathsList(); - return pathsList.getPathsString(); - } - - private static final class RemoteClassValidityState implements ValidityState { - private final long myRemoteClassTimestamp; - private final long myStubTimestamp; - private final long mySkelTimestamp; - private final long myTieTimestamp; - - private RemoteClassValidityState(long remoteClassTimestamp, long stubTimestamp, long skelTimestamp, long tieTimestamp) { - myRemoteClassTimestamp = remoteClassTimestamp; - myStubTimestamp = stubTimestamp; - mySkelTimestamp = skelTimestamp; - myTieTimestamp = tieTimestamp; - } - - public boolean equalsTo(ValidityState otherState) { - if (otherState instanceof RemoteClassValidityState) { - final RemoteClassValidityState state = (RemoteClassValidityState)otherState; - return myRemoteClassTimestamp == state.myRemoteClassTimestamp && - myStubTimestamp == state.myStubTimestamp && - mySkelTimestamp == state.mySkelTimestamp && - myTieTimestamp == state.myTieTimestamp; - } - return false; - } - - public void save(DataOutput out) throws IOException { - out.writeLong(myRemoteClassTimestamp); - out.writeLong(myStubTimestamp); - out.writeLong(mySkelTimestamp); - out.writeLong(myTieTimestamp); - } - } - private static final class RmicProcessingItem implements ProcessingItem { - private final Module myModule; - private final VirtualFile myOutputClassFile; - private final File myOutputDir; - private final String myQName; - private RemoteClassValidityState myState; - private final File myStub; - private final File mySkel; - private final File myTie; - private boolean myIsRemoteObject = false; - - private RmicProcessingItem(Module module, final VirtualFile outputClassFile, File outputDir, String qName) { - myModule = module; - myOutputClassFile = outputClassFile; - myOutputDir = outputDir; - myQName = qName; - final String relativePath; - final String baseName; - - final int index = qName.lastIndexOf('.'); - if (index >= 0) { - relativePath = qName.substring(0, index + 1).replace('.', '/'); - baseName = qName.substring(index + 1); - } - else { - relativePath = ""; - baseName = qName; - } - final String path = outputDir.getPath().replace(File.separatorChar, '/') + "/" + relativePath; - //noinspection HardCodedStringLiteral - myStub = new File(path + "/" + baseName + "_Stub.class"); - //noinspection HardCodedStringLiteral - mySkel = new File(path + "/" + baseName + "_Skel.class"); - //noinspection HardCodedStringLiteral - myTie = new File(path + "/_" + baseName + "_Tie.class"); - updateState(); - } - - public boolean isRemoteObject() { - return myIsRemoteObject; - } - - public void setIsRemoteObject(boolean isRemote) { - myIsRemoteObject = isRemote; - } - - @NotNull - public VirtualFile getFile() { - return myOutputClassFile; - } - - public ValidityState getValidityState() { - return myState; - } - - public void updateState() { - myState = new RemoteClassValidityState( - myOutputClassFile.getTimeStamp(), - getTimestamp(myStub), - getTimestamp(mySkel), - getTimestamp(myTie) - ); - - } - - private static long getTimestamp(File file) { - long l = file.lastModified(); - return l == 0 ? -1L : l; - } - - public void deleteGeneratedFiles() { - if (FileUtil.delete(myStub)) { - CompilerUtil.refreshIOFile(myStub); - } - if (FileUtil.delete(mySkel)) { - CompilerUtil.refreshIOFile(mySkel); - } - if (FileUtil.delete(myTie)) { - CompilerUtil.refreshIOFile(myTie); - } - } - - public String getClassQName() { - return myQName; - } - - public File getOutputDir() { - return myOutputDir; - } - - public Module getModule() { - return myModule; - } - } -} diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/rmiCompiler/RmicSettingsBuilder.java b/java/compiler/impl/src/com/intellij/compiler/impl/rmiCompiler/RmicSettingsBuilder.java deleted file mode 100644 index e4b0aee451be..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/impl/rmiCompiler/RmicSettingsBuilder.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright 2000-2012 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.compiler.impl.rmiCompiler; - -import com.intellij.compiler.impl.javaCompiler.javac.JavacSettingsBuilder; -import com.intellij.openapi.module.Module; -import com.intellij.util.Chunk; -import org.jetbrains.jps.model.java.compiler.RmicCompilerOptions; - -import java.util.Collection; - -public class RmicSettingsBuilder extends JavacSettingsBuilder { - - public RmicSettingsBuilder(final RmicCompilerOptions options) { - super(options); - getOptions().DEPRECATION = false; // in this configuration deprecation is false by default - } - - @Override - public RmicCompilerOptions getOptions() { - return (RmicCompilerOptions)super.getOptions(); - } - - public Collection getOptions(Chunk chunk) { - final Collection options = super.getOptions(chunk); - if(getOptions().GENERATE_IIOP_STUBS) { - options.add("-iiop"); - } - return options; - } - - protected boolean acceptUserOption(String token) { - if (!super.acceptUserOption(token)) { - return false; - } - return !("-iiop".equals(token)); - } - - protected boolean acceptEncoding() { - return false; - } -} \ No newline at end of file diff --git a/java/compiler/impl/src/com/intellij/compiler/make/AnnotationTargets.java b/java/compiler/impl/src/com/intellij/compiler/make/AnnotationTargets.java deleted file mode 100644 index 100fd4a118b8..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/make/AnnotationTargets.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.compiler.make; - -import org.jetbrains.annotations.NonNls; - -/** - * @author Eugene Zhuravlev - * Date: Apr 7, 2004 - */ -public interface AnnotationTargets { - /** Class, interface or enum declaration */ - int TYPE = 0x1; - - @NonNls String TYPE_STR = "TYPE"; - - /** Field declaration (includes enum constants) */ - int FIELD = 0x2; - - @NonNls String FIELD_STR = "FIELD"; - - /** Method declaration */ - int METHOD = 0x4; - - @NonNls String METHOD_STR = "METHOD"; - - /** Parameter declaration */ - int PARAMETER = 0x8; - - @NonNls String PARAMETER_STR = "PARAMETER"; - - /** Constructor declaration */ - int CONSTRUCTOR = 0x10; - - @NonNls String CONSTRUCTOR_STR = "CONSTRUCTOR"; - - /** Local variable declaration */ - int LOCAL_VARIABLE = 0x20; - - @NonNls String LOCAL_VARIABLE_STR = "LOCAL_VARIABLE"; - - /** Annotation type declaration */ - int ANNOTATION_TYPE = 0x40; - - @NonNls String ANNOTATION_TYPE_STR = "ANNOTATION_TYPE"; - - /** Package declaration */ - int PACKAGE = 0x80; - - @NonNls String PACKAGE_STR = "PACKAGE"; - - int ALL = TYPE | FIELD | METHOD | PARAMETER | CONSTRUCTOR | LOCAL_VARIABLE | ANNOTATION_TYPE | PACKAGE; -} diff --git a/java/compiler/impl/src/com/intellij/compiler/make/BackwardDependenciesStorage.java b/java/compiler/impl/src/com/intellij/compiler/make/BackwardDependenciesStorage.java deleted file mode 100644 index 006debb3b43a..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/make/BackwardDependenciesStorage.java +++ /dev/null @@ -1,511 +0,0 @@ -/* - * Copyright 2000-2014 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.compiler.make; - -import com.intellij.openapi.Disposable; -import com.intellij.openapi.diagnostic.Logger; -import com.intellij.openapi.util.Ref; -import com.intellij.util.containers.SLRUCache; -import com.intellij.util.io.DataExternalizer; -import com.intellij.util.io.EnumeratorIntegerDescriptor; -import com.intellij.util.io.PersistentHashMap; -import gnu.trove.*; -import org.jetbrains.annotations.NotNull; - -import java.io.*; -import java.util.*; - -/** - * @author Eugene Zhuravlev - * Date: Dec 1, 2008 - */ -public class BackwardDependenciesStorage implements Flushable, Disposable { - private static final Logger LOG = Logger.getInstance("#com.intellij.compiler.make.CompilerDependencyStorage"); - protected final PersistentHashMap myMap; - protected final SLRUCache myCache; - private Integer myKeyToRemove; - private static final int FIELD = 1; - private static final int METHOD = 2; - private static final int CLASS = 3; - - public BackwardDependenciesStorage(File file, final int cacheSize) throws IOException { - myMap = new PersistentHashMap(file, EnumeratorIntegerDescriptor.INSTANCE, new MyDataExternalizer()); - - myCache = new SLRUCache(cacheSize * 2, cacheSize) { - @NotNull - public ReferencerSetHolder createValue(Integer key) { - return new ReferencerSetHolder(key); - } - - protected void onDropFromCache(Integer key, final ReferencerSetHolder holder) { - if (key.equals(myKeyToRemove) || !holder.isDirty()) { - return; - } - try { - if (holder.isDataLoaded() || !myMap.containsMapping(key)) { - myMap.put(key, new DependenciesSet(holder.getData())); - } - else { - myMap.appendData(key, new PersistentHashMap.ValueDataAppender() { - public void append(final DataOutput out) throws IOException { - final Ref exception = new Ref(null); - // process removed - holder.myRemoveRequested.forEach(new TIntProcedure() { - public boolean execute(int qName) { - try { - out.writeInt(-qName); - return true; - } - catch (IOException e) { - exception.set(e); - } - return false; - } - }); - final IOException _ex = exception.get(); - if (_ex != null) { - throw _ex; - } - // process added members - for (ReferencerItem item : holder.myAdded) { - item.save(out); - } - } - }); - } - } - catch (IOException e) { - LOG.error(e); - } - } - }; - } - - public synchronized void remove(Integer qName) throws IOException { - myKeyToRemove = qName; - try { - myCache.remove(qName); - } - finally { - myKeyToRemove = null; - } - myMap.remove(qName); - } - - public synchronized void removeReferencer(Integer qName, int referencerQName) throws IOException { - if (myMap.containsMapping(qName)) { - final ReferencerSetHolder set = myCache.get(qName); - set.removeReferencer(referencerQName); - } - } - - public synchronized void addClassReferencer(Integer qName, int referencerQName) { - myCache.get(qName).addReferencer(new ReferencerItem(referencerQName)); - } - - public synchronized void addFieldReferencer(Integer qName, int referencerQName, int fieldName) { - myCache.get(qName).addReferencer(new FieldReferencerItem(referencerQName, fieldName)); - } - - public synchronized void addMethodReferencer(Integer qName, int referencerQName, int methodName, int descriptor) { - myCache.get(qName).addReferencer(new MethodReferencerItem(referencerQName, methodName, descriptor)); - } - - public synchronized Dependency[] getDependencies(Integer classQName) throws CacheCorruptedException { - try { - if (!myMap.containsMapping(classQName)) { - return Dependency.EMPTY_ARRAY; - } - - return convertToDependencies(classQName.intValue(), myCache.get(classQName).getData()); - } - catch (Throwable e) { - throw new CacheCorruptedException(e); - } - } - - private static Dependency[] convertToDependencies(int classToSkip, Set data) { - final TIntObjectHashMap dependencies = new TIntObjectHashMap(); - for (ReferencerItem item : data) { - if (item.qName == classToSkip) { - continue; // skip self-dependencies - } - final Dependency dependency = addDependency(dependencies, item.qName); - if (item instanceof FieldReferencerItem) { - dependency.addField(((FieldReferencerItem)item).name); - } - else if (item instanceof MethodReferencerItem) { - final MethodReferencerItem methodItem = (MethodReferencerItem)item; - dependency.addMethod(methodItem.name, methodItem.descriptor); - } - } - - final Dependency[] dependencyArray = new Dependency[dependencies.size()]; - dependencies.forEachValue(new TObjectProcedure() { - private int index = 0; - public boolean execute(Dependency object) { - dependencyArray[index++] = object; - return true; - } - }); - return dependencyArray; - } - - private static Dependency addDependency(TIntObjectHashMap container, int classQName) { - Dependency dependency = container.get(classQName); - if (dependency == null) { - dependency = new Dependency(classQName); - container.put(classQName, dependency); - } - return dependency; - } - - public synchronized void flush() throws IOException { - myCache.clear(); - myMap.force(); - } - - private void flush(Integer key) { - myCache.remove(key); // makes changes into PersistentHashMap - myMap.force(); // flushes internal caches (which consume memory) and writes unsaved data to disk - } - - public synchronized void dispose() { - try { - flush(); - } - catch (IOException e) { - LOG.info(e); - } - try { - myMap.close(); - } - catch (IOException e) { - LOG.info(e); - } - } - - private static class ReferencerItem { - public final int qName; - - private ReferencerItem(int qName) { - this.qName = qName; - } - - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - ReferencerItem that = (ReferencerItem)o; - - if (qName != that.qName) return false; - - return true; - } - - public int hashCode() { - return qName; - } - - public void save(DataOutput out) throws IOException { - out.writeInt(qName); - out.writeByte(CLASS); - } - } - - private static final class MethodReferencerItem extends ReferencerItem { - public final int name; - public final int descriptor; - - MethodReferencerItem(int qName, int name, int descriptor) { - super(qName); - this.name = name; - this.descriptor = descriptor; - } - - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - if (!super.equals(o)) return false; - - MethodReferencerItem that = (MethodReferencerItem)o; - - if (descriptor != that.descriptor) return false; - if (name != that.name) return false; - - return true; - } - - public int hashCode() { - int result = super.hashCode(); - result = 31 * result + name; - result = 31 * result + descriptor; - return result; - } - - public void save(DataOutput out) throws IOException { - out.writeInt(qName); - out.writeByte(METHOD); - out.writeInt(name); - out.writeInt(descriptor); - } - } - - private static final class FieldReferencerItem extends ReferencerItem { - public final int name; - - FieldReferencerItem(int qName, int name) { - super(qName); - this.name = name; - } - - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - if (!super.equals(o)) return false; - - FieldReferencerItem that = (FieldReferencerItem)o; - - if (name != that.name) return false; - - return true; - } - - public int hashCode() { - int result = super.hashCode(); - result = 31 * result + name; - return result; - } - - public void save(DataOutput out) throws IOException { - out.writeInt(qName); - out.writeByte(FIELD); - out.writeInt(name); - } - } - - private class ReferencerSetHolder { - private final Integer myKey; - private TIntHashSet myRemoveRequested = new TIntHashSet(); - private Set myAdded = new THashSet(); - - private Set myData = null; - private boolean myIsDirty = false; - - public ReferencerSetHolder(Integer key) { - myKey = key; - } - - public void addReferencer(ReferencerItem referencer) { - if (myData != null) { - myIsDirty |= myData.add(referencer); - return; - } - myAdded.add(referencer); - } - - public void removeReferencer(int qName) { - if (myData != null) { - myIsDirty |= removeAllReferencerItems(myData, qName); - return; - } - myRemoveRequested.add(qName); - removeAllReferencerItems(myAdded, qName); - } - - public boolean isDirty() { - return myData != null? myIsDirty : myRemoveRequested.size() > 0 || myAdded.size() > 0; - } - - public boolean isDataLoaded() { - return myData != null; - } - - public Set getData() throws IOException { - if (myData == null) { - final DependenciesSet ds = myMap.get(myKey); - Set set = null; - if (ds != null) { - set = ds.set; - myIsDirty |= ds.needsCompacting; - } - if (set == null) { - set = new THashSet(); - } - myIsDirty |= removeAllReferencerItems(set, myRemoveRequested); - myIsDirty |= set.addAll(myAdded); - myData = set; - myAdded = null; - myRemoveRequested = null; - } - return Collections.unmodifiableSet(myData); - } - - } - - private static class MyDataExternalizer implements DataExternalizer { - public void save(@NotNull DataOutput out, DependenciesSet ds) throws IOException { - final TIntHashSet classes = new TIntHashSet(); - final Map fieldsMap = new HashMap(); - final Map methodsMap = new HashMap(); - for (ReferencerItem item : ds.set) { - if (item instanceof FieldReferencerItem) { - final Dependency.FieldRef ref = new Dependency.FieldRef(((FieldReferencerItem)item).name); - TIntHashSet referencers = fieldsMap.get(ref); - if (referencers == null) { - referencers = new TIntHashSet(); - fieldsMap.put(ref, referencers); - } - referencers.add(item.qName); - } - else if (item instanceof MethodReferencerItem) { - final MethodReferencerItem _item = (MethodReferencerItem)item; - final Dependency.MethodRef ref = new Dependency.MethodRef(_item.name, _item.descriptor); - TIntHashSet referencers = methodsMap.get(ref); - if (referencers == null) { - referencers = new TIntHashSet(); - methodsMap.put(ref, referencers); - } - referencers.add(item.qName); - } - else { - classes.add(item.qName); - } - } - - out.writeInt(classes.size()); - for (TIntIterator it = classes.iterator(); it.hasNext();) { - out.writeInt(it.next()); - } - - out.writeInt(fieldsMap.size()); - for (Map.Entry entry : fieldsMap.entrySet()) { - out.writeInt(entry.getKey().name); - final TIntHashSet referencers = entry.getValue(); - out.writeInt(referencers.size()); - for (TIntIterator rit = referencers.iterator(); rit.hasNext();) { - out.writeInt(rit.next()); - } - } - - out.writeInt(methodsMap.size()); - for (Map.Entry entry : methodsMap.entrySet()) { - final Dependency.MethodRef ref = entry.getKey(); - out.writeInt(ref.name); - out.writeInt(ref.descriptor); - final TIntHashSet referencers = entry.getValue(); - out.writeInt(referencers.size()); - for (TIntIterator rit = referencers.iterator(); rit.hasNext();) { - out.writeInt(rit.next()); - } - } - } - - public DependenciesSet read(@NotNull DataInput in) throws IOException { - final Set set = new THashSet(); - - int classesCount = in.readInt(); - while (classesCount-- > 0) { - set.add(new ReferencerItem(in.readInt())); - } - - int fieldsCount = in.readInt(); - while (fieldsCount-- > 0) { - final int fieldName = in.readInt(); - int referencersCount = in.readInt(); - while (referencersCount-- > 0) { - set.add(new FieldReferencerItem(in.readInt(), fieldName)); - } - } - - int methodsCount = in.readInt(); - while (methodsCount-- > 0) { - final int methodName = in.readInt(); - final int methodDescriptor = in.readInt(); - int referensersCount = in.readInt(); - while (referensersCount-- > 0) { - set.add(new MethodReferencerItem(in.readInt(), methodName, methodDescriptor)); - } - } - boolean needsCompacting = false; - // manage appends if exist qName, kind, {field | method} - final DataInputStream _in = (DataInputStream)in; - while (_in.available() > 0) { - needsCompacting = true; - final int qName = _in.readInt(); - if (qName < 0) { - removeAllReferencerItems(set, -qName); - } - else { - final byte kind = _in.readByte(); - if (kind == FIELD) { - set.add(new FieldReferencerItem(qName, _in.readInt())); - } - else if (kind == METHOD) { - final int name = _in.readInt(); - final int descriptor = _in.readInt(); - set.add(new MethodReferencerItem(qName, name, descriptor)); - } - else if (kind == CLASS){ - set.add(new ReferencerItem(qName)); - } - } - } - - return new DependenciesSet(set, needsCompacting); - } - } - - private static final class DependenciesSet { - public final Set set; - public final boolean needsCompacting; - - public DependenciesSet(Set set, boolean needsCompacting) { - this.set = set; - this.needsCompacting = needsCompacting; - } - - public DependenciesSet(Set set) { - this(set, false); - } - } - - - private static boolean removeAllReferencerItems(final Set from, final TIntHashSet qNames) { - boolean removed = false; - for (Iterator it = from.iterator(); it.hasNext();) { - final ReferencerItem item = it.next(); - if (qNames.contains(item.qName)) { - it.remove(); - removed = true; - } - } - return removed; - } - - private static boolean removeAllReferencerItems(final Set from, final int qNames) { - boolean removed = false; - for (Iterator it = from.iterator(); it.hasNext();) { - final ReferencerItem item = it.next(); - if (qNames == item.qName) { - it.remove(); - removed = true; - } - } - return removed; - } - -} \ No newline at end of file diff --git a/java/compiler/impl/src/com/intellij/compiler/make/BoundsParser.java b/java/compiler/impl/src/com/intellij/compiler/make/BoundsParser.java deleted file mode 100644 index 0ab9489c2a70..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/make/BoundsParser.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.compiler.make; - -import com.intellij.compiler.classParsing.SignatureParser; -import com.intellij.compiler.classParsing.SignatureParsingException; -import com.intellij.util.ArrayUtil; - -import java.text.CharacterIterator; -import java.text.StringCharacterIterator; -import java.util.ArrayList; -import java.util.List; - -/** - * @author Eugene Zhuravlev - * Date: Mar 10, 2004 - */ -public class BoundsParser extends SignatureParser{ - final List myInterfaceBounds = new ArrayList(); - private int myParsingBound; - - public void parseClassBound(CharacterIterator it, StringBuilder buf) throws SignatureParsingException { - myParsingBound += 1; - try { - super.parseClassBound(it, buf); - } - finally { - myParsingBound -= 1; - } - } - - public void parseInterfaceBound(CharacterIterator it, StringBuilder buf) throws SignatureParsingException { - myParsingBound += 1; - try { - super.parseInterfaceBound(it, buf); - } - finally { - myParsingBound -= 1; - } - } - - public void parseClassTypeSignature(CharacterIterator it, StringBuilder buf) throws SignatureParsingException { - if (myParsingBound > 0) { - final int start = buf.length(); - - super.parseClassTypeSignature(it, buf); - - final String qName = convertToQalifiedName(buf.substring(start + 1, buf.length() - 1)); - myInterfaceBounds.add(qName); - } - else { - super.parseClassTypeSignature(it, buf); - } - } - - private static String convertToQalifiedName(String ifaceSignature) { - ifaceSignature = ifaceSignature.replaceAll("<.*>", ""); - return ifaceSignature.replace('/', '.'); - } - - public String[] getBounds() { - return ArrayUtil.toStringArray(myInterfaceBounds); - } - - public static String[] getBounds(String classSignature) throws SignatureParsingException { - final BoundsParser parser = new BoundsParser(); - parser.parseClassSignature(new StringCharacterIterator(classSignature), new StringBuilder()); - return parser.getBounds(); - } -} diff --git a/java/compiler/impl/src/com/intellij/compiler/make/Cache.java b/java/compiler/impl/src/com/intellij/compiler/make/Cache.java deleted file mode 100644 index f80cb8e5bcaa..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/make/Cache.java +++ /dev/null @@ -1,521 +0,0 @@ -/* - * Copyright 2000-2014 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.compiler.make; - -import com.intellij.compiler.SymbolTable; -import com.intellij.compiler.classParsing.*; -import com.intellij.openapi.diagnostic.Logger; -import com.intellij.openapi.util.io.FileUtil; -import com.intellij.util.ArrayUtil; -import com.intellij.util.cls.ClsFormatException; -import com.intellij.util.io.DataExternalizer; -import com.intellij.util.io.EnumeratorIntegerDescriptor; -import com.intellij.util.io.PersistentHashMap; -import org.jetbrains.annotations.NonNls; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.io.DataInput; -import java.io.DataOutput; -import java.io.File; -import java.io.IOException; -import java.util.*; - -/** - * @author Eugene Zhuravlev - * Date: Aug 8, 2003 - * Time: 7:03:56 PM - */ -public class Cache { - private static final Logger LOG = Logger.getInstance("#com.intellij.compiler.make.Cache"); - public static final int UNKNOWN = -1; - - private final PersistentHashMap myQNameToClassInfoMap; - - private final BackwardDependenciesStorage myDependencies; - private final CompilerDependencyStorage myQNameToReferencedClassesMap; - private final CompilerDependencyStorage myQNameToSubclassesMap; - private final PersistentHashMap myRemoteQNames; - private final String myStorePath; - - public Cache(@NonNls final String storePath, final int cacheSize) throws IOException { - myStorePath = storePath; - new File(storePath).mkdirs(); - myQNameToClassInfoMap = new CachedPersistentHashMap(getOrCreateFile("classes"), EnumeratorIntegerDescriptor.INSTANCE, new DataExternalizer() { - public void save(@NotNull DataOutput out, ClassInfo value) throws IOException { - value.save(out); - } - public ClassInfo read(@NotNull DataInput in) throws IOException { - return new ClassInfo(in); - } - }, cacheSize * 2) { - protected boolean isValueDirty(ClassInfo classInfo) { - return classInfo.isDirty(); - } - }; - - myDependencies = new BackwardDependenciesStorage(getOrCreateFile("bdeps"), cacheSize); - myQNameToReferencedClassesMap = new CompilerDependencyStorage(getOrCreateFile("fdeps"), EnumeratorIntegerDescriptor.INSTANCE, cacheSize); - myQNameToSubclassesMap = new CompilerDependencyStorage(getOrCreateFile("subclasses"), EnumeratorIntegerDescriptor.INSTANCE, cacheSize); - - myRemoteQNames = new PersistentHashMap(getOrCreateFile("remote"), EnumeratorIntegerDescriptor.INSTANCE, new DataExternalizer() { - public void save(@NotNull DataOutput out, Boolean value) throws IOException { - out.writeBoolean(value.booleanValue()); - } - - public Boolean read(@NotNull DataInput in) throws IOException { - return in.readBoolean(); - } - }, cacheSize); - } - - private File getOrCreateFile(final String fileName) throws IOException { - final File file = new File(myStorePath, fileName); - FileUtil.createIfDoesntExist(file); - return file; - } - - public void dispose() throws CacheCorruptedException { - CacheCorruptedException ex = null; - try { - myQNameToClassInfoMap.close(); - } - catch (IOException e) { - LOG.info(e); - ex = new CacheCorruptedException(e); - } - try { - myRemoteQNames.close(); - } - catch (IOException e) { - LOG.info(e); - if (ex != null) { - ex = new CacheCorruptedException(e); - } - } - - myQNameToReferencedClassesMap.dispose(); - myDependencies.dispose(); - myQNameToSubclassesMap.dispose(); - - if (ex != null) { - throw ex; - } - - } - - public int[] getAllClassNames() throws CacheCorruptedException { - try { - final Collection allKeys = myQNameToClassInfoMap.getAllKeysWithExistingMapping(); - final int[] array = ArrayUtil.newIntArray(allKeys.size()); - int idx = 0; - for (Integer id : allKeys) { - array[idx++] = id.intValue(); - } - return array; - } - catch (IOException e) { - throw new CacheCorruptedException(e); - } - } - - public int importClassInfo(ClassFileReader reader, SymbolTable symbolTable) throws ClsFormatException, CacheCorruptedException { - try { - final ClassInfo classInfo = new ClassInfo(reader, symbolTable); - myQNameToClassInfoMap.put(classInfo.getQualifiedName(), classInfo); - return classInfo.getQualifiedName(); - } - catch (IOException e) { - throw new CacheCorruptedException(e); - } - } - - public void importClassInfo(Cache fromCache, final int qName) throws CacheCorruptedException { - try { - final ClassInfo classInfo = fromCache.myQNameToClassInfoMap.get(qName); - if (classInfo != null) { - final ClassInfo clone = classInfo.clone(); - clone.clearReferences(); - myQNameToClassInfoMap.put(qName, clone); - } - } - catch (Throwable e) { - throw new CacheCorruptedException(e); - } - } - - public AnnotationConstantValue[] getRuntimeVisibleAnnotations(int classId) throws CacheCorruptedException { - try { - final ClassInfo classInfo = myQNameToClassInfoMap.get(classId); - return classInfo != null? classInfo.getRuntimeVisibleAnnotations() : AnnotationConstantValue.EMPTY_ARRAY; - } - catch (Throwable e) { - throw new CacheCorruptedException(e); - } - } - - public AnnotationConstantValue[] getRuntimeInvisibleAnnotations(int classId) throws CacheCorruptedException { - try { - final ClassInfo classInfo = myQNameToClassInfoMap.get(classId); - return classInfo != null? classInfo.getRuntimeInvisibleAnnotations() : AnnotationConstantValue.EMPTY_ARRAY; - } - catch (Throwable e) { - throw new CacheCorruptedException(e); - } - } - - public int[] getSubclasses(int classId) throws CacheCorruptedException { - try { - return myQNameToSubclassesMap.getValues(classId); - } - catch (Throwable e) { - throw new CacheCorruptedException(e); - } - } - - public void addSubclass(int classId, int subclassQName) throws CacheCorruptedException { - try { - myQNameToSubclassesMap.addValue(classId, subclassQName); - } - catch (Throwable e) { - throw new CacheCorruptedException(e); - } - } - - public void removeSubclass(int classId, int subclassQName) throws CacheCorruptedException { - try { - myQNameToSubclassesMap.removeValue(classId, subclassQName); - } - catch (Throwable e) { - throw new CacheCorruptedException(e); - } - } - - public int[] getReferencedClasses(int qName) throws CacheCorruptedException { - try { - return myQNameToReferencedClassesMap.getValues(qName); - } - catch (Throwable e) { - throw new CacheCorruptedException(e); - } - } - - public void clearReferencedClasses(int qName) throws CacheCorruptedException { - try { - myQNameToReferencedClassesMap.remove(qName); - } - catch (Throwable e) { - throw new CacheCorruptedException(e); - } - } - - public Collection getReferences(int classId) throws CacheCorruptedException { - try { - final ClassInfo classInfo = myQNameToClassInfoMap.get(classId); - return classInfo != null? Arrays.asList(classInfo.getReferences()) : Collections.emptyList(); - } - catch (Throwable e) { - throw new CacheCorruptedException(e); - } - } - - public String getSourceFileName(int classId) throws CacheCorruptedException { - try { - final ClassInfo classInfo = myQNameToClassInfoMap.get(classId); - return classInfo != null? classInfo.getSourceFileName() : ""; - } - catch (Throwable e) { - throw new CacheCorruptedException(e); - } - } - - public boolean isRemote(int classId) throws CacheCorruptedException { - try { - return myRemoteQNames.containsMapping(classId); - } - catch (Throwable e) { - throw new CacheCorruptedException(e); - } - } - - public void setRemote(int classId, boolean remote) throws CacheCorruptedException { - try { - if (remote) { - myRemoteQNames.put(classId, Boolean.TRUE); - } - else { - myRemoteQNames.remove(classId); - } - } - catch (Throwable e) { - throw new CacheCorruptedException(e); - } - } - - public int getSuperQualifiedName(int classId) throws CacheCorruptedException { - try { - final ClassInfo classInfo = myQNameToClassInfoMap.get(classId); - return classInfo != null? classInfo.getSuperQualifiedName() : UNKNOWN; - } - catch (Throwable e) { - throw new CacheCorruptedException(e); - } - } - - public String getPath(int classId) throws CacheCorruptedException { - try { - final ClassInfo classInfo = myQNameToClassInfoMap.get(classId); - return classInfo != null? classInfo.getPath() : ""; - } - catch (Throwable e) { - throw new CacheCorruptedException(e); - } - } - - public void setPath(int classId, String path) throws CacheCorruptedException { - try { - final ClassInfo classInfo = myQNameToClassInfoMap.get(classId); - if (classInfo != null) { - classInfo.setPath(path); - } - } - catch (Throwable e) { - throw new CacheCorruptedException(e); - } - } - - public int getGenericSignature(int classId) throws CacheCorruptedException { - try { - final ClassInfo classInfo = myQNameToClassInfoMap.get(classId); - return classInfo != null? classInfo.getGenericSignature() : UNKNOWN; - } - catch (Throwable e) { - throw new CacheCorruptedException(e); - } - } - - public boolean containsClass(int qName) throws CacheCorruptedException { - try { - return myQNameToClassInfoMap.containsMapping(qName); - } - catch (IOException e) { - throw new CacheCorruptedException(e); - } - } - - public int[] getSuperInterfaces(int classId) throws CacheCorruptedException { - try { - final ClassInfo classInfo = myQNameToClassInfoMap.get(classId); - return classInfo != null? classInfo.getSuperInterfaces() : ArrayUtil.EMPTY_INT_ARRAY; - } - catch (Throwable e) { - throw new CacheCorruptedException(e); - } - } - - public int getFlags(int classId) throws CacheCorruptedException { - try { - final ClassInfo classInfo = myQNameToClassInfoMap.get(classId); - return classInfo != null? classInfo.getFlags() : UNKNOWN; - } - catch (Throwable e) { - throw new CacheCorruptedException(e); - } - } - - public FieldInfo[] getFields(int qName) throws CacheCorruptedException{ - try { - final ClassInfo classInfo = myQNameToClassInfoMap.get(qName); - return classInfo != null? classInfo.getFields() : FieldInfo.EMPTY_ARRAY; - } - catch (Throwable e) { - throw new CacheCorruptedException(e); - } - } - - @Nullable - public FieldInfo findField(final int classDeclarationId, final int name, final int descriptor) throws CacheCorruptedException{ - try { - for (FieldInfo fieldInfo : getFields(classDeclarationId)) { - if (fieldInfo.getName() == name && fieldInfo.getDescriptor() == descriptor) { - return fieldInfo; - } - } - return null; - } - catch (Throwable e) { - throw new CacheCorruptedException(e); - } - } - - @Nullable - public FieldInfo findFieldByName(final int classDeclarationId, final int name) throws CacheCorruptedException{ - try { - for (FieldInfo fieldInfo : getFields(classDeclarationId)) { - if (fieldInfo.getName() == name) { - return fieldInfo; - } - } - return null; - } - catch (Throwable e) { - throw new CacheCorruptedException(e); - } - } - - public MethodInfo[] getMethods(int classQName) throws CacheCorruptedException{ - try { - final ClassInfo classInfo = myQNameToClassInfoMap.get(classQName); - return classInfo != null? classInfo.getMethods() : MethodInfo.EMPTY_ARRAY; - } - catch (Throwable e) { - throw new CacheCorruptedException(e); - } - } - - @Nullable - public MethodInfo findMethod(final int classQName, final int name, final int descriptor) throws CacheCorruptedException{ - try { - for (MethodInfo methodInfo : getMethods(classQName)) { - if (methodInfo.getName() == name && methodInfo.getDescriptor() == descriptor) { - return methodInfo; - } - } - return null; - } - catch (Throwable e) { - throw new CacheCorruptedException(e); - } - } - - public List findMethodsByName(final int classDeclarationId, final int name) throws CacheCorruptedException{ - try { - final List methods = new ArrayList(); - for (MethodInfo methodInfo : getMethods(classDeclarationId)) { - if (methodInfo.getName() == name) { - methods.add(methodInfo); - } - } - return methods; - } - catch (Throwable e) { - throw new CacheCorruptedException(e); - } - } - - @Nullable - public MethodInfo findMethodsBySignature(final int classDeclarationId, final String signature, SymbolTable symbolTable) throws CacheCorruptedException{ - try { - for (MethodInfo methodInfo : getMethods(classDeclarationId)) { - if (signature.equals(CacheUtils.getMethodSignature(symbolTable.getSymbol(methodInfo.getName()), symbolTable.getSymbol(methodInfo.getDescriptor())))) { - return methodInfo; - } - } - return null; - } - catch (Throwable e) { - throw new CacheCorruptedException(e); - } - } - - public void addClassReferencer(int qName, int referencerQName) throws CacheCorruptedException { - try { - if (qName == referencerQName) { - return; // do not log self-dependencies - } - if (myQNameToClassInfoMap.containsMapping(qName)) { - myDependencies.addClassReferencer(qName, referencerQName); - myQNameToReferencedClassesMap.addValue(referencerQName, qName); - } - } - catch (Throwable e) { - throw new CacheCorruptedException(e); - } - } - - public void removeClassReferencer(int qName, int referencerQName) throws CacheCorruptedException { - try { - myDependencies.removeReferencer(qName, referencerQName); - } - catch (Throwable e) { - throw new CacheCorruptedException(e); - } - } - - public void addFieldReferencer(int qName, int fieldName, int referencerQName) throws CacheCorruptedException { - try { - if (qName != referencerQName && myQNameToClassInfoMap.containsMapping(qName)) { - myDependencies.addFieldReferencer(qName, referencerQName, fieldName); - myQNameToReferencedClassesMap.addValue(referencerQName, qName); - } - } - catch (Throwable e) { - throw new CacheCorruptedException(e); - } - } - - public void addMethodReferencer(int qName, int methodName, int methodDescriptor, int referencerQName) throws CacheCorruptedException { - try { - if (qName != referencerQName && myQNameToClassInfoMap.containsMapping(qName)) { - myDependencies.addMethodReferencer(qName, referencerQName, methodName, methodDescriptor); - myQNameToReferencedClassesMap.addValue(referencerQName, qName); - } - } - catch (Throwable e) { - throw new CacheCorruptedException(e); - } - } - - /** @NotNull */ - public Dependency[] getBackDependencies(final int classQName) throws CacheCorruptedException{ - return myDependencies.getDependencies(classQName); - } - - public void wipe() { - try { - dispose(); - } - catch (CacheCorruptedException ignored) { - } - finally { - final File[] files = new File(myStorePath).listFiles(); - if (files != null) { - for (File file : files) { - if (!file.isDirectory()) { - FileUtil.delete(file); - } - } - } - } - } - - public void removeClass(final int qName) throws CacheCorruptedException { - try { - final ClassInfo classInfo = myQNameToClassInfoMap.get(qName); - if (classInfo == null) { - return; - } - myDependencies.remove(qName); - myQNameToClassInfoMap.remove(qName); - myQNameToReferencedClassesMap.remove(qName); - myQNameToSubclassesMap.remove(qName); - myRemoteQNames.remove(qName); - } - catch (Throwable e) { - throw new CacheCorruptedException(e); - } - } -} diff --git a/java/compiler/impl/src/com/intellij/compiler/make/CacheCorruptedException.java b/java/compiler/impl/src/com/intellij/compiler/make/CacheCorruptedException.java deleted file mode 100644 index 916a3700d2b7..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/make/CacheCorruptedException.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * @author: Eugene Zhuravlev - * Date: Jul 10, 2003 - * Time: 4:51:25 PM - */ -package com.intellij.compiler.make; - -import com.intellij.openapi.compiler.CompilerBundle; - -public class CacheCorruptedException extends Exception{ - private static final String DEFAULT_MESSAGE = CompilerBundle.message("error.dependency.info.on.disk.corrupted"); - public CacheCorruptedException(String message) { - super((message == null || message.length() == 0)? DEFAULT_MESSAGE : message); - } - - public CacheCorruptedException(Throwable cause) { - super(DEFAULT_MESSAGE, cause); - } - - public CacheCorruptedException(String message, Throwable cause) { - super((message == null || message.length() == 0)? DEFAULT_MESSAGE : message, cause); - } - - public String getMessage() { - return super.getMessage(); - } -} diff --git a/java/compiler/impl/src/com/intellij/compiler/make/CacheUtils.java b/java/compiler/impl/src/com/intellij/compiler/make/CacheUtils.java deleted file mode 100644 index 51cb953e9935..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/make/CacheUtils.java +++ /dev/null @@ -1,205 +0,0 @@ -/* - * Copyright 2000-2014 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.compiler.make; - -import com.intellij.compiler.CompilerConfiguration; -import com.intellij.compiler.CompilerManagerImpl; -import com.intellij.compiler.SymbolTable; -import com.intellij.compiler.classParsing.MethodInfo; -import com.intellij.compiler.impl.ExitException; -import com.intellij.openapi.application.ApplicationManager; -import com.intellij.openapi.compiler.CompilerBundle; -import com.intellij.openapi.compiler.CompilerMessage; -import com.intellij.openapi.compiler.CompilerMessageCategory; -import com.intellij.openapi.compiler.ex.CompileContextEx; -import com.intellij.openapi.diagnostic.Logger; -import com.intellij.openapi.util.Pair; -import com.intellij.openapi.util.ThrowableComputable; -import com.intellij.openapi.util.text.StringUtil; -import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.util.ArrayUtil; -import com.intellij.util.Function; -import com.intellij.util.StringBuilderSpinAllocator; -import gnu.trove.TIntHashSet; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.util.*; - -/** - * @author Eugene Zhuravlev - * Date: Aug 18, 2003 - * Time: 6:32:32 PM - */ -public class CacheUtils { - private static final Logger LOG = Logger.getInstance("#com.intellij.compiler.make.CacheUtils"); - - public static String[] getParameterSignatures(MethodInfo methodDeclarationId, SymbolTable symbolTable) throws CacheCorruptedException { - String descriptor = symbolTable.getSymbol(methodDeclarationId.getDescriptor()); - int endIndex = descriptor.indexOf(')'); - if (endIndex <= 0) { - LOG.error("Corrupted method descriptor: " + descriptor); - } - return parseSignature(descriptor.substring(1, endIndex)); - } - - private static String[] parseSignature(String signature) { - final ArrayList list = new ArrayList(); - String paramSignature = parseParameterSignature(signature); - while (paramSignature != null && !"".equals(paramSignature)) { - list.add(paramSignature); - signature = signature.substring(paramSignature.length()); - paramSignature = parseParameterSignature(signature); - } - return ArrayUtil.toStringArray(list); - } - - @SuppressWarnings({"HardCodedStringLiteral"}) - private static @Nullable String parseParameterSignature(String signature) { - if (StringUtil.startsWithChar(signature, 'B')) { - return "B"; - } - if (StringUtil.startsWithChar(signature, 'C')) { - return "C"; - } - if (StringUtil.startsWithChar(signature, 'D')) { - return "D"; - } - if (StringUtil.startsWithChar(signature, 'F')) { - return "F"; - } - if (StringUtil.startsWithChar(signature, 'I')) { - return "I"; - } - if (StringUtil.startsWithChar(signature, 'J')) { - return "J"; - } - if (StringUtil.startsWithChar(signature, 'S')) { - return "S"; - } - if (StringUtil.startsWithChar(signature, 'Z')) { - return "Z"; - } - if (StringUtil.startsWithChar(signature, 'L')) { - return signature.substring(0, signature.indexOf(";") + 1); - } - if (StringUtil.startsWithChar(signature, '[')) { - String s = parseParameterSignature(signature.substring(1)); - return (s != null) ? ("[" + s) : null; - } - return null; - } - - public static String getMethodSignature(String name, String descriptor) { - final StringBuilder builder = StringBuilderSpinAllocator.alloc(); - try { - builder.append(name); - builder.append(descriptor.substring(0, descriptor.indexOf(')') + 1)); - return builder.toString(); - } - finally { - StringBuilderSpinAllocator.dispose(builder); - } - } - - public static boolean areArraysContentsEqual(int[] exceptions1, int[] exceptions2) { - if (exceptions1.length != exceptions2.length) { - return false; - } - if (exceptions1.length != 0) { // optimization - TIntHashSet exceptionsSet = new TIntHashSet(exceptions1); - for (int exception : exceptions2) { - if (!exceptionsSet.contains(exception)) { - return false; - } - } - } - return true; - } - - public static Collection findDependentFiles( - final CompileContextEx context, - final Set compiledWithErrors, - final @Nullable Function>, Pair>> filter) - throws CacheCorruptedException, ExitException { - - if (!CompilerConfiguration.MAKE_ENABLED) { - return Collections.emptyList(); - } - context.getProgressIndicator().setText(CompilerBundle.message("progress.checking.dependencies")); - - final DependencyCache dependencyCache = context.getDependencyCache(); - - final Pair> deps = dependencyCache.findDependentClasses(context, context.getProject(), compiledWithErrors); - final Pair> filteredDeps = filter != null ? filter.fun(deps) : deps; - - final Set dependentFiles = new HashSet(); - ApplicationManager.getApplication().runReadAction(new ThrowableComputable() { - @Override - public Void compute() throws CacheCorruptedException { - CompilerConfiguration compilerConfiguration = CompilerConfiguration.getInstance(context.getProject()); - SourceFileFinder sourceFileFinder = new SourceFileFinder(context.getProject(), context); - final Cache cache = dependencyCache.getCache(); - for (final int infoQName : filteredDeps.getFirst()) { - final String qualifiedName = dependencyCache.resolve(infoQName); - final String sourceFileName = cache.getSourceFileName(infoQName); - final VirtualFile file = sourceFileFinder.findSourceFile(qualifiedName, sourceFileName, true); - if (file != null) { - dependentFiles.add(file); - if (ApplicationManager.getApplication().isUnitTestMode()) { - LOG.assertTrue(file.isValid()); - CompilerManagerImpl.addRecompiledPath(file.getPath()); - } - } - else { - LOG.info("No source file for " + dependencyCache.resolve(infoQName) + " found; source file name=" + sourceFileName); - } - } - for (final VirtualFile file : filteredDeps.getSecond()) { - if (!compilerConfiguration.isExcludedFromCompilation(file)) { - dependentFiles.add(file); - if (ApplicationManager.getApplication().isUnitTestMode()) { - LOG.assertTrue(file.isValid()); - CompilerManagerImpl.addRecompiledPath(file.getPath()); - } - } - } - return null; - } - }); - context.getProgressIndicator().setText( - dependentFiles.size() > 0 ? CompilerBundle.message("progress.found.dependent.files", dependentFiles.size()) : "" - ); - - return dependentFiles; - } - - @NotNull - public static Set getFilesCompiledWithErrors(final CompileContextEx context) { - CompilerMessage[] messages = context.getMessages(CompilerMessageCategory.ERROR); - Set compiledWithErrors = Collections.emptySet(); - if (messages.length > 0) { - compiledWithErrors = new HashSet(messages.length); - for (CompilerMessage message : messages) { - final VirtualFile file = message.getVirtualFile(); - if (file != null) { - compiledWithErrors.add(file); - } - } - } - return compiledWithErrors; - } -} diff --git a/java/compiler/impl/src/com/intellij/compiler/make/CachedPersistentHashMap.java b/java/compiler/impl/src/com/intellij/compiler/make/CachedPersistentHashMap.java deleted file mode 100644 index 324a14a6b1e2..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/make/CachedPersistentHashMap.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Copyright 2000-2013 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.compiler.make; - -import com.intellij.openapi.diagnostic.Logger; -import com.intellij.util.containers.SLRUMap; -import com.intellij.util.io.DataExternalizer; -import com.intellij.util.io.KeyDescriptor; -import com.intellij.util.io.PersistentHashMap; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.io.File; -import java.io.IOException; - -/** - * @author Eugene Zhuravlev - * Date: Dec 1, 2008 - */ -public class CachedPersistentHashMap extends PersistentHashMap { - private static final Logger LOG = Logger.getInstance("#com.intellij.compiler.make.CachedPersistentHashMap"); - protected final SLRUMap myCache; - - public CachedPersistentHashMap(File file, KeyDescriptor keyDescriptor, DataExternalizer valDescriptor, final int cacheSize) throws IOException { - super(file, keyDescriptor, valDescriptor); - myCache = new SLRUMap(cacheSize * 2, cacheSize) { - protected void onDropFromCache(Key key, Value value) { - if (isValueDirty(value)) { - try { - CachedPersistentHashMap.super.put(key, value); - } - catch (IOException e) { - LOG.info(e); - } - } - } - }; - } - - protected boolean isValueDirty(Value value) { - return false; - } - - @Override - protected void doPut(Key key, Value value) throws IOException { - myCache.remove(key); - super.doPut(key, value); - } - - @Override - protected void doAppendData(Key key, @NotNull ValueDataAppender appender) throws IOException { - myCache.remove(key); - super.doAppendData(key, appender); - } - - @Nullable - protected Value doGet(Key key) throws IOException { - Value value = myCache.get(key); - if (value == null) { - value = super.doGet(key); - if (value != null) { - myCache.put(key, value); - } - } - return value; - } - - @Override - protected boolean doContainsMapping(Key key) throws IOException { - final Value value = myCache.get(key); - return value != null || super.doContainsMapping(key); - } - - @Override - protected void doRemove(Key key) throws IOException { - myCache.remove(key); - super.doRemove(key); - } - - @Override - protected void doForce() { - try { - clearCache(); - } - finally { - super.doForce(); - } - } - - @Override - protected void doClose() throws IOException { - try { - clearCache(); - } - finally { - super.doClose(); - } - } - - private void clearCache() { - myCache.clear(); - } -} diff --git a/java/compiler/impl/src/com/intellij/compiler/make/CachingSearcher.java b/java/compiler/impl/src/com/intellij/compiler/make/CachingSearcher.java deleted file mode 100644 index b232c2ee9485..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/make/CachingSearcher.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright 2000-2014 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.compiler.make; - -import com.intellij.openapi.fileTypes.StdFileTypes; -import com.intellij.openapi.project.Project; -import com.intellij.openapi.util.Pair; -import com.intellij.psi.PsiElement; -import com.intellij.psi.PsiReference; -import com.intellij.psi.search.GlobalSearchScope; -import com.intellij.psi.search.searches.ReferencesSearch; -import com.intellij.util.Query; -import com.intellij.util.containers.SoftHashMap; - -import java.util.Collection; -import java.util.Map; - -/** - * @author Eugene Zhuravlev - * Date: Oct 15 - * @author 2003 - */ -public class CachingSearcher { - private final Project myProject; - private final Map, Collection> myElementToReferencersMap = new SoftHashMap, Collection>(); - - public CachingSearcher(Project project) { - myProject = project; - } - - public Collection findReferences(PsiElement element, final boolean ignoreAccessScope) { - final Pair key = Pair.create(element, ignoreAccessScope ? Boolean.TRUE : Boolean.FALSE); - Collection psiReferences = myElementToReferencersMap.get(key); - if (psiReferences == null) { - GlobalSearchScope searchScope = GlobalSearchScope.projectScope(myProject); - searchScope = GlobalSearchScope.getScopeRestrictedByFileTypes(searchScope, StdFileTypes.JAVA); - final Query query = ReferencesSearch.search(element, searchScope, ignoreAccessScope); - psiReferences = query.findAll(); - myElementToReferencersMap.put(key, psiReferences); - } - return psiReferences; - } - -} diff --git a/java/compiler/impl/src/com/intellij/compiler/make/ChangeDescription.java b/java/compiler/impl/src/com/intellij/compiler/make/ChangeDescription.java deleted file mode 100644 index 1f5f8a345ca0..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/make/ChangeDescription.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.compiler.make; - -/** - * @author Eugene Zhuravlev - * Date: Apr 7, 2004 - */ -abstract class ChangeDescription { - public abstract boolean isChanged(); -} diff --git a/java/compiler/impl/src/com/intellij/compiler/make/ChangedConstantsDependencyProcessor.java b/java/compiler/impl/src/com/intellij/compiler/make/ChangedConstantsDependencyProcessor.java deleted file mode 100644 index ade40349bb47..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/make/ChangedConstantsDependencyProcessor.java +++ /dev/null @@ -1,370 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * created at Feb 24, 2002 - * @author Jeka - */ -package com.intellij.compiler.make; - -import com.intellij.compiler.classParsing.FieldInfo; -import com.intellij.compiler.impl.ExitException; -import com.intellij.compiler.impl.ExitStatus; -import com.intellij.lang.StdLanguages; -import com.intellij.openapi.compiler.CompileContext; -import com.intellij.openapi.diagnostic.Logger; -import com.intellij.openapi.progress.ProcessCanceledException; -import com.intellij.openapi.project.DumbService; -import com.intellij.openapi.project.Project; -import com.intellij.openapi.util.Key; -import com.intellij.openapi.util.Ref; -import com.intellij.openapi.util.registry.Registry; -import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.psi.*; -import com.intellij.psi.search.*; -import com.intellij.psi.util.PsiUtil; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.util.Collection; -import java.util.HashSet; -import java.util.Set; - -public class ChangedConstantsDependencyProcessor { - private static final Logger LOG = Logger.getInstance("#com.intellij.compiler.make.ChangedConstantsDependencyProcessor"); - private final Project myProject; - private final CachingSearcher mySearcher; - private final DependencyCache myDependencyCache; - private final int myQName; - private final CompileContext myContext; - private final FieldChangeInfo[] myChangedFields; - private final FieldChangeInfo[] myRemovedFields; - private final int MAX_CONSTANT_SEARCHES = Registry.intValue("compiler.max.static.constants.searches"); - - - public ChangedConstantsDependencyProcessor(Project project, - CachingSearcher searcher, - DependencyCache dependencyCache, - int qName, CompileContext context, FieldChangeInfo[] changedFields, - FieldChangeInfo[] removedFields) { - myProject = project; - mySearcher = searcher; - myDependencyCache = dependencyCache; - myQName = qName; - myContext = context; - myChangedFields = changedFields; - myRemovedFields = removedFields; - } - - public void run() throws CacheCorruptedException, ExitException { - final Ref _ex = new Ref(); - final Ref exitException = new Ref(null); - DumbService.getInstance(myProject).runReadActionInSmartMode(new Runnable() { - public void run() { - try { - final String qName = myDependencyCache.resolve(myQName); - PsiClass[] classes = JavaPsiFacade.getInstance(myProject).findClasses(qName.replace('$', '.'), GlobalSearchScope.allScope(myProject)); - for (PsiClass aClass : classes) { - PsiField[] psiFields = aClass.getFields(); - for (PsiField psiField : psiFields) { - final FieldChangeInfo changeInfo = findChangeInfo(psiField); - if (changeInfo != null) { // this field has been changed - processFieldChanged(psiField, aClass, changeInfo.isAccessibilityChange); - } - } - for (FieldChangeInfo removedField : myRemovedFields) { - processFieldRemoved(removedField.fieldInfo, aClass); - } - } - } - catch (CacheCorruptedException e) { - _ex.set(e); - } - catch (ExitException e) { - exitException.set(e); - } - catch (ProcessCanceledException e) { - // supressed deliberately - } - } - }); - if (_ex.get() != null) { - throw _ex.get(); - } - if (exitException.get() != null) { - throw exitException.get(); - } - } - - private void processFieldRemoved(FieldInfo info, final PsiClass aClass) throws CacheCorruptedException { - if (info.isPrivate()) { - return; // optimization: don't need to search, cause may be used only in this class - } - SearchScope searchScope = GlobalSearchScope.projectScope(myProject); - if (info.isPackageLocal()) { - final PsiFile containingFile = aClass.getContainingFile(); - if (containingFile instanceof PsiJavaFile) { - final String packageName = ((PsiJavaFile)containingFile).getPackageName(); - final PsiPackage aPackage = JavaPsiFacade.getInstance(myProject).findPackage(packageName); - if (aPackage != null) { - searchScope = PackageScope.packageScope(aPackage, false); - searchScope = searchScope.intersectWith(aClass.getUseScope()); - } - } - } - final PsiSearchHelper psiSearchHelper = PsiSearchHelper.SERVICE.getInstance(myProject); - - final Ref exRef = new Ref(null); - processIdentifiers(psiSearchHelper, new PsiElementProcessor() { - @Override - public synchronized boolean execute(@NotNull PsiIdentifier identifier) { - try { - final PsiElement parent = identifier.getParent(); - if (parent instanceof PsiReferenceExpression) { - final PsiClass ownerClass = getOwnerClass(parent); - if (ownerClass != null && !ownerClass.equals(aClass)) { - final String _qName = ownerClass.getQualifiedName(); - if (_qName != null) { - int qualifiedName = myDependencyCache.getSymbolTable().getId(_qName); - // should force marking of the class no matter was it compiled or not - // This will ensure the class was recompiled _after_ all the constants get their new values - if (myDependencyCache.markClass(qualifiedName, true)) { - if (LOG.isDebugEnabled()) { - LOG.debug("Mark dependent class " + myDependencyCache.resolve(qualifiedName) + "; reason: some constants were removed from " + myDependencyCache.resolve(myQName)); - } - } - } - else { - LOG.warn("Class with null qualified name was not expected here: " + ownerClass); - } - } - } - return true; - } - catch (CacheCorruptedException e) { - exRef.set(e); - return false; - } - } - }, myDependencyCache.resolve(info.getName()), searchScope, UsageSearchContext.IN_CODE); - - final CacheCorruptedException cacheCorruptedException = exRef.get(); - if (cacheCorruptedException != null) { - throw cacheCorruptedException; - } - } - - private static boolean processIdentifiers(PsiSearchHelper helper, - @NotNull final PsiElementProcessor processor, - @NotNull final String identifier, - @NotNull SearchScope searchScope, - short searchContext) { - TextOccurenceProcessor processor1 = new TextOccurenceProcessor() { - public boolean execute(PsiElement element, int offsetInElement) { - return !(element instanceof PsiIdentifier) || processor.execute((PsiIdentifier)element); - } - }; - return helper.processElementsWithWord(processor1, searchScope, identifier, searchContext, true); - } - - private void processFieldChanged(PsiField field, PsiClass aClass, final boolean isAccessibilityChange) - throws CacheCorruptedException, ExitException { - if (!isAccessibilityChange && field.hasModifierProperty(PsiModifier.PRIVATE)) { - return; // optimization: don't need to search, cause may be used only in this class - } - Set usages = new HashSet(); - addUsages(field, usages, isAccessibilityChange); - if (LOG.isDebugEnabled()) { - LOG.debug("++++++++++++++++++++++++++++++++++++++++++++++++"); - LOG.debug("Processing changed field: " + aClass.getQualifiedName() + "." + field.getName()); - } - for (final PsiElement usage : usages) { - PsiClass ownerClass = getOwnerClass(usage); - if (LOG.isDebugEnabled()) { - if (ownerClass != null) { - LOG.debug("Usage " + usage + " found in class: " + ownerClass.getQualifiedName()); - } - else { - LOG.debug("Usage " + usage + " found in class: null"); - } - } - if (ownerClass != null && !ownerClass.equals(aClass)) { - int qualifiedName = myDependencyCache.getSymbolTable().getId(ownerClass.getQualifiedName()); - // should force marking of the class no matter was it compiled or not - // This will ensure the class was recompiled _after_ all the constants get their new values - if (LOG.isDebugEnabled()) { - LOG.debug("Marking class id = [" + qualifiedName + "], name=[" + myDependencyCache.resolve(qualifiedName) + "]"); - } - if (myDependencyCache.markClass(qualifiedName, true)) { - if (LOG.isDebugEnabled()) { - LOG.debug("Marked dependent class " + myDependencyCache.resolve(qualifiedName) + "; reason: constants changed in " + - myDependencyCache.resolve(myQName)); - } - } - } - else if (ownerClass == null) { - final PsiFile containingFile = usage.getContainingFile(); - if (containingFile != null) { - final VirtualFile file = containingFile.getVirtualFile(); - if (file != null) { - myDependencyCache.markFile(file); - } - } - } - } - if (LOG.isDebugEnabled()) { - LOG.debug("+++++++++++++++++++++++++++++++++++++++++++++++"); - } - } - - private void addUsages(PsiField psiField, Collection usages, final boolean ignoreAccessScope) throws ExitException { - final int count = getConstantSearchesCount(); - if (count > MAX_CONSTANT_SEARCHES) { - myContext.requestRebuildNextTime("Too many changed compile-time constants, project rebuild scheduled"); - throw new ExitException(ExitStatus.CANCELLED); - } - Collection references = mySearcher.findReferences(psiField, ignoreAccessScope)/*doFindReferences(searchHelper, psiField)*/; - - incConstantSearchesCount(); - - for (final PsiReference ref : references) { - if (!(ref instanceof PsiReferenceExpression)) { - continue; - } - PsiElement e = ref.getElement(); - usages.add(e); - PsiField ownerField = getOwnerField(e); - if (ownerField != null) { - if (ownerField.hasModifierProperty(PsiModifier.FINAL)) { - PsiExpression initializer = ownerField.getInitializer(); - if (initializer != null && PsiUtil.isConstantExpression(initializer)) { - // if the field depends on the compile-time-constant expression and is itself final - addUsages(ownerField, usages, ignoreAccessScope); - } - } - } - } - } - - /* - private PsiReference[] doFindReferences(final PsiSearchHelper searchHelper, final PsiField psiField) { - final ProgressManager progressManager = ProgressManager.getInstance(); - final ProgressIndicator currentProgress = progressManager.getProgressIndicator(); - final PsiReference[][] references = new PsiReference[][] {null}; - progressManager.runProcess(new Runnable() { - public void run() { - references[0] = searchHelper.findReferences(psiField, GlobalSearchScope.projectScope(myProject), false); - if (ENABLE_TRACING) { - System.out.println("Finding referencers for " + psiField); - } - } - }, new NonCancellableProgressAdapter(currentProgress)); - return references[0]; - } - */ - - @Nullable - private static PsiField getOwnerField(PsiElement element) { - while (!(element instanceof PsiFile)) { - if (element instanceof PsiClass) { - break; - } - if (element instanceof PsiField) { // top-level class - return (PsiField)element; - } - element = element.getParent(); - } - return null; - } - - @Nullable - private FieldChangeInfo findChangeInfo(PsiField field) throws CacheCorruptedException { - String name = field.getName(); - for (final FieldChangeInfo changeInfo : myChangedFields) { - if (name.equals(myDependencyCache.resolve(changeInfo.fieldInfo.getName()))) { - return changeInfo; - } - } - return null; - } - - @Nullable - private static PsiClass getOwnerClass(PsiElement element) { - while (!(element instanceof PsiFile)) { - if (element instanceof PsiClass && element.getParent() instanceof PsiJavaFile) { // top-level class - final PsiClass psiClass = (PsiClass)element; - if (JspPsiUtil.isInJspFile(psiClass)) { - return null; - } - final PsiFile containingFile = psiClass.getContainingFile(); - if (containingFile == null) { - return null; - } - return StdLanguages.JAVA.equals(containingFile.getLanguage())? psiClass : null; - } - element = element.getParent(); - } - return null; - } - - public static class FieldChangeInfo { - final FieldInfo fieldInfo; - final boolean isAccessibilityChange; - - public FieldChangeInfo(final FieldInfo fieldId) { - this(fieldId, false); - } - - public FieldChangeInfo(final FieldInfo fieldInfo, final boolean accessibilityChange) { - this.fieldInfo = fieldInfo; - isAccessibilityChange = accessibilityChange; - } - - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - final FieldChangeInfo fieldChangeInfo = (FieldChangeInfo)o; - - if (isAccessibilityChange != fieldChangeInfo.isAccessibilityChange) return false; - if (!fieldInfo.equals(fieldChangeInfo.fieldInfo)) return false; - - return true; - } - - public int hashCode() { - int result; - result = fieldInfo.hashCode(); - result = 29 * result + (isAccessibilityChange ? 1 : 0); - return result; - } - } - - private static final Key CONSTANTS_COUNTER = Key.create("_constant_searches_counter_"); - - private int getConstantSearchesCount() { - return getConstantSearchesCount(myContext); - } - - public static int getConstantSearchesCount(CompileContext context) { - final Integer value = CONSTANTS_COUNTER.get(context); - return value != null? value.intValue() : 0; - } - - private void incConstantSearchesCount() { - CONSTANTS_COUNTER.set(myContext, getConstantSearchesCount() + 1); - } -} diff --git a/java/compiler/impl/src/com/intellij/compiler/make/ChangedRetentionPolicyDependencyProcessor.java b/java/compiler/impl/src/com/intellij/compiler/make/ChangedRetentionPolicyDependencyProcessor.java deleted file mode 100644 index 314fce992937..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/make/ChangedRetentionPolicyDependencyProcessor.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.compiler.make; - -import com.intellij.compiler.SymbolTable; -import com.intellij.openapi.application.ApplicationManager; -import com.intellij.openapi.diagnostic.Logger; -import com.intellij.openapi.progress.ProcessCanceledException; -import com.intellij.openapi.project.Project; -import com.intellij.psi.*; -import com.intellij.psi.search.GlobalSearchScope; -import com.intellij.util.cls.ClsUtil; - -import java.util.Collection; - -public class ChangedRetentionPolicyDependencyProcessor { - private static final Logger LOG = Logger.getInstance("#com.intellij.compiler.make.ChangedConstantsDependencyProcessor"); - private final Project myProject; - private final CachingSearcher mySearcher; - private final DependencyCache myDependencyCache; - - public ChangedRetentionPolicyDependencyProcessor(Project project, CachingSearcher searcher, DependencyCache dependencyCache) { - myProject = project; - mySearcher = searcher; - myDependencyCache = dependencyCache; - } - - public void checkAnnotationRetentionPolicyChanges(final int annotationQName) throws CacheCorruptedException { - final Cache oldCache = myDependencyCache.getCache(); - if (!ClsUtil.isAnnotation(oldCache.getFlags(annotationQName))) { - return; - } - if (!hasRetentionPolicyChanged(annotationQName, oldCache, myDependencyCache.getNewClassesCache(), myDependencyCache.getSymbolTable())) { - return; - } - final CacheCorruptedException[] _ex = new CacheCorruptedException[] {null}; - ApplicationManager.getApplication().runReadAction(new Runnable() { - public void run() { - try { - final String qName = myDependencyCache.resolve(annotationQName); - PsiClass[] classes = JavaPsiFacade.getInstance(myProject).findClasses(qName.replace('$', '.'), GlobalSearchScope.allScope(myProject)); - for (final PsiClass aClass : classes) { - if (!aClass.isAnnotationType()) { - continue; - } - final Collection references = mySearcher.findReferences(aClass, true); - for (PsiReference reference : references) { - final PsiClass ownerClass = getOwnerClass(reference.getElement()); - if (ownerClass != null && !ownerClass.equals(aClass)) { - int qualifiedName = myDependencyCache.getSymbolTable().getId(ownerClass.getQualifiedName()); - if (myDependencyCache.markClass(qualifiedName, false)) { - if (LOG.isDebugEnabled()) { - LOG.debug("Marked dependent class " + myDependencyCache.resolve(qualifiedName) + - "; reason: annotation's retention policy changed from SOURCE to CLASS or RUNTIME " + - myDependencyCache.resolve(annotationQName)); - } - } - } - } - } - } - catch (CacheCorruptedException e) { - _ex[0] = e; - } - catch (ProcessCanceledException e) { - // supressed deliberately - } - } - }); - if (_ex[0] != null) { - throw _ex[0]; - } - } - - private boolean hasRetentionPolicyChanged(int annotationQName, final Cache oldCache, final Cache newCache, SymbolTable symbolTable) throws CacheCorruptedException { - // if retention policy changed from SOURCE to CLASS or RUNTIME, all sources should be recompiled to propagate changes - final int oldPolicy = MakeUtil.getAnnotationRetentionPolicy(annotationQName, oldCache, symbolTable); - final int newPolicy = MakeUtil.getAnnotationRetentionPolicy(annotationQName, newCache, symbolTable); - if ((oldPolicy == RetentionPolicies.SOURCE) && (newPolicy == RetentionPolicies.CLASS || newPolicy == RetentionPolicies.RUNTIME)) { - return true; - } - return false; - } - - private static PsiClass getOwnerClass(PsiElement element) { - while (!(element instanceof PsiFile)) { - if (element instanceof PsiClass && element.getParent() instanceof PsiJavaFile) { // top-level class - return (PsiClass)element; - } - element = element.getParent(); - } - return null; - } -} diff --git a/java/compiler/impl/src/com/intellij/compiler/make/ClassInfoProcessor.java b/java/compiler/impl/src/com/intellij/compiler/make/ClassInfoProcessor.java deleted file mode 100644 index 5298a8c2a7de..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/make/ClassInfoProcessor.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * @author: Eugene Zhuravlev - * Date: May 14, 2003 - * Time: 10:42:29 AM - */ -package com.intellij.compiler.make; - - - -public interface ClassInfoProcessor { - /** - * @param classQName of a class info to be processed - * @return true if superclasses of info should be processed and false otherwise - */ - boolean process(int classQName) throws CacheCorruptedException; -} diff --git a/java/compiler/impl/src/com/intellij/compiler/make/CompilerDependencyStorage.java b/java/compiler/impl/src/com/intellij/compiler/make/CompilerDependencyStorage.java deleted file mode 100644 index 2466881b14fd..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/make/CompilerDependencyStorage.java +++ /dev/null @@ -1,257 +0,0 @@ -/* - * Copyright 2000-2014 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.compiler.make; - -import com.intellij.openapi.Disposable; -import com.intellij.openapi.diagnostic.Logger; -import com.intellij.openapi.util.Ref; -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.TIntProcedure; -import org.jetbrains.annotations.NotNull; - -import java.io.*; - -/** - * @author Eugene Zhuravlev - * Date: Dec 1, 2008 - */ -public class CompilerDependencyStorage implements Flushable, Disposable { - private static final Logger LOG = Logger.getInstance("#com.intellij.compiler.make.CompilerDependencyStorage"); - protected final PersistentHashMap myMap; - protected final SLRUCache myCache; - private Key myKeyToRemove; - - public CompilerDependencyStorage(File file, KeyDescriptor keyDescriptor, final int cacheSize) throws IOException { - myMap = new PersistentHashMap(file, keyDescriptor, new DataExternalizer() { - public void save(@NotNull DataOutput out, int[] array) throws IOException { - out.writeInt(array.length); - for (int value : array) { - out.writeInt(value); - } - } - - public int[] read(@NotNull DataInput in) throws IOException { - final TIntHashSet set = new TIntHashSet(); - DataInputStream stream = (DataInputStream)in; - while(stream.available() > 0) { - final int size = stream.readInt(); - final int _size = Math.abs(size); - for (int idx = 0; idx < _size; idx++) { - if (size > 0) { - set.add(stream.readInt()); - } - else { - set.remove(stream.readInt()); - } - } - } - return set.toArray(); - } - }); - - myCache = new SLRUCache(cacheSize * 2, cacheSize) { - @NotNull - public IntSet createValue(Key key) { - return new IntSet(key); - } - - protected void onDropFromCache(Key key, final IntSet set) { - if (key == myKeyToRemove || !set.isDirty()) { - return; - } - try { - if (set.needsCompacting()) { - myMap.put(key, set.getValues()); - } - else { - myMap.appendData(key, new PersistentHashMap.ValueDataAppender() { - public void append(final DataOutput out) throws IOException { - final Ref exception = new Ref(null); - final TIntProcedure saveProc = new TIntProcedure() { - public boolean execute(int value) { - try { - out.writeInt(value); - return true; - } - catch (IOException e) { - exception.set(e); - return false; - } - } - }; - - out.writeInt(-set.getRemovedCount()); - set.processRemovedValues(saveProc); - if (exception.get() != null) { - throw exception.get(); - } - - out.writeInt(set.getAddedCount()); - set.processAddedValues(saveProc); - if (exception.get() != null) { - throw exception.get(); - } - } - }); - } - } - catch (IOException e) { - LOG.error(e); - } - } - }; - } - - public synchronized void remove(Key key) throws IOException { - myKeyToRemove = key; - try { - myCache.remove(key); - } - finally { - myKeyToRemove = null; - } - myMap.remove(key); - } - - public synchronized void removeValue(Key key, int value) throws IOException { - final IntSet set = myCache.get(key); - set.remove(value); - if (set.needsFlushing()) { - flush(key); - } - } - - - public synchronized void addValue(Key key, int value) throws IOException { - final IntSet set = myCache.get(key); - set.add(value); - if (set.needsFlushing()) { - flush(key); - } - } - - public synchronized int[] getValues(Key key) throws IOException { - return myCache.get(key).getValues(); - } - - - public synchronized void flush() throws IOException { - myCache.clear(); - myMap.force(); - } - - private void flush(Key key) { - myCache.remove(key); // makes changes into PersistentHashMap - myMap.force(); // flushes internal caches (which consume memory) and writes unsaved data to disk - } - - public synchronized void dispose() { - try { - flush(); - } - catch (IOException e) { - LOG.info(e); - } - try { - myMap.close(); - } - catch (IOException e) { - LOG.info(e); - } - } - - private class IntSet { - private final TIntHashSet myAdded = new TIntHashSet(); - private final TIntHashSet myRemoved = new TIntHashSet(); - private TIntHashSet myMerged = null; - private final Key myKey; - - public IntSet(Key key) { - myKey = key; - } - - public void add(int value) { - if (myMerged != null) { - myMerged.add(value); - } - if (!myRemoved.remove(value)) { - myAdded.add(value); - } - } - - public void remove(int value) { - if (myMerged != null) { - myMerged.remove(value); - } - if (!myAdded.remove(value)) { - myRemoved.add(value); - } - } - - public boolean isDirty() { - return myAdded.size() > 0 || myRemoved.size() > 0; - } - - public boolean needsCompacting() { - return myMerged != null; - } - - public boolean needsFlushing() { - return myAdded.size() > 3000 || myRemoved.size() > 3000; - } - - public int getAddedCount() { - return myAdded.size(); - } - - public void processAddedValues(final TIntProcedure procedure) { - myAdded.forEach(procedure); - } - - public int getRemovedCount() { - return myRemoved.size(); - } - - public void processRemovedValues(final TIntProcedure procedure) { - myRemoved.forEach(procedure); - } - - public int[] getValues() throws IOException { - return getMerged().toArray(); - } - - private TIntHashSet getMerged() throws IOException { - if (myMerged == null) { - myMerged = new TIntHashSet(); - final int[] fromDisk = myMap.get(myKey); - if (fromDisk != null) { - myMerged.addAll(fromDisk); - } - if (myRemoved.size() > 0) { - myMerged.removeAll(myRemoved.toArray()); - } - if (myAdded.size() > 0) { - myMerged.addAll(myAdded.toArray()); - } - } - return myMerged; - } - } -} \ No newline at end of file diff --git a/java/compiler/impl/src/com/intellij/compiler/make/Dependency.java b/java/compiler/impl/src/com/intellij/compiler/make/Dependency.java deleted file mode 100644 index bd2c5cf9017c..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/make/Dependency.java +++ /dev/null @@ -1,188 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * created at Jan 4, 2002 - * @author Jeka - */ -package com.intellij.compiler.make; - -import com.intellij.compiler.SymbolTable; -import com.intellij.openapi.diagnostic.Logger; -import com.intellij.util.ArrayUtil; -import org.jetbrains.annotations.NonNls; - -import java.util.*; - -public class Dependency { - private static final Logger LOG = Logger.getInstance("#com.intellij.compiler.make.Dependency"); - public static final Dependency[] EMPTY_ARRAY = new Dependency[0]; - private final int myClassQualifiedName; - private Set myUsedFields; - private Set myUsedMethods; - - public static class FieldRef { - public final int name; - - public FieldRef(int name) { - this.name = name; - } - - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - FieldRef fieldRef = (FieldRef)o; - - if (name != fieldRef.name) return false; - - return true; - } - - public int hashCode() { - return name; - } - } - - public static class MethodRef { - public final int name; - public final int descriptor; - private String[] myParameterDescriptors; - - public MethodRef(int name, int descriptor) { - this.name = name; - this.descriptor = descriptor; - } - - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - MethodRef methodRef = (MethodRef)o; - - if (descriptor != methodRef.descriptor) return false; - if (name != methodRef.name) return false; - - return true; - } - - public int hashCode() { - int result = name; - result = 31 * result + descriptor; - return result; - } - - public String getDescriptor(SymbolTable symbolTable) throws CacheCorruptedException { - final String descriptorStr = symbolTable.getSymbol(descriptor); - final String nameStr = symbolTable.getSymbol(name); - return CacheUtils.getMethodSignature(nameStr, descriptorStr); - } - - - public String[] getParameterDescriptors(SymbolTable symbolTable) throws CacheCorruptedException { - if (myParameterDescriptors == null) { - String descriptorStr = symbolTable.getSymbol(descriptor); - int endIndex = descriptorStr.indexOf(')'); - if (endIndex <= 0) { - LOG.error("Corrupted method descriptor: " + descriptorStr); - } - myParameterDescriptors = parseParameterDescriptors(descriptorStr.substring(1, endIndex)); - } - return myParameterDescriptors; - } - } - - public Dependency(int classQualifiedName) { - myClassQualifiedName = classQualifiedName; - } - - public int getClassQualifiedName() { - return myClassQualifiedName; - } - - public void addMethod(int name, int descriptor) { - if (myUsedMethods == null) { - myUsedMethods = new HashSet(); - } - myUsedMethods.add(new MethodRef(name, descriptor)); - } - - public void addField(int name) { - if (myUsedFields == null) { - myUsedFields = new HashSet(); - } - myUsedFields.add(new FieldRef(name)); - } - - public Collection getFieldRefs() { - return myUsedFields != null? Collections.unmodifiableSet(myUsedFields) : Collections.emptySet(); - } - - public Collection getMethodRefs() { - return myUsedMethods != null? Collections.unmodifiableSet(myUsedMethods) : Collections.emptySet(); - } - - private static String[] parseParameterDescriptors(String signature) { - ArrayList list = new ArrayList(); - String paramSignature = parseFieldType(signature); - while (paramSignature != null && !paramSignature.isEmpty()) { - list.add(paramSignature); - signature = signature.substring(paramSignature.length()); - paramSignature = parseFieldType(signature); - } - return ArrayUtil.toStringArray(list); - } - - private static String parseFieldType(@NonNls String signature) { - if (signature.isEmpty()) { - return null; - } - char first = signature.charAt(0); - if (first == 'I') { - return "I"; - } - if (first == 'L') { - return signature.substring(0, signature.indexOf(';') + 1); - } - if (first == 'B') { - return "B"; - } - if (first == 'C') { - return "C"; - } - if (first == 'D') { - return "D"; - } - if (first == 'F') { - return "F"; - } - if (first == 'J') { - return "J"; - } - if (first == 'S') { - return "S"; - } - if (first == 'Z') { - return "Z"; - } - if (first == '[') { - String s = parseFieldType(signature.substring(1)); - return s == null ? null : "[" + s; - } - return null; - } - -} \ No newline at end of file diff --git a/java/compiler/impl/src/com/intellij/compiler/make/DependencyCache.java b/java/compiler/impl/src/com/intellij/compiler/make/DependencyCache.java deleted file mode 100644 index 722f9faa8be5..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/make/DependencyCache.java +++ /dev/null @@ -1,659 +0,0 @@ -/* - * Copyright 2000-2014 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * created at Jan 7, 2002 - * @author Jeka - */ -package com.intellij.compiler.make; - -import com.intellij.compiler.DependencyProcessor; -import com.intellij.compiler.SymbolTable; -import com.intellij.compiler.classParsing.*; -import com.intellij.compiler.impl.ExitException; -import com.intellij.openapi.application.ApplicationManager; -import com.intellij.openapi.compiler.CompileContext; -import com.intellij.openapi.diagnostic.Logger; -import com.intellij.openapi.progress.ProcessCanceledException; -import com.intellij.openapi.project.Project; -import com.intellij.openapi.util.Computable; -import com.intellij.openapi.util.Pair; -import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.util.ArrayUtil; -import com.intellij.util.cls.ClsFormatException; -import com.intellij.util.cls.ClsUtil; -import gnu.trove.TIntHashSet; -import org.jetbrains.annotations.NonNls; -import org.jetbrains.annotations.NotNull; - -import java.io.File; -import java.io.IOException; -import java.rmi.Remote; -import java.util.*; - -public class DependencyCache { - private static final Logger LOG = Logger.getInstance("#com.intellij.compiler.make.DependencyCache"); - - private volatile Cache myCache; - private volatile Cache myNewClassesCache; - - private static final String REMOTE_INTERFACE_NAME = Remote.class.getName(); - private final TIntHashSet myToUpdate = new TIntHashSet(); // qName strings to be updated. - private final TIntHashSet myTraverseRoots = new TIntHashSet(); // Dependencies are calculated from these clasess - private final TIntHashSet myClassesWithSourceRemoved = new TIntHashSet(); - private final TIntHashSet myPreviouslyRemoteClasses = new TIntHashSet(); // classes that were Remote, but became non-Remote for some reason - private final TIntHashSet myMarkedInfos = new TIntHashSet(); // classes to be recompiled - private final Set myMarkedFiles = new HashSet(); - - private volatile DependencyCacheNavigator myCacheNavigator; - private volatile SymbolTable mySymbolTable; - private final String mySymbolTableFilePath; - private final String myStoreDirectoryPath; - @NonNls - private static final String SYMBOLTABLE_FILE_NAME = "symboltable.dat"; - - public DependencyCache(@NonNls String storeDirectoryPath) { - myStoreDirectoryPath = storeDirectoryPath; - LOG.assertTrue(myStoreDirectoryPath != null); - - mySymbolTableFilePath = myStoreDirectoryPath + "/" + SYMBOLTABLE_FILE_NAME; - } - - public DependencyCacheNavigator getCacheNavigator() throws CacheCorruptedException { - if (myCacheNavigator == null) { - myCacheNavigator = new DependencyCacheNavigator(getCache()); - } - return myCacheNavigator; - } - - public void wipe() throws CacheCorruptedException { - getCache().wipe(); - getNewClassesCache().wipe(); - } - - public Cache getCache() throws CacheCorruptedException { - try { - if (myCache == null) { - // base number of cached record views of each type - myCache = new Cache(myStoreDirectoryPath, 512); - } - - return myCache; - } - catch (IOException e) { - throw new CacheCorruptedException(e); - } - } - - public Cache getNewClassesCache() throws CacheCorruptedException { - try { - if (myNewClassesCache == null) { - myNewClassesCache = new Cache(myStoreDirectoryPath + "/tmp", 16); - } - return myNewClassesCache; - } - catch (IOException e) { - throw new CacheCorruptedException(e); - } - } - - public void addTraverseRoot(int qName) { - myTraverseRoots.add(qName); - } - - public void clearTraverseRoots() { - myTraverseRoots.clear(); - } - - public boolean hasUnprocessedTraverseRoots() { - return !myTraverseRoots.isEmpty(); - } - - public void markSourceRemoved(int qName) { - myClassesWithSourceRemoved.add(qName); - } - - public void addClassToUpdate(int qName) { - myToUpdate.add(qName); - } - - public int reparseClassFile(@NotNull File file, final byte[] fileContent) throws ClsFormatException, CacheCorruptedException { - SymbolTable symbolTable = getSymbolTable(); - - final int qName = getNewClassesCache().importClassInfo(new ClassFileReader(file, symbolTable, fileContent), symbolTable); - addClassToUpdate(qName); - addTraverseRoot(qName); - return qName; - } - - // for profiling purposes - /* - private static void pause() { - System.out.println("PAUSED. ENTER A CHAR."); - byte[] buf = new byte[1]; - try { - System.in.read(buf); - } - catch (IOException e) { - e.printStackTrace(); - } - } - */ - - public void update() throws CacheCorruptedException { - if (myToUpdate.isEmpty()) { - return; // optimization - } - - //pause(); - - final int[] namesToUpdate = myToUpdate.toArray(); - final Cache cache = getCache(); - final Cache newCache = getNewClassesCache(); - final DependencyCacheNavigator navigator = getCacheNavigator(); - - // remove unnecesary dependencies - for (final int qName : namesToUpdate) { - // process use-dependencies - for (int referencedClassQName : cache.getReferencedClasses(qName)) { - if (!cache.containsClass(referencedClassQName)) { - continue; - } - cache.removeClassReferencer(referencedClassQName, qName); - } - cache.clearReferencedClasses(qName); - // process inheritance dependencies - navigator.walkSuperClasses(qName, new ClassInfoProcessor() { - public boolean process(int classQName) throws CacheCorruptedException { - cache.removeSubclass(classQName, qName); - return true; - } - }); - } - - // do update of classInfos - for (final int qName : namesToUpdate) { - cache.importClassInfo(newCache, qName); - } - - // build forward-dependencies for the new infos, all new class infos must be already in the main cache! - - final SymbolTable symbolTable = getSymbolTable(); - - for (final int qName : namesToUpdate) { - if (!newCache.containsClass(qName)) { - continue; - } - buildForwardDependencies(qName, newCache.getReferences(qName)); - boolean isRemote = false; - // "remote objects" are classes that _directly_ implement remote interfaces - final int[] superInterfaces = cache.getSuperInterfaces(qName); - if (superInterfaces.length > 0) { - final int remoteInterfaceName = symbolTable.getId(REMOTE_INTERFACE_NAME); - for (int superInterface : superInterfaces) { - if (isRemoteInterface(cache, superInterface, remoteInterfaceName)) { - isRemote = true; - break; - } - } - } - final boolean wasRemote = cache.isRemote(qName); - if (wasRemote && !isRemote) { - synchronized (myPreviouslyRemoteClasses) { - myPreviouslyRemoteClasses.add(qName); - } - } - cache.setRemote(qName, isRemote); - } - - // building subclass dependencies - for (final int qName : namesToUpdate) { - buildSubclassDependencies(getCache(), qName, qName); - } - - for (final int qName : myClassesWithSourceRemoved.toArray()) { - cache.removeClass(qName); - } - myToUpdate.clear(); - - //pause(); - } - - private void buildForwardDependencies(final int classQName, final Collection references) throws CacheCorruptedException { - final Cache cache = getCache(); - - final int genericSignature = cache.getGenericSignature(classQName); - if (genericSignature != -1) { - final String genericClassSignature = resolve(genericSignature); - final int[] bounds = findBounds(genericClassSignature); - for (int boundClassQName : bounds) { - cache.addClassReferencer(boundClassQName, classQName); - } - } - - buildAnnotationDependencies(classQName, cache.getRuntimeVisibleAnnotations(classQName)); - buildAnnotationDependencies(classQName, cache.getRuntimeInvisibleAnnotations(classQName)); - - for (final ReferenceInfo refInfo : references) { - final int declaringClassName = getActualDeclaringClassForReference(refInfo); - if (declaringClassName == Cache.UNKNOWN) { - continue; - } - if (refInfo instanceof MemberReferenceInfo) { - final MemberInfo memberInfo = ((MemberReferenceInfo)refInfo).getMemberInfo(); - if (memberInfo instanceof FieldInfo) { - cache.addFieldReferencer(declaringClassName, memberInfo.getName(), classQName); - } - else if (memberInfo instanceof MethodInfo) { - cache.addMethodReferencer(declaringClassName, memberInfo.getName(), memberInfo.getDescriptor(), classQName); - } - else { - LOG.error("Unknown member info class: " + memberInfo.getClass().getName()); - } - } - else { // reference to class - cache.addClassReferencer(declaringClassName, classQName); - } - } - final SymbolTable symbolTable = getSymbolTable(); - - for (final FieldInfo fieldInfo : cache.getFields(classQName)) { - buildAnnotationDependencies(classQName, fieldInfo.getRuntimeVisibleAnnotations()); - buildAnnotationDependencies(classQName, fieldInfo.getRuntimeInvisibleAnnotations()); - - String className = MakeUtil.parseObjectType(symbolTable.getSymbol(fieldInfo.getDescriptor()), 0); - if (className == null) { - continue; - } - final int cls = symbolTable.getId(className); - cache.addClassReferencer(cls, classQName); - } - - for (final MethodInfo methodInfo : cache.getMethods(classQName)) { - buildAnnotationDependencies(classQName, methodInfo.getRuntimeVisibleAnnotations()); - buildAnnotationDependencies(classQName, methodInfo.getRuntimeInvisibleAnnotations()); - buildAnnotationDependencies(classQName, methodInfo.getRuntimeVisibleParameterAnnotations()); - buildAnnotationDependencies(classQName, methodInfo.getRuntimeInvisibleParameterAnnotations()); - - if (methodInfo.isConstructor()) { - continue; - } - - final String returnTypeClassName = MakeUtil.parseObjectType(methodInfo.getReturnTypeDescriptor(symbolTable), 0); - if (returnTypeClassName != null) { - final int returnTypeClassQName = symbolTable.getId(returnTypeClassName); - cache.addClassReferencer(returnTypeClassQName, classQName); - } - - String[] parameterSignatures = CacheUtils.getParameterSignatures(methodInfo, symbolTable); - for (String parameterSignature : parameterSignatures) { - String paramClassName = MakeUtil.parseObjectType(parameterSignature, 0); - if (paramClassName != null) { - final int paramClassId = symbolTable.getId(paramClassName); - cache.addClassReferencer(paramClassId, classQName); - } - } - } - } - - private static boolean isRemoteInterface(Cache cache, int ifaceName, final int remoteInterfaceName) throws CacheCorruptedException { - if (ifaceName == remoteInterfaceName) { - return true; - } - for (int superInterfaceName : cache.getSuperInterfaces(ifaceName)) { - if (isRemoteInterface(cache, superInterfaceName, remoteInterfaceName)) { - return true; - } - } - return false; - } - - - private void buildAnnotationDependencies(int classQName, AnnotationConstantValue[][] annotations) throws CacheCorruptedException { - if (annotations == null || annotations.length == 0) { - return; - } - for (AnnotationConstantValue[] annotation : annotations) { - buildAnnotationDependencies(classQName, annotation); - } - } - - private void buildAnnotationDependencies(int classQName, AnnotationConstantValue[] annotations) throws CacheCorruptedException { - if (annotations == null || annotations.length == 0) { - return; - } - final Cache cache = getCache(); - for (AnnotationConstantValue annotation : annotations) { - final int annotationQName = annotation.getAnnotationQName(); - - cache.addClassReferencer(annotationQName, classQName); - - final AnnotationNameValuePair[] memberValues = annotation.getMemberValues(); - for (final AnnotationNameValuePair nameValuePair : memberValues) { - for (MethodInfo annotationMember : cache.findMethodsByName(annotationQName, nameValuePair.getName())) { - cache.addMethodReferencer(annotationQName, annotationMember.getName(), annotationMember.getDescriptor(), classQName); - } - } - } - } - - private int[] findBounds(final String genericClassSignature) throws CacheCorruptedException{ - try { - final String[] boundInterfaces = BoundsParser.getBounds(genericClassSignature); - int[] ids = ArrayUtil.newIntArray(boundInterfaces.length); - for (int i = 0; i < boundInterfaces.length; i++) { - ids[i] = getSymbolTable().getId(boundInterfaces[i]); - } - return ids; - } - catch (SignatureParsingException e) { - return ArrayUtil.EMPTY_INT_ARRAY; - } - } - - // fixes JDK 1.4 javac bug that generates references in the constant pool - // to the subclass even if the field was declared in a superclass - private int getActualDeclaringClassForReference(final ReferenceInfo refInfo) throws CacheCorruptedException { - if (!(refInfo instanceof MemberReferenceInfo)) { - return refInfo.getClassName(); - } - final int declaringClassName = refInfo.getClassName(); - final Cache cache = getCache(); - final MemberInfo memberInfo = ((MemberReferenceInfo)refInfo).getMemberInfo(); - if (memberInfo instanceof FieldInfo) { - if (cache.findFieldByName(declaringClassName, memberInfo.getName()) != null) { - return declaringClassName; - } - } - else if (memberInfo instanceof MethodInfo) { - if (cache.findMethod(declaringClassName, memberInfo.getName(), memberInfo.getDescriptor()) != null) { - return declaringClassName; - } - } - final DeclaringClassFinder finder = new DeclaringClassFinder(memberInfo); - getCacheNavigator().walkSuperClasses(declaringClassName, finder); - return finder.getDeclaringClassName(); - } - - /** - * @return qualified names of the classes that should be additionally recompiled - */ - public Pair> findDependentClasses(CompileContext context, Project project, Set compiledWithErrors) - throws CacheCorruptedException, ExitException { - - markDependencies(context, project, compiledWithErrors); - return Pair.create(myMarkedInfos.toArray(), Collections.unmodifiableSet(myMarkedFiles)); - } - - private void markDependencies(CompileContext context, Project project, final Set compiledWithErrors) - throws CacheCorruptedException, ExitException { - try { - if (LOG.isDebugEnabled()) { - LOG.debug("====================Marking dependent files====================="); - } - // myToUpdate can be modified during the mark procedure, so use toArray() to iterate it - final int[] traverseRoots = myTraverseRoots.toArray(); - final SourceFileFinder sourceFileFinder = new SourceFileFinder(project, context); - final CachingSearcher searcher = new CachingSearcher(project); - final ChangedRetentionPolicyDependencyProcessor changedRetentionPolicyDependencyProcessor = new ChangedRetentionPolicyDependencyProcessor(project, searcher, this); - for (final int qName : traverseRoots) { - if (!getCache().containsClass(qName)) { - continue; - } - if (getNewClassesCache().containsClass(qName)) { // there is a new class file created - new JavaDependencyProcessor(project, this, qName).run(); - ArrayList changed = - new ArrayList(); - ArrayList removed = - new ArrayList(); - findModifiedConstants(qName, changed, removed); - if (!changed.isEmpty() || !removed.isEmpty()) { - new ChangedConstantsDependencyProcessor( - project, searcher, this, qName, context, - changed.toArray(new ChangedConstantsDependencyProcessor.FieldChangeInfo[changed.size()]), - removed.toArray(new ChangedConstantsDependencyProcessor.FieldChangeInfo[removed.size()]) - ).run(); - } - changedRetentionPolicyDependencyProcessor.checkAnnotationRetentionPolicyChanges(qName); - for (DependencyProcessor additionalProcessor : DependencyProcessor.EXTENSION_POINT_NAME.getExtensions()) { - additionalProcessor.processDependencies(context, qName, searcher); - } - } - else { - boolean isSourceDeleted = false; - if (myClassesWithSourceRemoved.contains(qName)) { // no recompiled class file, check whether the classfile exists - isSourceDeleted = true; - } - else if (!new File(getCache().getPath(qName)).exists()) { - final String qualifiedName = resolve(qName); - final String sourceFileName = getCache().getSourceFileName(qName); - final boolean markAsRemovedSource = ApplicationManager.getApplication().runReadAction(new Computable() { - public Boolean compute() { - VirtualFile sourceFile = sourceFileFinder.findSourceFile(qualifiedName, sourceFileName, false); - return sourceFile == null || !compiledWithErrors.contains(sourceFile) ? Boolean.TRUE : Boolean.FALSE; - } - }).booleanValue(); - if (markAsRemovedSource) { - // for Inner classes: sourceFile may exist, but the inner class declaration inside it may not, - // thus the source for the class info should be considered removed - isSourceDeleted = true; - markSourceRemoved(qName); - myMarkedInfos.remove(qName); // if the info has been marked already, the mark should be removed - } - } - if (isSourceDeleted) { - Dependency[] backDependencies = getCache().getBackDependencies(qName); - for (Dependency backDependency : backDependencies) { - if (markTargetClassInfo(backDependency)) { - if (LOG.isDebugEnabled()) { - LOG.debug( - "Mark dependent class " + backDependency.getClassQualifiedName() + "; reason: no class file found for " + qName); - } - } - } - } - } - } - if (LOG.isDebugEnabled()) { - LOG.debug("================================================================"); - } - } - catch (ProcessCanceledException ignored) { - // deliberately suppressed - } - } - - private void findModifiedConstants( - final int qName, - Collection changedConstants, - Collection removedConstants) throws CacheCorruptedException { - - final Cache cache = getCache(); - for (final FieldInfo field : cache.getFields(qName)) { - final int oldFlags = field.getFlags(); - if (ClsUtil.isStatic(oldFlags) && ClsUtil.isFinal(oldFlags)) { - final Cache newClassesCache = getNewClassesCache(); - FieldInfo newField = newClassesCache.findFieldByName(qName, field.getName()); - if (newField == null) { - if (!ConstantValue.EMPTY_CONSTANT_VALUE.equals(field.getConstantValue())) { - // if the field was really compile time constant - removedConstants.add(new ChangedConstantsDependencyProcessor.FieldChangeInfo(field)); - } - } - else { - final boolean visibilityRestricted = MakeUtil.isMoreAccessible(oldFlags, newField.getFlags()); - if (!field.getConstantValue().equals(newField.getConstantValue()) || visibilityRestricted) { - changedConstants.add(new ChangedConstantsDependencyProcessor.FieldChangeInfo(field, visibilityRestricted)); - } - } - } - } - } - - private static void buildSubclassDependencies(Cache cache, final int qName, int targetClassId) throws CacheCorruptedException { - final int superQName = cache.getSuperQualifiedName(targetClassId); - if (superQName != Cache.UNKNOWN) { - cache.addSubclass(superQName, qName); - buildSubclassDependencies(cache, qName, superQName); - } - - int[] interfaces = cache.getSuperInterfaces(targetClassId); - for (final int interfaceName : interfaces) { - cache.addSubclass(interfaceName, qName); - buildSubclassDependencies(cache, qName, interfaceName); - } - } - - - /** - * Marks ClassInfo targeted by the dependency - * @return true if really added, false otherwise - */ - public boolean markTargetClassInfo(Dependency dependency) throws CacheCorruptedException { - return markClassInfo(dependency.getClassQualifiedName(), false); - } - - /** - * Marks ClassInfo that corresponds to the specified qualified name - * If class info is already recompiled, it is not marked - * @return true if really added, false otherwise - */ - public boolean markClass(int qualifiedName) throws CacheCorruptedException { - return markClass(qualifiedName, false); - } - - /** - * Marks ClassInfo that corresponds to the specified qualified name - * If class info is already recompiled, it is not marked unless force parameter is true - * @return true if really added, false otherwise - */ - public boolean markClass(int qualifiedName, boolean force) throws CacheCorruptedException { - return markClassInfo(qualifiedName, force); - } - - public boolean isTargetClassInfoMarked(Dependency dependency) { - return isClassInfoMarked(dependency.getClassQualifiedName()); - } - - public boolean isClassInfoMarked(int qName) { - return myMarkedInfos.contains(qName); - } - - public void markFile(VirtualFile file) { - myMarkedFiles.add(file); - } - - /** - * @return true if really marked, false otherwise - */ - private boolean markClassInfo(int qName, boolean force) throws CacheCorruptedException { - if (!getCache().containsClass(qName)) { - return false; - } - if (myClassesWithSourceRemoved.contains(qName)) { - return false; // no need to recompile since source has been removed - } - if (!force) { - if (getNewClassesCache().containsClass(qName)) { // already recompiled - return false; - } - } - return myMarkedInfos.add(qName); - } - - public void resetState() { - myClassesWithSourceRemoved.clear(); - myMarkedFiles.clear(); - myMarkedInfos.clear(); - myToUpdate.clear(); - myTraverseRoots.clear(); - if (myNewClassesCache != null) { - myNewClassesCache.wipe(); - myNewClassesCache = null; - } - myCacheNavigator = null; - try { - if (myCache != null) { - myCache.dispose(); - myCache = null; - } - } - catch (CacheCorruptedException e) { - LOG.info(e); - } - try { - if (mySymbolTable != null) { - mySymbolTable.dispose(); - mySymbolTable = null; - } - } - catch (CacheCorruptedException e) { - LOG.info(e); - } - } - - - public SymbolTable getSymbolTable() throws CacheCorruptedException { - if (mySymbolTable == null) { - mySymbolTable = new SymbolTable(new File(mySymbolTableFilePath)); - } - return mySymbolTable; - } - - public String resolve(int id) throws CacheCorruptedException { - return getSymbolTable().getSymbol(id); - } - - public boolean wasRemote(int qName) { - return myPreviouslyRemoteClasses.contains(qName); - } - - private class DeclaringClassFinder implements ClassInfoProcessor { - private final int myMemberName; - private final int myMemberDescriptor; - private int myDeclaringClass = Cache.UNKNOWN; - private final boolean myIsField; - - private DeclaringClassFinder(MemberInfo memberInfo) { - myMemberName = memberInfo.getName(); - myMemberDescriptor = memberInfo.getDescriptor(); - myIsField = memberInfo instanceof FieldInfo; - } - - public int getDeclaringClassName() { - return myDeclaringClass; - } - - public boolean process(int classQName) throws CacheCorruptedException { - final Cache cache = getCache(); - if (myIsField) { - final FieldInfo fieldId = cache.findField(classQName, myMemberName, myMemberDescriptor); - if (fieldId != null) { - myDeclaringClass = classQName; - return false; - } - } - else { - final MethodInfo methodId = cache.findMethod(classQName, myMemberName, myMemberDescriptor); - if (methodId != null) { - myDeclaringClass = classQName; - return false; - } - } - return true; - } - } -} diff --git a/java/compiler/impl/src/com/intellij/compiler/make/DependencyCacheNavigator.java b/java/compiler/impl/src/com/intellij/compiler/make/DependencyCacheNavigator.java deleted file mode 100644 index a93caa2aeb54..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/make/DependencyCacheNavigator.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * @author: Eugene Zhuravlev - * Date: May 26, 2003 - * Time: 8:13:56 PM - */ -package com.intellij.compiler.make; - -import com.intellij.openapi.diagnostic.Logger; - -public class DependencyCacheNavigator { - private static final Logger LOG = Logger.getInstance("#com.intellij.compiler.make.DependencyCacheNavigator"); - - private final Cache myCache; - - public DependencyCacheNavigator(Cache cache) { - myCache = cache; - } - - public void walkSuperClasses(int classQName, ClassInfoProcessor processor) throws CacheCorruptedException { - if (classQName == Cache.UNKNOWN) { - return; - } - int superQName = myCache.getSuperQualifiedName(classQName); - - if (classQName == superQName) { - LOG.error("Superclass qualified name is the same as class' name: " + classQName); - return; - } - - if (superQName != Cache.UNKNOWN) { - if (processor.process(superQName)) { - walkSuperClasses(superQName, processor); - } - } - for (int superInterfaceQName : myCache.getSuperInterfaces(classQName)) { - if (processor.process(superInterfaceQName)) { - walkSuperClasses(superInterfaceQName, processor); - } - } - } - - public void walkSuperInterfaces(int classQName, ClassInfoProcessor processor) throws CacheCorruptedException { - if (classQName == Cache.UNKNOWN) { - return; - } - - for (int superInterfaceQName : myCache.getSuperInterfaces(classQName)) { - if (processor.process(superInterfaceQName)) { - walkSuperInterfaces(superInterfaceQName, processor); - } - } - } - - public void walkSubClasses(int fromClassQName, ClassInfoProcessor processor) throws CacheCorruptedException { - for (int subQName : myCache.getSubclasses(fromClassQName)) { - if (fromClassQName == subQName) { - LOG.error("Subclass qualified name is the same as class' name: " + fromClassQName); - return; - } - if (subQName != Cache.UNKNOWN) { - if (!processor.process(subQName)) { - break; - } - } - } - } - -} diff --git a/java/compiler/impl/src/com/intellij/compiler/make/FieldChangeDescription.java b/java/compiler/impl/src/com/intellij/compiler/make/FieldChangeDescription.java deleted file mode 100644 index 9d0ef4726d97..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/make/FieldChangeDescription.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.compiler.make; - -import com.intellij.compiler.classParsing.FieldInfo; - -/** - * @author Eugene Zhuravlev - * Date: Apr 7, 2004 - */ -class FieldChangeDescription extends ChangeDescription { - public final boolean flagsChanged; - public final boolean descriptorChanged; - public final boolean genericSignatureChanged; - - public FieldChangeDescription(final FieldInfo oldField, final FieldInfo newField) { - descriptorChanged = oldField.getDescriptor() != newField.getDescriptor(); - flagsChanged = oldField.getFlags() != newField.getFlags(); - genericSignatureChanged = oldField.getGenericSignature() != newField.getGenericSignature(); - } - - public boolean isChanged() { - return flagsChanged || descriptorChanged || genericSignatureChanged; - } -} diff --git a/java/compiler/impl/src/com/intellij/compiler/make/JavaDependencyProcessor.java b/java/compiler/impl/src/com/intellij/compiler/make/JavaDependencyProcessor.java deleted file mode 100644 index b00d886713fd..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/make/JavaDependencyProcessor.java +++ /dev/null @@ -1,1322 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * created at Feb 19, 2002 - * @author Jeka - */ -package com.intellij.compiler.make; - -import com.intellij.compiler.SymbolTable; -import com.intellij.compiler.classParsing.*; -import com.intellij.openapi.application.ApplicationManager; -import com.intellij.openapi.diagnostic.Logger; -import com.intellij.openapi.project.Project; -import com.intellij.openapi.util.Computable; -import com.intellij.pom.java.LanguageLevel; -import com.intellij.psi.*; -import com.intellij.psi.search.GlobalSearchScope; -import com.intellij.util.IncorrectOperationException; -import com.intellij.util.cls.ClsUtil; -import gnu.trove.TIntHashSet; -import gnu.trove.TIntObjectHashMap; -import gnu.trove.TIntObjectIterator; -import gnu.trove.TIntObjectProcedure; -import org.jetbrains.annotations.NonNls; - -import java.util.*; - -class JavaDependencyProcessor { - private static final Logger LOG = Logger.getInstance("#com.intellij.compiler.make.JavaDependencyProcessor"); - private final DependencyCache myDependencyCache; - private final int myQName; - private final Map myRefToMethodMap = new HashMap(); - private final Map myRefToFieldMap = new HashMap(); - private final Set myAddedMembers = new HashSet(); - private final Set myRemovedMembers = new HashSet(); - private final Set myChangedMembers = new HashSet(); - private final Map myChangeDescriptions = new HashMap(); - private Dependency[] myBackDependencies; - private final boolean myMembersChanged; - private final boolean mySuperInterfaceAdded; - private final boolean mySuperInterfaceRemoved; - private final boolean mySuperClassChanged; - private final boolean mySuperlistGenericSignatureChanged; - private final boolean mySuperClassAdded; - private final Project myProject; - private final boolean myIsAnnotation; - private final boolean myIsRemoteInterface; - private final boolean myWereAnnotationTargetsRemoved; - private final boolean myRetentionPolicyChanged; - private final boolean myAnnotationSemanticsChanged; - - public JavaDependencyProcessor(Project project, DependencyCache dependencyCache, int qName) throws CacheCorruptedException { - myProject = project; - myDependencyCache = dependencyCache; - myQName = qName; - final Cache cache = dependencyCache.getCache(); - final Cache newClassesCache = dependencyCache.getNewClassesCache(); - - final MethodInfo[] oldMethods = cache.getMethods(qName); - for (MethodInfo method : oldMethods) { - myRefToMethodMap.put(new Dependency.MethodRef(method.getName(), method.getDescriptor()), method); - } - final TIntObjectHashMap oldFieldsMap = getFieldInfos(cache, qName); - oldFieldsMap.forEachEntry(new TIntObjectProcedure() { - public boolean execute(int fieldName, FieldInfo fieldInfo) { - myRefToFieldMap.put(new Dependency.FieldRef(fieldName), fieldInfo); - return true; - } - }); - final Map oldMethodsMap = getMethodInfos(oldMethods); - final Map newMethodsMap = getMethodInfos(newClassesCache.getMethods(qName)); - final TIntObjectHashMap newFieldsMap = getFieldInfos(newClassesCache, qName); - addAddedMembers(oldFieldsMap, oldMethodsMap, newFieldsMap, newMethodsMap, myAddedMembers); - addRemovedMembers(oldFieldsMap, oldMethodsMap, newFieldsMap, newMethodsMap, myRemovedMembers); - addChangedMembers(oldFieldsMap, oldMethodsMap, newFieldsMap, newMethodsMap, myChangedMembers); - - myMembersChanged = !myAddedMembers.isEmpty() || !myRemovedMembers.isEmpty() || !myChangedMembers.isEmpty(); - // track changes in super list - - myIsRemoteInterface = MakeUtil.isInterface(cache.getFlags(myQName)) && cache.isRemote(qName); - myIsAnnotation = ClsUtil.isAnnotation(cache.getFlags(qName)); - myWereAnnotationTargetsRemoved = myIsAnnotation && wereAnnotationTargesRemoved(cache, newClassesCache); - myRetentionPolicyChanged = myIsAnnotation && hasRetentionPolicyChanged(cache, newClassesCache); - myAnnotationSemanticsChanged = myIsAnnotation && hasAnnotationSemanticsChanged(cache, newClassesCache); - - int[] oldInterfaces = cache.getSuperInterfaces(qName); - int[] newInterfaces = newClassesCache.getSuperInterfaces(qName); - mySuperInterfaceRemoved = wereInterfacesRemoved(oldInterfaces, newInterfaces); - mySuperInterfaceAdded = wereInterfacesRemoved(newInterfaces, oldInterfaces); - - mySuperlistGenericSignatureChanged = isSuperlistGenericSignatureChanged(cache.getGenericSignature(qName), newClassesCache.getGenericSignature(qName)); - - boolean superclassesDiffer = cache.getSuperQualifiedName(qName) != newClassesCache.getSuperQualifiedName(qName); - boolean wasDerivedFromObject = CommonClassNames.JAVA_LANG_OBJECT.equals(dependencyCache.resolve(cache.getSuperQualifiedName(qName))); - mySuperClassChanged = !wasDerivedFromObject && superclassesDiffer; - mySuperClassAdded = wasDerivedFromObject && superclassesDiffer; - } - - private static boolean hasMembersWithoutDefaults(Set addedMembers) { - for (final Object addedMember : addedMembers) { - MemberInfo memberInfo = (MemberInfo)addedMember; - if (memberInfo instanceof MethodInfo) { - final ConstantValue annotationDefault = ((MethodInfo)memberInfo).getAnnotationDefault(); - if (annotationDefault == null || ConstantValue.EMPTY_CONSTANT_VALUE.equals(annotationDefault)) { - return true; - } - } - } - return false; - } - - private boolean wereAnnotationDefaultsRemoved() { - for (final MemberInfo memberInfo : myChangeDescriptions.keySet()) { - if (memberInfo instanceof MethodInfo) { - MethodChangeDescription description = (MethodChangeDescription)myChangeDescriptions.get(memberInfo); - if (description.removedAnnotationDefault) { - return true; - } - } - } - return false; - } - - private boolean isSuperlistGenericSignatureChanged(int oldGenericSignature, int newGenericSignature) throws CacheCorruptedException { - if (oldGenericSignature == newGenericSignature) { - return false; - } - if (oldGenericSignature != -1 && newGenericSignature != -1) { - final SymbolTable symbolTable = myDependencyCache.getSymbolTable(); - final String _oldGenericMethodSignature = cutFormalParams(symbolTable.getSymbol(oldGenericSignature)); - final String _newGenericMethodSignature = cutFormalParams(symbolTable.getSymbol(newGenericSignature)); - return !_oldGenericMethodSignature.equals(_newGenericMethodSignature); - } - return true; - } - - private static String cutFormalParams(String genericClassSignature) { - if (genericClassSignature.charAt(0) == '<') { - int idx = genericClassSignature.indexOf('>'); - return genericClassSignature.substring(idx + 1); - } - return genericClassSignature; - } - - public void run() throws CacheCorruptedException { - if (LOG.isDebugEnabled()) { - LOG.debug("Checking dependencies for " + myDependencyCache.resolve(myQName)); - } - final boolean superListChanged = mySuperClassChanged || mySuperClassAdded || mySuperInterfaceAdded || mySuperInterfaceRemoved || mySuperlistGenericSignatureChanged; - final Cache oldCache = myDependencyCache.getCache(); - final Cache newCache = myDependencyCache.getNewClassesCache(); - - if (!myMembersChanged && - oldCache.getFlags(myQName) == newCache.getFlags(myQName) && - !superListChanged && !myWereAnnotationTargetsRemoved && !myRetentionPolicyChanged && !myAnnotationSemanticsChanged) { - return; // nothing to do - } - - if (myIsAnnotation) { - if (myAnnotationSemanticsChanged) { - final TIntHashSet visited = new TIntHashSet(); - visited.add(myQName); - markAnnotationDependenciesRecursively(getBackDependencies(), LOG.isDebugEnabled()? "; reason: semantics changed for " + myDependencyCache.resolve(myQName) : "", visited); - return; - } - if (hasMembersWithoutDefaults(myAddedMembers)) { - markAll(getBackDependencies(), LOG.isDebugEnabled()? "; reason: added annotation type member without default " + myDependencyCache.resolve(myQName) : ""); - return; - } - if (!myRemovedMembers.isEmpty()) { - markAll(getBackDependencies(), LOG.isDebugEnabled()? "; reason: removed annotation type member " + myDependencyCache.resolve(myQName) : ""); - return; - } - if (!myChangedMembers.isEmpty()) { // for annotations "changed" means return type changed - markAll(getBackDependencies(), LOG.isDebugEnabled()? "; reason: changed annotation member's type " + myDependencyCache.resolve(myQName) : ""); - return; - } - if (wereAnnotationDefaultsRemoved()) { - markAll(getBackDependencies(), LOG.isDebugEnabled()? "; reason: removed annotation member's default value " + myDependencyCache.resolve(myQName): ""); - return; - } - if (myWereAnnotationTargetsRemoved) { - markAll(getBackDependencies(), LOG.isDebugEnabled()? "; reason: removed annotation's targets " + myDependencyCache.resolve(myQName) : ""); - return; - } - if (myRetentionPolicyChanged) { - markAll(getBackDependencies(), LOG.isDebugEnabled()? "; reason: retention policy changed for " + myDependencyCache.resolve(myQName) : ""); - return; - } - } - - final DependencyCacheNavigator cacheNavigator = myDependencyCache.getCacheNavigator(); - - if (mySuperClassChanged || mySuperInterfaceRemoved || mySuperlistGenericSignatureChanged) { - // superclass changed == old removed and possibly new added - // if anything (class or interface) in the superlist was removed, should recompile all subclasses (both direct and indirect) - // and all back-dependencies of this class and its subclasses - markAll(getBackDependencies(), LOG.isDebugEnabled()? "; reason: deleted items from the superlist or changed superlist generic signature of " + myDependencyCache.resolve(myQName) : ""); - cacheNavigator.walkSubClasses(myQName, new ClassInfoProcessor() { - public boolean process(int classQName) throws CacheCorruptedException { - markAll(oldCache.getBackDependencies(classQName), LOG.isDebugEnabled()? "; reason: deleted items from the superlist or changed superlist generic signature of " + myDependencyCache.resolve(myQName) : ""); - return true; - } - }); - return; - } - - final boolean isKindChanged = - (MakeUtil.isInterface(oldCache.getFlags(myQName)) && !MakeUtil.isInterface(newCache.getFlags(myQName))) || - (!MakeUtil.isInterface(oldCache.getFlags(myQName)) && MakeUtil.isInterface(newCache.getFlags(myQName))); - if (isKindChanged) { - markAll(getBackDependencies(), LOG.isDebugEnabled()? "; reason: class kind changed (class/interface) " + myDependencyCache.resolve(myQName) : ""); - cacheNavigator.walkSubClasses(myQName, new ClassInfoProcessor() { - public boolean process(int classQName) throws CacheCorruptedException { - markAll(oldCache.getBackDependencies(classQName), LOG.isDebugEnabled()? "; reason: class kind changed (class/interface) " + myDependencyCache.resolve(myQName) : ""); - return true; - } - }); - return; - } - - boolean becameFinal = !ClsUtil.isFinal(oldCache.getFlags(myQName)) && ClsUtil.isFinal(newCache.getFlags(myQName)); - if (becameFinal) { - markAll(getBackDependencies(), LOG.isDebugEnabled()? "; reason: class became final: " + myDependencyCache.resolve(myQName) : ""); - } - else { - boolean becameAbstract = !ClsUtil.isAbstract(oldCache.getFlags(myQName)) && ClsUtil.isAbstract(newCache.getFlags(myQName)); - boolean accessRestricted = MakeUtil.isMoreAccessible(oldCache.getFlags(myQName), newCache.getFlags(myQName)); - Set removedMethods = null; - Set addedMethods = null; - for (Dependency backDependency : getBackDependencies()) { - if (myDependencyCache.isTargetClassInfoMarked(backDependency)) continue; - - if (accessRestricted) { - if (myDependencyCache.markTargetClassInfo(backDependency)) { - if (LOG.isDebugEnabled()) { - LOG.debug("Mark dependent class " + myDependencyCache.resolve(backDependency.getClassQualifiedName()) + "; reason: " + - myDependencyCache.resolve(myQName) + " made less accessible"); - } - } - continue; - } - if (becameAbstract) { - if (processClassBecameAbstract(backDependency)) { - continue; - } - } - if (isDependentOnRemovedMembers(backDependency)) { - if (myDependencyCache.markTargetClassInfo(backDependency)) { - if (LOG.isDebugEnabled()) { - LOG.debug("Mark dependent class " + myDependencyCache.resolve(backDependency.getClassQualifiedName()) + - "; reason: the class uses removed members of " + myDependencyCache.resolve(myQName)); - } - } - continue; - } - if (isDependentOnChangedMembers(backDependency)) { - if (myDependencyCache.markTargetClassInfo(backDependency)) { - if (LOG.isDebugEnabled()) { - LOG.debug("Mark dependent class " + myDependencyCache.resolve(backDependency.getClassQualifiedName()) + - "; reason: the class uses changed members of " + myDependencyCache.resolve(myQName)); - } - } - continue; - } - final Collection usedMethods = backDependency.getMethodRefs(); - if (removedMethods == null) { - removedMethods = extractMethods(myRemovedMembers, true); - } - if (isDependentOnEquivalentMethods(usedMethods, removedMethods)) { - if (myDependencyCache.markTargetClassInfo(backDependency)) { - if (LOG.isDebugEnabled()) { - LOG.debug("Mark dependent class " + myDependencyCache.resolve(backDependency.getClassQualifiedName()) + - "; reason: some overloaded methods of " + myDependencyCache.resolve(myQName) + " were removed"); - } - } - continue; - } - if (addedMethods == null) { - addedMethods = extractMethods(myAddedMembers, true); - } - if (isDependentOnEquivalentMethods(usedMethods, addedMethods)) { - if (myDependencyCache.markTargetClassInfo(backDependency)) { - if (LOG.isDebugEnabled()) { - LOG.debug("Mark dependent class " + myDependencyCache.resolve(backDependency.getClassQualifiedName()) + - "; reason: some overloaded methods of " + myDependencyCache.resolve(myQName) + " were added"); - } - } - } - } - } - - final Set methodsToCheck = new HashSet(); - extractMethods(myRemovedMembers, methodsToCheck, false); - - processInheritanceDependencies(methodsToCheck); - - extractMethods(myAddedMembers, methodsToCheck, false); - - if (!MakeUtil.isAnonymous(myDependencyCache.resolve(myQName))) { - // these checks make no sense for anonymous classes - - final TIntHashSet fieldNames = new TIntHashSet(); - extractFieldNames(myAddedMembers, fieldNames); - int addedFieldsCount = fieldNames.size(); - extractFieldNames(myRemovedMembers, fieldNames); - - if (!fieldNames.isEmpty()) { - cacheNavigator.walkSuperClasses(myQName, new ClassInfoProcessor() { - public boolean process(final int classQName) throws CacheCorruptedException { - markUseDependenciesOnFields(classQName, fieldNames); - return true; - } - }); - } - - if (addedFieldsCount > 0 && MakeUtil.isInterface(oldCache.getFlags(myQName))) { - final TIntHashSet visitedClasses = new TIntHashSet(); - visitedClasses.add(myQName); - cacheNavigator.walkSubClasses(myQName, new ClassInfoProcessor() { - public boolean process(int subclassQName) throws CacheCorruptedException { - markUseDependenciesOnFields(subclassQName, fieldNames); - visitedClasses.add(subclassQName); - cacheNavigator.walkSuperClasses(subclassQName, new ClassInfoProcessor() { - public boolean process(int superclassQName) throws CacheCorruptedException { - if (visitedClasses.contains(superclassQName)) { - return false; - } - markUseDependenciesOnFields(superclassQName, fieldNames); - visitedClasses.add(superclassQName); - return true; - } - }); - return true; - } - }); - } - - if (!methodsToCheck.isEmpty()) { - cacheNavigator.walkSuperClasses(myQName, new ClassInfoProcessor() { - public boolean process(int classQName) throws CacheCorruptedException { - markUseDependenciesOnEquivalentMethods(classQName, methodsToCheck, myQName); - return true; - } - }); - - cacheNavigator.walkSubClasses(myQName, new ClassInfoProcessor() { - public boolean process(int classQName) throws CacheCorruptedException { - markUseDependenciesOnEquivalentMethods(classQName, methodsToCheck, myQName); - return true; - } - }); - } - // check referencing members in subclasses - - final TIntHashSet addedOrRemovedFields = new TIntHashSet(); - final TIntHashSet addedOrRemovedMethods = new TIntHashSet(); - for (Set infos : Arrays.asList(myAddedMembers, myRemovedMembers)) { - for (MemberInfo member : infos) { - if (!member.isPrivate()) { - if (member instanceof FieldInfo) { - addedOrRemovedFields.add(member.getName()); - } - else if (member instanceof MethodInfo){ - addedOrRemovedMethods.add(member.getName()); - } - } - } - - } - if (!addedOrRemovedFields.isEmpty() || !addedOrRemovedMethods.isEmpty()) { - cacheNavigator.walkSubClasses(myQName, new ClassInfoProcessor() { - public boolean process(final int subclassQName) throws CacheCorruptedException { - if (!myDependencyCache.isClassInfoMarked(subclassQName)) { - if (referencesMembersWithNames(oldCache, subclassQName, addedOrRemovedFields, addedOrRemovedMethods)) { - final boolean marked = myDependencyCache.markClass(subclassQName); - if (marked && LOG.isDebugEnabled()) { - LOG.debug("Mark dependent class " + myDependencyCache.resolve(subclassQName) + "; Reason: members were added/removed in superclass with names, that may clash with the names of members of another classes that this class references"); - } - } - } - return true; - } - }); - } - } - } - - private static boolean referencesMembersWithNames(Cache cache, final int qName, TIntHashSet fieldNames, TIntHashSet methodNames) throws CacheCorruptedException { - for (final int referencedClass : cache.getReferencedClasses(qName)) { - for (Dependency dependency : cache.getBackDependencies(referencedClass)) { - if (dependency.getClassQualifiedName() == qName) { - for (Dependency.FieldRef ref : dependency.getFieldRefs()) { - if (fieldNames.contains(ref.name)) { - return true; - } - } - for (Dependency.MethodRef ref : dependency.getMethodRefs()) { - if (methodNames.contains(ref.name)) { - return true; - } - } - } - } - } - return false; - } - - private void markAnnotationDependenciesRecursively(final Dependency[] dependencies, final @NonNls String reason, final TIntHashSet visitedAnnotations) - throws CacheCorruptedException { - final Cache oldCache = myDependencyCache.getCache(); - for (Dependency dependency : dependencies) { - if (myDependencyCache.markTargetClassInfo(dependency)) { - if (LOG.isDebugEnabled()) { - LOG.debug("Mark dependent class " + myDependencyCache.resolve(dependency.getClassQualifiedName()) + reason); - } - } - final int depQName = dependency.getClassQualifiedName(); - if (ClsUtil.isAnnotation(oldCache.getFlags(depQName))) { - if (!visitedAnnotations.contains(depQName)) { - visitedAnnotations.add(depQName); - markAnnotationDependenciesRecursively(oldCache.getBackDependencies(depQName), LOG.isDebugEnabled()? "; reason: cascade semantics change for " + myDependencyCache.resolve(depQName) : "", visitedAnnotations); - } - } - } - } - - private static final int[] ALL_TARGETS = { - AnnotationTargets.ANNOTATION_TYPE, - AnnotationTargets.CONSTRUCTOR, - AnnotationTargets.FIELD, - AnnotationTargets.LOCAL_VARIABLE, - AnnotationTargets.METHOD, - AnnotationTargets.PACKAGE, - AnnotationTargets.PARAMETER, - AnnotationTargets.TYPE - }; - private boolean wereAnnotationTargesRemoved(final Cache oldCache, final Cache newCache) throws CacheCorruptedException { - final int oldAnnotationTargets = MakeUtil.getAnnotationTargets(oldCache, myQName, myDependencyCache.getSymbolTable()); - final int newAnnotationTargets = MakeUtil.getAnnotationTargets(newCache, myQName, myDependencyCache.getSymbolTable()); - if (oldAnnotationTargets == newAnnotationTargets) { - return false; - } - for (final int target : ALL_TARGETS) { - if ((oldAnnotationTargets & target) != 0 && (newAnnotationTargets & target) == 0) { - return true; - } - } - return false; - } - - private boolean hasRetentionPolicyChanged(final Cache oldCache, final Cache newCache) throws CacheCorruptedException { - // if retention policy changed from SOURCE to CLASS or RUNTIME, all sources should be recompiled to propagate changes - final int oldPolicy = MakeUtil.getAnnotationRetentionPolicy(myQName, oldCache, myDependencyCache.getSymbolTable()); - final int newPolicy = MakeUtil.getAnnotationRetentionPolicy(myQName, newCache, myDependencyCache.getSymbolTable()); - if (oldPolicy == RetentionPolicies.SOURCE && (newPolicy == RetentionPolicies.CLASS || newPolicy == RetentionPolicies.RUNTIME)) { - return true; - } - return oldPolicy == RetentionPolicies.CLASS && newPolicy == RetentionPolicies.RUNTIME; - } - - private boolean hasAnnotationSemanticsChanged(final Cache oldCache, final Cache newCache) throws CacheCorruptedException { - final TIntObjectHashMap oldAnnotations = fetchAllAnnotations(oldCache); - final TIntObjectHashMap newAnnotations = fetchAllAnnotations(newCache); - // filter certain known annotation which are processed separately - final int retentionAnnotation = myDependencyCache.getSymbolTable().getId("java.lang.annotation.Retention"); - final int targetAnnotation = myDependencyCache.getSymbolTable().getId("java.lang.annotation.Target"); - oldAnnotations.remove(retentionAnnotation); - oldAnnotations.remove(targetAnnotation); - newAnnotations.remove(retentionAnnotation); - newAnnotations.remove(targetAnnotation); - - if (oldAnnotations.size() != newAnnotations.size()) { - return true; // number of annotation has changed - } - for (int annotName : oldAnnotations.keys()) { - if (!newAnnotations.contains(annotName)) { - return true; - } - final AnnotationNameValuePair[] oldValues = oldAnnotations.get(annotName).getMemberValues(); - final AnnotationNameValuePair[] newValues = newAnnotations.get(annotName).getMemberValues(); - if (annotationValuesDiffer(oldValues, newValues)) { - return true; - } - } - return false; - } - - private boolean annotationValuesDiffer(final AnnotationNameValuePair[] oldValues, final AnnotationNameValuePair[] newValues) { - if (oldValues.length != newValues.length) { - return true; - } - final TIntObjectHashMap names = new TIntObjectHashMap(); - for (AnnotationNameValuePair value : oldValues) { - names.put(value.getName(), value.getValue()); - } - for (AnnotationNameValuePair value : newValues) { - if (!names.containsKey(value.getName())) { - return true; - } - if (!value.getValue().equals(names.get(value.getName()))) { - return true; - } - } - return false; - } - - - private TIntObjectHashMap fetchAllAnnotations(final Cache cache) throws CacheCorruptedException { - final int classId = myQName; - TIntObjectHashMap oldAnnotations = new TIntObjectHashMap(); - for (AnnotationConstantValue annot : cache.getRuntimeVisibleAnnotations(classId)) { - oldAnnotations.put(annot.getAnnotationQName(), annot); - } - for (AnnotationConstantValue annot : cache.getRuntimeInvisibleAnnotations(classId)) { - oldAnnotations.put(annot.getAnnotationQName(), annot); - } - return oldAnnotations; - } - - private void markAll(Dependency[] backDependencies, @NonNls String reason) throws CacheCorruptedException { - for (Dependency backDependency : backDependencies) { - if (myDependencyCache.markTargetClassInfo(backDependency)) { - if (LOG.isDebugEnabled()) { - LOG.debug("Mark dependent class " + myDependencyCache.resolve(backDependency.getClassQualifiedName()) + reason); - } - } - } - } - - private static void extractFieldNames(Collection fromCollection, TIntHashSet toCollection) { - for (final Object aFromCollection : fromCollection) { - MemberInfo memberInfo = (MemberInfo)aFromCollection; - if (memberInfo instanceof FieldInfo) { - toCollection.add(memberInfo.getName()); - } - } - } - - private static Set extractMethods(Collection fromCollection, boolean includeConstructors) { - final Set methods = new HashSet(); - extractMethods(fromCollection, methods, includeConstructors); - return methods; - } - - private static void extractMethods(Collection fromCollection, Collection toCollection, boolean includeConstructors) { - for (final MemberInfo memberInfo : fromCollection) { - if (memberInfo instanceof MethodInfo) { - final MethodInfo methodInfo = (MethodInfo)memberInfo; - if (includeConstructors) { - toCollection.add(methodInfo); - } - else { - if (!methodInfo.isConstructor()) { - toCollection.add(methodInfo); - } - } - } - } - } - - private boolean processClassBecameAbstract(Dependency dependency) throws CacheCorruptedException { - for (Dependency.MethodRef ref : dependency.getMethodRefs()) { - final MethodInfo usedMethod = myRefToMethodMap.get(ref); - if (usedMethod == null) { - continue; - } - if (usedMethod.isConstructor()) { - if (myDependencyCache.markTargetClassInfo(dependency)) { - if (LOG.isDebugEnabled()) { - LOG.debug("Mark dependent class " + myDependencyCache.resolve(dependency.getClassQualifiedName()) + "; reason: " + - myDependencyCache.resolve(myQName) + " made abstract"); - } - } - return true; - } - } - return false; - } - - private boolean isDependentOnRemovedMembers(Dependency dependency) { - for (Dependency.MethodRef ref : dependency.getMethodRefs()) { - if (myRemovedMembers.contains(myRefToMethodMap.get(ref))) { - return true; - } - } - for (Dependency.FieldRef ref : dependency.getFieldRefs()) { - if (myRemovedMembers.contains(myRefToFieldMap.get(ref))) { - return true; - } - } - return false; - } - - private boolean isDependentOnChangedMembers(Dependency dependency) { - for (Dependency.FieldRef ref : dependency.getFieldRefs()) { - final FieldInfo fieldInfo = myRefToFieldMap.get(ref); - if (myChangedMembers.contains(fieldInfo)) { - return true; - } - } - - for (Dependency.MethodRef ref : dependency.getMethodRefs()) { - final MethodInfo methodInfo = myRefToMethodMap.get(ref); - if (myChangedMembers.contains(methodInfo)) { - final MethodChangeDescription changeDescription = (MethodChangeDescription)myChangeDescriptions.get(methodInfo); - if (changeDescription.returnTypeDescriptorChanged || - changeDescription.returnTypeGenericSignatureChanged || - changeDescription.paramsGenericSignatureChanged || - changeDescription.throwsListChanged || - changeDescription.staticPropertyChanged || - changeDescription.accessRestricted) { - return true; - } - } - } - - return false; - } - - private boolean isDependentOnEquivalentMethods(Collection checkedMembers, Set members) throws CacheCorruptedException { - // check if 'members' contains method with the same name and the same numbers of parameters, but with different types - if (checkedMembers.isEmpty() || members.isEmpty()) { - return false; // optimization - } - for (Dependency.MethodRef checkedMethod : checkedMembers) { - if (hasEquivalentMethod(members, checkedMethod)) { - return true; - } - } - return false; - } - - private void markUseDependenciesOnEquivalentMethods(final int checkedInfoQName, Set methodsToCheck, int methodsClassName) throws CacheCorruptedException { - final Dependency[] backDependencies = myDependencyCache.getCache().getBackDependencies(checkedInfoQName); - for (Dependency dependency : backDependencies) { - if (myDependencyCache.isTargetClassInfoMarked(dependency)) { - continue; - } - if (isDependentOnEquivalentMethods(dependency.getMethodRefs(), methodsToCheck)) { - if (myDependencyCache.markTargetClassInfo(dependency)) { - if (LOG.isDebugEnabled()) { - LOG.debug("Mark dependent class " + myDependencyCache.resolve(dependency.getClassQualifiedName()) + - "; reason: more specific methods added to " + myDependencyCache.resolve(methodsClassName)); - } - } - myDependencyCache.addClassToUpdate(checkedInfoQName); - } - } - } - - private void markUseDependenciesOnFields(final int classQName, TIntHashSet fieldNames) throws CacheCorruptedException { - final Cache oldCache = myDependencyCache.getCache(); - for (Dependency useDependency : oldCache.getBackDependencies(classQName)) { - if (!myDependencyCache.isTargetClassInfoMarked(useDependency)) { - for (Dependency.FieldRef field : useDependency.getFieldRefs()) { - if (fieldNames.contains(field.name)) { - if (myDependencyCache.markTargetClassInfo(useDependency)) { - if (LOG.isDebugEnabled()) { - LOG.debug("Mark dependent class " + myDependencyCache.resolve(useDependency.getClassQualifiedName()) + - "; reason: conflicting fields were added to the hierarchy of the class " + myDependencyCache.resolve(classQName)); - } - } - myDependencyCache.addClassToUpdate(classQName); - break; // stop iterating fields - } - } - } - } - } - - private void processInheritanceDependencies(final Set removedMethods) throws CacheCorruptedException { - final Cache oldCache = myDependencyCache.getCache(); - final Cache newCache = myDependencyCache.getNewClassesCache(); - - final boolean becameFinal = !ClsUtil.isFinal(oldCache.getFlags(myQName)) && ClsUtil.isFinal(newCache.getFlags(myQName)); - final SymbolTable symbolTable = myDependencyCache.getSymbolTable(); - - final Set removedConcreteMethods = fetchNonAbstractMethods(myRemovedMembers); - final Set removedOverridableMethods; - if (!removedMethods.isEmpty()) { - removedOverridableMethods = new HashSet(removedMethods); - for (Iterator it = removedOverridableMethods.iterator(); it.hasNext();) { - final MethodInfo method = it.next(); - if (method.isFinal() || method.isStatic() || method.isPrivate() || method.isConstructor()) { - it.remove(); - } - } - } - else { - removedOverridableMethods = Collections.emptySet(); - } - myDependencyCache.getCacheNavigator().walkSubClasses(myQName, new ClassInfoProcessor() { - public boolean process(final int subclassQName) throws CacheCorruptedException { - if (myDependencyCache.isClassInfoMarked(subclassQName)) { - return true; - } - - if (!oldCache.containsClass(subclassQName)) { - return true; - } - - if (!removedMethods.isEmpty() && myIsRemoteInterface && !MakeUtil.isInterface(oldCache.getFlags(subclassQName))) { - if (myDependencyCache.markClass(subclassQName)) { - if (LOG.isDebugEnabled()) { - LOG.debug("Mark dependent class " + myDependencyCache.resolve(subclassQName) + - "; reason: methods were removed from remote interface: " + myDependencyCache.resolve(myQName)); - } - } - return true; - } - - if (mySuperClassAdded || mySuperInterfaceAdded) { - if (myDependencyCache.markClass(subclassQName)) { - if (LOG.isDebugEnabled()) { - LOG.debug("Mark dependent class " + myDependencyCache.resolve(subclassQName) + "; reason: the superlist of " + - myDependencyCache.resolve(myQName) + " is changed"); - } - } - return true; - } - - // if info became final, mark direct inheritors - if (becameFinal) { - if (myQName == oldCache.getSuperQualifiedName(subclassQName)) { - if (myDependencyCache.markClass(subclassQName)) { - if (LOG.isDebugEnabled()) { - LOG.debug("Mark dependent class " + myDependencyCache.resolve(subclassQName) + "; reason: the class " + - myDependencyCache.resolve(myQName) + " was made final"); - } - } - return true; - } - } - - // process added members - for (final MemberInfo member : myAddedMembers) { - if (member instanceof MethodInfo) { - final MethodInfo method = (MethodInfo)member; - if (method.isAbstract()) { - // all derived classes should be marked in case an abstract method was added - if (myDependencyCache.markClass(subclassQName)) { - if (LOG.isDebugEnabled()) { - LOG.debug("Mark dependent class " + myDependencyCache.resolve(subclassQName) + "; reason: added abstract method to " + - myDependencyCache.resolve(myQName)); - } - } - return true; - } - if (!method.isPrivate()) { - final MethodInfo derivedMethod = oldCache.findMethodsBySignature(subclassQName, method.getDescriptor(symbolTable), symbolTable); - if (derivedMethod != null) { - if (!method.getReturnTypeDescriptor(symbolTable).equals(derivedMethod.getReturnTypeDescriptor(symbolTable))) { - if (myDependencyCache.markClass(subclassQName)) { - if (LOG.isDebugEnabled()) { - LOG.debug("Mark dependent class " + myDependencyCache.resolve(subclassQName) + "; reason: return types of method " + - method + " in base and derived classes are different"); - } - } - return true; - } - if (MakeUtil.isMoreAccessible(method.getFlags(), derivedMethod.getFlags())) { - if (myDependencyCache.markClass(subclassQName)) { - if (LOG.isDebugEnabled()) { - LOG.debug("Mark dependent class " + myDependencyCache.resolve(subclassQName) + "; reason: the method " + method + - " in derived class is less accessible than in base class"); - } - } - return true; - } - if (!method.isStatic() && derivedMethod.isStatic()) { - if (myDependencyCache.markClass(subclassQName)) { - if (LOG.isDebugEnabled()) { - LOG.debug("Mark dependent class " + myDependencyCache.resolve(subclassQName) + "; reason: the method " + method + - " in derived class is static, but added method in the base class is not"); - } - } - return true; - } - if (method.isFinal() && !derivedMethod.isFinal()) { - if (myDependencyCache.markClass(subclassQName)) { - if (LOG.isDebugEnabled()) { - LOG.debug("Mark dependent class " + myDependencyCache.resolve(subclassQName) + "; reason: the method " + method + - " in base class is final, but in derived class is not"); - } - } - return true; - } - if (!CacheUtils.areArraysContentsEqual(method.getThrownExceptions(), derivedMethod.getThrownExceptions())) { - if (myDependencyCache.markClass(subclassQName)) { - if (LOG.isDebugEnabled()) { - LOG.debug("Mark dependent class " + myDependencyCache.resolve(subclassQName) + "; reason: exception lists of " + - method + " in base and derived classes are different"); - } - } - return true; - } - } - if (hasGenericsNameClashes(method, oldCache, subclassQName)) { - if (myDependencyCache.markClass(subclassQName)) { - if (LOG.isDebugEnabled()) { - LOG.debug("Mark dependent class " + myDependencyCache.resolve(subclassQName) + - "; reason: found method with the same name, different generic signature, but the same erasure as " + method); - } - } - return true; - } - } - } - else if (member instanceof FieldInfo) { - if (oldCache.findFieldByName(subclassQName, member.getName()) != null) { - if (myDependencyCache.markClass(subclassQName)) { - if (LOG.isDebugEnabled()) { - LOG.debug("Mark dependent class " + myDependencyCache.resolve(subclassQName) + "; reason: added field " + member + - " to base class"); - } - } - return true; - } - } - } - - // process changed members - for (final MemberInfo changedMember : myChangedMembers) { - if (changedMember instanceof MethodInfo) { - final MethodInfo oldMethod = (MethodInfo)changedMember; - MethodChangeDescription changeDescription = (MethodChangeDescription)myChangeDescriptions.get(oldMethod); - if (changeDescription.becameAbstract) { - if (!ClsUtil.isAbstract(oldCache.getFlags(subclassQName))) { // if the subclass was not abstract - if (myDependencyCache.markClass(subclassQName)) { - if (LOG.isDebugEnabled()) { - LOG.debug( - "Mark dependent class " + myDependencyCache.resolve(subclassQName) + "; reason: changed base method " + oldMethod); - } - } - return true; - } - } - - final String oldMethodDescriptor = oldMethod.getDescriptor(symbolTable); - - final MethodInfo derivedMethod = oldCache.findMethodsBySignature(subclassQName, oldMethodDescriptor, symbolTable); - if (derivedMethod != null) { - if (myDependencyCache.markClass(subclassQName)) { - if (LOG.isDebugEnabled()) { - LOG.debug("Mark dependent class " + myDependencyCache.resolve(subclassQName) + "; reason: changed base method " + oldMethod); - } - } - return true; - } - // now check if the changed method is compatible with methods declared in implemented interfaces of subclasses - myDependencyCache.getCacheNavigator().walkSuperInterfaces(subclassQName, new ClassInfoProcessor() { - boolean found = false; - public boolean process(final int ifaceQName) throws CacheCorruptedException { - if (found) { - return false; - } - final MethodInfo implementee = oldCache.findMethodsBySignature(ifaceQName, oldMethodDescriptor, symbolTable); - if (implementee != null) { - found = true; - if (myDependencyCache.markClass(subclassQName)) { - if (LOG.isDebugEnabled()) { - LOG.debug("Mark dependent class " + myDependencyCache.resolve(subclassQName) + "; reason: changed base method, implementing corresponding method inherited from an interface" + oldMethod); - } - } - } - return !found; - } - }); - if (myDependencyCache.isClassInfoMarked(subclassQName)) { - return true; - } - } - } - - if (!ClsUtil.isAbstract(oldCache.getFlags(subclassQName))) { - if (hasUnimplementedAbstractMethods(subclassQName, new HashSet(removedConcreteMethods))) { - if (myDependencyCache.markClass(subclassQName)) { - if (LOG.isDebugEnabled()) { - LOG.debug("Mark dependent class " + myDependencyCache.resolve(subclassQName) + "; reason: the class should be declared abstract because abstract method implementation was removed from its superclass: " + - myDependencyCache.resolve(myQName)); - } - } - return true; - } - } - - if (!removedOverridableMethods.isEmpty() && !myDependencyCache.isClassInfoMarked(subclassQName) && !myDependencyCache.getNewClassesCache().containsClass(subclassQName) /*not compiled in this session*/) { - final Cache cache = myDependencyCache.getCache(); - for (MethodInfo subclassMethod : cache.getMethods(subclassQName)) { - if (!subclassMethod.isConstructor()) { - for (MethodInfo removedMethod : removedOverridableMethods) { - if (removedMethod.getName() == subclassMethod.getName() /*todo: check param signatures here for better accuracy*/) { - // got it - if (myDependencyCache.markClass(subclassQName)) { - if (LOG.isDebugEnabled()) { - LOG.debug("Mark dependent subclass " + myDependencyCache.resolve(subclassQName) + "; reason: the class has methods annotated with @Override and some methods were changed or removed in a base class" + - myDependencyCache.resolve(myQName)); - } - } - return true; - } - } - } - } - } - // end of subclass processor - return true; - } - }); - } - - private static boolean hasGenericsNameClashes(final MethodInfo baseMethod, final Cache oldCache, final int subclassQName) throws CacheCorruptedException { - // it is illegal if 2 methods in a hierarchy have 1) same name 2) different signatures 3) same erasure - final List methods = oldCache.findMethodsByName(subclassQName, baseMethod.getName()); - if (methods.size() > 0) { - for (final MethodInfo methodInSubclass : methods) { - if (ClsUtil.isBridge(methodInSubclass.getFlags())) { - continue; - } - if (baseMethod.getDescriptor() == methodInSubclass.getDescriptor() && baseMethod.getGenericSignature() != methodInSubclass.getGenericSignature()) { - return true; - } - } - } - return false; - } - - private static Set fetchNonAbstractMethods(Set membersToCheck) { - final Set methodsToCheck = new HashSet(); - for (final Object aMembersToCheck : membersToCheck) { - final MemberInfo memberInfo = (MemberInfo)aMembersToCheck; - if (memberInfo instanceof MethodInfo) { - final MethodInfo methodInfo = (MethodInfo)memberInfo; - if (!methodInfo.isAbstract() && !methodInfo.isConstructor()) { - methodsToCheck.add(memberInfo); - } - } - } - return methodsToCheck; - } - - private boolean hasUnimplementedAbstractMethods(int superQName, final Set methodsToCheck) throws CacheCorruptedException { - if (myDependencyCache.getCache().containsClass(superQName)) { - return hasBaseAbstractMethods(superQName, methodsToCheck) || - hasBaseAbstractMethodsInHierarchy(superQName, methodsToCheck); - } - else { - final String qName = myDependencyCache.resolve(superQName); - if (!CommonClassNames.JAVA_LANG_OBJECT.equals(qName)) { - if (hasBaseAbstractMethods2(qName, methodsToCheck)) { - return true; - } - } - } - return false; - } - - private boolean hasBaseAbstractMethodsInHierarchy(int fromClassQName, final Set methodsToCheck) throws CacheCorruptedException { - if (fromClassQName == Cache.UNKNOWN || methodsToCheck.isEmpty()) { - return false; - } - final Cache cache = myDependencyCache.getCache(); - int superName = cache.getSuperQualifiedName(fromClassQName); - if (superName != Cache.UNKNOWN) { - if (hasUnimplementedAbstractMethods(superName, methodsToCheck)) { - return true; - } - } - if (methodsToCheck.isEmpty()) { - return false; - } - int[] superInterfaces = cache.getSuperInterfaces(fromClassQName); - for (int superInterface : superInterfaces) { - if (hasUnimplementedAbstractMethods(superInterface, methodsToCheck)) { - return true; - } - } - return false; - } - - private boolean hasBaseAbstractMethods(int qName, Set methodsToCheck) throws CacheCorruptedException { - final SymbolTable symbolTable = myDependencyCache.getSymbolTable(); - final Cache oldCache = myDependencyCache.getCache(); - final Cache newCache = myDependencyCache.getNewClassesCache(); - final Cache cache = newCache.containsClass(qName)? newCache : oldCache; // use recompiled version (if any) for searching methods - for (Iterator it = methodsToCheck.iterator(); it.hasNext();) { - final MethodInfo methodInfo = (MethodInfo)it.next(); - final MethodInfo superMethod = cache.findMethodsBySignature(qName, methodInfo.getDescriptor(symbolTable), symbolTable); - if (superMethod != null) { - if (ClsUtil.isAbstract(superMethod.getFlags())) { - return true; - } - it.remove(); - } - } - return false; - } - - // search using PSI - private boolean hasBaseAbstractMethods2(final String qName, final Set methodsToCheck) throws CacheCorruptedException { - final boolean[] found = {false}; - final CacheCorruptedException ex = ApplicationManager.getApplication().runReadAction(new Computable() { - public CacheCorruptedException compute() { - try { - final PsiManager psiManager = PsiManager.getInstance(myProject); - final PsiClass aClass = JavaPsiFacade.getInstance(psiManager.getProject()).findClass(qName, GlobalSearchScope.allScope(myProject)); - if (aClass == null) { - return null; - } - final PsiElementFactory factory = JavaPsiFacade.getInstance(psiManager.getProject()).getElementFactory(); - final PsiNameHelper nameHelper = JavaPsiFacade.getInstance(myProject).getNameHelper(); - for (Iterator it = methodsToCheck.iterator(); it.hasNext();) { - final MethodInfo methodInfo = (MethodInfo)it.next(); - if (!nameHelper.isIdentifier(myDependencyCache.resolve(methodInfo.getName()), LanguageLevel.JDK_1_3)) { // fix for SCR 16068 - continue; - } - // language level 1.3 will prevent exceptions from PSI if there are methods named "assert" - final PsiMethod methodPattern = factory.createMethodFromText(getMethodText(methodInfo), null, LanguageLevel.JDK_1_3); - final PsiMethod superMethod = aClass.findMethodBySignature(methodPattern, true); - if (superMethod != null) { - if (superMethod.hasModifierProperty(PsiModifier.ABSTRACT)) { - found[0] = true; - return null; - } - it.remove(); - } - } - } - catch (IncorrectOperationException e) { - LOG.error(e); - } - catch (CacheCorruptedException e) { - return e; - } - return null; - } - }); - if (ex != null) { - throw ex; - } - return found[0]; - } - - @SuppressWarnings({"HardCodedStringLiteral"}) - private @NonNls String getMethodText(MethodInfo methodInfo) throws CacheCorruptedException { - final SymbolTable symbolTable = myDependencyCache.getSymbolTable(); - StringBuilder text = new StringBuilder(16); - final String returnType = signatureToSourceTypeName(methodInfo.getReturnTypeDescriptor(symbolTable)); - text.append(returnType); - text.append(" "); - text.append(myDependencyCache.resolve(methodInfo.getName())); - text.append("("); - final String[] parameterSignatures = methodInfo.getParameterDescriptors(symbolTable); - for (int idx = 0; idx < parameterSignatures.length; idx++) { - String parameterSignature = parameterSignatures[idx]; - if (idx > 0) { - text.append(","); - } - text.append(signatureToSourceTypeName(parameterSignature)); - text.append(" arg"); - text.append(idx); - } - text.append(")"); - return text.toString(); - } - - private static boolean wereInterfacesRemoved(int[] oldInterfaces, int[] newInterfaces) { - for (int oldInterface : oldInterfaces) { - boolean found = false; - for (int newInterface : newInterfaces) { - found = oldInterface == newInterface; - if (found) { - break; - } - } - if (!found) { - return true; - } - } - return false; - } - - /** @return a map [fieldName->FieldInfo]*/ - private static TIntObjectHashMap getFieldInfos(Cache cache, int qName) throws CacheCorruptedException { - final TIntObjectHashMap map = new TIntObjectHashMap(); - for (FieldInfo fieldInfo : cache.getFields(qName)) { - map.put(fieldInfo.getName(), fieldInfo); - } - return map; - } - - /** @return a map [methodSignature->MethodInfo]*/ - private Map getMethodInfos(final MethodInfo[] methods) throws CacheCorruptedException { - final Map map = new HashMap(); - final SymbolTable symbolTable = myDependencyCache.getSymbolTable(); - for (MethodInfo methodInfo : methods) { - final String signature = methodInfo.getDescriptor(symbolTable); - final MethodInfoContainer currentValue = map.get(signature); - // covariant methods have the same signature, so there might be several MethodInfos for one key - if (currentValue == null) { - map.put(signature, new MethodInfoContainer(methodInfo)); - } - else { - currentValue.add(methodInfo); - } - } - return map; - } - - private static void addAddedMembers(TIntObjectHashMap oldFields, Map oldMethods, - TIntObjectHashMap newFields, Map newMethods, - Collection members) { - - for (final TIntObjectIterator it = newFields.iterator(); it.hasNext();) { - it.advance(); - final int fieldName = it.key(); - final FieldInfo fieldInfo = it.value(); - if (!oldFields.containsKey(fieldName)) { - members.add(fieldInfo); - } - } - for (final String signature : newMethods.keySet()) { - if (!oldMethods.containsKey(signature)) { - members.addAll(newMethods.get(signature).getMethods()); - } - } - } - - private static void addRemovedMembers(TIntObjectHashMap oldFields, Map oldMethods, - TIntObjectHashMap newFields, Map newMethods, - Collection members) { - addAddedMembers(newFields, newMethods, oldFields, oldMethods, members); - } - - private void addChangedMembers(TIntObjectHashMap oldFields, Map oldMethods, - TIntObjectHashMap newFields, Map newMethods, - Collection members) throws CacheCorruptedException { - for (final TIntObjectIterator it = oldFields.iterator(); it.hasNext();) { - it.advance(); - final int fieldName = it.key(); - final FieldInfo oldInfo = it.value(); - final FieldInfo newInfo = newFields.get(fieldName); - if (newInfo != null) { - final FieldChangeDescription changeDescription = new FieldChangeDescription(oldInfo, newInfo); - if (changeDescription.isChanged()) { - members.add(oldInfo); - myChangeDescriptions.put(oldInfo, changeDescription); - } - } - } - - if (!oldMethods.isEmpty()) { - final SymbolTable symbolTable = myDependencyCache.getSymbolTable(); - final Set processed = new HashSet(); - for (final String signature : oldMethods.keySet()) { - final MethodInfoContainer oldMethodsContainer = oldMethods.get(signature); - final MethodInfoContainer newMethodsContainer = newMethods.get(signature); - if (newMethodsContainer != null) { - processed.clear(); - if (oldMethodsContainer.size() == newMethodsContainer.size()) { - // first, process all corresponding method infos - for (MethodInfo oldInfo : oldMethodsContainer.getMethods()) { - MethodInfo _newInfo = null; - for (MethodInfo newInfo : newMethodsContainer.getMethods()) { - if (oldInfo.equals(newInfo)) { - _newInfo = newInfo; - break; - } - } - if (_newInfo != null) { - processed.add(oldInfo); - processed.add(_newInfo); - final MethodChangeDescription changeDescription = new MethodChangeDescription(oldInfo, _newInfo, symbolTable); - if (changeDescription.isChanged()) { - members.add(oldInfo); - myChangeDescriptions.put(oldInfo, changeDescription); - } - } - } - } - // processing the rest of infos, each pair - for (MethodInfo oldInfo : oldMethodsContainer.getMethods()) { - if (processed.contains(oldInfo)) { - continue; - } - for (MethodInfo newInfo : newMethodsContainer.getMethods()) { - if (processed.contains(newInfo)) { - continue; - } - final MethodChangeDescription changeDescription = new MethodChangeDescription(oldInfo, newInfo, symbolTable); - if (changeDescription.isChanged()) { - members.add(oldInfo); - myChangeDescriptions.put(oldInfo, changeDescription); - } - } - } - } - } - } - } - - private boolean hasEquivalentMethod(Collection members, Dependency.MethodRef modelMethod) throws CacheCorruptedException { - final String[] modelSignature = modelMethod.getParameterDescriptors(myDependencyCache.getSymbolTable()); - for (final MethodInfo method : members) { - if (modelMethod.name != method.getName()) { - continue; - } - final String[] methodSignature = method.getParameterDescriptors(myDependencyCache.getSymbolTable()); - if (modelSignature.length != methodSignature.length) { - continue; - } - - for (int i = 0; i < methodSignature.length; i++) { - if (!methodSignature[i].equals(modelSignature[i])) { - if (LOG.isDebugEnabled()) { - LOG.debug("Equivalent: " + modelMethod.getDescriptor(myDependencyCache.getSymbolTable()) + " <=> " + - method.getDescriptor(myDependencyCache.getSymbolTable())); - } - return true; - } - } - } - return false; - } - - private static @NonNls - String signatureToSourceTypeName(String signature) - { - try { - switch(signature.charAt(0)) { - case 'B' : return "byte"; - case 'C' : return "char"; - case 'D' : return "double"; - case 'F' : return "float"; - case 'I' : return "int"; - case 'J' : return "long"; - - case 'L' : { // Full class name - int index = signature.indexOf(';'); // Look for closing `;' - - if(index < 0) - throw new RuntimeException("Invalid signature: " + signature); - - return signature.substring(1, index).replace('/', '.'); - } - - case 'S' : return "short"; - case 'Z' : return "boolean"; - - case '[' : { // Array declaration - int n; - StringBuffer brackets; - String type; - - brackets = new StringBuffer(); // Accumulate []'s - - // Count opening brackets and look for optional size argument - for(n=0; signature.charAt(n) == '['; n++) - brackets.append("[]"); - - - // The rest of the string denotes a `' - type = signatureToSourceTypeName(signature.substring(n)); - - return type + brackets.toString(); - } - - case 'V' : return "void"; - - default : throw new RuntimeException("Invalid signature: `" + - signature + "'"); - } - } catch(StringIndexOutOfBoundsException e) { // Should never occur - throw new RuntimeException("Invalid signature: " + e + ":" + signature); - } - } - - private Dependency[] getBackDependencies() throws CacheCorruptedException { - if (myBackDependencies == null) { - myBackDependencies = myDependencyCache.getCache().getBackDependencies(myQName); - } - return myBackDependencies; - } - - private static class MethodInfoContainer { - private List myInfos = null; - - protected MethodInfoContainer(MethodInfo info) { - myInfos = Collections.singletonList(info); - } - - public List getMethods() { - return myInfos; - } - - public int size() { - return myInfos.size(); - } - - public void add(MethodInfo info) { - if (myInfos.size() == 1) { - myInfos = new ArrayList(myInfos); - } - myInfos.add(info); - } - } -} diff --git a/java/compiler/impl/src/com/intellij/compiler/make/MakeUtil.java b/java/compiler/impl/src/com/intellij/compiler/make/MakeUtil.java deleted file mode 100644 index 52f347f2ea52..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/make/MakeUtil.java +++ /dev/null @@ -1,300 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * created at Jan 17, 2002 - * @author Jeka - */ -package com.intellij.compiler.make; - -import com.intellij.compiler.SymbolTable; -import com.intellij.compiler.classParsing.*; -import com.intellij.openapi.application.ApplicationManager; -import com.intellij.openapi.compiler.CompileContext; -import com.intellij.openapi.diagnostic.Logger; -import com.intellij.openapi.module.Module; -import com.intellij.openapi.roots.CompilerModuleExtension; -import com.intellij.openapi.roots.ProjectFileIndex; -import com.intellij.openapi.roots.ProjectRootManager; -import com.intellij.openapi.util.Computable; -import com.intellij.openapi.util.SystemInfo; -import com.intellij.openapi.util.text.StringUtil; -import com.intellij.openapi.vfs.VfsUtil; -import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.util.StringBuilderSpinAllocator; -import com.intellij.util.cls.ClsUtil; -import org.jetbrains.annotations.NonNls; -import org.jetbrains.annotations.Nullable; - -public class MakeUtil { - - private MakeUtil() { - } - - private static final Logger LOG = Logger.getInstance("#com.intellij.compiler.make.MakeUtil"); - - - public static VirtualFile getSourceRoot(CompileContext context, Module module, VirtualFile file) { - final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(module.getProject()).getFileIndex(); - final VirtualFile root = fileIndex.getSourceRootForFile(file); - if (root != null) { - return root; - } - // try to find among roots of generated files. - final VirtualFile[] sourceRoots = context.getSourceRoots(module); - for (final VirtualFile sourceRoot : sourceRoots) { - if (fileIndex.isInSourceContent(sourceRoot)) { - continue; // skip content source roots, need only roots for generated files - } - if (VfsUtil.isAncestor(sourceRoot, file, false)) { - return sourceRoot; - } - } - return null; - } - - /** - * cuts inner or anonymous class' parts and translates package names to lower case - */ - private static String normalizeClassName(String qName) { - int index = qName.indexOf('$'); - if (index >= 0) { - qName = qName.substring(0, index); - } - if (SystemInfo.isFileSystemCaseSensitive) { - return qName; - } - // the name of a dir should be lowercased because javac seem to allow difference in case - // between the physical directory and package name. - final int dotIndex = qName.lastIndexOf('.'); - final StringBuilder builder = StringBuilderSpinAllocator.alloc(); - try { - builder.append(qName); - for (int idx = 0; idx < dotIndex; idx++) { - builder.setCharAt(idx, Character.toLowerCase(builder.charAt(idx))); - } - return builder.toString(); - } - finally { - StringBuilderSpinAllocator.dispose(builder); - } - } - - public static boolean isAnonymous(String name) { - int index = name.lastIndexOf('$'); - if (index >= 0) { - index++; - if (index < name.length()) { - try { - Integer.parseInt(name.substring(index)); - return true; - } - catch (NumberFormatException e) { - } - } - } - return false; - } - - /* - not needed currently - public static String getEnclosingClassName(String anonymousQName) { - return anonymousQName.substring(0, anonymousQName.lastIndexOf('$')); - } - */ - - /* - not needed currently - public static boolean isNative(int flags) { - return (ClsUtil.ACC_NATIVE & flags) != 0; - } - */ - - /** - * tests if the accessibility, denoted by flags1 is less restricted than the accessibility denoted by flags2 - * @return true means flags1 is less restricted than flags2
- * false means flags1 define more restricted access than flags2 or they have equal accessibility - */ - public static boolean isMoreAccessible(int flags1, int flags2) { - if (ClsUtil.isPrivate(flags2)) { - return ClsUtil.isPackageLocal(flags1) || ClsUtil.isProtected(flags1) || ClsUtil.isPublic(flags1); - } - if (ClsUtil.isPackageLocal(flags2)) { - return ClsUtil.isProtected(flags1) || ClsUtil.isPublic(flags1); - } - if (ClsUtil.isProtected(flags2)) { - return ClsUtil.isPublic(flags1); - } - return false; - } - - @Nullable - @SuppressWarnings({"HardCodedStringLiteral"}) - public static String relativeClassPathToQName(String relativePath, char separator) { - if (!relativePath.endsWith(".class")) { - return null; - } - int start = 0; - int end = relativePath.length() - ".class".length(); - if (relativePath.startsWith(String.valueOf(separator))) { - start += 1; - } - return (start <= end)? relativePath.substring(start, end).replace(separator, '.') : null; - } - - public static @NonNls String parseObjectType(final String descriptor, int fromIndex) { - int semicolonIndex = descriptor.indexOf(';', fromIndex); - if (descriptor.charAt(fromIndex) == 'L' && semicolonIndex > fromIndex) { // isObjectType - return descriptor.substring(fromIndex + 1, semicolonIndex).replace('/', '.'); - } - if (descriptor.charAt(fromIndex) == '[' && (descriptor.length() - fromIndex) > 0) { // isArrayType - return parseObjectType(descriptor, fromIndex + 1); - } - return null; - } - - @SuppressWarnings({"HardCodedStringLiteral"}) - public static boolean isPrimitiveType(String descriptor) { - return - "V".equals(descriptor) || - "B".equals(descriptor) || - "C".equals(descriptor) || - "D".equals(descriptor) || - "F".equals(descriptor) || - "I".equals(descriptor) || - "J".equals(descriptor) || - "S".equals(descriptor) || - "Z".equals(descriptor); - } - - public static boolean isArrayType(String descriptor) { - return StringUtil.startsWithChar(descriptor, '['); - } - - public static String getComponentType(String descriptor) { - if (!isArrayType(descriptor)) { - return null; - } - return descriptor.substring(1); - } - - - /** - * @return a normalized path to source relative to a source root by class qualified name and sourcefile short name. - * The path uses forward slashes "/". - */ - public static String createRelativePathToSource(String qualifiedName, String srcName) { - qualifiedName = normalizeClassName(qualifiedName); - int index = qualifiedName.lastIndexOf('.'); - if (index >= 0) { - srcName = qualifiedName.substring(0, index).replace('.', '/') + "/" + srcName; - } - return srcName; - } - - public static boolean isInterface(int flags) { - return (ClsUtil.ACC_INTERFACE & flags) != 0; - } - - public static int getAnnotationTargets(final Cache cache, final int annotationQName, final SymbolTable symbolTable) throws CacheCorruptedException { - final AnnotationConstantValue targetAnnotation = findAnnotation( - "java.lang.annotation.Target", - cache.getRuntimeVisibleAnnotations(annotationQName), symbolTable); - if (targetAnnotation == null) { - return AnnotationTargets.ALL; // all program elements are annotation targets by default - } - final AnnotationNameValuePair[] memberValues = targetAnnotation.getMemberValues(); - ConstantValueArray value = (ConstantValueArray)memberValues[0].getValue(); - final ConstantValue[] targets = value.getValue(); - int annotationTargets = 0; - for (final ConstantValue target : targets) { - if (target instanceof EnumConstantValue) { - final String constantName = symbolTable.getSymbol(((EnumConstantValue)target).getConstantName()); - if (AnnotationTargets.TYPE_STR.equals(constantName)) { - annotationTargets |= AnnotationTargets.TYPE; - } - if (AnnotationTargets.FIELD_STR.equals(constantName)) { - annotationTargets |= AnnotationTargets.FIELD; - } - if (AnnotationTargets.METHOD_STR.equals(constantName)) { - annotationTargets |= AnnotationTargets.METHOD; - } - if (AnnotationTargets.PARAMETER_STR.equals(constantName)) { - annotationTargets |= AnnotationTargets.PARAMETER; - } - if (AnnotationTargets.CONSTRUCTOR_STR.equals(constantName)) { - annotationTargets |= AnnotationTargets.CONSTRUCTOR; - } - if (AnnotationTargets.LOCAL_VARIABLE_STR.equals(constantName)) { - annotationTargets |= AnnotationTargets.LOCAL_VARIABLE; - } - if (AnnotationTargets.ANNOTATION_TYPE_STR.equals(constantName)) { - annotationTargets |= AnnotationTargets.ANNOTATION_TYPE; - } - if (AnnotationTargets.PACKAGE_STR.equals(constantName)) { - annotationTargets |= AnnotationTargets.PACKAGE; - } - } - } - return annotationTargets; - } - - public static int getAnnotationRetentionPolicy(final int annotationQName, final Cache cache, final SymbolTable symbolTable) throws CacheCorruptedException { - final AnnotationConstantValue retentionPolicyAnnotation = findAnnotation( - "java.lang.annotation.Retention", - cache.getRuntimeVisibleAnnotations(annotationQName), symbolTable - ); - if (retentionPolicyAnnotation == null) { - return RetentionPolicies.CLASS; // default retention policy - } - final AnnotationNameValuePair[] memberValues = retentionPolicyAnnotation.getMemberValues(); - final EnumConstantValue value = (EnumConstantValue)memberValues[0].getValue(); - final String constantName = symbolTable.getSymbol(value.getConstantName()); - if (RetentionPolicies.SOURCE_STR.equals(constantName)) { - return RetentionPolicies.SOURCE; - } - if (RetentionPolicies.CLASS_STR.equals(constantName)) { - return RetentionPolicies.CLASS; - } - if (RetentionPolicies.RUNTIME_STR.equals(constantName)) { - return RetentionPolicies.RUNTIME; - } - LOG.error("Unknown retention policy: " + constantName); - return -1; - } - - public static AnnotationConstantValue findAnnotation(@NonNls final String annotationQName, - AnnotationConstantValue[] annotations, final SymbolTable symbolTable) throws CacheCorruptedException { - for (final AnnotationConstantValue annotation : annotations) { - if (annotationQName.equals(symbolTable.getSymbol(annotation.getAnnotationQName()))) { - return annotation; - } - } - return null; - } - - public static String getModuleOutputDirPath(final Module module) { - return ApplicationManager.getApplication().runReadAction(new Computable() { - public String compute() { - final String url = CompilerModuleExtension.getInstance(module).getCompilerOutputUrl(); - if (url == null) { - return null; - } - return VfsUtil.urlToPath(url); - } - }); - } -} diff --git a/java/compiler/impl/src/com/intellij/compiler/make/MethodChangeDescription.java b/java/compiler/impl/src/com/intellij/compiler/make/MethodChangeDescription.java deleted file mode 100644 index 246570384a0d..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/make/MethodChangeDescription.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.compiler.make; - -import com.intellij.compiler.SymbolTable; -import com.intellij.compiler.classParsing.ConstantValue; -import com.intellij.compiler.classParsing.GenericMethodSignature; -import com.intellij.compiler.classParsing.MethodInfo; -import com.intellij.compiler.classParsing.SignatureParsingException; -import com.intellij.util.cls.ClsUtil; - -import java.util.Arrays; - -/** - * @author Eugene Zhuravlev - * Date: Apr 7, 2004 - */ -class MethodChangeDescription extends ChangeDescription { - public final boolean returnTypeDescriptorChanged; - public final boolean returnTypeGenericSignatureChanged; - public final boolean paramsGenericSignatureChanged; - public final boolean throwsListChanged; - public final boolean flagsChanged; - public final boolean staticPropertyChanged; - public final boolean accessRestricted; - public final boolean becameAbstract; - public final boolean removedAnnotationDefault; - - public MethodChangeDescription(final MethodInfo oldMethod, final MethodInfo newMethod, SymbolTable symbolTable) throws CacheCorruptedException { - final String oldRtDescriptor = oldMethod.getReturnTypeDescriptor(symbolTable); - final String newRtDescriptor = newMethod.getReturnTypeDescriptor(symbolTable); - returnTypeDescriptorChanged = !oldRtDescriptor.equals(newRtDescriptor); - - final int oldGenericSignature = oldMethod.getGenericSignature(); - final int newGenericSignature = newMethod.getGenericSignature(); - if (oldGenericSignature == newGenericSignature) { - returnTypeGenericSignatureChanged = false; - paramsGenericSignatureChanged = false; - } - else { - if (oldGenericSignature != -1 && newGenericSignature != -1) { - try { - final GenericMethodSignature _oldGenericMethodSignature = GenericMethodSignature.parse(symbolTable.getSymbol(oldGenericSignature)); - final GenericMethodSignature _newGenericMethodSignature = GenericMethodSignature.parse(symbolTable.getSymbol(newGenericSignature)); - returnTypeGenericSignatureChanged = !_oldGenericMethodSignature.getReturnTypeSignature().equals(_newGenericMethodSignature.getReturnTypeSignature()); - paramsGenericSignatureChanged = !_oldGenericMethodSignature.getFormalTypeParams().equals(_newGenericMethodSignature.getFormalTypeParams()) || - !Arrays.equals(_oldGenericMethodSignature.getParamSignatures(), _newGenericMethodSignature.getParamSignatures()); - } - catch (SignatureParsingException e) { - throw new CacheCorruptedException(e); - } - } - else { - returnTypeGenericSignatureChanged = true; - paramsGenericSignatureChanged = true; - } - } - - throwsListChanged = !CacheUtils.areArraysContentsEqual(oldMethod.getThrownExceptions(), newMethod.getThrownExceptions()); - - final int oldFlags = oldMethod.getFlags(); - final int newFlags = newMethod.getFlags(); - flagsChanged = oldFlags != newFlags; - - staticPropertyChanged = (ClsUtil.isStatic(oldFlags) && !ClsUtil.isStatic(newFlags)) || (!ClsUtil.isStatic(oldFlags) && ClsUtil.isStatic(newFlags)); // was not static and became static or was static and became not static - accessRestricted = MakeUtil.isMoreAccessible(oldFlags, newFlags); - becameAbstract = !ClsUtil.isAbstract(oldFlags) && ClsUtil.isAbstract(newFlags); - - final ConstantValue oldDefault = oldMethod.getAnnotationDefault(); - final ConstantValue newDefault = newMethod.getAnnotationDefault(); - removedAnnotationDefault = (oldDefault != null && !ConstantValue.EMPTY_CONSTANT_VALUE.equals(oldDefault)) && (newDefault == null || ConstantValue.EMPTY_CONSTANT_VALUE.equals(newDefault)); - } - - public boolean isChanged() { - return returnTypeDescriptorChanged || throwsListChanged || flagsChanged || returnTypeGenericSignatureChanged || paramsGenericSignatureChanged || removedAnnotationDefault; - } -} diff --git a/java/compiler/impl/src/com/intellij/compiler/make/RetentionPolicies.java b/java/compiler/impl/src/com/intellij/compiler/make/RetentionPolicies.java deleted file mode 100644 index 13cfaa5dba11..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/make/RetentionPolicies.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.compiler.make; - -import org.jetbrains.annotations.NonNls; - -/** - * @author Eugene Zhuravlev - * Date: Apr 7, 2004 - */ -public interface RetentionPolicies { - /** - * Annotations are to be discarded by the compiler. - */ - int SOURCE = 0x1; - - @NonNls String SOURCE_STR = "SOURCE"; - - /** - * Annotations are to be recorded in the class file by the compiler - * but need not be retained by the VM at run time. This is the default - * behavior. - */ - int CLASS = 0x2; - - @NonNls String CLASS_STR = "CLASS"; - - /** - * Annotations are to be recorded in the class file by the compiler and - * retained by the VM at run time, so they may be read reflectively. - */ - int RUNTIME = 0x4; - - @NonNls String RUNTIME_STR = "RUNTIME"; - - int ALL = SOURCE | CLASS | RUNTIME; -} diff --git a/java/compiler/impl/src/com/intellij/compiler/make/SourceFileFinder.java b/java/compiler/impl/src/com/intellij/compiler/make/SourceFileFinder.java deleted file mode 100644 index 1e17b86f7d34..000000000000 --- a/java/compiler/impl/src/com/intellij/compiler/make/SourceFileFinder.java +++ /dev/null @@ -1,122 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.compiler.make; - -import com.intellij.compiler.CompilerConfiguration; -import com.intellij.openapi.application.ApplicationManager; -import com.intellij.openapi.compiler.CompileContext; -import com.intellij.openapi.module.Module; -import com.intellij.openapi.module.ModuleManager; -import com.intellij.openapi.project.Project; -import com.intellij.openapi.roots.ProjectFileIndex; -import com.intellij.openapi.roots.ProjectRootManager; -import com.intellij.openapi.util.io.FileUtil; -import com.intellij.openapi.util.text.StringUtil; -import com.intellij.openapi.vfs.LocalFileSystem; -import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.psi.JavaPsiFacade; -import com.intellij.psi.PsiClass; -import com.intellij.psi.PsiFile; -import com.intellij.psi.search.GlobalSearchScope; -import com.intellij.util.containers.HashMap; - -import java.util.Map; - -/** - * Assumes that source roots in the project has not changed and caches the snapshot of source roots for effective searching - * User: JEKA - * Date: Jul 17, 2003 - * Time: 9:52:26 PM - */ -public class SourceFileFinder { - private final Project myProject; - private final CompileContext myCompileContext; - private Map myProjectSourceRoots = null; - private final CompilerConfiguration myCompilerConfiguration; - - public SourceFileFinder(Project project, CompileContext compileContext) { - myProject = project; - myCompileContext = compileContext; - myCompilerConfiguration = CompilerConfiguration.getInstance(project); - } - - public VirtualFile findSourceFile(String qualifiedName, final String srcName, boolean checkIfExcludedFromMake) { - // optimization - final int dollar = qualifiedName.indexOf('$'); - final String outerQName = (dollar >= 0)? qualifiedName.substring(0, dollar) : qualifiedName; - final PsiClass[] classes = JavaPsiFacade.getInstance(myProject).findClasses(outerQName, GlobalSearchScope.projectScope(myProject)); - for (PsiClass aClass : classes) { - final PsiFile file = aClass.getContainingFile(); - if (srcName.equals(file.getName())) { - final VirtualFile vFile = file.getVirtualFile(); - if (vFile != null && (!checkIfExcludedFromMake || !myCompilerConfiguration.isExcludedFromCompilation(vFile))) { - return vFile; - } - } - } - - String relativePath = MakeUtil.createRelativePathToSource(qualifiedName, srcName); - Map dirs = getAllSourceRoots(); - if (!StringUtil.startsWithChar(relativePath, '/')) { - relativePath = "/" + relativePath; - } - LocalFileSystem fs = LocalFileSystem.getInstance(); - for (final VirtualFile virtualFile : dirs.keySet()) { - final String prefix = dirs.get(virtualFile); - String path; - if (prefix.length() > 0) { - if (FileUtil.startsWith(relativePath, prefix)) { - // if there is package prefix assigned to the root, the relative path should be corrected - path = virtualFile.getPath() + relativePath.substring(prefix.length() - 1); - } - else { - // if there is package prefix, but the relative path does not match it, skip the root - continue; - } - } - else { - path = virtualFile.getPath() + relativePath; - } - VirtualFile file = fs.findFileByPath(path); - if (file != null && (!checkIfExcludedFromMake || !myCompilerConfiguration.isExcludedFromCompilation(virtualFile))) { - return file; - } - } - return null; - } - - private Map getAllSourceRoots() { - if (myProjectSourceRoots == null) { - myProjectSourceRoots = new HashMap(); - ApplicationManager.getApplication().runReadAction(new Runnable() { - public void run() { - final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(myProject).getFileIndex(); - final Module[] allModules = ModuleManager.getInstance(myProject).getModules(); - for (Module allModule : allModules) { - final VirtualFile[] sourceRoots = myCompileContext.getSourceRoots(allModule); - for (final VirtualFile sourceRoot : sourceRoots) { - String packageName = fileIndex.getPackageNameByDirectory(sourceRoot); - myProjectSourceRoots - .put(sourceRoot, packageName == null || packageName.length() == 0 ? "" : "/" + packageName.replace('.', '/') + "/"); - } - } - } - }); - } - return myProjectSourceRoots; - } - -} diff --git a/java/compiler/impl/src/com/intellij/compiler/options/JavaCompilersTab.java b/java/compiler/impl/src/com/intellij/compiler/options/JavaCompilersTab.java index 09adabaa075b..d90a48f2cb7f 100644 --- a/java/compiler/impl/src/com/intellij/compiler/options/JavaCompilersTab.java +++ b/java/compiler/impl/src/com/intellij/compiler/options/JavaCompilersTab.java @@ -46,20 +46,13 @@ public class JavaCompilersTab implements SearchableConfigurable, Configurable.No private JPanel myTargetOptionsPanel; private final CardLayout myCardLayout; - private final Project myProject; private final BackendCompiler myDefaultCompiler; private BackendCompiler mySelectedCompiler; private final CompilerConfigurationImpl myCompilerConfiguration; private final Collection myConfigurables; private final TargetOptionsComponent myTargetLevelComponent; - public JavaCompilersTab(final Project project) { - this(project, ((CompilerConfigurationImpl)CompilerConfiguration.getInstance(project)).getRegisteredJavaCompilers(), - ((CompilerConfigurationImpl)CompilerConfiguration.getInstance(project)).getDefaultCompiler()); - } - public JavaCompilersTab(final Project project, Collection compilers, BackendCompiler defaultCompiler) { - myProject = project; myDefaultCompiler = defaultCompiler; myCompilerConfiguration = (CompilerConfigurationImpl)CompilerConfiguration.getInstance(project); myConfigurables = new ArrayList(compilers.size()); diff --git a/java/compiler/impl/src/com/intellij/compiler/server/BuildManager.java b/java/compiler/impl/src/com/intellij/compiler/server/BuildManager.java index 50227a71b35f..a2404e863a6e 100644 --- a/java/compiler/impl/src/com/intellij/compiler/server/BuildManager.java +++ b/java/compiler/impl/src/com/intellij/compiler/server/BuildManager.java @@ -101,7 +101,8 @@ import org.jetbrains.jps.cmdline.ClasspathBootstrap; import org.jetbrains.jps.incremental.Utils; import org.jetbrains.jps.model.serialization.JpsGlobalLoader; -import javax.tools.*; +import javax.tools.JavaCompiler; +import javax.tools.ToolProvider; import java.awt.*; import java.io.File; import java.io.IOException; @@ -457,7 +458,7 @@ public class BuildManager implements ApplicationComponent{ return false; } final CompilerWorkspaceConfiguration config = CompilerWorkspaceConfiguration.getInstance(project); - if (!config.useOutOfProcessBuild() || !config.MAKE_PROJECT_ON_SAVE) { + if (!config.MAKE_PROJECT_ON_SAVE) { return false; } if (!config.allowAutoMakeWhileRunningApplication() && hasRunningProcess(project)) { diff --git a/java/compiler/impl/src/com/intellij/openapi/compiler/ex/CompileContextEx.java b/java/compiler/impl/src/com/intellij/openapi/compiler/ex/CompileContextEx.java index 8f8f4e35b89f..6251b56c5b21 100644 --- a/java/compiler/impl/src/com/intellij/openapi/compiler/ex/CompileContextEx.java +++ b/java/compiler/impl/src/com/intellij/openapi/compiler/ex/CompileContextEx.java @@ -15,29 +15,16 @@ */ package com.intellij.openapi.compiler.ex; -import com.intellij.compiler.make.DependencyCache; import com.intellij.openapi.compiler.CompileContext; import com.intellij.openapi.compiler.CompileScope; import com.intellij.openapi.compiler.CompilerMessage; -import com.intellij.openapi.module.Module; import com.intellij.openapi.vfs.VirtualFile; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.util.Collection; -import java.util.Set; public interface CompileContextEx extends CompileContext { - DependencyCache getDependencyCache(); - - @Nullable - VirtualFile getSourceFileByOutputFile(VirtualFile outputFile); void addMessage(CompilerMessage message); - @NotNull - Set getTestOutputDirectories(); - /** * the same as FileIndex.isInTestSourceContent(), but takes into account generated output dirs */ @@ -47,13 +34,4 @@ public interface CompileContextEx extends CompileContext { void addScope(CompileScope additionalScope); - long getStartCompilationStamp(); - - void recalculateOutputDirs(); - - void markGenerated(Collection files); - - boolean isGenerated(VirtualFile file); - - void assignModule(@NotNull VirtualFile root, @NotNull Module module, boolean isTestSource, @Nullable com.intellij.openapi.compiler.Compiler compiler); } diff --git a/java/compiler/impl/src/com/intellij/openapi/compiler/generic/GenericCompiler.java b/java/compiler/impl/src/com/intellij/openapi/compiler/generic/GenericCompiler.java index 87136283737b..3a81718443bf 100644 --- a/java/compiler/impl/src/com/intellij/openapi/compiler/generic/GenericCompiler.java +++ b/java/compiler/impl/src/com/intellij/openapi/compiler/generic/GenericCompiler.java @@ -69,7 +69,7 @@ public abstract class GenericCompiler implements return myOrderPlace; } - public static enum CompileOrderPlace { + public enum CompileOrderPlace { CLASS_INSTRUMENTING, CLASS_POST_PROCESSING, PACKAGING, VALIDATING } diff --git a/java/compiler/impl/src/com/intellij/openapi/deployment/DeploymentUtilImpl.java b/java/compiler/impl/src/com/intellij/openapi/deployment/DeploymentUtilImpl.java index d36d28f10058..773493c8ded0 100644 --- a/java/compiler/impl/src/com/intellij/openapi/deployment/DeploymentUtilImpl.java +++ b/java/compiler/impl/src/com/intellij/openapi/deployment/DeploymentUtilImpl.java @@ -15,11 +15,9 @@ */ package com.intellij.openapi.deployment; -import com.intellij.compiler.impl.packagingCompiler.BuildRecipeImpl; import com.intellij.openapi.compiler.CompileContext; import com.intellij.openapi.compiler.CompilerBundle; import com.intellij.openapi.compiler.CompilerMessageCategory; -import com.intellij.openapi.compiler.make.BuildRecipe; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleType; @@ -119,14 +117,6 @@ public class DeploymentUtilImpl extends DeploymentUtil { FileUtil.toSystemDependentName(toFile.getPath())); } - public final boolean addItemsRecursively(@NotNull BuildRecipe items, @NotNull File root, String outputRelativePath) { - if (outputRelativePath == null) outputRelativePath = ""; - outputRelativePath = trimForwardSlashes(outputRelativePath); - - items.addFileCopyInstruction(root, true, outputRelativePath); - return true; - } - public void reportDeploymentDescriptorDoesNotExists(ConfigFile descriptor, CompileContext context, Module module) { final String description = ModuleType.get(module).getName() + " '" + module.getName() + '\''; String descriptorPath = VfsUtil.urlToPath(descriptor.getUrl()); @@ -150,10 +140,6 @@ public class DeploymentUtilImpl extends DeploymentUtil { } } - public BuildRecipe createBuildRecipe() { - return new BuildRecipeImpl(); - } - @Nullable public String getConfigFileErrorMessage(final ConfigFile configFile) { if (configFile.getVirtualFile() == null) { diff --git a/java/compiler/impl/src/com/intellij/packaging/impl/compiler/ArtifactAdditionalCompileScopeProvider.java b/java/compiler/impl/src/com/intellij/packaging/impl/compiler/ArtifactAdditionalCompileScopeProvider.java deleted file mode 100644 index ceb8bb47b490..000000000000 --- a/java/compiler/impl/src/com/intellij/packaging/impl/compiler/ArtifactAdditionalCompileScopeProvider.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.packaging.impl.compiler; - -import com.intellij.compiler.impl.AdditionalCompileScopeProvider; -import com.intellij.openapi.application.ReadAction; -import com.intellij.openapi.application.Result; -import com.intellij.openapi.compiler.CompileScope; -import com.intellij.openapi.compiler.CompilerFilter; -import com.intellij.openapi.project.Project; -import com.intellij.packaging.artifacts.Artifact; -import org.jetbrains.annotations.NotNull; - -import java.util.Set; - -/** - * @author nik - */ -public class ArtifactAdditionalCompileScopeProvider extends AdditionalCompileScopeProvider { - @Override - public CompileScope getAdditionalScope(@NotNull final CompileScope baseScope, @NotNull CompilerFilter filter, @NotNull final Project project) { - if (ArtifactCompileScope.getArtifacts(baseScope) != null) { - return null; - } - final ArtifactsCompiler compiler = ArtifactsCompiler.getInstance(project); - if (compiler == null || !filter.acceptCompiler(compiler)) { - return null; - } - return new ReadAction() { - protected void run(final Result result) { - final Set artifacts = ArtifactCompileScope.getArtifactsToBuild(project, baseScope, false); - result.setResult(ArtifactCompileScope.createScopeForModulesInArtifacts(project, artifacts)); - } - }.execute().getResultObject(); - } -} diff --git a/java/compiler/impl/src/com/intellij/packaging/impl/compiler/ArtifactsCompiler.java b/java/compiler/impl/src/com/intellij/packaging/impl/compiler/ArtifactsCompiler.java index 9875816045ea..8cb3d1938780 100644 --- a/java/compiler/impl/src/com/intellij/packaging/impl/compiler/ArtifactsCompiler.java +++ b/java/compiler/impl/src/com/intellij/packaging/impl/compiler/ArtifactsCompiler.java @@ -16,16 +16,12 @@ package com.intellij.packaging.impl.compiler; import com.intellij.openapi.compiler.CompileContext; +import com.intellij.openapi.compiler.CompileScope; +import com.intellij.openapi.compiler.Compiler; import com.intellij.openapi.compiler.CompilerManager; -import com.intellij.openapi.compiler.generic.CompileItem; -import com.intellij.openapi.compiler.generic.GenericCompiler; -import com.intellij.openapi.compiler.generic.GenericCompilerInstance; -import com.intellij.openapi.compiler.generic.VirtualFilePersistentState; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Key; import com.intellij.packaging.artifacts.Artifact; -import com.intellij.util.io.DataExternalizer; -import com.intellij.util.io.KeyDescriptor; import gnu.trove.THashSet; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -35,12 +31,15 @@ import java.util.Set; /** * @author nik */ -public class ArtifactsCompiler extends GenericCompiler { +public class ArtifactsCompiler implements Compiler { private static final Key> WRITTEN_PATHS_KEY = Key.create("artifacts_written_paths"); private static final Key> CHANGED_ARTIFACTS = Key.create("affected_artifacts"); public ArtifactsCompiler() { - super("artifacts_compiler", 0, GenericCompiler.CompileOrderPlace.PACKAGING); + } + + public boolean validateConfiguration(CompileScope scope) { + return false; } @Nullable @@ -67,31 +66,6 @@ public class ArtifactsCompiler extends GenericCompiler getItemKeyDescriptor() { - return STRING_KEY_DESCRIPTOR; - } - - @NotNull - @Override - public DataExternalizer getSourceStateExternalizer() { - return VirtualFilePersistentState.EXTERNALIZER; - } - - @NotNull - @Override - public DataExternalizer getOutputStateExternalizer() { - return new ArtifactPackagingItemExternalizer(); - } - - @NotNull - @Override - public GenericCompilerInstance, String, VirtualFilePersistentState, ArtifactPackagingItemOutputState> createInstance( - @NotNull CompileContext context) { - return new ArtifactsCompilerInstance(context); - } - @NotNull public String getDescription() { return "Artifacts Packaging Compiler"; diff --git a/java/compiler/impl/src/com/intellij/packaging/impl/compiler/ArtifactsCompilerInstance.java b/java/compiler/impl/src/com/intellij/packaging/impl/compiler/ArtifactsCompilerInstance.java deleted file mode 100644 index d0c7c233a3f3..000000000000 --- a/java/compiler/impl/src/com/intellij/packaging/impl/compiler/ArtifactsCompilerInstance.java +++ /dev/null @@ -1,425 +0,0 @@ -/* - * 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.packaging.impl.compiler; - -import com.intellij.compiler.CompilerManagerImpl; -import com.intellij.compiler.impl.CompilerUtil; -import com.intellij.compiler.impl.packagingCompiler.*; -import com.intellij.openapi.application.ApplicationManager; -import com.intellij.openapi.application.ReadAction; -import com.intellij.openapi.application.Result; -import com.intellij.openapi.compiler.CompileContext; -import com.intellij.openapi.compiler.CompilerBundle; -import com.intellij.openapi.compiler.CompilerMessageCategory; -import com.intellij.openapi.compiler.generic.GenericCompilerCacheState; -import com.intellij.openapi.compiler.generic.GenericCompilerInstance; -import com.intellij.openapi.compiler.generic.GenericCompilerProcessingItem; -import com.intellij.openapi.compiler.generic.VirtualFilePersistentState; -import com.intellij.openapi.compiler.make.BuildParticipant; -import com.intellij.openapi.compiler.make.BuildParticipantProvider; -import com.intellij.openapi.deployment.DeploymentUtil; -import com.intellij.openapi.diagnostic.Logger; -import com.intellij.openapi.module.Module; -import com.intellij.openapi.module.ModuleManager; -import com.intellij.openapi.progress.ProcessCanceledException; -import com.intellij.openapi.project.DumbService; -import com.intellij.openapi.util.Pair; -import com.intellij.openapi.util.Ref; -import com.intellij.openapi.util.io.FileUtil; -import com.intellij.openapi.vfs.*; -import com.intellij.packaging.artifacts.Artifact; -import com.intellij.packaging.artifacts.ArtifactManager; -import com.intellij.packaging.artifacts.ArtifactProperties; -import com.intellij.packaging.artifacts.ArtifactPropertiesProvider; -import com.intellij.packaging.elements.CompositePackagingElement; -import com.intellij.packaging.elements.PackagingElementResolvingContext; -import com.intellij.packaging.impl.artifacts.ArtifactSortingUtil; -import com.intellij.util.ThrowableRunnable; -import com.intellij.util.containers.ContainerUtil; -import gnu.trove.THashSet; -import org.jetbrains.annotations.NotNull; - -import java.io.*; -import java.util.*; - -/** - * @author nik - */ -public class ArtifactsCompilerInstance extends GenericCompilerInstance { - private static final Logger LOG = Logger.getInstance("#com.intellij.packaging.impl.compiler.ArtifactsCompilerInstance"); - public static final Logger FULL_LOG = Logger.getInstance("#com.intellij.full-artifacts-compiler-log"); - private ArtifactsProcessingItemsBuilderContext myBuilderContext; - - public ArtifactsCompilerInstance(CompileContext context) { - super(context); - } - - @NotNull - @Override - public List getAllTargets() { - return getArtifactTargets(false); - } - - @NotNull - @Override - public List getSelectedTargets() { - return getArtifactTargets(true); - } - - private List getArtifactTargets(final boolean selectedOnly) { - final List targets = new ArrayList(); - new ReadAction() { - protected void run(final Result result) { - final Set artifacts; - if (selectedOnly) { - artifacts = ArtifactCompileScope.getArtifactsToBuild(getProject(), myContext.getCompileScope(), true); - } - else { - artifacts = new HashSet(Arrays.asList(ArtifactManager.getInstance(getProject()).getArtifacts())); - } - - Map artifactsMap = new HashMap(); - for (Artifact artifact : artifacts) { - artifactsMap.put(artifact.getName(), artifact); - } - for (String name : ArtifactSortingUtil.getInstance(getProject()).getArtifactsSortedByInclusion()) { - Artifact artifact = artifactsMap.get(name); - if (artifact != null) { - targets.add(new ArtifactBuildTarget(artifact)); - } - } - - for (BuildParticipantProvider provider : BuildParticipantProvider.EXTENSION_POINT_NAME.getExtensions()) { - for (Module module : ModuleManager.getInstance(getProject()).getModules()) { - final Collection participants = provider.getParticipants(module); - for (BuildParticipant participant : participants) { - Artifact artifact = participant.createArtifact(myContext); - if (artifact != null) { - LOG.debug("additional artifact to build: " + artifact); - targets.add(new ArtifactBuildTarget(artifact)); - } - } - } - } - } - }.execute(); - return targets; - } - - @Override - public void processObsoleteTarget(@NotNull String targetId, - @NotNull List> obsoleteItems) { - deleteFiles(obsoleteItems, Collections.>emptyList()); - } - - @NotNull - @Override - public List getItems(@NotNull ArtifactBuildTarget target) { - myBuilderContext = new ArtifactsProcessingItemsBuilderContext(myContext); - final Artifact artifact = target.getArtifact(); - - final Map selfIncludingArtifacts = new ReadAction>() { - protected void run(final Result> result) { - result.setResult(ArtifactSortingUtil.getInstance(getProject()).getArtifactToSelfIncludingNameMap()); - } - }.execute().getResultObject(); - final String selfIncludingName = selfIncludingArtifacts.get(artifact.getName()); - if (selfIncludingName != null) { - String name = selfIncludingName.equals(artifact.getName()) ? "it" : "'" + selfIncludingName + "' artifact"; - myContext.addMessage(CompilerMessageCategory.ERROR, "Cannot build '" + artifact.getName() + "' artifact: " + name + " includes itself in the output layout", null, -1, -1); - return Collections.emptyList(); - } - - final String outputPath = artifact.getOutputPath(); - if (outputPath == null || outputPath.length() == 0) { - myContext.addMessage(CompilerMessageCategory.ERROR, "Cannot build '" + artifact.getName() + "' artifact: output path is not specified", - null, -1, -1); - return Collections.emptyList(); - } - - DumbService.getInstance(getProject()).runReadActionInSmartMode(new Runnable() { - @Override - public void run() { - collectItems(artifact, outputPath); - } - }); - return new ArrayList(myBuilderContext.getProcessingItems()); - } - - private void collectItems(@NotNull Artifact artifact, @NotNull String outputPath) { - final CompositePackagingElement rootElement = artifact.getRootElement(); - final VirtualFile outputFile = LocalFileSystem.getInstance().findFileByPath(outputPath); - final CopyToDirectoryInstructionCreator instructionCreator = new CopyToDirectoryInstructionCreator(myBuilderContext, outputPath, outputFile); - final PackagingElementResolvingContext resolvingContext = ArtifactManager.getInstance(getProject()).getResolvingContext(); - FULL_LOG.debug("Collecting items for " + artifact.getName()); - rootElement.computeIncrementalCompilerInstructions(instructionCreator, resolvingContext, myBuilderContext, artifact.getArtifactType()); - } - - private boolean doBuild(@NotNull Artifact artifact, - final List> changedItems, - final Set processedItems, - final @NotNull Set writtenPaths, - final Set deletedJars) { - FULL_LOG.debug("Building " + artifact.getName()); - final boolean testMode = ApplicationManager.getApplication().isUnitTestMode(); - - final DeploymentUtil deploymentUtil = DeploymentUtil.getInstance(); - final FileFilter fileFilter = new IgnoredFileFilter(); - final Set changedJars = new THashSet(); - for (String deletedJar : deletedJars) { - ContainerUtil.addIfNotNull(myBuilderContext.getJarInfo(deletedJar), changedJars); - } - - try { - onBuildStartedOrFinished(artifact, false); - if (myContext.getMessageCount(CompilerMessageCategory.ERROR) > 0) { - return false; - } - - int i = 0; - for (final GenericCompilerProcessingItem item : changedItems) { - final ArtifactCompilerCompileItem sourceItem = item.getItem(); - myContext.getProgressIndicator().checkCanceled(); - - final Ref exception = Ref.create(null); - new ReadAction() { - protected void run(final Result result) { - final VirtualFile sourceFile = sourceItem.getFile(); - for (DestinationInfo destination : sourceItem.getDestinations()) { - if (destination instanceof ExplodedDestinationInfo) { - final ExplodedDestinationInfo explodedDestination = (ExplodedDestinationInfo)destination; - File toFile = new File(FileUtil.toSystemDependentName(explodedDestination.getOutputPath())); - try { - if (sourceFile.isInLocalFileSystem()) { - final File ioFromFile = VfsUtilCore.virtualToIoFile(sourceFile); - if (ioFromFile.exists()) { - deploymentUtil.copyFile(ioFromFile, toFile, myContext, writtenPaths, fileFilter); - } - else { - LOG.debug("Cannot copy " + ioFromFile.getAbsolutePath() + ": file doesn't exist"); - } - } - else { - extractFile(sourceFile, toFile, writtenPaths, fileFilter); - } - } - catch (IOException e) { - exception.set(e); - return; - } - } - else { - changedJars.add(((JarDestinationInfo)destination).getJarInfo()); - } - } - } - }.execute(); - if (exception.get() != null) { - throw exception.get(); - } - - myContext.getProgressIndicator().setFraction(++i * 1.0 / changedItems.size()); - processedItems.add(sourceItem); - if (testMode) { - CompilerManagerImpl.addRecompiledPath(FileUtil.toSystemDependentName(sourceItem.getFile().getPath())); - } - } - - JarsBuilder builder = new JarsBuilder(changedJars, fileFilter, myContext); - final boolean processed = builder.buildJars(writtenPaths); - if (!processed) { - return false; - } - - Set recompiledSources = new HashSet(); - for (JarInfo info : builder.getJarsToBuild()) { - for (Pair pair : info.getPackedFiles()) { - recompiledSources.add(pair.getSecond()); - } - } - for (VirtualFile source : recompiledSources) { - ArtifactCompilerCompileItem item = myBuilderContext.getItemBySource(source); - LOG.assertTrue(item != null, source); - processedItems.add(item); - if (testMode) { - CompilerManagerImpl.addRecompiledPath(FileUtil.toSystemDependentName(item.getFile().getPath())); - } - } - - onBuildStartedOrFinished(artifact, true); - } - catch (ProcessCanceledException e) { - throw e; - } - catch (Exception e) { - LOG.info(e); - myContext.addMessage(CompilerMessageCategory.ERROR, e.getLocalizedMessage(), null, -1, -1); - return false; - } - return true; - } - - private void extractFile(VirtualFile sourceFile, File toFile, Set writtenPaths, FileFilter fileFilter) throws IOException { - if (!writtenPaths.add(toFile.getPath())) { - return; - } - - if (!FileUtil.createParentDirs(toFile)) { - myContext.addMessage(CompilerMessageCategory.ERROR, "Cannot create directory for '" + toFile.getAbsolutePath() + "' file", null, -1, -1); - return; - } - - final BufferedInputStream input = ArtifactCompilerUtil.getJarEntryInputStream(sourceFile, myContext); - if (input == null) return; - final BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(toFile)); - try { - FileUtil.copy(input, output); - } - finally { - input.close(); - output.close(); - } - } - - private void onBuildStartedOrFinished(@NotNull Artifact artifact, final boolean finished) throws Exception { - for (ArtifactPropertiesProvider provider : artifact.getPropertiesProviders()) { - final ArtifactProperties properties = artifact.getProperties(provider); - if (finished) { - properties.onBuildFinished(artifact, myContext); - } - else { - properties.onBuildStarted(artifact, myContext); - } - } - } - - private static THashSet createPathsHashSet() { - return new THashSet(FileUtil.PATH_HASHING_STRATEGY); - } - - @Override - public void processItems(@NotNull final ArtifactBuildTarget target, - @NotNull final List> changedItems, - @NotNull List> obsoleteItems, - @NotNull OutputConsumer consumer) { - - final THashSet deletedJars = deleteFiles(obsoleteItems, changedItems); - - final Set writtenPaths = createPathsHashSet(); - final Ref built = Ref.create(false); - final Set processedItems = new HashSet(); - CompilerUtil.runInContext(myContext, "Copying files", new ThrowableRunnable() { - public void run() throws RuntimeException { - built.set(doBuild(target.getArtifact(), changedItems, processedItems, writtenPaths, deletedJars)); - } - }); - if (!built.get()) { - return; - } - - myContext.getProgressIndicator().setText(CompilerBundle.message("packaging.compiler.message.updating.caches")); - myContext.getProgressIndicator().setText2(""); - for (String path : writtenPaths) { - consumer.addFileToRefresh(new File(path)); - } - for (ArtifactCompilerCompileItem item : processedItems) { - consumer.addProcessedItem(item); - } - ArtifactsCompiler.addWrittenPaths(myContext, writtenPaths); - ArtifactsCompiler.addChangedArtifact(myContext, target.getArtifact()); - } - - private THashSet deleteFiles(List> obsoleteItems, - List> changedItems) { - myContext.getProgressIndicator().setText(CompilerBundle.message("packaging.compiler.message.deleting.outdated.files")); - - final boolean testMode = ApplicationManager.getApplication().isUnitTestMode(); - final THashSet deletedJars = new THashSet(); - final THashSet notDeletedJars = new THashSet(); - if (LOG.isDebugEnabled()) { - LOG.debug("Deleting outdated files..."); - } - - Set pathToDelete = new THashSet(); - for (GenericCompilerProcessingItem item : changedItems) { - final ArtifactPackagingItemOutputState cached = item.getCachedOutputState(); - if (cached != null) { - for (Pair destination : cached.myDestinations) { - pathToDelete.add(destination.getFirst()); - } - } - } - for (GenericCompilerProcessingItem item : changedItems) { - for (DestinationInfo destination : item.getItem().getDestinations()) { - pathToDelete.remove(destination.getOutputPath()); - } - } - for (GenericCompilerCacheState item : obsoleteItems) { - for (Pair destination : item.getOutputState().myDestinations) { - pathToDelete.add(destination.getFirst()); - } - } - - int notDeletedFilesCount = 0; - List filesToRefresh = new ArrayList(); - - for (String fullPath : pathToDelete) { - int end = fullPath.indexOf(JarFileSystem.JAR_SEPARATOR); - boolean isJar = end != -1; - String filePath = isJar ? fullPath.substring(0, end) : fullPath; - boolean deleted = false; - if (isJar) { - if (notDeletedJars.contains(filePath)) { - continue; - } - deleted = deletedJars.contains(filePath); - } - - File file = new File(FileUtil.toSystemDependentName(filePath)); - if (!deleted) { - filesToRefresh.add(file); - deleted = FileUtil.delete(file); - } - - if (deleted) { - if (isJar) { - deletedJars.add(filePath); - } - if (testMode) { - CompilerManagerImpl.addDeletedPath(file.getAbsolutePath()); - } - } - else { - if (isJar) { - notDeletedJars.add(filePath); - } - if (notDeletedFilesCount++ > 50) { - myContext.addMessage(CompilerMessageCategory.WARNING, "Deletion of outdated files stopped because too many files cannot be deleted", null, -1, -1); - break; - } - myContext.addMessage(CompilerMessageCategory.WARNING, "Cannot delete file '" + filePath + "'", null, -1, -1); - if (LOG.isDebugEnabled()) { - LOG.debug("Cannot delete file " + file); - } - } - } - - CompilerUtil.refreshIOFiles(filesToRefresh); - return deletedJars; - } - -} diff --git a/java/compiler/impl/src/com/intellij/packaging/impl/compiler/ArtifactsProcessingItemsBuilderContext.java b/java/compiler/impl/src/com/intellij/packaging/impl/compiler/ArtifactsProcessingItemsBuilderContext.java deleted file mode 100644 index a96663c96294..000000000000 --- a/java/compiler/impl/src/com/intellij/packaging/impl/compiler/ArtifactsProcessingItemsBuilderContext.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Copyright 2000-2010 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.packaging.impl.compiler; - -import com.intellij.compiler.impl.packagingCompiler.DestinationInfo; -import com.intellij.compiler.impl.packagingCompiler.ExplodedDestinationInfo; -import com.intellij.compiler.impl.packagingCompiler.JarInfo; -import com.intellij.openapi.compiler.CompileContext; -import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.packaging.elements.ArtifactIncrementalCompilerContext; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; - -/** - * @author nik - */ -public class ArtifactsProcessingItemsBuilderContext implements ArtifactIncrementalCompilerContext { - protected final Map myItemsBySource; - private final Map mySourceByOutput; - private final Map myJarByPath; - private final CompileContext myCompileContext; - private final boolean myPrintToLog; - - public ArtifactsProcessingItemsBuilderContext(CompileContext compileContext) { - myCompileContext = compileContext; - myItemsBySource = new HashMap(); - mySourceByOutput = new HashMap(); - myJarByPath = new HashMap(); - myPrintToLog = ArtifactsCompilerInstance.FULL_LOG.isDebugEnabled(); - } - - public boolean addDestination(@NotNull VirtualFile sourceFile, @NotNull DestinationInfo destinationInfo) { - if (destinationInfo instanceof ExplodedDestinationInfo && sourceFile.equals(destinationInfo.getOutputFile())) { - return false; - } - - if (checkOutputPath(destinationInfo.getOutputPath(), sourceFile)) { - if (myPrintToLog) { - ArtifactsCompilerInstance.FULL_LOG.debug(" " + sourceFile.getPath() + " -> " + destinationInfo); - } - getOrCreateProcessingItem(sourceFile).addDestination(destinationInfo); - return true; - } - return false; - } - - public Collection getProcessingItems() { - return myItemsBySource.values(); - } - - public boolean checkOutputPath(final String outputPath, final VirtualFile sourceFile) { - VirtualFile old = mySourceByOutput.get(outputPath); - if (old == null) { - mySourceByOutput.put(outputPath, sourceFile); - return true; - } - //todo[nik] show warning? - return false; - } - - public ArtifactCompilerCompileItem getItemBySource(VirtualFile source) { - return myItemsBySource.get(source); - } - - public boolean registerJarFile(@NotNull JarInfo jarInfo, @NotNull String outputPath) { - if (mySourceByOutput.containsKey(outputPath) || myJarByPath.containsKey(outputPath)) { - return false; - } - myJarByPath.put(outputPath, jarInfo); - return true; - } - - @Nullable - public JarInfo getJarInfo(String outputPath) { - return myJarByPath.get(outputPath); - } - - @Nullable - public VirtualFile getSourceByOutput(String outputPath) { - return mySourceByOutput.get(outputPath); - } - - public CompileContext getCompileContext() { - return myCompileContext; - } - - public ArtifactCompilerCompileItem getOrCreateProcessingItem(VirtualFile sourceFile) { - ArtifactCompilerCompileItem item = myItemsBySource.get(sourceFile); - if (item == null) { - item = new ArtifactCompilerCompileItem(sourceFile); - myItemsBySource.put(sourceFile, item); - } - return item; - } -} diff --git a/java/compiler/impl/src/com/intellij/packaging/impl/compiler/CopyToDirectoryInstructionCreator.java b/java/compiler/impl/src/com/intellij/packaging/impl/compiler/CopyToDirectoryInstructionCreator.java deleted file mode 100644 index 3043468e1f44..000000000000 --- a/java/compiler/impl/src/com/intellij/packaging/impl/compiler/CopyToDirectoryInstructionCreator.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.packaging.impl.compiler; - -import com.intellij.compiler.impl.packagingCompiler.ExplodedDestinationInfo; -import com.intellij.compiler.impl.packagingCompiler.JarInfo; -import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.packaging.elements.IncrementalCompilerInstructionCreator; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * @author nik - */ -public class CopyToDirectoryInstructionCreator extends IncrementalCompilerInstructionCreatorBase { - private final String myOutputPath; - private final @Nullable VirtualFile myOutputFile; - - public CopyToDirectoryInstructionCreator(ArtifactsProcessingItemsBuilderContext context, String outputPath, - @Nullable VirtualFile outputFile) { - super(context); - myOutputPath = outputPath; - myOutputFile = outputFile; - } - - public void addFileCopyInstruction(@NotNull VirtualFile file, @NotNull String outputFileName) { - myContext.addDestination(file, new ExplodedDestinationInfo(myOutputPath + "/" + outputFileName, outputChild(outputFileName))); - } - - public CopyToDirectoryInstructionCreator subFolder(@NotNull String directoryName) { - return new CopyToDirectoryInstructionCreator(myContext, myOutputPath + "/" + directoryName, outputChild(directoryName)); - } - - public IncrementalCompilerInstructionCreator archive(@NotNull String archiveFileName) { - String jarOutputPath = myOutputPath + "/" + archiveFileName; - final JarInfo jarInfo = new JarInfo(); - if (!myContext.registerJarFile(jarInfo, jarOutputPath)) { - return new SkipAllInstructionCreator(myContext); - } - VirtualFile outputFile = outputChild(archiveFileName); - final ExplodedDestinationInfo destination = new ExplodedDestinationInfo(jarOutputPath, outputFile); - jarInfo.addDestination(destination); - return new PackIntoArchiveInstructionCreator(myContext, jarInfo, "", destination); - } - - @Nullable - private VirtualFile outputChild(String name) { - return myOutputFile != null ? myOutputFile.findChild(name) : null; - } -} diff --git a/java/compiler/impl/src/com/intellij/packaging/impl/compiler/IncrementalCompilerInstructionCreatorBase.java b/java/compiler/impl/src/com/intellij/packaging/impl/compiler/IncrementalCompilerInstructionCreatorBase.java deleted file mode 100644 index 9837b9f37626..000000000000 --- a/java/compiler/impl/src/com/intellij/packaging/impl/compiler/IncrementalCompilerInstructionCreatorBase.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * 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.packaging.impl.compiler; - -import com.intellij.openapi.fileTypes.FileTypeManager; -import com.intellij.openapi.roots.ProjectFileIndex; -import com.intellij.openapi.roots.ProjectRootManager; -import com.intellij.openapi.util.text.StringUtil; -import com.intellij.openapi.vfs.VfsUtilCore; -import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.openapi.vfs.VirtualFileVisitor; -import com.intellij.packaging.elements.IncrementalCompilerInstructionCreator; -import com.intellij.packaging.elements.PackagingFileFilter; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.util.List; - -/** - * @author nik - */ -public abstract class IncrementalCompilerInstructionCreatorBase implements IncrementalCompilerInstructionCreator { - protected final ArtifactsProcessingItemsBuilderContext myContext; - - public IncrementalCompilerInstructionCreatorBase(ArtifactsProcessingItemsBuilderContext context) { - myContext = context; - } - - public void addDirectoryCopyInstructions(@NotNull VirtualFile directory) { - addDirectoryCopyInstructions(directory, null); - } - - public void addDirectoryCopyInstructions(@NotNull VirtualFile directory, @Nullable PackagingFileFilter filter) { - final ProjectFileIndex index = ProjectRootManager.getInstance(myContext.getCompileContext().getProject()).getFileIndex(); - final boolean copyExcluded = index.isIgnored(directory); - collectInstructionsRecursively(directory, this, filter, index, copyExcluded); - } - - private static void collectInstructionsRecursively(VirtualFile directory, - final IncrementalCompilerInstructionCreatorBase creator, - @Nullable final PackagingFileFilter filter, - final ProjectFileIndex index, - final boolean copyExcluded) { - final FileTypeManager fileTypeManager = FileTypeManager.getInstance(); - VfsUtilCore.visitChildrenRecursively(directory, new VirtualFileVisitor(VirtualFileVisitor.SKIP_ROOT) { - { setValueForChildren(creator); } - - @Override - public boolean visitFile(@NotNull VirtualFile child) { - if (copyExcluded) { - if (fileTypeManager.isFileIgnored(child)) return false; - } - else { - if (index.isIgnored(child)) return false; - } - - final IncrementalCompilerInstructionCreatorBase creator = getCurrentValue(); - if (filter != null && !filter.accept(child, creator.myContext.getCompileContext())) { - return false; - } - - if (!child.isDirectory()) { - creator.addFileCopyInstruction(child, child.getName()); - } - else { - setValueForChildren(creator.subFolder(child.getName())); - } - - return true; - } - }); - } - - @Override - public abstract IncrementalCompilerInstructionCreatorBase subFolder(@NotNull String directoryName); - - public IncrementalCompilerInstructionCreator subFolderByRelativePath(@NotNull String relativeDirectoryPath) { - final List folders = StringUtil.split(relativeDirectoryPath, "/"); - IncrementalCompilerInstructionCreator current = this; - for (String folder : folders) { - current = current.subFolder(folder); - } - return current; - } -} diff --git a/java/compiler/impl/src/com/intellij/packaging/impl/compiler/PackIntoArchiveInstructionCreator.java b/java/compiler/impl/src/com/intellij/packaging/impl/compiler/PackIntoArchiveInstructionCreator.java deleted file mode 100644 index c51b8e703e5b..000000000000 --- a/java/compiler/impl/src/com/intellij/packaging/impl/compiler/PackIntoArchiveInstructionCreator.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.packaging.impl.compiler; - -import com.intellij.compiler.impl.packagingCompiler.DestinationInfo; -import com.intellij.compiler.impl.packagingCompiler.JarDestinationInfo; -import com.intellij.compiler.impl.packagingCompiler.JarInfo; -import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.packaging.elements.IncrementalCompilerInstructionCreator; -import org.jetbrains.annotations.NotNull; - -/** - * @author nik - */ -public class PackIntoArchiveInstructionCreator extends IncrementalCompilerInstructionCreatorBase { - private final DestinationInfo myJarDestination; - private final JarInfo myJarInfo; - private final String myPathInJar; - - public PackIntoArchiveInstructionCreator(ArtifactsProcessingItemsBuilderContext context, JarInfo jarInfo, - String pathInJar, DestinationInfo jarDestination) { - super(context); - myJarInfo = jarInfo; - myPathInJar = pathInJar; - myJarDestination = jarDestination; - } - - public void addFileCopyInstruction(@NotNull VirtualFile file, @NotNull String outputFileName) { - final String pathInJar = childPathInJar(outputFileName); - if (myContext.addDestination(file, new JarDestinationInfo(pathInJar, myJarInfo, myJarDestination))) { - myJarInfo.addContent(pathInJar, file); - } - } - - private String childPathInJar(String fileName) { - return myPathInJar.length() == 0 ? fileName : myPathInJar + "/" + fileName; - } - - public PackIntoArchiveInstructionCreator subFolder(@NotNull String directoryName) { - return new PackIntoArchiveInstructionCreator(myContext, myJarInfo, childPathInJar(directoryName), myJarDestination); - } - - public IncrementalCompilerInstructionCreator archive(@NotNull String archiveFileName) { - final JarInfo jarInfo = new JarInfo(); - final String outputPath = myJarDestination.getOutputPath() + "/" + archiveFileName; - if (!myContext.registerJarFile(jarInfo, outputPath)) { - return new SkipAllInstructionCreator(myContext); - } - final JarDestinationInfo destination = new JarDestinationInfo(childPathInJar(archiveFileName), myJarInfo, myJarDestination); - jarInfo.addDestination(destination); - return new PackIntoArchiveInstructionCreator(myContext, jarInfo, "", destination); - } -} diff --git a/java/compiler/impl/src/com/intellij/packaging/impl/compiler/SkipAllInstructionCreator.java b/java/compiler/impl/src/com/intellij/packaging/impl/compiler/SkipAllInstructionCreator.java deleted file mode 100644 index b7d409f9c970..000000000000 --- a/java/compiler/impl/src/com/intellij/packaging/impl/compiler/SkipAllInstructionCreator.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.packaging.impl.compiler; - -import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.packaging.elements.IncrementalCompilerInstructionCreator; -import org.jetbrains.annotations.NotNull; - -/** - * @author nik - */ -public class SkipAllInstructionCreator extends IncrementalCompilerInstructionCreatorBase { - public SkipAllInstructionCreator(ArtifactsProcessingItemsBuilderContext context) { - super(context); - } - - public void addFileCopyInstruction(@NotNull VirtualFile file, @NotNull String outputFileName) { - } - - public SkipAllInstructionCreator subFolder(@NotNull String directoryName) { - return this; - } - - public IncrementalCompilerInstructionCreator archive(@NotNull String archiveFileName) { - return this; - } -} diff --git a/java/compiler/impl/src/com/intellij/packaging/impl/elements/ArchivePackagingElement.java b/java/compiler/impl/src/com/intellij/packaging/impl/elements/ArchivePackagingElement.java index 0064ee2dfd48..0127900eeb34 100644 --- a/java/compiler/impl/src/com/intellij/packaging/impl/elements/ArchivePackagingElement.java +++ b/java/compiler/impl/src/com/intellij/packaging/impl/elements/ArchivePackagingElement.java @@ -22,7 +22,10 @@ import com.intellij.compiler.ant.artifacts.ArchiveAntCopyInstructionCreator; import com.intellij.compiler.ant.taskdefs.Jar; import com.intellij.compiler.ant.taskdefs.Zip; import com.intellij.packaging.artifacts.ArtifactType; -import com.intellij.packaging.elements.*; +import com.intellij.packaging.elements.AntCopyInstructionCreator; +import com.intellij.packaging.elements.ArtifactAntGenerationContext; +import com.intellij.packaging.elements.PackagingElement; +import com.intellij.packaging.elements.PackagingElementResolvingContext; import com.intellij.packaging.impl.ui.ArchiveElementPresentation; import com.intellij.packaging.ui.ArtifactEditorContext; import com.intellij.packaging.ui.PackagingElementPresentation; @@ -74,13 +77,6 @@ public class ArchivePackagingElement extends CompositeElementWithManifest { return computeChildrenGenerators(resolvingContext, creator, generationContext, artifactType); } - @Override - public void computeIncrementalCompilerInstructions(@NotNull IncrementalCompilerInstructionCreator creator, - @NotNull PackagingElementResolvingContext resolvingContext, - @NotNull ArtifactIncrementalCompilerContext compilerContext, @NotNull ArtifactType artifactType) { - computeChildrenInstructions(creator, resolvingContext, compilerContext, artifactType); - } - public String getName() { return ""; } diff --git a/java/compiler/impl/src/com/intellij/packaging/impl/elements/DirectoryCopyPackagingElement.java b/java/compiler/impl/src/com/intellij/packaging/impl/elements/DirectoryCopyPackagingElement.java index c5c10dca16ed..e9f1fc1b91b1 100644 --- a/java/compiler/impl/src/com/intellij/packaging/impl/elements/DirectoryCopyPackagingElement.java +++ b/java/compiler/impl/src/com/intellij/packaging/impl/elements/DirectoryCopyPackagingElement.java @@ -16,9 +16,10 @@ package com.intellij.packaging.impl.elements; import com.intellij.compiler.ant.Generator; -import com.intellij.openapi.vfs.VirtualFile; import com.intellij.packaging.artifacts.ArtifactType; -import com.intellij.packaging.elements.*; +import com.intellij.packaging.elements.AntCopyInstructionCreator; +import com.intellij.packaging.elements.ArtifactAntGenerationContext; +import com.intellij.packaging.elements.PackagingElementResolvingContext; import com.intellij.packaging.impl.ui.DirectoryCopyPresentation; import com.intellij.packaging.ui.ArtifactEditorContext; import com.intellij.packaging.ui.PackagingElementPresentation; @@ -54,17 +55,6 @@ public class DirectoryCopyPackagingElement extends FileOrDirectoryCopyPackagingE return Collections.singletonList(creator.createDirectoryContentCopyInstruction(path)); } - @Override - public void computeIncrementalCompilerInstructions(@NotNull IncrementalCompilerInstructionCreator creator, - @NotNull PackagingElementResolvingContext resolvingContext, - @NotNull ArtifactIncrementalCompilerContext compilerContext, - @NotNull ArtifactType artifactType) { - final VirtualFile file = findFile(); - if (file != null && file.isValid() && file.isDirectory()) { - creator.addDirectoryCopyInstructions(file); - } - } - public DirectoryCopyPackagingElement getState() { return this; } diff --git a/java/compiler/impl/src/com/intellij/packaging/impl/elements/DirectoryPackagingElement.java b/java/compiler/impl/src/com/intellij/packaging/impl/elements/DirectoryPackagingElement.java index 0fd3a34aabd7..815d0c2674f7 100644 --- a/java/compiler/impl/src/com/intellij/packaging/impl/elements/DirectoryPackagingElement.java +++ b/java/compiler/impl/src/com/intellij/packaging/impl/elements/DirectoryPackagingElement.java @@ -16,15 +16,18 @@ package com.intellij.packaging.impl.elements; import com.intellij.compiler.ant.Generator; -import com.intellij.packaging.elements.*; -import com.intellij.packaging.impl.ui.DirectoryElementPresentation; -import com.intellij.packaging.ui.PackagingElementPresentation; -import com.intellij.packaging.ui.ArtifactEditorContext; import com.intellij.packaging.artifacts.ArtifactType; -import com.intellij.util.xmlb.annotations.Attribute; +import com.intellij.packaging.elements.AntCopyInstructionCreator; +import com.intellij.packaging.elements.ArtifactAntGenerationContext; +import com.intellij.packaging.elements.PackagingElement; +import com.intellij.packaging.elements.PackagingElementResolvingContext; +import com.intellij.packaging.impl.ui.DirectoryElementPresentation; +import com.intellij.packaging.ui.ArtifactEditorContext; +import com.intellij.packaging.ui.PackagingElementPresentation; import com.intellij.util.xmlb.XmlSerializerUtil; -import org.jetbrains.annotations.NotNull; +import com.intellij.util.xmlb.annotations.Attribute; import org.jetbrains.annotations.NonNls; +import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.List; @@ -65,13 +68,6 @@ public class DirectoryPackagingElement extends CompositeElementWithManifest element) { return element instanceof ExtractedDirectoryPackagingElement && super.isEqualTo(element) diff --git a/java/compiler/impl/src/com/intellij/packaging/impl/elements/FileCopyPackagingElement.java b/java/compiler/impl/src/com/intellij/packaging/impl/elements/FileCopyPackagingElement.java index 6513c765e76e..b3bf1a9650d3 100644 --- a/java/compiler/impl/src/com/intellij/packaging/impl/elements/FileCopyPackagingElement.java +++ b/java/compiler/impl/src/com/intellij/packaging/impl/elements/FileCopyPackagingElement.java @@ -76,16 +76,6 @@ public class FileCopyPackagingElement extends FileOrDirectoryCopyPackagingElemen return myRenamedOutputFileName != null ? myRenamedOutputFileName : PathUtil.getFileName(myFilePath); } - @Override - public void computeIncrementalCompilerInstructions(@NotNull IncrementalCompilerInstructionCreator creator, - @NotNull PackagingElementResolvingContext resolvingContext, - @NotNull ArtifactIncrementalCompilerContext compilerContext, @NotNull ArtifactType artifactType) { - final VirtualFile file = findFile(); - if (file != null && file.isValid() && !file.isDirectory()) { - creator.addFileCopyInstruction(file, getOutputFileName()); - } - } - @NonNls @Override public String toString() { return "file:" + myFilePath + (myRenamedOutputFileName != null ? ",rename to:" + myRenamedOutputFileName : ""); diff --git a/java/compiler/impl/src/com/intellij/packaging/impl/elements/ModuleOutputPackagingElementBase.java b/java/compiler/impl/src/com/intellij/packaging/impl/elements/ModuleOutputPackagingElementBase.java index 084cf6ebd456..231a379c3163 100644 --- a/java/compiler/impl/src/com/intellij/packaging/impl/elements/ModuleOutputPackagingElementBase.java +++ b/java/compiler/impl/src/com/intellij/packaging/impl/elements/ModuleOutputPackagingElementBase.java @@ -68,22 +68,6 @@ public abstract class ModuleOutputPackagingElementBase extends PackagingElement< protected abstract String getModuleOutputAntProperty(ArtifactAntGenerationContext generationContext); - @Override - public void computeIncrementalCompilerInstructions(@NotNull IncrementalCompilerInstructionCreator creator, - @NotNull PackagingElementResolvingContext resolvingContext, - @NotNull ArtifactIncrementalCompilerContext compilerContext, @NotNull ArtifactType artifactType) { - final Module module = findModule(resolvingContext); - if (module != null) { - final CompilerModuleExtension extension = CompilerModuleExtension.getInstance(module); - if (extension != null) { - final VirtualFile output = getModuleOutputPath(extension); - if (output != null) { - creator.addDirectoryCopyInstructions(output, null); - } - } - } - } - @Nullable protected abstract VirtualFile getModuleOutputPath(CompilerModuleExtension extension); diff --git a/java/compiler/impl/src/com/intellij/packaging/impl/run/BuildArtifactsBeforeRunTaskProvider.java b/java/compiler/impl/src/com/intellij/packaging/impl/run/BuildArtifactsBeforeRunTaskProvider.java index a9ea9c369300..a111eaacbca3 100644 --- a/java/compiler/impl/src/com/intellij/packaging/impl/run/BuildArtifactsBeforeRunTaskProvider.java +++ b/java/compiler/impl/src/com/intellij/packaging/impl/run/BuildArtifactsBeforeRunTaskProvider.java @@ -15,6 +15,7 @@ */ package com.intellij.packaging.impl.run; +import com.intellij.compiler.impl.CompileScopeUtil; import com.intellij.execution.BeforeRunTask; import com.intellij.execution.BeforeRunTaskProvider; import com.intellij.execution.RunManagerEx; @@ -30,25 +31,24 @@ import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.application.ReadAction; import com.intellij.openapi.application.Result; import com.intellij.openapi.compiler.*; -import com.intellij.openapi.compiler.Compiler; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.DialogBuilder; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.Ref; import com.intellij.packaging.artifacts.*; -import com.intellij.packaging.impl.compiler.ArtifactAwareCompiler; import com.intellij.packaging.impl.compiler.ArtifactCompileScope; -import com.intellij.packaging.impl.compiler.ArtifactsCompiler; import com.intellij.util.concurrency.Semaphore; import com.intellij.util.containers.ContainerUtil; import gnu.trove.THashSet; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; +import org.jetbrains.jps.api.CmdlineRemoteProto; import javax.swing.*; import java.awt.*; import java.util.ArrayList; +import java.util.Collections; import java.util.List; import java.util.Set; @@ -185,20 +185,15 @@ public class BuildArtifactsBeforeRunTaskProvider extends BeforeRunTaskProvideremptyList()); ExecutionManagerImpl.EXECUTION_SESSION_ID_KEY.set(scope, ExecutionManagerImpl.EXECUTION_SESSION_ID_KEY.get(env)); - manager.make(scope, compilerFilter, callback); + manager.make(scope, CompilerFilter.ALL, callback); } }, ModalityState.NON_MODAL); diff --git a/java/compiler/impl/src/com/intellij/packaging/impl/ui/actions/PackageFileAction.java b/java/compiler/impl/src/com/intellij/packaging/impl/ui/actions/PackageFileAction.java index 5cbfdfb450b6..cd3092fdb35f 100644 --- a/java/compiler/impl/src/com/intellij/packaging/impl/ui/actions/PackageFileAction.java +++ b/java/compiler/impl/src/com/intellij/packaging/impl/ui/actions/PackageFileAction.java @@ -6,7 +6,6 @@ package com.intellij.packaging.impl.ui.actions; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.CommonDataKeys; -import com.intellij.openapi.actionSystem.PlatformDataKeys; import com.intellij.openapi.compiler.CompilerBundle; import com.intellij.openapi.compiler.CompilerManager; import com.intellij.openapi.fileEditor.FileDocumentManager; @@ -16,6 +15,7 @@ import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.util.Clock; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; +import com.intellij.openapi.wm.StatusBar; import com.intellij.openapi.wm.WindowManager; import com.intellij.packaging.artifacts.Artifact; import com.intellij.packaging.artifacts.ArtifactManager; @@ -100,7 +100,10 @@ public class PackageFileAction extends AnAction { } String time = TIME_FORMAT.format(Clock.getTime()); final String statusText = CompilerBundle.message("status.text.file.has.been.packaged", files.size(), fileNames, time); - WindowManager.getInstance().getStatusBar(project).setInfo(statusText); + final StatusBar statusBar = WindowManager.getInstance().getStatusBar(project); + if (statusBar != null) { + statusBar.setInfo(statusText); + } } } } diff --git a/java/compiler/impl/testSrc/com/intellij/compiler/BaseCompilerTestCase.java b/java/compiler/impl/testSrc/com/intellij/compiler/BaseCompilerTestCase.java index ee88a678cabc..5822e9433bed 100644 --- a/java/compiler/impl/testSrc/com/intellij/compiler/BaseCompilerTestCase.java +++ b/java/compiler/impl/testSrc/com/intellij/compiler/BaseCompilerTestCase.java @@ -46,9 +46,6 @@ import java.util.*; * @author nik */ public abstract class BaseCompilerTestCase extends ModuleTestCase { - protected boolean useExternalCompiler() { - return false; - } @Override protected void setUpModule() { @@ -57,19 +54,14 @@ public abstract class BaseCompilerTestCase extends ModuleTestCase { @Override protected void setUp() throws Exception { super.setUp(); - if (useExternalCompiler()) { - myProject.getMessageBus().connect(myTestRootDisposable).subscribe(ProjectTopics.PROJECT_ROOTS, new ModuleRootAdapter() { - @Override - public void rootsChanged(ModuleRootEvent event) { - //todo[nik] projectOpened isn't called in tests so we need to add this listener manually - forceFSRescan(); - } - }); - CompilerTestUtil.enableExternalCompiler(myProject); - } - else { - CompilerTestUtil.disableExternalCompiler(myProject); - } + myProject.getMessageBus().connect(myTestRootDisposable).subscribe(ProjectTopics.PROJECT_ROOTS, new ModuleRootAdapter() { + @Override + public void rootsChanged(ModuleRootEvent event) { + //todo[nik] projectOpened isn't called in tests so we need to add this listener manually + forceFSRescan(); + } + }); + CompilerTestUtil.enableExternalCompiler(); } protected void forceFSRescan() { @@ -78,10 +70,7 @@ public abstract class BaseCompilerTestCase extends ModuleTestCase { @Override protected Sdk getTestProjectJdk() { - if (useExternalCompiler()) { - return JavaAwareProjectJdkTableImpl.getInstanceEx().getInternalJdk(); - } - return super.getTestProjectJdk(); + return JavaAwareProjectJdkTableImpl.getInstanceEx().getInternalJdk(); } @Override @@ -92,9 +81,7 @@ public abstract class BaseCompilerTestCase extends ModuleTestCase { FileUtil.delete(new File(FileUtil.toSystemDependentName(outputPath))); } } - if (useExternalCompiler()) { - CompilerTestUtil.disableExternalCompiler(myProject); - } + CompilerTestUtil.disableExternalCompiler(); super.tearDown(); } @@ -279,11 +266,9 @@ public abstract class BaseCompilerTestCase extends ModuleTestCase { } } }; - if (useExternalCompiler()) { - myProject.save(); - CompilerTestUtil.saveApplicationSettings(); - CompilerTestUtil.scanSourceRootsToRecompile(myProject); - } + myProject.save(); + CompilerTestUtil.saveApplicationSettings(); + CompilerTestUtil.scanSourceRootsToRecompile(myProject); action.run(callback); } }); @@ -353,31 +338,26 @@ public abstract class BaseCompilerTestCase extends ModuleTestCase { @Override protected File getIprFile() throws IOException { File iprFile = super.getIprFile(); - if (useExternalCompiler()) { - FileUtil.delete(iprFile); - } + FileUtil.delete(iprFile); return iprFile; } @Override protected Module doCreateRealModule(String moduleName) { - if (useExternalCompiler()) { - //todo[nik] reuse code from PlatformTestCase - final VirtualFile baseDir = myProject.getBaseDir(); - Assert.assertNotNull(baseDir); - final File moduleFile = new File(baseDir.getPath().replace('/', File.separatorChar), moduleName + ModuleFileType.DOT_DEFAULT_EXTENSION); - PlatformTestCase.myFilesToDelete.add(moduleFile); - return new WriteAction() { - @Override - protected void run(Result result) throws Throwable { - Module module = ModuleManager.getInstance(myProject) - .newModule(FileUtil.toSystemIndependentName(moduleFile.getAbsolutePath()), getModuleType().getId()); - module.getModuleFile(); - result.setResult(module); - } - }.execute().getResultObject(); - } - return super.doCreateRealModule(moduleName); + //todo[nik] reuse code from PlatformTestCase + final VirtualFile baseDir = myProject.getBaseDir(); + Assert.assertNotNull(baseDir); + final File moduleFile = new File(baseDir.getPath().replace('/', File.separatorChar), moduleName + ModuleFileType.DOT_DEFAULT_EXTENSION); + PlatformTestCase.myFilesToDelete.add(moduleFile); + return new WriteAction() { + @Override + protected void run(Result result) throws Throwable { + Module module = ModuleManager.getInstance(myProject) + .newModule(FileUtil.toSystemIndependentName(moduleFile.getAbsolutePath()), getModuleType().getId()); + module.getModuleFile(); + result.setResult(module); + } + }.execute().getResultObject(); } @Override @@ -451,13 +431,7 @@ public abstract class BaseCompilerTestCase extends ModuleTestCase { } public void assertUpToDate() { - if (useExternalCompiler()) { - assertTrue(myExternalBuildUpToDate); - } - else { - checkRecompiled(); - checkDeleted(); - } + assertTrue(myExternalBuildUpToDate); } public void assertRecompiled(String... expected) { @@ -480,13 +454,9 @@ public abstract class BaseCompilerTestCase extends ModuleTestCase { } private void checkRecompiled(String... expected) { - if (useExternalCompiler()) return; - assertSet("recompiled", myRecompiledPaths, expected); } private void checkDeleted(String... expected) { - if (useExternalCompiler()) return; - assertSet("deleted", myDeletedPaths, expected); } public CompilerMessage[] getErrors() { diff --git a/java/compiler/openapi/src/com/intellij/compiler/CompilerWorkspaceConfiguration.java b/java/compiler/openapi/src/com/intellij/compiler/CompilerWorkspaceConfiguration.java index 79f66c504c48..40db69f79f04 100644 --- a/java/compiler/openapi/src/com/intellij/compiler/CompilerWorkspaceConfiguration.java +++ b/java/compiler/openapi/src/com/intellij/compiler/CompilerWorkspaceConfiguration.java @@ -44,7 +44,6 @@ public class CompilerWorkspaceConfiguration implements PersistentStateComponent< public boolean DISPLAY_NOTIFICATION_POPUP = true; @Deprecated public boolean CLOSE_MESSAGE_VIEW_IF_SUCCESS = true; public boolean CLEAR_OUTPUT_DIRECTORY = true; - public boolean USE_OUT_OF_PROCESS_BUILD = true; public boolean MAKE_PROJECT_ON_SAVE = false; // until we fix problems with several open projects (IDEA-104064), daemon slowness (IDEA-104666) public boolean PARALLEL_COMPILATION = false; public int COMPILER_PROCESS_HEAP_SIZE = DEFAULT_COMPILE_PROCESS_HEAP_SIZE; @@ -63,10 +62,6 @@ public class CompilerWorkspaceConfiguration implements PersistentStateComponent< XmlSerializerUtil.copyBean(state, this); } - public boolean useOutOfProcessBuild() { - return USE_OUT_OF_PROCESS_BUILD; - } - public boolean allowAutoMakeWhileRunningApplication() { return false;/*ALLOW_AUTOMAKE_WHILE_RUNNING_APPLICATION*/ } diff --git a/java/compiler/openapi/src/com/intellij/compiler/ant/BuildTargetsFactory.java b/java/compiler/openapi/src/com/intellij/compiler/ant/BuildTargetsFactory.java index 65a758784894..339923fe6f65 100644 --- a/java/compiler/openapi/src/com/intellij/compiler/ant/BuildTargetsFactory.java +++ b/java/compiler/openapi/src/com/intellij/compiler/ant/BuildTargetsFactory.java @@ -20,12 +20,8 @@ */ package com.intellij.compiler.ant; -import com.intellij.compiler.ant.taskdefs.Target; -import com.intellij.openapi.compiler.make.BuildRecipe; import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.project.Project; -import org.jetbrains.annotations.NonNls; -import org.jetbrains.annotations.Nullable; public abstract class BuildTargetsFactory { public static BuildTargetsFactory getInstance() { diff --git a/java/compiler/openapi/src/com/intellij/openapi/compiler/CompileContext.java b/java/compiler/openapi/src/com/intellij/openapi/compiler/CompileContext.java index 7fa4a5f45cd3..6046c2835194 100644 --- a/java/compiler/openapi/src/com/intellij/openapi/compiler/CompileContext.java +++ b/java/compiler/openapi/src/com/intellij/openapi/compiler/CompileContext.java @@ -121,13 +121,6 @@ public interface CompileContext extends UserDataHolder { */ VirtualFile[] getSourceRoots(Module module); - /** - * Returns the list of all output directories. - * - * @return a list of all configured output directories from all modules (including output directories for tests) - */ - VirtualFile[] getAllOutputDirectories(); - /** * Returns the output directory for the specified module. * diff --git a/java/compiler/openapi/src/com/intellij/openapi/compiler/CompilerFilter.java b/java/compiler/openapi/src/com/intellij/openapi/compiler/CompilerFilter.java index c7a9f7fc87a4..36b2e5fd8a5c 100644 --- a/java/compiler/openapi/src/com/intellij/openapi/compiler/CompilerFilter.java +++ b/java/compiler/openapi/src/com/intellij/openapi/compiler/CompilerFilter.java @@ -16,8 +16,9 @@ package com.intellij.openapi.compiler; /** - * @author Eugene Zhuravlev - * Date: Jul 9, 2009 + * @deprecated this interface is a part of the obsolete build system which runs as part of the IDE process. Since IDEA 12 plugins need to + * integrate into 'external build system' instead (http://confluence.jetbrains.com/display/IDEADEV/External+Builder+API+and+Plugins). + * Since IDEA 13 users cannot switch to the old build system via UI and it will be completely removed in IDEA 14. */ public interface CompilerFilter { CompilerFilter ALL = new CompilerFilter() { diff --git a/java/compiler/openapi/src/com/intellij/openapi/compiler/CompilerManager.java b/java/compiler/openapi/src/com/intellij/openapi/compiler/CompilerManager.java index 1f0106c11fa4..58e540578f33 100644 --- a/java/compiler/openapi/src/com/intellij/openapi/compiler/CompilerManager.java +++ b/java/compiler/openapi/src/com/intellij/openapi/compiler/CompilerManager.java @@ -56,7 +56,7 @@ public abstract class CompilerManager { * @param compiler the compiler to register. */ public abstract void addCompiler(@NotNull Compiler compiler); - + /** * Registers a custom translating compiler. Input and output filetype sets allow compiler manager * to sort translating compilers so that output of one compiler will be used as input for another one @@ -71,12 +71,6 @@ public abstract class CompilerManager { */ public abstract void addTranslatingCompiler(@NotNull TranslatingCompiler compiler, Set inputTypes, Set outputTypes); - @NotNull - public abstract Set getRegisteredInputTypes(@NotNull TranslatingCompiler compiler); - - @NotNull - public abstract Set getRegisteredOutputTypes(@NotNull TranslatingCompiler compiler); - /** * Unregisters a custom compiler. * @@ -276,9 +270,6 @@ public abstract class CompilerManager { */ public abstract boolean isExcludedFromCompilation(@NotNull VirtualFile file); - @NotNull - public abstract OutputToSourceMapping getJavaCompilerOutputMapping(); - /* * Convetience methods for creating frequently-used compile scopes */ diff --git a/java/compiler/openapi/src/com/intellij/openapi/compiler/CompilerPaths.java b/java/compiler/openapi/src/com/intellij/openapi/compiler/CompilerPaths.java index 15c19335af85..fd749d136449 100644 --- a/java/compiler/openapi/src/com/intellij/openapi/compiler/CompilerPaths.java +++ b/java/compiler/openapi/src/com/intellij/openapi/compiler/CompilerPaths.java @@ -30,7 +30,6 @@ import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileManager; import com.intellij.util.PathUtil; -import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.Nullable; import org.jetbrains.jps.model.java.compiler.AnnotationProcessingConfiguration; @@ -198,12 +197,5 @@ public class CompilerPaths { } return StringUtil.isEmpty(sourceDirName)? path : path + "/" + sourceDirName; } - - @NonNls - public static String getGenerationOutputPath(IntermediateOutputCompiler compiler, Module module, final boolean forTestSources) { - final String generatedCompilerDirectoryPath = getGeneratedDataDirectory(module.getProject(), compiler).getPath(); - //noinspection HardCodedStringLiteral - final String moduleDir = module.getName().replaceAll("\\s+", "_") + "." + Integer.toHexString(module.getModuleFilePath().hashCode()); - return generatedCompilerDirectoryPath.replace(File.separatorChar, '/') + "/" + moduleDir + "/" + (forTestSources? "test" : "production"); - } + } diff --git a/java/compiler/openapi/src/com/intellij/openapi/compiler/DummyCompileContext.java b/java/compiler/openapi/src/com/intellij/openapi/compiler/DummyCompileContext.java index 297f293300b5..af4752e80675 100644 --- a/java/compiler/openapi/src/com/intellij/openapi/compiler/DummyCompileContext.java +++ b/java/compiler/openapi/src/com/intellij/openapi/compiler/DummyCompileContext.java @@ -97,10 +97,6 @@ public class DummyCompileContext implements CompileContext { return VirtualFile.EMPTY_ARRAY; } - public VirtualFile[] getAllOutputDirectories() { - return VirtualFile.EMPTY_ARRAY; - } - public VirtualFile getModuleOutputDirectory(final Module module) { return ApplicationManager.getApplication().runReadAction(new Computable() { public VirtualFile compute() { diff --git a/java/compiler/openapi/src/com/intellij/openapi/compiler/IntermediateOutputCompiler.java b/java/compiler/openapi/src/com/intellij/openapi/compiler/IntermediateOutputCompiler.java index a2893935823d..a55136eaccb6 100644 --- a/java/compiler/openapi/src/com/intellij/openapi/compiler/IntermediateOutputCompiler.java +++ b/java/compiler/openapi/src/com/intellij/openapi/compiler/IntermediateOutputCompiler.java @@ -18,6 +18,10 @@ package com.intellij.openapi.compiler; /** * A tag interface denoting that compiler's output should go into 'intermediate' directory * and can be used as input to another compiler + * + * @deprecated this interface is part of the obsolete build system which runs as part of the IDE process. Since IDEA 12 plugins need to + * integrate into 'external build system' instead (http://confluence.jetbrains.com/display/IDEADEV/External+Builder+API+and+Plugins). + * Since IDEA 13 users cannot switch to the old build system via UI and it will be completely removed in IDEA 14. */ public interface IntermediateOutputCompiler extends Compiler{ } diff --git a/java/compiler/openapi/src/com/intellij/openapi/compiler/SourceProcessingCompiler.java b/java/compiler/openapi/src/com/intellij/openapi/compiler/SourceProcessingCompiler.java index 8392fdc865ee..64d287ad3c11 100644 --- a/java/compiler/openapi/src/com/intellij/openapi/compiler/SourceProcessingCompiler.java +++ b/java/compiler/openapi/src/com/intellij/openapi/compiler/SourceProcessingCompiler.java @@ -15,5 +15,10 @@ */ package com.intellij.openapi.compiler; +/** + * @deprecated this interface is part of the obsolete build system which runs as part of the IDE process. Since IDEA 12 plugins need to + * integrate into 'external build system' instead (http://confluence.jetbrains.com/display/IDEADEV/External+Builder+API+and+Plugins). + * Since IDEA 13 users cannot switch to the old build system via UI and it will be completely removed in IDEA 14. + */ public interface SourceProcessingCompiler extends FileProcessingCompiler, IntermediateOutputCompiler { } \ No newline at end of file diff --git a/java/compiler/openapi/src/com/intellij/openapi/compiler/ex/CompilerPathsEx.java b/java/compiler/openapi/src/com/intellij/openapi/compiler/ex/CompilerPathsEx.java index 0f40216a0509..8235094c6e93 100644 --- a/java/compiler/openapi/src/com/intellij/openapi/compiler/ex/CompilerPathsEx.java +++ b/java/compiler/openapi/src/com/intellij/openapi/compiler/ex/CompilerPathsEx.java @@ -19,10 +19,7 @@ import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.compiler.CompilerPaths; import com.intellij.openapi.module.Module; import com.intellij.openapi.progress.ProgressManager; -import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.CompilerModuleExtension; -import com.intellij.openapi.util.Key; -import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileManager; import com.intellij.util.ArrayUtil; @@ -34,16 +31,6 @@ import java.util.Collection; import java.util.Set; public class CompilerPathsEx extends CompilerPaths { - public static final Key CLEAR_ALL_OUTPUTS_KEY = Key.create("_should_clear_all_outputs_"); - - public static File getZippedOutputPath(Project project, String outputDirectoryPath) { - final File outputDir = new File(outputDirectoryPath); - return new File(getZipStoreDirectory(project), "_" + outputDir.getName() + Integer.toHexString(outputDirectoryPath.hashCode()) + ".zip"); - } - - public static File getZipStoreDirectory(Project project) { - return new File(getCompilerSystemDirectory(project), ".zip"); - } public static class FileVisitor { protected void accept(final VirtualFile file, final String fileRoot, final String filePath) { @@ -107,19 +94,4 @@ public class CompilerPathsEx extends CompilerPaths { } return ArrayUtil.toStringArray(outputPaths); } - - public static VirtualFile[] getOutputDirectories(final Module[] modules) { - final Set dirs = new OrderedSet(); - for (Module module : modules) { - final VirtualFile outputDir = getModuleOutputDirectory(module, false); - if (outputDir != null) { - dirs.add(outputDir); - } - VirtualFile testsOutputDir = getModuleOutputDirectory(module, true); - if (testsOutputDir != null) { - dirs.add(testsOutputDir); - } - } - return VfsUtil.toVirtualFileArray(dirs); - } } diff --git a/java/compiler/openapi/src/com/intellij/openapi/compiler/make/BuildRecipe.java b/java/compiler/openapi/src/com/intellij/openapi/compiler/make/BuildRecipe.java deleted file mode 100644 index ad30291c5fda..000000000000 --- a/java/compiler/openapi/src/com/intellij/openapi/compiler/make/BuildRecipe.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.openapi.compiler.make; - -import org.jetbrains.annotations.NotNull; - -import java.io.File; - -@Deprecated -public interface BuildRecipe { - void addInstruction(BuildInstruction instruction); - - boolean visitInstructions(BuildInstructionVisitor visitor, boolean reverseOrder); - boolean visitInstructionsWithExceptions(BuildInstructionVisitor visitor, boolean reverseOrder) throws Exception; - - void addFileCopyInstruction(@NotNull File file, boolean isDirectory, String outputRelativePath); -} \ No newline at end of file diff --git a/java/compiler/openapi/src/com/intellij/openapi/deployment/DeploymentUtil.java b/java/compiler/openapi/src/com/intellij/openapi/deployment/DeploymentUtil.java index dc1ff57c02ff..4919789ca176 100644 --- a/java/compiler/openapi/src/com/intellij/openapi/deployment/DeploymentUtil.java +++ b/java/compiler/openapi/src/com/intellij/openapi/deployment/DeploymentUtil.java @@ -16,7 +16,6 @@ package com.intellij.openapi.deployment; import com.intellij.openapi.compiler.CompileContext; -import com.intellij.openapi.compiler.make.BuildRecipe; import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.module.Module; import com.intellij.openapi.util.text.StringUtil; @@ -41,9 +40,6 @@ public abstract class DeploymentUtil { @Nullable Set writtenPaths, @Nullable FileFilter fileFilter) throws IOException; - @Deprecated - public abstract boolean addItemsRecursively(@NotNull BuildRecipe items, @NotNull File root, String outputRelativePath); - public static String trimForwardSlashes(@NotNull String path) { while (path.length() != 0 && (path.charAt(0) == '/' || path.charAt(0) == File.separatorChar)) { path = path.substring(1); @@ -83,9 +79,6 @@ public abstract class DeploymentUtil { return basePath + tail; } - @Deprecated - public abstract BuildRecipe createBuildRecipe(); - @Nullable public abstract String getConfigFileErrorMessage(ConfigFile configFile); diff --git a/java/compiler/openapi/src/com/intellij/packaging/elements/ComplexPackagingElement.java b/java/compiler/openapi/src/com/intellij/packaging/elements/ComplexPackagingElement.java index 5a09569da093..e30af39a1773 100644 --- a/java/compiler/openapi/src/com/intellij/packaging/elements/ComplexPackagingElement.java +++ b/java/compiler/openapi/src/com/intellij/packaging/elements/ComplexPackagingElement.java @@ -20,9 +20,9 @@ import com.intellij.packaging.artifacts.ArtifactType; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.List; import java.util.ArrayList; import java.util.Collections; +import java.util.List; /** * @author nik @@ -48,23 +48,6 @@ public abstract class ComplexPackagingElement extends PackagingElement { return fileSets; } - @Override - public void computeIncrementalCompilerInstructions(@NotNull IncrementalCompilerInstructionCreator creator, - @NotNull PackagingElementResolvingContext resolvingContext, - @NotNull ArtifactIncrementalCompilerContext compilerContext, @NotNull ArtifactType artifactType) { - final List> substitution = getSubstitution(resolvingContext, artifactType); - if (substitution == null) return; - - for (PackagingElement element : substitution) { - element.computeIncrementalCompilerInstructions(creator, resolvingContext, compilerContext, - getArtifactTypeForSubstitutedElements(resolvingContext, artifactType)); - } - } - - protected ArtifactType getArtifactTypeForSubstitutedElements(PackagingElementResolvingContext resolvingContext, ArtifactType artifactType) { - return artifactType; - } - @Nullable public abstract List> getSubstitution(@NotNull PackagingElementResolvingContext context, @NotNull ArtifactType artifactType); diff --git a/java/compiler/openapi/src/com/intellij/packaging/elements/CompositePackagingElement.java b/java/compiler/openapi/src/com/intellij/packaging/elements/CompositePackagingElement.java index fbfa5e00b784..c0f3ff0efbbc 100644 --- a/java/compiler/openapi/src/com/intellij/packaging/elements/CompositePackagingElement.java +++ b/java/compiler/openapi/src/com/intellij/packaging/elements/CompositePackagingElement.java @@ -116,14 +116,6 @@ public abstract class CompositePackagingElement extends PackagingElement i return generators; } - protected void computeChildrenInstructions(@NotNull IncrementalCompilerInstructionCreator creator, - @NotNull PackagingElementResolvingContext resolvingContext, - @NotNull ArtifactIncrementalCompilerContext compilerContext, ArtifactType artifactType) { - for (PackagingElement child : myChildren) { - child.computeIncrementalCompilerInstructions(creator, resolvingContext, compilerContext, artifactType); - } - } - public void removeAllChildren() { myChildren.clear(); } diff --git a/java/compiler/openapi/src/com/intellij/packaging/elements/IncrementalCompilerInstructionCreator.java b/java/compiler/openapi/src/com/intellij/packaging/elements/IncrementalCompilerInstructionCreator.java deleted file mode 100644 index 7c1f1d0a5f39..000000000000 --- a/java/compiler/openapi/src/com/intellij/packaging/elements/IncrementalCompilerInstructionCreator.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.packaging.elements; - -import com.intellij.openapi.vfs.VirtualFile; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * @author nik - */ -public interface IncrementalCompilerInstructionCreator { - - void addFileCopyInstruction(@NotNull VirtualFile file, @NotNull String outputFileName); - - void addDirectoryCopyInstructions(@NotNull VirtualFile directory); - - void addDirectoryCopyInstructions(@NotNull VirtualFile directory, @Nullable PackagingFileFilter filter); - - IncrementalCompilerInstructionCreator subFolder(@NotNull String directoryName); - - IncrementalCompilerInstructionCreator archive(@NotNull String archiveFileName); - - IncrementalCompilerInstructionCreator subFolderByRelativePath(@NotNull String relativeDirectoryPath); -} diff --git a/java/compiler/openapi/src/com/intellij/packaging/elements/PackagingElement.java b/java/compiler/openapi/src/com/intellij/packaging/elements/PackagingElement.java index 377616b8be1d..5c54f50dee76 100644 --- a/java/compiler/openapi/src/com/intellij/packaging/elements/PackagingElement.java +++ b/java/compiler/openapi/src/com/intellij/packaging/elements/PackagingElement.java @@ -44,10 +44,6 @@ public abstract class PackagingElement implements PersistentStateComponent @NotNull ArtifactAntGenerationContext generationContext, @NotNull ArtifactType artifactType); - public abstract void computeIncrementalCompilerInstructions(@NotNull IncrementalCompilerInstructionCreator creator, @NotNull PackagingElementResolvingContext resolvingContext, - @NotNull ArtifactIncrementalCompilerContext compilerContext, - @NotNull ArtifactType artifactType); - public abstract boolean isEqualTo(@NotNull PackagingElement element); @NotNull diff --git a/java/debugger/impl/src/com/intellij/debugger/ui/HotSwapUIImpl.java b/java/debugger/impl/src/com/intellij/debugger/ui/HotSwapUIImpl.java index 71e5cfbdff5e..11df707ae4a6 100644 --- a/java/debugger/impl/src/com/intellij/debugger/ui/HotSwapUIImpl.java +++ b/java/debugger/impl/src/com/intellij/debugger/ui/HotSwapUIImpl.java @@ -16,7 +16,6 @@ package com.intellij.debugger.ui; import com.intellij.CommonBundle; -import com.intellij.compiler.CompilerWorkspaceConfiguration; import com.intellij.debugger.DebuggerBundle; import com.intellij.debugger.DebuggerManager; import com.intellij.debugger.DebuggerManagerEx; @@ -153,8 +152,7 @@ public class HotSwapUIImpl extends HotSwapUI implements ProjectComponent { return; } - final boolean isOutOfProcessMode = CompilerWorkspaceConfiguration.getInstance(myProject).useOutOfProcessBuild(); - final boolean shouldPerformScan = !isOutOfProcessMode || generatedPaths == null; + final boolean shouldPerformScan = generatedPaths == null; final HotSwapProgressImpl findClassesProgress; if (shouldPerformScan) { @@ -175,7 +173,7 @@ public class HotSwapUIImpl extends HotSwapUI implements ProjectComponent { public void run() { final Map> modifiedClasses; if (shouldPerformScan) { - modifiedClasses = scanForModifiedClassesWithProgress(sessions, findClassesProgress, !isOutOfProcessMode); + modifiedClasses = scanForModifiedClassesWithProgress(sessions, findClassesProgress, false); } else { final List toScan = new ArrayList(); @@ -189,7 +187,7 @@ public class HotSwapUIImpl extends HotSwapUI implements ProjectComponent { modifiedClasses.putAll(HotSwapManager.findModifiedClasses(toUseGenerated, generatedPaths)); } if (!toScan.isEmpty()) { - modifiedClasses.putAll(scanForModifiedClassesWithProgress(toScan, findClassesProgress, !isOutOfProcessMode)); + modifiedClasses.putAll(scanForModifiedClassesWithProgress(toScan, findClassesProgress, !true)); } } diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/completion/AbstractCompilerAwareTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/completion/AbstractCompilerAwareTest.java index 2ee1079cc158..a16641f97e68 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/completion/AbstractCompilerAwareTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/completion/AbstractCompilerAwareTest.java @@ -33,7 +33,7 @@ public abstract class AbstractCompilerAwareTest extends JavaCodeInsightFixtureTe @Override protected void setUp() throws Exception { super.setUp(); - myCompilerTester = new CompilerTester(true, myModule); + myCompilerTester = new CompilerTester(myModule); } @Override diff --git a/java/testFramework/src/com/intellij/compiler/CompilerTestUtil.java b/java/testFramework/src/com/intellij/compiler/CompilerTestUtil.java index 15b858fea0ec..ecd7af710ca3 100644 --- a/java/testFramework/src/com/intellij/compiler/CompilerTestUtil.java +++ b/java/testFramework/src/com/intellij/compiler/CompilerTestUtil.java @@ -1,9 +1,6 @@ package com.intellij.compiler; -import com.intellij.compiler.impl.TranslatingCompilerFilesMonitor; import com.intellij.compiler.impl.javaCompiler.javac.JavacConfiguration; -import com.intellij.compiler.options.ExternalBuildOptionListener; -import com.intellij.compiler.server.BuildManager; import com.intellij.openapi.application.PathManager; import com.intellij.openapi.application.Result; import com.intellij.openapi.application.WriteAction; @@ -50,7 +47,8 @@ public class CompilerTestUtil { public static void scanSourceRootsToRecompile(Project project) { // need this to emulate project opening final List roots = ProjectRootManager.getInstance(project).getModuleSourceRoots(JavaModuleSourceRootTypes.SOURCES); - TranslatingCompilerFilesMonitor.getInstance().scanSourceContent(new TranslatingCompilerFilesMonitor.ProjectRef(project), roots, roots.size(), true); + // todo: forced source roots scan is not needed? + //TranslatingCompilerFilesMonitor.getInstance().scanSourceContent(new TranslatingCompilerFilesMonitor.ProjectRef(project), roots, roots.size(), true); } public static void saveApplicationSettings() { @@ -78,11 +76,9 @@ public class CompilerTestUtil { JDOMUtil.writeDocument(new Document(root), file, SystemProperties.getLineSeparator()); } - public static void enableExternalCompiler(final Project project) { + public static void enableExternalCompiler() { new WriteAction() { protected void run(final Result result) { - CompilerWorkspaceConfiguration.getInstance(project).USE_OUT_OF_PROCESS_BUILD = true; - project.getMessageBus().syncPublisher(ExternalBuildOptionListener.TOPIC).externalBuildOptionChanged(true); ApplicationManagerEx.getApplicationEx().doNotSave(false); JavaAwareProjectJdkTableImpl table = JavaAwareProjectJdkTableImpl.getInstanceEx(); table.addJdk(table.getInternalJdk()); @@ -90,15 +86,12 @@ public class CompilerTestUtil { }.execute(); } - public static void disableExternalCompiler(final Project project) { + public static void disableExternalCompiler() { new WriteAction() { protected void run(final Result result) { - CompilerWorkspaceConfiguration.getInstance(project).USE_OUT_OF_PROCESS_BUILD = false; - project.getMessageBus().syncPublisher(ExternalBuildOptionListener.TOPIC).externalBuildOptionChanged(false); ApplicationManagerEx.getApplicationEx().doNotSave(true); JavaAwareProjectJdkTableImpl table = JavaAwareProjectJdkTableImpl.getInstanceEx(); table.removeJdk(table.getInternalJdk()); - BuildManager.getInstance().stopWatchingProject(project); } }.execute(); } diff --git a/java/testFramework/src/com/intellij/testFramework/CompilerTester.java b/java/testFramework/src/com/intellij/testFramework/CompilerTester.java index 75b9a4b4c27e..c7ecfac84daf 100644 --- a/java/testFramework/src/com/intellij/testFramework/CompilerTester.java +++ b/java/testFramework/src/com/intellij/testFramework/CompilerTester.java @@ -53,12 +53,11 @@ import java.util.List; * @author peter */ public class CompilerTester { - private final boolean myExternalMake; + private Module myModule; private TempDirTestFixture myMainOutput; - public CompilerTester(boolean externalMake, Module module) throws Exception { - myExternalMake = externalMake; + public CompilerTester(Module module) throws Exception { myModule = module; myMainOutput = new TempDirTestFixtureImpl(); myMainOutput.setUp(); @@ -69,29 +68,23 @@ public class CompilerTester { protected void run(Result result) throws Throwable { //noinspection ConstantConditions CompilerProjectExtension.getInstance(getProject()).setCompilerOutputUrl(myMainOutput.findOrCreateDir("out").getUrl()); - if (myExternalMake) { - CompilerTestUtil.enableExternalCompiler(getProject()); - ModuleRootModificationUtil.setModuleSdk(myModule, JavaAwareProjectJdkTableImpl.getInstanceEx().getInternalJdk()); - } - else { - CompilerTestUtil.disableExternalCompiler(getProject()); - } + CompilerTestUtil.enableExternalCompiler(); + ModuleRootModificationUtil.setModuleSdk(myModule, JavaAwareProjectJdkTableImpl.getInstanceEx().getInternalJdk()); } }.execute(); } public void tearDown() { - if (myExternalMake) { - CompilerTestUtil.disableExternalCompiler(getProject()); - } + CompilerTestUtil.disableExternalCompiler(); try { myMainOutput.tearDown(); } catch (Exception e) { throw new RuntimeException(e); - } finally { + } + finally { myMainOutput = null; myModule = null; } @@ -104,15 +97,8 @@ public class CompilerTester { public void deleteClassFile(final String className) throws IOException { AccessToken token = WriteAction.start(); try { - if (myExternalMake) { //noinspection ConstantConditions - touch( - JavaPsiFacade.getInstance(getProject()).findClass(className, GlobalSearchScope.allScope(getProject())).getContainingFile().getVirtualFile()); - } - else { - //noinspection ConstantConditions - findClassFile(className, myModule).delete(this); - } + touch(JavaPsiFacade.getInstance(getProject()).findClass(className, GlobalSearchScope.allScope(getProject())).getContainingFile().getVirtualFile()); } finally { token.finish(); @@ -206,14 +192,13 @@ public class CompilerTester { @Override public void run() { try { - if (myExternalMake) { + getProject().save(); + CompilerTestUtil.saveApplicationSettings(); + final VirtualFile moduleFile = myModule.getModuleFile(); + File ioFile = VfsUtil.virtualToIoFile(moduleFile); + if (!ioFile.exists()) { getProject().save(); - CompilerTestUtil.saveApplicationSettings(); - File ioFile = VfsUtil.virtualToIoFile(myModule.getModuleFile()); - if (!ioFile.exists()) { - getProject().save(); - assert ioFile.exists() : "File does not exist: " + ioFile.getPath(); - } + assert ioFile.exists() : "File does not exist: " + ioFile.getPath(); } runnable.consume(callback); } diff --git a/plugins/ByteCodeViewer/src/com/intellij/byteCodeViewer/ShowByteCodeAction.java b/plugins/ByteCodeViewer/src/com/intellij/byteCodeViewer/ShowByteCodeAction.java index 9add78362ae2..39d01579b342 100644 --- a/plugins/ByteCodeViewer/src/com/intellij/byteCodeViewer/ShowByteCodeAction.java +++ b/plugins/ByteCodeViewer/src/com/intellij/byteCodeViewer/ShowByteCodeAction.java @@ -17,10 +17,13 @@ package com.intellij.byteCodeViewer; import com.intellij.codeInsight.documentation.DocumentationManager; import com.intellij.codeInsight.lookup.LookupManager; -import com.intellij.compiler.impl.TranslatingCompilerFilesMonitor; import com.intellij.icons.AllIcons; -import com.intellij.openapi.actionSystem.*; +import com.intellij.openapi.actionSystem.AnAction; +import com.intellij.openapi.actionSystem.AnActionEvent; +import com.intellij.openapi.actionSystem.CommonDataKeys; +import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.application.ApplicationManager; +import com.intellij.openapi.compiler.CompilerManager; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; @@ -39,7 +42,6 @@ import com.intellij.psi.util.PsiUtilBase; import com.intellij.psi.util.PsiUtilCore; import com.intellij.ui.awt.RelativePoint; import com.intellij.ui.popup.NotLookupOrSearchCondition; -import com.intellij.ui.popup.PopupPositionManager; import com.intellij.util.Processor; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -90,8 +92,7 @@ public class ShowByteCodeAction extends AnAction { @Override public void run(@NotNull ProgressIndicator indicator) { - if (ProjectRootManager.getInstance(project).getFileIndex().isInContent(virtualFile) && - TranslatingCompilerFilesMonitor.getInstance().isMarkedForCompilation(project, virtualFile)) { + if (ProjectRootManager.getInstance(project).getFileIndex().isInContent(virtualFile) && isMarkedForCompilation(project, virtualFile)) { myErrorMessage = "Unable to show byte code for '" + psiElementTitle + "'. Class file does not exist or is out-of-date."; myErrorTitle = "Class File Out-Of-Date"; } @@ -158,6 +159,11 @@ public class ShowByteCodeAction extends AnAction { }); } + private static boolean isMarkedForCompilation(Project project, VirtualFile virtualFile) { + final CompilerManager compilerManager = CompilerManager.getInstance(project); + return !compilerManager.isUpToDate(compilerManager.createFilesCompileScope(new VirtualFile[]{virtualFile})); + } + @Nullable private static PsiElement getPsiElement(DataContext dataContext, Project project, Editor editor) { PsiElement psiElement = null; diff --git a/plugins/IntelliLang/java-support/org/intellij/plugins/intelliLang/pattern/compiler/AnnotationBasedInstrumentingCompiler.java b/plugins/IntelliLang/java-support/org/intellij/plugins/intelliLang/pattern/compiler/AnnotationBasedInstrumentingCompiler.java deleted file mode 100644 index a421f475dba7..000000000000 --- a/plugins/IntelliLang/java-support/org/intellij/plugins/intelliLang/pattern/compiler/AnnotationBasedInstrumentingCompiler.java +++ /dev/null @@ -1,215 +0,0 @@ -/* - * Copyright 2006 Sascha Weinreuter - * - * 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.intellij.plugins.intelliLang.pattern.compiler; - -import com.intellij.compiler.PsiClassWriter; -import com.intellij.lang.StdLanguages; -import com.intellij.openapi.application.ApplicationManager; -import com.intellij.openapi.compiler.*; -import com.intellij.openapi.diagnostic.Logger; -import com.intellij.openapi.module.Module; -import com.intellij.openapi.progress.ProgressIndicator; -import com.intellij.openapi.project.DumbService; -import com.intellij.openapi.project.Project; -import com.intellij.openapi.projectRoots.JavaSdk; -import com.intellij.openapi.projectRoots.JavaSdkVersion; -import com.intellij.openapi.projectRoots.Sdk; -import com.intellij.openapi.roots.CompilerModuleExtension; -import com.intellij.openapi.roots.ModuleRootManager; -import com.intellij.openapi.roots.ProjectFileIndex; -import com.intellij.openapi.roots.ProjectRootManager; -import com.intellij.openapi.util.text.StringUtil; -import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.psi.JavaPsiFacade; -import com.intellij.psi.PsiClass; -import com.intellij.psi.PsiFile; -import com.intellij.psi.PsiJavaFile; -import com.intellij.psi.search.GlobalSearchScope; -import com.intellij.psi.search.PsiSearchHelper; -import com.intellij.util.Processor; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import org.jetbrains.asm4.ClassReader; -import org.jetbrains.asm4.ClassWriter; - -import java.io.DataInput; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.Set; - -/** - * Based on NotNullVerifyingCompiler, kindly provided by JetBrains for reference. - */ -public abstract class AnnotationBasedInstrumentingCompiler implements ClassInstrumentingCompiler { - private static final Logger LOG = Logger.getInstance("org.intellij.lang.pattern.compiler.AnnotationBasedInstrumentingCompiler"); - - public AnnotationBasedInstrumentingCompiler() { - } - - @NotNull - public ProcessingItem[] getProcessingItems(final CompileContext context) { - if (!isEnabled()) { - return ProcessingItem.EMPTY_ARRAY; - } - - final Project project = context.getProject(); - final Set result = new HashSet(); - final PsiSearchHelper searchHelper = PsiSearchHelper.SERVICE.getInstance(context.getProject()); - - DumbService.getInstance(project).runReadActionInSmartMode(new Runnable() { - public void run() { - final String[] names = getAnnotationNames(project); - for (String name : names) { - final GlobalSearchScope scope = GlobalSearchScope.projectScope(project); - - final PsiClass psiClass = JavaPsiFacade.getInstance(project).findClass(name, GlobalSearchScope.allScope(project)); - if (psiClass == null) { - context.addMessage(CompilerMessageCategory.ERROR, "Cannot find class " + name, null, -1, -1); - continue; - } - - // wow, this is a sweet trick... ;) - searchHelper.processAllFilesWithWord(StringUtil.getShortName(name), scope, new Processor() { - public boolean process(PsiFile psifile) { - if (StdLanguages.JAVA == psifile.getLanguage() && psifile.getVirtualFile() != null && psifile instanceof PsiJavaFile) { - addClassFiles((PsiJavaFile)psifile, result, project); - } - return true; - } - }, true); - } - } - }); - return result.toArray(new ProcessingItem[result.size()]); - } - - private static void addClassFiles(PsiJavaFile srcFile, Set result, final Project project) { - - final VirtualFile sourceFile = srcFile.getVirtualFile(); - assert sourceFile != null; - - final ProjectFileIndex index = ProjectRootManager.getInstance(project).getFileIndex(); - final Module module = index.getModuleForFile(sourceFile); - if (module != null) { - final Sdk jdk = ModuleRootManager.getInstance(module).getSdk(); - final boolean jdk6 = jdk != null && JavaSdk.getInstance().isOfVersionOrHigher(jdk, JavaSdkVersion.JDK_1_6); - - final CompilerModuleExtension extension = CompilerModuleExtension.getInstance(module); - final VirtualFile compilerOutputPath = extension != null ? extension.getCompilerOutputPath() : null; - if (compilerOutputPath != null) { - final String packageName = srcFile.getPackageName(); - final VirtualFile packageDir = - packageName.length() > 0 ? compilerOutputPath.findFileByRelativePath(packageName.replace('.', '/')) : compilerOutputPath; - - if (packageDir != null && packageDir.isDirectory()) { - final PsiClass[] classes = srcFile.getClasses(); - final VirtualFile[] children = packageDir.getChildren(); - for (VirtualFile classFile : children) { - if (classFile.isDirectory() || !"class".equals(classFile.getExtension())) { - // no point in looking at directories or non-class files - continue; - } - final String name = classFile.getName(); - for (PsiClass clazz : classes) { - final String className = clazz.getName(); - if (className != null && name.startsWith(className)) { - result.add(new InstrumentationItem(classFile, jdk6)); - } - } - } - } - } - } - } - - public ProcessingItem[] process(final CompileContext context, final ProcessingItem[] items) { - final ProgressIndicator progressIndicator = context.getProgressIndicator(); - progressIndicator.setText(getProgressMessage()); - - final Project project = context.getProject(); - final ArrayList result = new ArrayList(items.length); - ApplicationManager.getApplication().runReadAction(new Runnable() { - - public void run() { - int filesProcessed = 0; - - for (ProcessingItem pi : items) { - final InstrumentationItem item = ((InstrumentationItem)pi); - final VirtualFile classFile = item.getClassFile(); - - try { - final byte[] bytes = classFile.contentsToByteArray(); - final ClassReader classreader; - try { - classreader = new ClassReader(bytes, 0, bytes.length); - } - catch (Exception e) { - LOG.debug("ASM failed to read class file <" + classFile.getPresentableUrl() + ">", e); - continue; - } - - final ClassWriter classwriter = new PsiClassWriter(project, item.isJDK6()); - final Instrumenter instrumenter = createInstrumenter(classwriter); - - classreader.accept(instrumenter, 0); - - if (instrumenter.instrumented()) { - // only dump the class if it has actually been instrumented - final FileOutputStream out = new FileOutputStream(classFile.getPath()); - try { - out.write(classwriter.toByteArray()); - } - finally { - out.close(); - } - } - - result.add(item); - progressIndicator.setFraction(++filesProcessed / (double)items.length); - } - catch (InstrumentationException e) { - context.addMessage(CompilerMessageCategory.ERROR, "[" + getDescription() + "]: " + e.getLocalizedMessage(), null, -1, -1); - } - catch (IOException e) { - context.addMessage(CompilerMessageCategory.ERROR, "[" + getDescription() + "]: " + e.getLocalizedMessage(), null, -1, -1); - } - } - } - }); - return result.toArray(new ProcessingItem[result.size()]); - } - - protected abstract boolean isEnabled(); - - protected abstract String[] getAnnotationNames(Project project); - - protected abstract Instrumenter createInstrumenter(ClassWriter classwriter); - - protected abstract String getProgressMessage(); - - public boolean validateConfiguration(CompileScope compilescope) { - return true; - } - - @Nullable - public ValidityState createValidityState(DataInput datainputstream) throws IOException { -// return TimestampValidityState.load(datainputstream); - return null; - } -} diff --git a/plugins/IntelliLang/java-support/org/intellij/plugins/intelliLang/pattern/compiler/impl/PatternValidationCompiler.java b/plugins/IntelliLang/java-support/org/intellij/plugins/intelliLang/pattern/compiler/impl/PatternValidationCompiler.java deleted file mode 100644 index 2d602471b30d..000000000000 --- a/plugins/IntelliLang/java-support/org/intellij/plugins/intelliLang/pattern/compiler/impl/PatternValidationCompiler.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright 2006 Sascha Weinreuter - * - * 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.intellij.plugins.intelliLang.pattern.compiler.impl; - -import com.intellij.codeInsight.AnnotationUtil; -import com.intellij.openapi.project.Project; -import com.intellij.openapi.util.Pair; -import com.intellij.psi.JavaPsiFacade; -import com.intellij.psi.PsiAnnotation; -import com.intellij.psi.PsiClass; -import com.intellij.psi.PsiMember; -import com.intellij.psi.search.GlobalSearchScope; -import com.intellij.psi.search.searches.AnnotatedMembersSearch; -import com.intellij.util.ArrayUtil; -import com.intellij.util.Processor; -import com.intellij.util.Query; -import org.intellij.plugins.intelliLang.Configuration; -import org.intellij.plugins.intelliLang.pattern.compiler.AnnotationBasedInstrumentingCompiler; -import org.intellij.plugins.intelliLang.pattern.compiler.Instrumenter; -import org.intellij.plugins.intelliLang.util.AnnotationUtilEx; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.asm4.ClassWriter; - -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - -public class PatternValidationCompiler extends AnnotationBasedInstrumentingCompiler { - - private final Map myAnnotations = new HashMap(); - - protected String[] getAnnotationNames(Project project) { - synchronized (myAnnotations) { - myAnnotations.clear(); - final Pair> patternAnnotation = - Configuration.getProjectInstance(project).getAdvancedConfiguration().getPatternAnnotationPair(); - - final GlobalSearchScope scope = GlobalSearchScope.allScope(project); - final PsiClass psiClass = JavaPsiFacade.getInstance(project).findClass(patternAnnotation.first, scope); - - if (psiClass == null) { - // annotation is not present in project's classpath, nothing to instrument - return ArrayUtil.EMPTY_STRING_ARRAY; - } - - final Query query = AnnotatedMembersSearch.search(psiClass, GlobalSearchScope.allScope(project)); - - query.forEach(new Processor() { - public boolean process(PsiMember psiMember) { - if (psiMember instanceof PsiClass) { - final PsiClass clazz = (PsiClass)psiMember; - if (clazz.isAnnotationType()) { - final PsiAnnotation annotation = AnnotationUtil.findAnnotation(clazz, patternAnnotation.second); - if (annotation != null) { - final String s = AnnotationUtilEx.calcAnnotationValue(annotation, "value"); - if (s != null) { - myAnnotations.put(clazz.getQualifiedName(), s); - } - } - } - } - return true; - } - }); - - myAnnotations.put(patternAnnotation.first, null); - - final Set names = myAnnotations.keySet(); - return ArrayUtil.toStringArray(names); - } - } - - protected boolean isEnabled() { - final Configuration.InstrumentationType option = Configuration.getInstance().getAdvancedConfiguration().getInstrumentation(); - return option == Configuration.InstrumentationType.ASSERT || option == Configuration.InstrumentationType.EXCEPTION; - } - - @NotNull - protected Instrumenter createInstrumenter(ClassWriter classwriter) { - synchronized (myAnnotations) { - final Configuration.InstrumentationType instrumentation = Configuration.getInstance().getAdvancedConfiguration().getInstrumentation(); - return new PatternValidationInstrumenter(new HashMap(myAnnotations), classwriter, instrumentation); - } - } - - protected String getProgressMessage() { - return "Inserting @Pattern assertions"; - } - - @NotNull - public String getDescription() { - return "Pattern Validation"; - } -} diff --git a/plugins/IntelliLang/src/META-INF/intellilang-java-support.xml b/plugins/IntelliLang/src/META-INF/intellilang-java-support.xml index 2821e74ae71b..f233b6399a6a 100644 --- a/plugins/IntelliLang/src/META-INF/intellilang-java-support.xml +++ b/plugins/IntelliLang/src/META-INF/intellilang-java-support.xml @@ -3,8 +3,6 @@ - - = 0) { - return true; - } - } - } - return false; - } - private static int getNextTwoPoints(int offset, String message) { for (int i = offset + 1; i < message.length(); i++) { char c = message.charAt(i); @@ -220,30 +194,18 @@ public class OutputParser{ } private static void processJavacMessages(final List javacMessages, final AntBuildMessageView messageView, Project project) { - if (javacMessages == null) return; - - boolean isJikes = false; - for (String errorMessage : javacMessages) { - if (isJikesMessage(errorMessage)) { - isJikes = true; - break; - } + if (javacMessages == null) { + return; } - com.intellij.compiler.OutputParser outputParser; - if (isJikes) { - outputParser = new JikesOutputParser(project); - } - else { - outputParser = new JavacOutputParser(project); - } + final com.intellij.compiler.OutputParser outputParser = new JavacOutputParser(project); com.intellij.compiler.OutputParser.Callback callback = new com.intellij.compiler.OutputParser.Callback() { private int myIndex = -1; @Nullable public String getCurrentLine() { - if (javacMessages == null || myIndex >= javacMessages.size()) { + if (myIndex >= javacMessages.size()) { return null; } return javacMessages.get(myIndex); @@ -289,7 +251,7 @@ public class OutputParser{ public void fileProcessed(String path) { } - public void fileGenerated(FileObject path) { + public void fileGenerated(String path) { } }; try { diff --git a/plugins/devkit/testSources/build/PluginModuleCompilationTest.java b/plugins/devkit/testSources/build/PluginModuleCompilationTest.java index 4a46d708e60a..d9862edcea97 100644 --- a/plugins/devkit/testSources/build/PluginModuleCompilationTest.java +++ b/plugins/devkit/testSources/build/PluginModuleCompilationTest.java @@ -67,11 +67,6 @@ public class PluginModuleCompilationTest extends BaseCompilerTestCase { return getProjectBasePath() + "/sandbox"; } - @Override - protected boolean useExternalCompiler() { - return true; - } - @Override protected void tearDown() throws Exception { new WriteAction() { diff --git a/plugins/google-app-engine/resources/META-INF/google-app-engine-plugin.xml b/plugins/google-app-engine/resources/META-INF/google-app-engine-plugin.xml index 445407413b8a..910b6fa5c5d4 100644 --- a/plugins/google-app-engine/resources/META-INF/google-app-engine-plugin.xml +++ b/plugins/google-app-engine/resources/META-INF/google-app-engine-plugin.xml @@ -15,7 +15,6 @@ - diff --git a/plugins/google-app-engine/source/com/intellij/appengine/enhancement/EnhancerCompiler.java b/plugins/google-app-engine/source/com/intellij/appengine/enhancement/EnhancerCompiler.java deleted file mode 100644 index 4e3d69f1c614..000000000000 --- a/plugins/google-app-engine/source/com/intellij/appengine/enhancement/EnhancerCompiler.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright 2000-2013 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * 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.appengine.enhancement; - -import com.intellij.openapi.compiler.CompileContext; -import com.intellij.openapi.compiler.generic.*; -import com.intellij.openapi.project.Project; -import com.intellij.util.io.DataExternalizer; -import com.intellij.util.io.KeyDescriptor; -import org.jetbrains.annotations.NotNull; - -/** - * @author nik - */ -public class EnhancerCompiler extends GenericCompiler { - public EnhancerCompiler(Project project) { - super("appengine-enhancer", 0, CompileOrderPlace.CLASS_POST_PROCESSING); - } - - @NotNull - @Override - public KeyDescriptor getItemKeyDescriptor() { - return STRING_KEY_DESCRIPTOR; - } - - @NotNull - @Override - public DataExternalizer getSourceStateExternalizer() { - return VirtualFileWithDependenciesState.EXTERNALIZER; - } - - @NotNull - @Override - public DataExternalizer getOutputStateExternalizer() { - return DummyPersistentState.EXTERNALIZER; - } - - @NotNull - @Override - public GenericCompilerInstance, String, VirtualFileWithDependenciesState, DummyPersistentState> createInstance( - @NotNull CompileContext context) { - return new EnhancerCompilerInstance(context); - } - - @NotNull - public String getDescription() { - return "Google App Engine Enhancer"; - } -} diff --git a/plugins/google-app-engine/source/com/intellij/appengine/enhancement/EnhancerCompilerInstance.java b/plugins/google-app-engine/source/com/intellij/appengine/enhancement/EnhancerCompilerInstance.java deleted file mode 100644 index b02b6cea9be8..000000000000 --- a/plugins/google-app-engine/source/com/intellij/appengine/enhancement/EnhancerCompilerInstance.java +++ /dev/null @@ -1,290 +0,0 @@ -/* - * Copyright 2000-2013 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * 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.appengine.enhancement; - -import com.intellij.appengine.facet.AppEngineFacet; -import com.intellij.appengine.rt.EnhancerRunner; -import com.intellij.appengine.sdk.AppEngineSdk; -import com.intellij.compiler.SymbolTable; -import com.intellij.compiler.impl.CompilerUtil; -import com.intellij.compiler.make.Cache; -import com.intellij.compiler.make.CacheCorruptedException; -import com.intellij.execution.CantRunException; -import com.intellij.execution.configurations.CommandLineBuilder; -import com.intellij.execution.configurations.GeneralCommandLine; -import com.intellij.execution.configurations.JavaParameters; -import com.intellij.execution.configurations.ParametersList; -import com.intellij.facet.FacetManager; -import com.intellij.openapi.application.ReadAction; -import com.intellij.openapi.application.Result; -import com.intellij.openapi.compiler.CompileContext; -import com.intellij.openapi.compiler.CompilerMessageCategory; -import com.intellij.openapi.compiler.ex.CompileContextEx; -import com.intellij.openapi.compiler.generic.*; -import com.intellij.openapi.diagnostic.Logger; -import com.intellij.openapi.fileTypes.StdFileTypes; -import com.intellij.openapi.module.Module; -import com.intellij.openapi.module.ModuleManager; -import com.intellij.openapi.progress.ProcessCanceledException; -import com.intellij.openapi.project.Project; -import com.intellij.openapi.roots.CompilerModuleExtension; -import com.intellij.openapi.roots.libraries.LibraryUtil; -import com.intellij.openapi.util.io.FileUtil; -import com.intellij.openapi.util.text.StringUtil; -import com.intellij.openapi.vfs.*; -import com.intellij.util.PathUtil; -import com.intellij.util.PathsList; -import com.intellij.util.SmartList; -import com.intellij.util.ThrowableRunnable; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.jps.appengine.model.PersistenceApi; - -import java.io.File; -import java.io.PrintWriter; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -/** - * @author nik - */ -public class EnhancerCompilerInstance extends GenericCompilerInstance { - private static final Logger LOG = Logger.getInstance("#com.intellij.appengine.enhancement.EnhancerCompilerInstance"); - private Project myProject; - - public EnhancerCompilerInstance(CompileContext context) { - super(context); - myProject = context.getProject(); - } - - @NotNull - @Override - public List getAllTargets() { - List targets = new ArrayList(); - for (Module module : ModuleManager.getInstance(myProject).getModules()) { - for (AppEngineFacet facet : FacetManager.getInstance(module).getFacetsByType(AppEngineFacet.ID)) { - if (facet.getConfiguration().isRunEnhancerOnMake()) { - final CompilerModuleExtension moduleExtension = CompilerModuleExtension.getInstance(module); - if (moduleExtension != null) { - final VirtualFile outputRoot = moduleExtension.getCompilerOutputPath(); - if (outputRoot != null) { - targets.add(new EnhancementTarget(facet, outputRoot)); - } - } - } - } - } - return targets; - } - - @NotNull - @Override - public List getSelectedTargets() { - return getAllTargets(); - } - - @Override - public void processObsoleteTarget(@NotNull String targetId, - @NotNull List> obsoleteItems) { - } - - @NotNull - @Override - public List getItems(@NotNull EnhancementTarget target) { - List items = new ArrayList(); - try { - final ClassFilesCollector classFilesCollector = new ClassFilesCollector((CompileContextEx)myContext, items, target.getFacet()); - classFilesCollector.collectItems(target.getOutputRoot(), ""); - } - catch (CacheCorruptedException e) { - myContext.addMessage(CompilerMessageCategory.ERROR, e.getMessage(), null, -1, -1); - LOG.info(e); - } - return items; - } - - @Override - public void processItems(@NotNull final EnhancementTarget target, - @NotNull final List> changedItems, - @NotNull List> obsoleteItems, - @NotNull final OutputConsumer consumer) { - CompilerUtil.runInContext(myContext, "Enhancing classes...", new ThrowableRunnable() { - @Override - public void run() { - List toEnhance = new ArrayList(); - for (GenericCompilerProcessingItem item : changedItems) { - final ClassFileItem classFileItem = item.getItem(); - if (myContext.getCompileScope().belongs(classFileItem.getSourceFile().getUrl())) { - toEnhance.add(classFileItem); - } - } - - if (!toEnhance.isEmpty()) { - if (runEnhancer(target.getFacet(), toEnhance)) { - for (ClassFileItem item : toEnhance) { - consumer.addProcessedItem(item); - } - } - } - } - }); - - } - - private boolean runEnhancer(final AppEngineFacet facet, final Collection items) { - try { - final AppEngineSdk sdk = facet.getSdk(); - if (!sdk.isValid()) { - throw new CantRunException("Valid App Engine SDK isn't specified for '" + facet.getName() + "' facet (module '" + facet.getModule().getName() + "')"); - } - - final JavaParameters javaParameters = new JavaParameters(); - new ReadAction() { - protected void run(final Result result) throws Throwable { - myContext.getProgressIndicator().setText2("'" + facet.getModule().getName() + "' module, processing " + items.size() + " classes..."); - javaParameters.configureByModule(facet.getModule(), JavaParameters.JDK_AND_CLASSES); - - final PathsList classPath = javaParameters.getClassPath(); - classPath.addFirst(sdk.getToolsApiJarFile().getAbsolutePath()); - removeAsmJarFromClasspath(classPath); - - final ParametersList vmParameters = javaParameters.getVMParametersList(); - vmParameters.add("-Xmx256m"); - - javaParameters.setMainClass(EnhancerRunner.class.getName()); - classPath.addFirst(PathUtil.getJarPathForClass(EnhancerRunner.class)); - - final File argsFile = FileUtil.createTempFile("appEngineEnhanceFiles", ".txt"); - PrintWriter writer = new PrintWriter(argsFile); - try { - for (ClassFileItem item : items) { - writer.println(FileUtil.toSystemDependentName(item.getFile().getPath())); - } - } - finally { - writer.close(); - } - - final ParametersList programParameters = javaParameters.getProgramParametersList(); - programParameters.add(argsFile.getAbsolutePath()); - programParameters.add("com.google.appengine.tools.enhancer.Enhance"); - programParameters.add("-api"); - PersistenceApi api = facet.getConfiguration().getPersistenceApi(); - programParameters.add(api.getEnhancerApiName()); - if (api.getEnhancerVersion() == 2) { - programParameters.add("-enhancerVersion"); - programParameters.add("v2"); - } - programParameters.add("-v"); - - } - }.execute().throwException(); - - - final GeneralCommandLine commandLine = CommandLineBuilder.createFromJavaParameters(javaParameters); - if (LOG.isDebugEnabled()) { - LOG.debug("starting enhancer: " + commandLine.getCommandLineString()); - } - final Process process = commandLine.createProcess(); - EnhancerProcessHandler handler = new EnhancerProcessHandler(process, commandLine.getCommandLineString(), myContext); - handler.startNotify(); - handler.waitFor(); - } - catch (ProcessCanceledException e) { - throw e; - } - catch (Throwable e) { - myContext.addMessage(CompilerMessageCategory.ERROR, e.getMessage(), null, -1, -1); - LOG.info(e); - } - return myContext.getMessageCount(CompilerMessageCategory.ERROR) == 0; - } - - private static void removeAsmJarFromClasspath(PathsList classPath) { - List toRemove = new ArrayList(); - for (String filePath : classPath.getPathList()) { - if (filePath.endsWith(".jar")) { - final VirtualFile root = - JarFileSystem.getInstance().findFileByPath(FileUtil.toSystemIndependentName(filePath) + JarFileSystem.JAR_SEPARATOR); - if (root != null && LibraryUtil.isClassAvailableInLibrary(new VirtualFile[]{root}, "org.objectweb.asm.ClassReader")) { - toRemove.add(filePath); - } - } - } - for (String path : toRemove) { - classPath.remove(path); - } - } - - private static class ClassFilesCollector { - private CompileContextEx myContext; - private List myItems; - private AppEngineFacet myFacet; - private final SymbolTable mySymbolTable; - private final Cache myCache; - private final LocalFileSystem myLocalFileSystem; - - public ClassFilesCollector(CompileContextEx context, - List items, - AppEngineFacet facet) throws CacheCorruptedException { - myContext = context; - myItems = items; - myFacet = facet; - mySymbolTable = myContext.getDependencyCache().getSymbolTable(); - myCache = myContext.getDependencyCache().getCache(); - myLocalFileSystem = LocalFileSystem.getInstance(); - } - - public void collectItems(@NotNull VirtualFile file, final String fullName) throws CacheCorruptedException { - VfsUtilCore.visitChildrenRecursively(file, new VirtualFileVisitor() { - { setValueForChildren(fullName); } - - @Override - public boolean visitFile(@NotNull VirtualFile file) { - try { - final String fullName = getCurrentValue(); - if (file.isDirectory()) { - setValueForChildren(StringUtil.getQualifiedName(fullName, file.getName())); - } - else if (StdFileTypes.CLASS.equals(file.getFileType())) { - final VirtualFile sourceFile = myContext.getSourceFileByOutputFile(file); - if (sourceFile != null && myFacet.shouldRunEnhancerFor(sourceFile)) { - String className = StringUtil.trimEnd(fullName, ".class"); - int classId = mySymbolTable.getId(className); - List dependencies = new SmartList(); - while (classId != Cache.UNKNOWN) { - final String path = myCache.getPath(classId); - if (!StringUtil.isEmpty(path)) { - final VirtualFile classFile = myLocalFileSystem.findFileByPath(FileUtil.toSystemIndependentName(path)); - if (classFile != null) { - dependencies.add(classFile); - } - } - classId = myCache.getSuperQualifiedName(classId); - } - myItems.add(new ClassFileItem(file, sourceFile, dependencies)); - } - } - return true; - } - catch (CacheCorruptedException e) { - throw new VisitorException(e); - } - } - }, CacheCorruptedException.class); - } - } -} diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/compiler/GroovyCompiler.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/compiler/GroovyCompiler.java deleted file mode 100644 index 9c714e1be66d..000000000000 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/compiler/GroovyCompiler.java +++ /dev/null @@ -1,165 +0,0 @@ -/* - * Copyright 2000-2014 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.plugins.groovy.compiler; - -import com.intellij.compiler.CompilerConfiguration; -import com.intellij.openapi.compiler.CompileContext; -import com.intellij.openapi.compiler.CompileScope; -import com.intellij.openapi.compiler.CompilerManager; -import com.intellij.openapi.diagnostic.Logger; -import com.intellij.openapi.module.Module; -import com.intellij.openapi.project.Project; -import com.intellij.openapi.projectRoots.JavaSdkType; -import com.intellij.openapi.projectRoots.Sdk; -import com.intellij.openapi.roots.ModuleRootManager; -import com.intellij.openapi.roots.ProjectFileIndex; -import com.intellij.openapi.roots.ProjectRootManager; -import com.intellij.openapi.roots.ui.configuration.ClasspathEditor; -import com.intellij.openapi.roots.ui.configuration.ModulesConfigurator; -import com.intellij.openapi.ui.Messages; -import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.psi.search.FilenameIndex; -import com.intellij.psi.search.GlobalSearchScope; -import icons.JetgroovyIcons; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.plugins.groovy.GroovyBundle; -import org.jetbrains.plugins.groovy.GroovyFileType; -import org.jetbrains.plugins.groovy.GroovyFileTypeLoader; -import org.jetbrains.plugins.groovy.config.GroovyFacetUtil; -import org.jetbrains.plugins.groovy.util.LibrariesUtil; - -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -/** - * @author Dmitry.Krasilschikov - */ - -public class GroovyCompiler extends GroovyCompilerBase { - private static final Logger LOG = Logger.getInstance("#org.jetbrains.plugins.groovy.compiler.GroovyCompiler"); - private static final String AST_TRANSFORM_FILE_NAME = "org.codehaus.groovy.transform.ASTTransformation"; - - public GroovyCompiler(Project project) { - super(project); - } - - @Override - @NotNull - public String getDescription() { - return "groovy compiler"; - } - - @Override - protected void compileFiles(final CompileContext context, final Module module, List toCompile, OutputSink sink, boolean tests) { - context.getProgressIndicator().checkCanceled(); - context.getProgressIndicator().setText("Starting Groovy compiler..."); - - runGroovycCompiler(context, module, toCompile, false, getMainOutput(context, module, tests), sink, tests); - } - - @Override - public boolean validateConfiguration(CompileScope compileScope) { - VirtualFile[] files = compileScope.getFiles(GroovyFileType.GROOVY_FILE_TYPE, true); - if (files.length == 0) return true; - - final Set scriptExtensions = GroovyFileTypeLoader.getCustomGroovyScriptExtensions(); - - final CompilerManager compilerManager = CompilerManager.getInstance(myProject); - Set modules = new HashSet(); - for (VirtualFile file : files) { - if (scriptExtensions.contains(file.getExtension()) || - compilerManager.isExcludedFromCompilation(file) || - CompilerConfiguration.getInstance(myProject).isResourceFile(file)) { - continue; - } - - ProjectRootManager rootManager = ProjectRootManager.getInstance(myProject); - Module module = rootManager.getFileIndex().getModuleForFile(file); - if (module != null) { - modules.add(module); - } - } - - Set nojdkModules = new HashSet(); - for (Module module : modules) { - if(!GroovyFacetUtil.isSuitableModule(module)) continue; - final Sdk sdk = ModuleRootManager.getInstance(module).getSdk(); - if (sdk == null || !(sdk.getSdkType() instanceof JavaSdkType)) { - nojdkModules.add(module); - continue; - } - - if (!LibrariesUtil.hasGroovySdk(module)) { - if (!GroovyFacetUtil.tryToSetUpGroovyFacetOnTheFly(module)) { - Messages.showErrorDialog(myProject, GroovyBundle.message("cannot.compile.groovy.files.no.facet", module.getName()), - GroovyBundle.message("cannot.compile")); - ModulesConfigurator.showDialog(module.getProject(), module.getName(), ClasspathEditor.NAME); - return false; - } - } - } - - if (!nojdkModules.isEmpty()) { - final Module[] noJdkArray = nojdkModules.toArray(new Module[nojdkModules.size()]); - if (noJdkArray.length == 1) { - Messages.showErrorDialog(myProject, GroovyBundle.message("cannot.compile.groovy.files.no.sdk", noJdkArray[0].getName()), - GroovyBundle.message("cannot.compile")); - } - else { - StringBuilder modulesList = new StringBuilder(); - for (int i = 0; i < noJdkArray.length; i++) { - if (i > 0) modulesList.append(", "); - modulesList.append(noJdkArray[i].getName()); - } - Messages.showErrorDialog(myProject, GroovyBundle.message("cannot.compile.groovy.files.no.sdk.mult", modulesList.toString()), - GroovyBundle.message("cannot.compile")); - } - return false; - } - - final GroovyCompilerConfiguration configuration = GroovyCompilerConfiguration.getInstance(myProject); - if (!configuration.transformsOk && needTransformCopying(compileScope)) { - final int result = Messages.showYesNoDialog(myProject, - "You seem to have global Groovy AST transformations defined in your project,\n" + - "but they won't be applied to your code because they are not marked as compiler resources.\n" + - "Do you want to add them to compiler resource list?\n" + - "(you can do it yourself later in Settings | Compiler | Resource patterns)", - "AST Transformations Found", - JetgroovyIcons.Groovy.Groovy_32x32); - if (result == Messages.YES) { - CompilerConfiguration.getInstance(myProject).addResourceFilePattern(AST_TRANSFORM_FILE_NAME); - } else { - configuration.transformsOk = true; - } - } - - return true; - } - - private boolean needTransformCopying(CompileScope compileScope) { - final CompilerConfiguration configuration = CompilerConfiguration.getInstance(myProject); - final ProjectFileIndex index = ProjectRootManager.getInstance(myProject).getFileIndex(); - for (VirtualFile file : FilenameIndex.getVirtualFilesByName(myProject, AST_TRANSFORM_FILE_NAME, GlobalSearchScope.projectScope(myProject))) { - if (compileScope.belongs(file.getUrl()) && index.isInSource(file) && !configuration.isResourceFile(file)) { - return true; - } - } - return false; - } - -} diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/compiler/GroovyCompilerBase.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/compiler/GroovyCompilerBase.java deleted file mode 100644 index b810b6898f21..000000000000 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/compiler/GroovyCompilerBase.java +++ /dev/null @@ -1,432 +0,0 @@ -/* - * Copyright 2000-2014 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.plugins.groovy.compiler; - -import com.intellij.compiler.CompilerConfiguration; -import com.intellij.compiler.impl.CompilerUtil; -import com.intellij.compiler.impl.FileSetCompileScope; -import com.intellij.compiler.impl.TranslatingCompilerFilesMonitor; -import com.intellij.compiler.impl.javaCompiler.ModuleChunk; -import com.intellij.compiler.impl.javaCompiler.OutputItemImpl; -import com.intellij.compiler.make.CacheCorruptedException; -import com.intellij.compiler.make.DependencyCache; -import com.intellij.execution.ExecutionException; -import com.intellij.execution.configurations.JavaParameters; -import com.intellij.openapi.application.AccessToken; -import com.intellij.openapi.application.ApplicationManager; -import com.intellij.openapi.application.PathManager; -import com.intellij.openapi.compiler.CompileContext; -import com.intellij.openapi.compiler.CompilerMessageCategory; -import com.intellij.openapi.compiler.CompilerPaths; -import com.intellij.openapi.compiler.TranslatingCompiler; -import com.intellij.openapi.compiler.ex.CompileContextEx; -import com.intellij.openapi.diagnostic.Logger; -import com.intellij.openapi.fileTypes.FileType; -import com.intellij.openapi.fileTypes.StdFileTypes; -import com.intellij.openapi.module.Module; -import com.intellij.openapi.progress.ProgressIndicator; -import com.intellij.openapi.progress.ProgressManager; -import com.intellij.openapi.project.Project; -import com.intellij.openapi.projectRoots.JavaSdkType; -import com.intellij.openapi.projectRoots.JdkUtil; -import com.intellij.openapi.projectRoots.Sdk; -import com.intellij.openapi.projectRoots.SdkTypeId; -import com.intellij.openapi.roots.ContentIterator; -import com.intellij.openapi.roots.ModuleFileIndex; -import com.intellij.openapi.roots.ModuleRootManager; -import com.intellij.openapi.roots.OrderRootType; -import com.intellij.openapi.roots.libraries.Library; -import com.intellij.openapi.util.Comparing; -import com.intellij.openapi.util.io.FileUtil; -import com.intellij.openapi.vfs.CharsetToolkit; -import com.intellij.openapi.vfs.LocalFileSystem; -import com.intellij.openapi.vfs.VfsUtilCore; -import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.openapi.vfs.encoding.EncodingProjectManager; -import com.intellij.psi.PsiFile; -import com.intellij.psi.PsiManager; -import com.intellij.util.*; -import com.intellij.util.cls.ClsFormatException; -import com.intellij.util.containers.ContainerUtil; -import com.intellij.util.net.HttpConfigurable; -import gnu.trove.THashSet; -import org.jetbrains.annotations.Nullable; -import org.jetbrains.groovy.compiler.rt.GroovycRunner; -import org.jetbrains.jps.incremental.groovy.GroovycOSProcessHandler; -import org.jetbrains.jps.incremental.messages.BuildMessage; -import org.jetbrains.jps.incremental.messages.CompilerMessage; -import org.jetbrains.plugins.groovy.GroovyFileType; -import org.jetbrains.plugins.groovy.config.GroovyConfigUtils; -import org.jetbrains.plugins.groovy.config.GroovyFacetUtil; -import org.jetbrains.plugins.groovy.extensions.GroovyScriptType; -import org.jetbrains.plugins.groovy.lang.psi.GroovyFile; -import org.jetbrains.plugins.groovy.runner.GroovyScriptUtil; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.nio.charset.Charset; -import java.util.*; - -/** - * @author peter - */ -public abstract class GroovyCompilerBase implements TranslatingCompiler { - private static final Logger LOG = Logger.getInstance("#org.jetbrains.plugins.groovy.compiler.GroovyCompilerBase"); - protected final Project myProject; - - public GroovyCompilerBase(Project project) { - myProject = project; - } - - protected void runGroovycCompiler(final CompileContext compileContext, final Module module, - final List toCompile, - boolean forStubs, - VirtualFile outputDir, - OutputSink sink, boolean tests) { - //assert !ApplicationManager.getApplication().isDispatchThread(); - final Sdk sdk = ModuleRootManager.getInstance(module).getSdk(); - assert sdk != null; //verified before - SdkTypeId sdkType = sdk.getSdkType(); - assert sdkType instanceof JavaSdkType; - final String exePath = ((JavaSdkType)sdkType).getVMExecutablePath(sdk); - - final JavaParameters parameters = new JavaParameters(); - final PathsList classPathBuilder = parameters.getClassPath(); - - // IMPORTANT: must be the first entry to avoid collisions - classPathBuilder.add(PathUtil.getJarPathForClass(GroovycRunner.class)); - - final ModuleChunk chunk = createChunk(module, compileContext); - - final Library[] libraries = GroovyConfigUtils.getInstance().getSDKLibrariesByModule(module); - if (libraries.length > 0) { - classPathBuilder.addVirtualFiles(Arrays.asList(libraries[0].getFiles(OrderRootType.CLASSES))); - } - - classPathBuilder.addVirtualFiles(chunk.getCompilationBootClasspathFiles(false)); - classPathBuilder.addVirtualFiles(chunk.getCompilationClasspathFiles(false)); - appendOutputPath(module, classPathBuilder, false); - if (tests) { - appendOutputPath(module, classPathBuilder, true); - } - - final List patchers = new SmartList(); - - AccessToken accessToken = ApplicationManager.getApplication().acquireReadActionLock(); - try { - for (final GroovyCompilerExtension extension : GroovyCompilerExtension.EP_NAME.getExtensions()) { - extension.enhanceCompilationClassPath(chunk, classPathBuilder); - patchers.addAll(extension.getCompilationUnitPatchers(chunk)); - } - } - finally { - accessToken.finish(); - } - - final boolean profileGroovyc = "true".equals(System.getProperty("profile.groovy.compiler")); - if (profileGroovyc) { - parameters.getVMParametersList().defineProperty("java.library.path", PathManager.getBinPath()); - parameters.getVMParametersList().defineProperty("profile.groovy.compiler", "true"); - parameters.getVMParametersList().add("-agentlib:yjpagent=disablej2ee,disablealloc,delay=10000,sessionname=GroovyCompiler"); - classPathBuilder.add(PathManager.findFileInLibDirectory("yjp-controller-api-redist.jar").getAbsolutePath()); - } - - final GroovyCompilerConfiguration compilerConfiguration = GroovyCompilerConfiguration.getInstance(myProject); - parameters.getVMParametersList().add("-Xmx" + compilerConfiguration.getHeapSize() + "m"); - if (profileGroovyc) { - parameters.getVMParametersList().add("-XX:+HeapDumpOnOutOfMemoryError"); - } - parameters.getVMParametersList().addAll(HttpConfigurable.convertArguments(HttpConfigurable.getJvmPropertiesList(false, null))); - - //debug - //parameters.getVMParametersList().add("-Xdebug"); parameters.getVMParametersList().add("-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5239"); - - // Setting up process encoding according to locale - final ArrayList list = new ArrayList(); - CompilerUtil.addLocaleOptions(list, false); - for (String s : list) { - parameters.getVMParametersList().add(s); - } - - parameters.setMainClass(GroovycRunner.class.getName()); - - List finalOutputs = ContainerUtil.newArrayList(); - for (Module eachModule : chunk.getModules()) { - final VirtualFile finalOutputDir = getMainOutput(compileContext, eachModule, tests); - if (finalOutputDir == null) { - compileContext.addMessage(CompilerMessageCategory.ERROR, "No output directory for module " + eachModule.getName() + (tests ? " tests" : " production"), null, -1, -1); - return; - } - finalOutputs.add(FileUtil.toSystemDependentName(finalOutputDir.getPath())); - } - - final Charset ideCharset = EncodingProjectManager.getInstance(myProject).getDefaultCharset(); - String encoding = ideCharset != null && !Comparing.equal(CharsetToolkit.getDefaultSystemCharset(), ideCharset) ? ideCharset.name() : null; - Set paths2Compile = ContainerUtil.map2Set(toCompile, new Function() { - @Override - public String fun(VirtualFile file) { - return file.getPath(); - } - }); - Map class2Src = new HashMap(); - - for (VirtualFile file : enumerateGroovyFiles(module)) { - if (!paths2Compile.contains(file.getPath())) { - for (String name : TranslatingCompilerFilesMonitor.getInstance().getCompiledClassNames(file, myProject)) { - class2Src.put(name, file.getPath()); - } - } - } - - final File fileWithParameters; - try { - fileWithParameters = GroovycOSProcessHandler - .fillFileWithGroovycParameters(outputDir.getPath(), paths2Compile, finalOutputs, - class2Src, encoding, patchers, ""); - } - catch (IOException e) { - LOG.info(e); - compileContext.addMessage(CompilerMessageCategory.ERROR, "Error creating a temp file to launch Groovy compiler: " + e.getMessage(), null, -1, -1); - return; - } - - parameters.getProgramParametersList().add("do_not_optimize"); - parameters.getProgramParametersList().add(forStubs ? "stubs" : "groovyc"); - parameters.getProgramParametersList().add(fileWithParameters.getPath()); - if (compilerConfiguration.isInvokeDynamic()) { - parameters.getProgramParametersList().add("--indy"); - } - - try { - Process process = JdkUtil.setupJVMCommandLine(exePath, parameters, true).createProcess(); - GroovycOSProcessHandler processHandler = GroovycOSProcessHandler.runGroovyc(process, new Consumer() { - @Override - public void consume(String s) { - compileContext.getProgressIndicator().setText(s); - } - }); - - final List toRecompile = new ArrayList(); - for (File toRecompileFile : processHandler.getToRecompileFiles()) { - final VirtualFile vFile = LocalFileSystem.getInstance().findFileByIoFile(toRecompileFile); - LOG.assertTrue(vFile != null); - toRecompile.add(vFile); - } - - for (CompilerMessage compilerMessage : processHandler.getCompilerMessages(module.getName())) { - final String url = compilerMessage.getSourcePath(); - compileContext.addMessage(getMessageCategory(compilerMessage), compilerMessage.getMessageText(), - url == null ? null : VfsUtilCore.pathToUrl(FileUtil.toSystemIndependentName(url)), - (int)compilerMessage.getLine(), - (int)compilerMessage.getColumn()); - } - - List outputItems = processHandler.getSuccessfullyCompiled(); - ArrayList items = new ArrayList(); - if (forStubs) { - List outputPaths = new ArrayList(); - for (final GroovycOSProcessHandler.OutputItem outputItem : outputItems) { - outputPaths.add(outputItem.outputPath); - } - addStubsToCompileScope(outputPaths, compileContext, module); - } - else { - final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator(); - if (indicator != null) { - indicator.setText("Updating caches..."); - } - - final DependencyCache dependencyCache = ((CompileContextEx)compileContext).getDependencyCache(); - for (GroovycOSProcessHandler.OutputItem outputItem : outputItems) { - final VirtualFile sourceVirtualFile = LocalFileSystem.getInstance().findFileByIoFile(new File(outputItem.sourcePath)); - if (sourceVirtualFile == null) { - continue; - } - - if (indicator != null) { - indicator.setText2(sourceVirtualFile.getName()); - } - - LocalFileSystem.getInstance().refreshAndFindFileByIoFile(new File(outputItem.outputPath)); - items.add(new OutputItemImpl(outputItem.outputPath, sourceVirtualFile)); - - final File classFile = new File(outputItem.outputPath); - try { - dependencyCache.reparseClassFile(classFile, FileUtil.loadFileBytes(classFile)); - } - catch (ClsFormatException e) { - LOG.error(e); - } - catch (CacheCorruptedException e) { - LOG.error(e); - } - catch (FileNotFoundException ignored) { - } - catch (IOException e) { - LOG.error(e); - } - } - } - - sink.add(outputDir.getPath(), items, VfsUtilCore.toVirtualFileArray(toRecompile)); - } - catch (ExecutionException e) { - LOG.info(e); - compileContext.addMessage(CompilerMessageCategory.ERROR, "Error running Groovy compiler: " + e.getMessage(), null, -1, -1); - } - } - - protected Set enumerateGroovyFiles(final Module module) { - final Set moduleClasses = new THashSet(); - ModuleRootManager.getInstance(module).getFileIndex().iterateContent(new ContentIterator() { - @Override - public boolean processFile(final VirtualFile vfile) { - if (!vfile.isDirectory() && - GroovyFileType.GROOVY_FILE_TYPE.equals(vfile.getFileType())) { - - AccessToken accessToken = ApplicationManager.getApplication().acquireReadActionLock(); - - try { - if (PsiManager.getInstance(myProject).findFile(vfile) instanceof GroovyFile) { - moduleClasses.add(vfile); - } - } - finally { - accessToken.finish(); - } - } - return true; - } - }); - return moduleClasses; - } - - protected static void addStubsToCompileScope(List outputPaths, CompileContext compileContext, Module module) { - List stubFiles = new ArrayList(); - for (String outputPath : outputPaths) { - final File stub = new File(outputPath); - CompilerUtil.refreshIOFile(stub); - final VirtualFile file = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(stub); - ContainerUtil.addIfNotNull(file, stubFiles); - } - ((CompileContextEx)compileContext).addScope(new FileSetCompileScope(stubFiles, new Module[]{module})); - } - - @Nullable - protected static VirtualFile getMainOutput(CompileContext compileContext, Module module, boolean tests) { - return tests ? compileContext.getModuleOutputDirectoryForTests(module) : compileContext.getModuleOutputDirectory(module); - } - - private static CompilerMessageCategory getMessageCategory(CompilerMessage compilerMessage) { - BuildMessage.Kind category = compilerMessage.getKind(); - - if (BuildMessage.Kind.ERROR.equals(category)) return CompilerMessageCategory.ERROR; - if (BuildMessage.Kind.INFO.equals(category)) return CompilerMessageCategory.INFORMATION; - if (BuildMessage.Kind.WARNING.equals(category)) return CompilerMessageCategory.WARNING; - - return CompilerMessageCategory.ERROR; - } - - private static void appendOutputPath(Module module, PathsList compileClasspath, final boolean forTestClasses) { - String output = CompilerPaths.getModuleOutputPath(module, forTestClasses); - if (output != null) { - compileClasspath.add(FileUtil.toSystemDependentName(output)); - } - } - - private static ModuleChunk createChunk(Module module, CompileContext context) { - return new ModuleChunk((CompileContextEx)context, new Chunk(module), Collections.>emptyMap()); - } - - @Override - public void compile(final CompileContext compileContext, Chunk moduleChunk, final VirtualFile[] virtualFiles, OutputSink sink) { - Map> mapModulesToVirtualFiles; - if (moduleChunk.getNodes().size() == 1) { - mapModulesToVirtualFiles = Collections.singletonMap(moduleChunk.getNodes().iterator().next(), Arrays.asList(virtualFiles)); - } - else { - mapModulesToVirtualFiles = CompilerUtil.buildModuleToFilesMap(compileContext, virtualFiles); - } - for (final Module module : moduleChunk.getNodes()) { - final List moduleFiles = mapModulesToVirtualFiles.get(module); - if (moduleFiles == null) { - continue; - } - - final ModuleFileIndex index = ModuleRootManager.getInstance(module).getFileIndex(); - final List toCompile = new ArrayList(); - final List toCompileTests = new ArrayList(); - final CompilerConfiguration configuration = CompilerConfiguration.getInstance(myProject); - final PsiManager psiManager = PsiManager.getInstance(myProject); - - if (GroovyFacetUtil.isSuitableModule(module)) { - for (final VirtualFile file : moduleFiles) { - if (shouldCompile(file, configuration, psiManager)) { - (index.isInTestSourceContent(file) ? toCompileTests : toCompile).add(file); - } - } - } - - if (!toCompile.isEmpty()) { - compileFiles(compileContext, module, toCompile, sink, false); - } - if (!toCompileTests.isEmpty()) { - compileFiles(compileContext, module, toCompileTests, sink, true); - } - - } - - } - - private static boolean shouldCompile(final VirtualFile file, CompilerConfiguration configuration, final PsiManager manager) { - if (configuration.isResourceFile(file)) { - return false; - } - - final FileType fileType = file.getFileType(); - if (fileType == GroovyFileType.GROOVY_FILE_TYPE) { - AccessToken accessToken = ApplicationManager.getApplication().acquireReadActionLock(); - - try { - PsiFile psiFile = manager.findFile(file); - if (psiFile instanceof GroovyFile && ((GroovyFile)psiFile).isScript()) { - final GroovyScriptType scriptType = GroovyScriptUtil.getScriptType((GroovyFile)psiFile); - return scriptType.shouldBeCompiled((GroovyFile)psiFile); - } - return true; - } - finally { - accessToken.finish(); - } - } - - return fileType == StdFileTypes.JAVA; - } - - protected abstract void compileFiles(CompileContext compileContext, Module module, - List toCompile, OutputSink sink, boolean tests); - - @Override - public boolean isCompilableFile(VirtualFile file, CompileContext context) { - final boolean result = GroovyFileType.GROOVY_FILE_TYPE.equals(file.getFileType()); - if (result && LOG.isDebugEnabled()) { - LOG.debug("compilable file: " + file.getPath()); - } - return result; - } -} diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/compiler/GroovyCompilerLoader.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/compiler/GroovyCompilerLoader.java index b8f6e94d8149..eafcd9a108ad 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/compiler/GroovyCompilerLoader.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/compiler/GroovyCompilerLoader.java @@ -21,46 +21,60 @@ import com.intellij.openapi.fileEditor.FileEditor; import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.fileEditor.FileEditorManagerAdapter; import com.intellij.openapi.fileEditor.FileEditorManagerListener; -import com.intellij.openapi.fileTypes.FileType; -import com.intellij.openapi.fileTypes.StdFileTypes; +import com.intellij.openapi.module.Module; +import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.project.Project; +import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; +import com.intellij.psi.JavaPsiFacade; import com.intellij.psi.PsiClass; +import com.intellij.psi.search.GlobalSearchScope; import com.intellij.ui.EditorNotificationPanel; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.groovy.GroovyFileType; -import org.jetbrains.plugins.groovy.compiler.generator.GroovycStubGenerator; import java.util.Arrays; -import java.util.HashSet; /** * @author ilyas */ public class GroovyCompilerLoader extends AbstractProjectComponent { + public static final String GROOVY_STUBS = "groovyStubs"; + public GroovyCompilerLoader(Project project) { super(project); } + @Nullable + public static PsiClass findClassByStub(Project project, VirtualFile stubFile) { + final String[] components = StringUtil.trimEnd(stubFile.getPath(), ".java").split("[\\\\/]"); + final int stubs = Arrays.asList(components).indexOf(GROOVY_STUBS); + if (stubs < 0 || stubs >= components.length - 3) { + return null; + } + + final String moduleName = components[stubs + 1]; + final Module module = ModuleManager.getInstance(project).findModuleByName(moduleName); + if (module == null) { + return null; + } + + final String fqn = StringUtil.join(Arrays.asList(components).subList(stubs + 3, components.length), "."); + return JavaPsiFacade.getInstance(project).findClass(fqn, GlobalSearchScope.moduleScope(module)); + } + @Override public void projectOpened() { CompilerManager compilerManager = CompilerManager.getInstance(myProject); compilerManager.addCompilableFileType(GroovyFileType.GROOVY_FILE_TYPE); - compilerManager.addTranslatingCompiler(new GroovycStubGenerator(myProject), - new HashSet(Arrays.asList(StdFileTypes.JAVA, GroovyFileType.GROOVY_FILE_TYPE)), - new HashSet(Arrays.asList(StdFileTypes.JAVA))); - - compilerManager.addTranslatingCompiler(new GroovyCompiler(myProject), - new HashSet(Arrays.asList(GroovyFileType.GROOVY_FILE_TYPE, StdFileTypes.CLASS)), - new HashSet(Arrays.asList(StdFileTypes.CLASS))); - myProject.getMessageBus().connect().subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER, new FileEditorManagerAdapter() { @Override public void fileOpened(@NotNull FileEditorManager source, @NotNull final VirtualFile file) { - if (file.getName().endsWith(".java") && file.getPath().contains(GroovycStubGenerator.GROOVY_STUBS)) { - final PsiClass psiClass = GroovycStubGenerator.findClassByStub(myProject, file); + if (file.getName().endsWith(".java") && file.getPath().contains(GROOVY_STUBS)) { + final PsiClass psiClass = findClassByStub(myProject, file); if (psiClass != null) { final FileEditorManager fileEditorManager = FileEditorManager.getInstance(myProject); final FileEditor[] editors = fileEditorManager.getEditors(file); @@ -80,7 +94,7 @@ public class GroovyCompilerLoader extends AbstractProjectComponent { panel.createActionLabel("Go to the Groovy class", new Runnable() { @Override public void run() { - final PsiClass original = GroovycStubGenerator.findClassByStub(myProject, file); + final PsiClass original = findClassByStub(myProject, file); if (original != null) { original.navigate(true); } @@ -89,7 +103,7 @@ public class GroovyCompilerLoader extends AbstractProjectComponent { panel.createActionLabel("Exclude from stub generation", new Runnable() { @Override public void run() { - final PsiClass psiClass = GroovycStubGenerator.findClassByStub(myProject, file); + final PsiClass psiClass = findClassByStub(myProject, file); if (psiClass != null) { ExcludeFromStubGenerationAction.doExcludeFromStubGeneration(psiClass.getContainingFile()); } diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/compiler/generator/GroovycStubGenerator.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/compiler/generator/GroovycStubGenerator.java deleted file mode 100644 index bfdd0eb55e7a..000000000000 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/compiler/generator/GroovycStubGenerator.java +++ /dev/null @@ -1,270 +0,0 @@ -/* - * Copyright 2000-2014 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.plugins.groovy.compiler.generator; - -import com.intellij.compiler.impl.CompilerUtil; -import com.intellij.compiler.impl.FileSetCompileScope; -import com.intellij.compiler.impl.TranslatingCompilerFilesMonitor; -import com.intellij.ide.highlighter.JavaFileType; -import com.intellij.openapi.application.AccessToken; -import com.intellij.openapi.application.ApplicationManager; -import com.intellij.openapi.application.ModalityState; -import com.intellij.openapi.application.WriteAction; -import com.intellij.openapi.compiler.CompileContext; -import com.intellij.openapi.compiler.CompileScope; -import com.intellij.openapi.compiler.CompilerPaths; -import com.intellij.openapi.compiler.ex.CompileContextEx; -import com.intellij.openapi.compiler.options.ExcludedEntriesConfiguration; -import com.intellij.openapi.diagnostic.Logger; -import com.intellij.openapi.module.Module; -import com.intellij.openapi.module.ModuleManager; -import com.intellij.openapi.progress.ProgressIndicator; -import com.intellij.openapi.project.Project; -import com.intellij.openapi.roots.*; -import com.intellij.openapi.util.Pair; -import com.intellij.openapi.util.io.FileUtil; -import com.intellij.openapi.util.text.StringUtil; -import com.intellij.openapi.vfs.LocalFileSystem; -import com.intellij.openapi.vfs.VfsUtil; -import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.psi.JavaPsiFacade; -import com.intellij.psi.PsiClass; -import com.intellij.psi.PsiManager; -import com.intellij.psi.search.GlobalSearchScope; -import com.intellij.util.Chunk; -import com.intellij.util.Processor; -import com.intellij.util.containers.ContainerUtil; -import com.intellij.util.containers.FactoryMap; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import org.jetbrains.jps.model.java.JavaModuleSourceRootTypes; -import org.jetbrains.jps.model.java.JavaSourceRootType; -import org.jetbrains.plugins.groovy.compiler.GroovyCompilerBase; -import org.jetbrains.plugins.groovy.compiler.GroovyCompilerConfiguration; -import org.jetbrains.plugins.groovy.lang.psi.GroovyFile; -import org.jetbrains.plugins.groovy.lang.psi.impl.GroovyNamesUtil; -import org.jetbrains.plugins.groovy.refactoring.convertToJava.GroovyToJavaGenerator; - -import java.io.File; -import java.io.IOException; -import java.util.*; - -/** - * @author peter - */ -public class GroovycStubGenerator extends GroovyCompilerBase { - private static final Logger LOG = Logger.getInstance("#org.jetbrains.plugins.groovy.compiler.generator.GroovycStubGenerator"); - - public static final String GROOVY_STUBS = "groovyStubs"; - - public GroovycStubGenerator(Project project) { - super(project); - } - - @Override - public void compile(CompileContext compileContext, Chunk moduleChunk, VirtualFile[] virtualFiles, OutputSink sink) { - final ExcludedEntriesConfiguration excluded = GroovyCompilerConfiguration.getExcludeConfiguration(myProject); - - @SuppressWarnings("MismatchedQueryAndUpdateOfCollection") FactoryMap, Boolean> hasJava = new FactoryMap, Boolean>() { - @Override - protected Boolean create(Pair key) { - return containsJavaSources(key.first, key.second); - } - }; - - ProjectFileIndex index = ProjectRootManager.getInstance(myProject).getFileIndex(); - - List total = new ArrayList(); - for (final VirtualFile virtualFile : virtualFiles) { - if (!excluded.isExcluded(virtualFile) && - GroovyNamesUtil.isIdentifier(virtualFile.getNameWithoutExtension())) { - Module module = index.getModuleForFile(virtualFile); - if (module == null || hasJava.get(Pair.create(module, index.isInTestSourceContent(virtualFile)))) { - total.add(virtualFile); - } - } - } - - if (total.isEmpty()) { - return; - } - - //long l = System.currentTimeMillis(); - super.compile(compileContext, moduleChunk, VfsUtil.toVirtualFileArray(total), sink); - //System.out.println("Stub generation took " + (System.currentTimeMillis() - l)); - } - - private static boolean containsJavaSources(Module module, boolean inTests) { - ModuleRootManager rootManager = ModuleRootManager.getInstance(module); - List roots = inTests ? rootManager.getSourceRoots(JavaSourceRootType.TEST_SOURCE) : rootManager.getSourceRoots(JavaModuleSourceRootTypes.SOURCES); - for (VirtualFile dir : roots) { - if (!rootManager.getFileIndex().iterateContentUnderDirectory(dir, new ContentIterator() { - @Override - public boolean processFile(VirtualFile fileOrDir) { - if (!fileOrDir.isDirectory() && JavaFileType.INSTANCE == fileOrDir.getFileType()) { - return false; - } - return true; - } - })) { - return true; - } - } - return false; - } - - @Override - protected void compileFiles(CompileContext compileContext, - Module module, - final List toCompile, - OutputSink sink, - boolean tests) { - final File outDir = getStubOutput(module, tests); - outDir.mkdirs(); - - final VirtualFile tempOutput = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(outDir); - assert tempOutput != null; - cleanDirectory(tempOutput); - - ((CompileContextEx)compileContext).assignModule(tempOutput, module, tests, this); - - ProgressIndicator indicator = compileContext.getProgressIndicator(); - indicator.pushState(); - - try { - final GroovyToJavaGenerator generator = new GroovyToJavaGenerator(myProject, new HashSet(toCompile)); - for (int i = 0; i < toCompile.size(); i++) { - indicator.setFraction((double)i / toCompile.size()); - - final Collection stubFiles = generateItems(generator, toCompile.get(i), tempOutput, compileContext, myProject); - ((CompileContextEx)compileContext).addScope(new FileSetCompileScope(stubFiles, new Module[]{module})); - } - } - finally { - indicator.popState(); - } - } - - private static File getStubOutput(Module module, boolean tests) { - final Project project = module.getProject(); - final String rootPath = CompilerPaths.getGeneratedDataDirectory(project).getPath() + "/" + GROOVY_STUBS + "/"; - return new File(rootPath + module.getName() + "/" + (tests ? "tests" : "production") + "/"); - } - - @Nullable - public static PsiClass findClassByStub(Project project, VirtualFile stubFile) { - final String[] components = StringUtil.trimEnd(stubFile.getPath(), ".java").split("[\\\\/]"); - final int stubs = Arrays.asList(components).indexOf(GROOVY_STUBS); - if (stubs < 0 || stubs >= components.length - 3) return null; - - final String moduleName = components[stubs + 1]; - final Module module = ModuleManager.getInstance(project).findModuleByName(moduleName); - if (module == null) return null; - - final String fqn = StringUtil.join(Arrays.asList(components).subList(stubs + 3, components.length), "."); - return JavaPsiFacade.getInstance(project).findClass(fqn, GlobalSearchScope.moduleScope(module)); - } - - private void cleanDirectory(final VirtualFile dir) { - Runnable runnable = new Runnable() { - @Override - public void run() { - AccessToken token = WriteAction.start(); - try { - VfsUtil.processFilesRecursively(dir, new Processor() { - @Override - public boolean process(VirtualFile virtualFile) { - if (!virtualFile.isDirectory()) { - TranslatingCompilerFilesMonitor.removeSourceInfo(virtualFile); - try { - virtualFile.delete(this); - } - catch (IOException e) { - LOG.info(e); - } - } - return true; - } - }); - } - finally { - token.finish(); - } - } - }; - if (ApplicationManager.getApplication().isDispatchThread()) { - assert ApplicationManager.getApplication().isUnitTestMode(); - runnable.run(); - } else { - ApplicationManager.getApplication().invokeAndWait(runnable, ModalityState.NON_MODAL); - } - } - - @Override - @NotNull - public String getDescription() { - return "Groovy to java source code generator"; - } - - @Override - public boolean validateConfiguration(CompileScope scope) { - return true; - } - - public static Collection generateItems(final GroovyToJavaGenerator generator, - final VirtualFile item, - final VirtualFile outputRootDirectory, - CompileContext context, - final Project project) { - ProgressIndicator indicator = context.getProgressIndicator(); - indicator.setText("Generating stubs for " + item.getName() + "..."); - - if (LOG.isDebugEnabled()) { - LOG.debug("Generating stubs for " + item.getName() + "..."); - } - - final Map output; - - AccessToken accessToken = ApplicationManager.getApplication().acquireReadActionLock(); - - try { - output = generator.generateStubs((GroovyFile)PsiManager.getInstance(project).findFile(item)); - } - finally { - accessToken.finish(); - } - - return writeStubs(outputRootDirectory, output, item); - } - - private static List writeStubs(VirtualFile outputRootDirectory, Map output, VirtualFile src) { - final ArrayList stubs = ContainerUtil.newArrayList(); - for (String relativePath : output.keySet()) { - final File stubFile = new File(outputRootDirectory.getPath(), relativePath); - FileUtil.createIfDoesntExist(stubFile); - try { - FileUtil.writeToFile(stubFile, output.get(relativePath).toString().getBytes(src.getCharset())); - } - catch (IOException e) { - LOG.error(e); - } - CompilerUtil.refreshIOFile(stubFile); - ContainerUtil.addIfNotNull(LocalFileSystem.getInstance().refreshAndFindFileByIoFile(stubFile), stubs); - } - return stubs; - } -} diff --git a/plugins/groovy/test/org/jetbrains/plugins/groovy/compiler/GroovyCompilerTest.groovy b/plugins/groovy/test/org/jetbrains/plugins/groovy/compiler/GroovyCompilerTest.groovy index 67ceec5d3c1f..2b5933fb4d31 100644 --- a/plugins/groovy/test/org/jetbrains/plugins/groovy/compiler/GroovyCompilerTest.groovy +++ b/plugins/groovy/test/org/jetbrains/plugins/groovy/compiler/GroovyCompilerTest.groovy @@ -15,9 +15,9 @@ */ package org.jetbrains.plugins.groovy.compiler + import com.intellij.compiler.CompilerConfiguration import com.intellij.compiler.CompilerConfigurationImpl -import com.intellij.compiler.server.BuildManager import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.compiler.CompilerMessage import com.intellij.openapi.compiler.CompilerMessageCategory @@ -25,16 +25,15 @@ import com.intellij.openapi.compiler.options.ExcludeEntryDescription import com.intellij.openapi.compiler.options.ExcludedEntriesConfiguration import com.intellij.openapi.module.Module import com.intellij.openapi.roots.ModuleRootModificationUtil -import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiFile import com.intellij.testFramework.TestLoggerFactory -import org.jetbrains.plugins.groovy.compiler.generator.GroovycStubGenerator import org.jetbrains.plugins.groovy.lang.psi.GroovyFile + /** * @author peter */ -public abstract class GroovyCompilerTest extends GroovyCompilerTestCase { +public class GroovyCompilerTest extends GroovyCompilerTestCase { @Override protected void setUp() { super.setUp(); addGroovyLibrary(myModule); @@ -543,9 +542,6 @@ class Indirect { def main = myFixture.addFileToProject('Main.groovy', 'class Main extends Java { }').virtualFile assertEmpty compileModule(myModule) - if (!useJps()) { - assertEmpty compileFiles(used.virtualFile, main) - } touch(used.virtualFile) touch(main) @@ -727,7 +723,7 @@ public class Main { assert messages def error = messages.find { it.message.contains('InvalidType') } assert error?.virtualFile - assert groovyFile.classes[0] == GroovycStubGenerator.findClassByStub(project, error.virtualFile) + assert groovyFile.classes[0] == GroovyCompilerLoader.findClassByStub(project, error.virtualFile) } @@ -819,30 +815,11 @@ class AppTest { assertOutput 'AppTest', 'b' } - public static class IdeaModeTest extends GroovyCompilerTest { - @Override protected boolean useJps() { false } - } + public void "test no groovy library"() { + myFixture.addFileToProject("dependent/a.groovy", ""); + addModule("dependent", true) - public static class JpsModeTest extends GroovyCompilerTest { - @Override protected boolean useJps() { true } - - @Override - protected void tearDown() { - File systemRoot = BuildManager.getInstance().getBuildSystemDirectory() - try { - super.tearDown() - } - finally { - FileUtil.delete(systemRoot); - } - } - - public void "test no groovy library"() { - myFixture.addFileToProject("dependent/a.groovy", ""); - addModule("dependent", true) - - def messages = make() - assert messages.find { it.message.contains("Cannot compile Groovy files: no Groovy library is defined for module 'dependent'") } - } + def messages = make() + assert messages.find { it.message.contains("Cannot compile Groovy files: no Groovy library is defined for module 'dependent'") } } } diff --git a/plugins/groovy/test/org/jetbrains/plugins/groovy/compiler/GroovyCompilerTestCase.java b/plugins/groovy/test/org/jetbrains/plugins/groovy/compiler/GroovyCompilerTestCase.java index 80e707cd51d5..7cbf9a9d665b 100644 --- a/plugins/groovy/test/org/jetbrains/plugins/groovy/compiler/GroovyCompilerTestCase.java +++ b/plugins/groovy/test/org/jetbrains/plugins/groovy/compiler/GroovyCompilerTestCase.java @@ -15,6 +15,7 @@ */ package org.jetbrains.plugins.groovy.compiler; +import com.intellij.compiler.server.BuildManager; import com.intellij.execution.ExecutionException; import com.intellij.execution.Executor; import com.intellij.execution.application.ApplicationConfiguration; @@ -37,6 +38,7 @@ import com.intellij.openapi.module.StdModuleTypes; import com.intellij.openapi.roots.*; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.Key; +import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiFile; @@ -64,13 +66,11 @@ import java.util.concurrent.atomic.AtomicReference; public abstract class GroovyCompilerTestCase extends JavaCodeInsightFixtureTestCase { @SuppressWarnings("AbstractMethodCallInConstructor") private CompilerTester myCompilerTester; - protected abstract boolean useJps(); - @Override protected void setUp() throws Exception { super.setUp(); getProject().getComponent(GroovyCompilerLoader.class).projectOpened(); - myCompilerTester = new CompilerTester(useJps(), myModule); + myCompilerTester = new CompilerTester(myModule); } @Override @@ -87,19 +87,25 @@ public abstract class GroovyCompilerTestCase extends JavaCodeInsightFixtureTestC @Override protected void tearDown() throws Exception { - UIUtil.invokeAndWaitIfNeeded(new Runnable() { - @Override - public void run() { - try { - myCompilerTester.tearDown(); - myCompilerTester = null; - GroovyCompilerTestCase.super.tearDown(); + final File systemRoot = BuildManager.getInstance().getBuildSystemDirectory(); + try { + UIUtil.invokeAndWaitIfNeeded(new Runnable() { + @Override + public void run() { + try { + myCompilerTester.tearDown(); + myCompilerTester = null; + GroovyCompilerTestCase.super.tearDown(); + } + catch (Exception e) { + throw new RuntimeException(e); + } } - catch (Exception e) { - throw new RuntimeException(e); - } - } - }); + }); + } + finally { + FileUtil.delete(systemRoot); + } } protected void setupTestSources() { diff --git a/plugins/groovy/test/org/jetbrains/plugins/groovy/compiler/GroovyDebuggerTest.groovy b/plugins/groovy/test/org/jetbrains/plugins/groovy/compiler/GroovyDebuggerTest.groovy index 6e1a4fa4100d..84e09567aee4 100644 --- a/plugins/groovy/test/org/jetbrains/plugins/groovy/compiler/GroovyDebuggerTest.groovy +++ b/plugins/groovy/test/org/jetbrains/plugins/groovy/compiler/GroovyDebuggerTest.groovy @@ -57,9 +57,6 @@ import com.intellij.util.concurrency.Semaphore * @author peter */ class GroovyDebuggerTest extends GroovyCompilerTestCase { - @Override - protected boolean useJps() { true } - @Override protected void setUp() { edt { diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/compiler/MavenResourceCompiler.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/compiler/MavenResourceCompiler.java deleted file mode 100644 index a3ce473eee3e..000000000000 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/compiler/MavenResourceCompiler.java +++ /dev/null @@ -1,605 +0,0 @@ -/* - * Copyright 2000-2014 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.idea.maven.compiler; - -import com.intellij.compiler.CompilerConfigurationImpl; -import com.intellij.compiler.CompilerIOUtil; -import com.intellij.compiler.impl.CompilerUtil; -import com.intellij.openapi.application.AccessToken; -import com.intellij.openapi.application.ReadAction; -import com.intellij.openapi.compiler.*; -import com.intellij.openapi.module.Module; -import com.intellij.openapi.module.ModuleManager; -import com.intellij.openapi.progress.ProgressIndicator; -import com.intellij.openapi.project.Project; -import com.intellij.openapi.roots.ProjectFileIndex; -import com.intellij.openapi.roots.ProjectRootManager; -import com.intellij.openapi.util.Key; -import com.intellij.openapi.util.io.FileUtil; -import com.intellij.openapi.util.text.StringUtil; -import com.intellij.openapi.vfs.*; -import com.intellij.testFramework.LightVirtualFile; -import com.intellij.util.containers.ContainerUtil; -import gnu.trove.THashMap; -import gnu.trove.THashSet; -import org.jdom.Element; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import org.jetbrains.idea.maven.dom.MavenPropertyResolver; -import org.jetbrains.idea.maven.dom.references.MavenPropertyPsiReference; -import org.jetbrains.idea.maven.model.MavenResource; -import org.jetbrains.idea.maven.project.MavenProject; -import org.jetbrains.idea.maven.project.MavenProjectsManager; -import org.jetbrains.idea.maven.utils.MavenJDOMUtil; -import org.jetbrains.idea.maven.utils.MavenLog; -import org.jetbrains.idea.maven.utils.MavenUtil; - -import java.io.*; -import java.text.SimpleDateFormat; -import java.util.*; -import java.util.regex.Pattern; - -public class MavenResourceCompiler implements ClassPostProcessingCompiler { - private static final Key> FILES_TO_DELETE_KEY = Key.create(MavenResourceCompiler.class.getSimpleName() + ".FILES_TO_DELETE"); - - // See org.apache.maven.shared.filtering.DefaultMavenResourcesFiltering#defaultNonFilteredFileExtensions - private static final Set DEFAULT_NON_FILTERED_EXTENSIONS = ContainerUtil.newHashSet("jpg", "jpeg", "gif", "bmp", "png"); - - private Map> myOutputItemsCache = new THashMap>(); - - public MavenResourceCompiler(Project project) { - loadCache(project); - } - - private void loadCache(final Project project) { - File file = getCacheFile(project); - if (!file.exists()) return; - - try { - DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream(file))); - try { - if (in.readInt() != CompilerConfigurationImpl.DEPENDENCY_FORMAT_VERSION) return; - int modulesSize = in.readInt(); - Map> temp = new THashMap>(); - while (modulesSize-- > 0) { - String module = CompilerIOUtil.readString(in); - int pathsSize = in.readInt(); - Set paths = createPathsSet(); - while (pathsSize-- > 0) { - paths.add(CompilerIOUtil.readString(in)); - } - temp.put(module, paths); - } - myOutputItemsCache = temp; - } - finally { - in.close(); - } - } - catch (IOException e) { - MavenLog.LOG.warn(e); - } - } - - private static Set createPathsSet() { - return new THashSet(FileUtil.PATH_HASHING_STRATEGY); - } - - private void saveCache(final Project project) { - File file = getCacheFile(project); - file.getParentFile().mkdirs(); - try { - DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file))); - try { - out.writeInt(CompilerConfigurationImpl.DEPENDENCY_FORMAT_VERSION); - out.writeInt(myOutputItemsCache.size()); - for (Map.Entry> eachEntry : myOutputItemsCache.entrySet()) { - String module = eachEntry.getKey(); - Set paths = eachEntry.getValue(); - - CompilerIOUtil.writeString(module, out); - out.writeInt(paths.size()); - for (String eachPath : paths) { - CompilerIOUtil.writeString(eachPath, out); - } - } - } - finally { - out.close(); - } - } - catch (IOException e) { - MavenLog.LOG.error(e); - } - } - - private static File getCacheFile(final Project project) { - return new File(CompilerPaths.getCompilerSystemDirectory(project), "maven_compiler_caches.dat"); - } - - @Override - public boolean validateConfiguration(CompileScope scope) { - return true; - } - - @Override - @NotNull - public ProcessingItem[] getProcessingItems(final CompileContext context) { - final Project project = context.getProject(); - final MavenProjectsManager mavenProjectManager = MavenProjectsManager.getInstance(project); - if (!mavenProjectManager.isMavenizedProject()) return ProcessingItem.EMPTY_ARRAY; - - List allItemsToProcess = new ArrayList(); - List filesToDelete = new ArrayList(); - - Date timestamp = new Date(); - - AccessToken accessToken = ReadAction.start(); - try { - for (Module eachModule : context.getCompileScope().getAffectedModules()) { - MavenProject mavenProject = mavenProjectManager.findProject(eachModule); - if (mavenProject == null) continue; - - Properties properties = loadPropertiesAndFilters(context, mavenProject); - - long propertiesHashCode = calculateHashCode(mavenProject, properties); // hash code MUST NOT contain maven.build.timestamp property! - - String timestampFormat = properties.getProperty("maven.build.timestamp.format"); - if (timestampFormat == null) { - timestampFormat = "yyyyMMdd-HHmm"; // See ModelInterpolator.DEFAULT_BUILD_TIMESTAMP_FORMAT - } - - String timestampString = new SimpleDateFormat(timestampFormat).format(timestamp); - properties.setProperty(MavenPropertyPsiReference.TIMESTAMP_PROP, timestampString); - - Set nonFilteredExtensions = collectNonFilteredExtensions(mavenProject); - String escapeString = MavenJDOMUtil.findChildValueByPath(mavenProject.getPluginConfiguration("org.apache.maven.plugins", - "maven-resources-plugin"), - "escapeString", null); - - List moduleItemsToProcess = new ArrayList(); - collectProcessingItems(eachModule, mavenProject, context, properties, propertiesHashCode, - nonFilteredExtensions, escapeString, false, moduleItemsToProcess); - collectProcessingItems(eachModule, mavenProject, context, properties, propertiesHashCode, - nonFilteredExtensions, escapeString, true, moduleItemsToProcess); - collectItemsToDelete(eachModule, moduleItemsToProcess, filesToDelete); - allItemsToProcess.addAll(moduleItemsToProcess); - } - - if (!filesToDelete.isEmpty()) { - allItemsToProcess.add(new FakeProcessingItem()); - } - context.putUserData(FILES_TO_DELETE_KEY, filesToDelete); - - removeObsoleteModulesFromCache(project); - saveCache(project); - } - finally { - accessToken.finish(); - } - - return allItemsToProcess.toArray(new ProcessingItem[allItemsToProcess.size()]); - } - - private static Set collectNonFilteredExtensions(MavenProject mavenProject) { - Element config = mavenProject.getPluginConfiguration("org.apache.maven.plugins", "maven-resources-plugin"); - if (config == null) return DEFAULT_NON_FILTERED_EXTENSIONS; - - List customNonFilteredExtensions = MavenJDOMUtil.findChildrenValuesByPath(config, "nonFilteredFileExtensions", "nonFilteredFileExtension"); - if (customNonFilteredExtensions.isEmpty()) return DEFAULT_NON_FILTERED_EXTENSIONS; - - Set result = new HashSet(); - result.addAll(DEFAULT_NON_FILTERED_EXTENSIONS); - result.addAll(customNonFilteredExtensions); - - return result; - } - - private static long calculateHashCode(MavenProject project, Properties properties) { - Map sorted = new TreeMap(); - for (Map.Entry each : properties.entrySet()) { - sorted.put(each.getKey().toString(), each.getValue().toString()); - } - return project.getLastReadStamp() + 31 * sorted.hashCode(); - } - - private static Properties loadPropertiesAndFilters(CompileContext context, MavenProject mavenProject) { - Properties properties = new Properties(); - - for (String each : mavenProject.getFilterPropertiesFiles()) { - try { - FileInputStream in = new FileInputStream(each); - try { - properties.load(in); - } - finally { - in.close(); - } - } - catch (IOException e) { - String url = VfsUtil.pathToUrl(mavenProject.getFile().getPath()); - context.addMessage(CompilerMessageCategory.WARNING, "Maven: Cannot read the filter. " + e.getMessage(), url, -1, -1); - } - } - - properties.putAll(mavenProject.getProperties()); - - return properties; - } - - private static void collectProcessingItems(Module module, - MavenProject mavenProject, - CompileContext context, - Properties properties, - long propertiesHashCode, - Set nonFilteredExtensions, - @Nullable String escapeString, - boolean tests, - List result) { - String outputDir = CompilerPaths.getModuleOutputPath(module, tests); - if (outputDir == null) { - context.addMessage(CompilerMessageCategory.ERROR, "Maven: Module '" + module.getName() + "'output is not specified", null, -1, -1); - return; - } - - List resources = tests ? mavenProject.getTestResources() : mavenProject.getResources(); - - for (MavenResource each : resources) { - VirtualFile dir = LocalFileSystem.getInstance().findFileByPath(each.getDirectory()); - if (dir == null) continue; - - List includes = collectPatterns(each.getIncludes(), "**/*"); - List excludes = collectPatterns(each.getExcludes(), null); - String targetPath = each.getTargetPath(); - String resourceOutputDir = StringUtil.isEmptyOrSpaces(targetPath) - ? outputDir - : (FileUtil.isAbsolute(targetPath) ? targetPath : outputDir + "/" + targetPath); - - collectProcessingItems(module, - dir, - dir, - resourceOutputDir, - includes, - excludes, - each.isFiltered(), - properties, - propertiesHashCode, - nonFilteredExtensions, - escapeString, - result, - context.getProgressIndicator()); - } - } - - public static List collectPatterns(@Nullable List values, @Nullable String defaultValue) { - List result = new ArrayList(); - if (values == null || values.isEmpty()) { - if (defaultValue == null) return Collections.emptyList(); - return MavenUtil.collectPattern(defaultValue, result); - } - for (String each : values) { - MavenUtil.collectPattern(each, result); - } - return result; - } - - private static void collectProcessingItems(final Module module, - final VirtualFile sourceRoot, - VirtualFile currentDir, - final String outputDir, - final List includes, - final List excludes, - final boolean isSourceRootFiltered, - final Properties properties, - final long propertiesHashCode, - final Set nonFilteredExtensions, - @Nullable final String escapeString, - final List result, - final ProgressIndicator indicator) { - VfsUtilCore.visitChildrenRecursively(currentDir, new VirtualFileVisitor() { - @Override - public boolean visitFile(@NotNull VirtualFile file) { - indicator.checkCanceled(); - - if (!file.isDirectory()) { - String relPath = VfsUtilCore.getRelativePath(file, sourceRoot, '/'); - if (relPath == null) { - MavenLog.LOG.error("Cannot calculate relate path for file: " + file + " in root: " + sourceRoot); - return true; - } - - ProjectFileIndex fileIndex = ProjectRootManager.getInstance(module.getProject()).getFileIndex(); - if (fileIndex.isIgnored(file)) return true; - if (!MavenUtil.isIncluded(relPath, includes, excludes)) return true; - - String outputPath = outputDir + "/" + relPath; - long outputFileTimestamp = -1; - File outputFile = new File(outputPath); - if (outputFile.exists()) { - outputFileTimestamp = outputFile.lastModified(); - } - boolean isFiltered = isSourceRootFiltered && !nonFilteredExtensions.contains(file.getExtension()); - result.add(new MyProcessingItem(module, - file, - outputPath, - outputFileTimestamp, - isFiltered, - properties, - propertiesHashCode, - escapeString)); - } - - return true; - } - }); - } - - private void collectItemsToDelete(Module module, List processingItems, List result) { - Set currentPaths = createPathsSet(); - for (MyProcessingItem each : processingItems) { - currentPaths.add(each.getOutputPath()); - } - - Set cachedPaths = myOutputItemsCache.put(module.getName(), currentPaths); - if (cachedPaths != null) { - for (Set set : myOutputItemsCache.values()) { - cachedPaths.removeAll(set); - } - - result.addAll(cachedPaths); - } - } - - private void removeObsoleteModulesFromCache(final Project project) { - Set existingModules = new THashSet(); - for (Module each : ModuleManager.getInstance(project).getModules()) { - existingModules.add(each.getName()); - } - - for (String each : new THashSet(myOutputItemsCache.keySet())) { - if (!existingModules.contains(each)) { - myOutputItemsCache.remove(each); - } - } - } - - @Override - public ProcessingItem[] process(final CompileContext context, ProcessingItem[] items) { - context.getProgressIndicator().setText("Processing Maven resources..."); - - List result = new ArrayList(items.length); - List filesToRefresh = new ArrayList(items.length); - - deleteOutdatedFile(context.getUserData(FILES_TO_DELETE_KEY), filesToRefresh); - - for (int i = 0; i < items.length; i++) { - if (!(items[i] instanceof MyProcessingItem)) continue; - - context.getProgressIndicator().setFraction(((double)i) / items.length); - context.getProgressIndicator().checkCanceled(); - - MyProcessingItem eachItem = (MyProcessingItem)items[i]; - VirtualFile sourceVirtualFile = eachItem.getFile(); - File sourceFile = new File(sourceVirtualFile.getPath()); - File outputFile = new File(eachItem.getOutputPath()); - - try { - outputFile.getParentFile().mkdirs(); - - boolean shouldFilter = eachItem.isFiltered(); - if (shouldFilter && sourceFile.length() > 10 * 1024 * 1024) { - context.addMessage(CompilerMessageCategory.WARNING, - "Maven: File is too big to be filtered. Most likely it is a binary file and should be excluded from filtering.", - sourceVirtualFile.getUrl(), -1, -1); - shouldFilter = false; - } - - if (shouldFilter) { - String charset = sourceVirtualFile.getCharset().name(); - String text = new String(FileUtil.loadFileBytes(sourceFile), charset); - - PrintWriter printWriter = new PrintWriter(outputFile, charset); - try { - MavenPropertyResolver.doFilterText(eachItem.getModule(), - text, - eachItem.getProperties(), - eachItem.getEscapeString(), - printWriter); - } - finally { - printWriter.close(); - } - } - else { - FileUtil.copy(sourceFile, outputFile); - } - - eachItem.getValidityState().setOutputFileTimestamp(outputFile.lastModified()); - result.add(eachItem); - filesToRefresh.add(outputFile); - } - catch (IOException e) { - MavenLog.LOG.info(e); - context.addMessage(CompilerMessageCategory.ERROR, - "Maven: Cannot process resource file: " + e.getMessage(), - sourceVirtualFile.getUrl(), - -1, - -1); - } - } - CompilerUtil.refreshIOFiles(filesToRefresh); - return result.toArray(new ProcessingItem[result.size()]); - } - - private static void deleteOutdatedFile(List filesToDelete, List filesToRefresh) { - for (String each : filesToDelete) { - File file = new File(each); - if (FileUtil.delete(file)) { - filesToRefresh.add(file); - } - } - } - - @Override - @NotNull - public String getDescription() { - return "Maven Resource Compiler"; - } - - @Override - public ValidityState createValidityState(DataInput in) throws IOException { - return MyValididtyState.load(in); - } - - private static class MyProcessingItem implements ProcessingItem { - private final Module myModule; - private final VirtualFile mySourceFile; - private final String myOutputPath; - private final boolean myFiltered; - private final Properties myProperties; - private final String myEscapeString; - private final MyValididtyState myState; - - public MyProcessingItem(Module module, - VirtualFile sourceFile, - String outputPath, - long outputFileTimestamp, - boolean isFiltered, - Properties properties, - long propertiesHashCode, - @Nullable String escapeString) { - myModule = module; - mySourceFile = sourceFile; - myOutputPath = outputPath; - myFiltered = isFiltered; - myProperties = properties; - myEscapeString = escapeString; - myState = new MyValididtyState(sourceFile.getTimeStamp(), outputFileTimestamp, isFiltered, propertiesHashCode, StringUtil.notNullize(escapeString)); - } - - @Override - @NotNull - public VirtualFile getFile() { - return mySourceFile; - } - - public String getOutputPath() { - return myOutputPath; - } - - public Module getModule() { - return myModule; - } - - public boolean isFiltered() { - return myFiltered; - } - - public Properties getProperties() { - return myProperties; - } - - @Nullable - public String getEscapeString() { - return myEscapeString; - } - - @Override - @NotNull - public MyValididtyState getValidityState() { - return myState; - } - } - - private static class FakeProcessingItem implements ProcessingItem { - private final LightVirtualFile myFile; - - private FakeProcessingItem() { - myFile = new LightVirtualFile(this.getClass().getName()); - } - - @Override - @NotNull - public VirtualFile getFile() { - return myFile; - } - - @Override - public ValidityState getValidityState() { - return null; - } - } - - private static class MyValididtyState implements ValidityState { - private final long mySourceFileTimestamp; - private long myOutputFileTimestamp; - private final boolean myFiltered; - private final long myPropertiesHashCode; - @NotNull private final String myEscapeString; - - public static MyValididtyState load(DataInput in) throws IOException { - return new MyValididtyState(in.readLong(), in.readLong(), in.readBoolean(), in.readLong(), in.readUTF()); - } - - public void setOutputFileTimestamp(long outputFileTimestamp) { - myOutputFileTimestamp = outputFileTimestamp; - } - - private MyValididtyState(long sourceFileTimestamp, - long outputFileTimestamp, - boolean isFiltered, - long propertiesHashCode, - @NotNull String escapeString) { - mySourceFileTimestamp = sourceFileTimestamp; - myOutputFileTimestamp = outputFileTimestamp; - myFiltered = isFiltered; - if (isFiltered) { - myPropertiesHashCode = propertiesHashCode; - myEscapeString = escapeString; - } - else { - myPropertiesHashCode = 0; - myEscapeString = ""; - } - } - - @Override - public String toString() { - return mySourceFileTimestamp + " " + myOutputFileTimestamp + " " + myFiltered + " " + myPropertiesHashCode + " " + myEscapeString; - } - - @Override - public boolean equalsTo(ValidityState otherState) { - if (!(otherState instanceof MyValididtyState)) return false; - MyValididtyState that = (MyValididtyState)otherState; - - return mySourceFileTimestamp == that.mySourceFileTimestamp - && myOutputFileTimestamp == that.myOutputFileTimestamp - && myFiltered == that.myFiltered - && myPropertiesHashCode == that.myPropertiesHashCode - && myEscapeString.equals(that.myEscapeString); - } - - @Override - public void save(DataOutput out) throws IOException { - out.writeLong(mySourceFileTimestamp); - out.writeLong(myOutputFileTimestamp); - out.writeBoolean(myFiltered); - out.writeLong(myPropertiesHashCode); - out.writeUTF(myEscapeString); - } - } -} diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsManager.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsManager.java index 2df814feda57..37a1a47cde6a 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsManager.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenProjectsManager.java @@ -15,7 +15,6 @@ */ package org.jetbrains.idea.maven.project; -import com.intellij.compiler.CompilerWorkspaceConfiguration; import com.intellij.ide.startup.StartupManagerEx; import com.intellij.openapi.application.AccessToken; import com.intellij.openapi.application.ApplicationManager; @@ -168,8 +167,6 @@ public class MavenProjectsManager extends MavenSimpleProjectComponent AccessToken token = ReadAction.start(); try { - if (!CompilerWorkspaceConfiguration.getInstance(myProject).useOutOfProcessBuild()) return true; - new MavenResourceCompilerConfigurationGenerator(myProject, myProjectsTree).generateBuildConfiguration(context.isRebuild()); } finally { diff --git a/plugins/maven/src/main/resources/META-INF/plugin.xml b/plugins/maven/src/main/resources/META-INF/plugin.xml index 9580f83405ed..960cb1c5df24 100644 --- a/plugins/maven/src/main/resources/META-INF/plugin.xml +++ b/plugins/maven/src/main/resources/META-INF/plugin.xml @@ -70,7 +70,6 @@ - diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/MavenImportingTestCase.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/MavenImportingTestCase.java index 860f78cabfe6..6cc0966180b0 100644 --- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/MavenImportingTestCase.java +++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/MavenImportingTestCase.java @@ -16,7 +16,6 @@ package org.jetbrains.idea.maven; -import com.intellij.compiler.CompilerTestUtil; import com.intellij.compiler.server.BuildManager; import com.intellij.openapi.application.AccessToken; import com.intellij.openapi.application.ApplicationManager; @@ -61,21 +60,11 @@ public abstract class MavenImportingTestCase extends MavenTestCase { protected MavenProjectsTree myProjectsTree; protected MavenProjectsManager myProjectsManager; - protected boolean useJps() { - return false; - } - @Override protected void setUpInWriteAction() throws Exception { super.setUpInWriteAction(); myProjectsManager = MavenProjectsManager.getInstance(myProject); removeFromLocalRepository("test"); - if (useJps()) { - CompilerTestUtil.enableExternalCompiler(myProject); - } - else { - CompilerTestUtil.disableExternalCompiler(myProject); - } } @Override @@ -84,10 +73,7 @@ public abstract class MavenImportingTestCase extends MavenTestCase { Messages.setTestDialog(TestDialog.DEFAULT); myProjectsManager.projectClosed(); removeFromLocalRepository("test"); - if (useJps()) { - CompilerTestUtil.disableExternalCompiler(myProject); - FileUtil.delete(BuildManager.getInstance().getBuildSystemDirectory()); - } + FileUtil.delete(BuildManager.getInstance().getBuildSystemDirectory()); } finally { super.tearDown(); @@ -534,7 +520,7 @@ public abstract class MavenImportingTestCase extends MavenTestCase { } protected Sdk setupJdkForModule(final String moduleName) { - final Sdk sdk = useJps()? JavaAwareProjectJdkTableImpl.getInstanceEx().getInternalJdk() : createJdk("Java 1.5"); + final Sdk sdk = true ? JavaAwareProjectJdkTableImpl.getInstanceEx().getInternalJdk() : createJdk("Java 1.5"); ModuleRootModificationUtil.setModuleSdk(getModule(moduleName), sdk); return sdk; } diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/compiler/MavenCompilingTestCase.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/compiler/MavenCompilingTestCase.java index 39583dd2887b..835d7c487afc 100644 --- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/compiler/MavenCompilingTestCase.java +++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/compiler/MavenCompilingTestCase.java @@ -19,7 +19,6 @@ import com.intellij.compiler.CompilerManagerImpl; import com.intellij.compiler.CompilerWorkspaceConfiguration; import com.intellij.compiler.artifacts.ArtifactsTestUtil; import com.intellij.compiler.impl.ModuleCompileScope; -import com.intellij.compiler.impl.TranslatingCompilerFilesMonitor; import com.intellij.openapi.compiler.CompileContext; import com.intellij.openapi.compiler.CompileScope; import com.intellij.openapi.compiler.CompileStatusNotification; @@ -63,10 +62,7 @@ public abstract class MavenCompilingTestCase extends MavenImportingTestCase { for (Module module : scope.getAffectedModules()) { setupJdkForModule(module.getName()); } - if (useJps()) { - new MavenResourceCompilerConfigurationGenerator(myProject, MavenProjectsManager.getInstance(myProject).getProjectsTreeForTests()) - .generateBuildConfiguration(false); - } + new MavenResourceCompilerConfigurationGenerator(myProject, MavenProjectsManager.getInstance(myProject).getProjectsTreeForTests()).generateBuildConfiguration(false); } }); @@ -74,9 +70,6 @@ public abstract class MavenCompilingTestCase extends MavenImportingTestCase { CompilerManagerImpl.testSetup(); List roots = Arrays.asList(ProjectRootManager.getInstance(myProject).getContentRoots()); - TranslatingCompilerFilesMonitor.getInstance() - .scanSourceContent(new TranslatingCompilerFilesMonitor.ProjectRef(myProject), roots, roots.size(), true); - final Semaphore semaphore = new Semaphore(); semaphore.down(); diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/compiler/ResourceCopyingTest.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/compiler/ResourceCopyingTest.java index e9f1f8a59ff2..057b799ffdbd 100644 --- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/compiler/ResourceCopyingTest.java +++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/compiler/ResourceCopyingTest.java @@ -29,10 +29,6 @@ import com.intellij.testFramework.PsiTestUtil; import java.io.File; public class ResourceCopyingTest extends MavenCompilingTestCase { - @Override - protected boolean useJps() { - return true; - } @Override protected void setUpInWriteAction() throws Exception { @@ -327,7 +323,7 @@ public class ResourceCopyingTest extends MavenCompilingTestCase { } public void testDoNotCopyExcludedStandardResources() throws Exception { - if (!useJps()) { + if (!true) { if (ignore()) return; } @@ -413,7 +409,7 @@ public class ResourceCopyingTest extends MavenCompilingTestCase { } public void testCopyManuallyDeletedFiles() throws Exception { - if (useJps()) { + if (true) { ignore(); return; } @@ -706,7 +702,7 @@ public class ResourceCopyingTest extends MavenCompilingTestCase { } private void assertCopied(String path) { - if (useJps()) { + if (true) { assertTrue(new File(myProjectPom.getParent().getPath(), path).exists()); } else { @@ -715,7 +711,7 @@ public class ResourceCopyingTest extends MavenCompilingTestCase { } private void assertNotCopied(String path) { - if (useJps()) { + if (true) { assertFalse(new File(myProjectPom.getParent().getPath(), path).exists()); } else { diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/compiler/ResourceFilteringTest.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/compiler/ResourceFilteringTest.java index bb1138c7e651..24b6e5f4e39c 100644 --- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/compiler/ResourceFilteringTest.java +++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/compiler/ResourceFilteringTest.java @@ -22,21 +22,7 @@ import com.intellij.openapi.vfs.VirtualFile; import java.util.Arrays; -public abstract class ResourceFilteringTest extends MavenCompilingTestCase { - - public static class IdeaModeTest extends ResourceFilteringTest { - @Override - protected boolean useJps() { - return false; - } - } - - public static class JpsModeTest extends ResourceFilteringTest { - @Override - protected boolean useJps() { - return true; - } - } +public class ResourceFilteringTest extends MavenCompilingTestCase { @Override protected boolean runInWriteAction() { @@ -905,7 +891,7 @@ public abstract class ResourceFilteringTest extends MavenCompilingTestCase { } public void testEscapingFiltering() throws Exception { - if (!useJps()) return; + if (!true) return; createProjectSubFile("filters/filter.properties", "xxx=value"); createProjectSubFile("resources/file.properties", @@ -1067,7 +1053,7 @@ public abstract class ResourceFilteringTest extends MavenCompilingTestCase { } public void testResourcesOrdering2() throws Exception { - if (!useJps()) return; + if (!true) return; createProjectSubFile("resources/file.properties", "value=${project.version}\n"); @@ -1095,7 +1081,7 @@ public abstract class ResourceFilteringTest extends MavenCompilingTestCase { } public void testResourcesOrdering3() throws Exception { - if (!useJps()) return; + if (!true) return; createProjectSubFile("resources1/a.txt", "1"); createProjectSubFile("resources2/a.txt", "2"); @@ -1149,7 +1135,7 @@ public abstract class ResourceFilteringTest extends MavenCompilingTestCase { } public void testOverwriteParameter1() throws Exception { - if (!useJps()) return; + if (!true) return; createProjectSubFile("resources1/a.txt", "1"); createProjectSubFile("resources2/a.txt", "2"); @@ -1185,7 +1171,7 @@ public abstract class ResourceFilteringTest extends MavenCompilingTestCase { } public void testOverwriteParameter2() throws Exception { - if (!useJps()) return; + if (!true) return; createProjectSubFile("resources1/a.txt", "1"); createProjectSubFile("resources2/a.txt", "2"); diff --git a/plugins/ui-designer/src/META-INF/plugin.xml b/plugins/ui-designer/src/META-INF/plugin.xml index 49e29d9e4c3c..6724c40198dd 100644 --- a/plugins/ui-designer/src/META-INF/plugin.xml +++ b/plugins/ui-designer/src/META-INF/plugin.xml @@ -125,7 +125,6 @@ - diff --git a/plugins/ui-designer/src/com/intellij/uiDesigner/actions/PreviewFormAction.java b/plugins/ui-designer/src/com/intellij/uiDesigner/actions/PreviewFormAction.java index b859b2702912..ce26a9b44264 100644 --- a/plugins/ui-designer/src/com/intellij/uiDesigner/actions/PreviewFormAction.java +++ b/plugins/ui-designer/src/com/intellij/uiDesigner/actions/PreviewFormAction.java @@ -54,7 +54,6 @@ import com.intellij.uiDesigner.compiler.FormErrorInfo; import com.intellij.uiDesigner.compiler.Utils; import com.intellij.uiDesigner.designSurface.GuiEditor; import com.intellij.uiDesigner.lw.*; -import com.intellij.uiDesigner.make.Form2ByteCodeCompiler; import com.intellij.uiDesigner.make.PreviewNestedFormLoader; import com.intellij.util.PathsList; import com.intellij.util.containers.HashSet; @@ -66,8 +65,11 @@ import org.jetbrains.jps.incremental.java.CopyResourcesUtil; import javax.swing.*; import java.io.File; import java.io.IOException; +import java.net.URL; +import java.util.ArrayList; import java.util.List; import java.util.Locale; +import java.util.StringTokenizer; /** * @author Anton Katilin @@ -84,6 +86,21 @@ public final class PreviewFormAction extends AnAction{ @NonNls private static final String RUNTIME_BUNDLE_PREFIX = "RuntimeBundle"; @NonNls public static final String PREVIEW_BINDING_FIELD = "myComponent"; + @NotNull + public static InstrumentationClassFinder createClassFinder(@NotNull final String classPath){ + final ArrayList urls = new ArrayList(); + for (StringTokenizer tokenizer = new StringTokenizer(classPath, File.pathSeparator); tokenizer.hasMoreTokens();) { + final String s = tokenizer.nextToken(); + try { + urls.add(new File(s).toURI().toURL()); + } + catch (Exception exc) { + throw new RuntimeException(exc); + } + } + return new InstrumentationClassFinder(urls.toArray(new URL[urls.size()])); + } + public void actionPerformed(final AnActionEvent e) { final GuiEditor editor = FormEditingUtil.getActiveEditor(e.getDataContext()); if (editor != null) { @@ -128,7 +145,7 @@ public final class PreviewFormAction extends AnAction{ final String classPath = OrderEnumerator.orderEntries(module).recursively().getPathsList().getPathsString() + File.pathSeparator + sources.getPathsString() + File.pathSeparator + /* resources bundles */ tempPath; - final InstrumentationClassFinder finder = Form2ByteCodeCompiler.createClassFinder(classPath); + final InstrumentationClassFinder finder = createClassFinder(classPath); try { final Document doc = FileDocumentManager.getInstance().getDocument(formFile); diff --git a/plugins/ui-designer/src/com/intellij/uiDesigner/make/Form2ByteCodeCompiler.java b/plugins/ui-designer/src/com/intellij/uiDesigner/make/Form2ByteCodeCompiler.java deleted file mode 100644 index dd60ce672596..000000000000 --- a/plugins/ui-designer/src/com/intellij/uiDesigner/make/Form2ByteCodeCompiler.java +++ /dev/null @@ -1,444 +0,0 @@ -/* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.intellij.uiDesigner.make; - -import com.intellij.compiler.PsiClassWriter; -import com.intellij.compiler.impl.CompilerUtil; -import com.intellij.compiler.instrumentation.InstrumentationClassFinder; -import com.intellij.openapi.application.ApplicationManager; -import com.intellij.openapi.compiler.*; -import com.intellij.openapi.diagnostic.Logger; -import com.intellij.openapi.editor.Document; -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.project.Project; -import com.intellij.openapi.roots.OrderEnumerator; -import com.intellij.openapi.util.Computable; -import com.intellij.openapi.vfs.VfsUtil; -import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.psi.JavaPsiFacade; -import com.intellij.psi.PsiClass; -import com.intellij.psi.PsiFile; -import com.intellij.psi.search.GlobalSearchScope; -import com.intellij.uiDesigner.FormEditingUtil; -import com.intellij.uiDesigner.GuiDesignerConfiguration; -import com.intellij.uiDesigner.UIDesignerBundle; -import com.intellij.uiDesigner.compiler.AlienFormFileException; -import com.intellij.uiDesigner.compiler.AsmCodeGenerator; -import com.intellij.uiDesigner.compiler.FormErrorInfo; -import com.intellij.uiDesigner.compiler.Utils; -import com.intellij.uiDesigner.lw.CompiledClassPropertiesProvider; -import com.intellij.uiDesigner.lw.LwRootContainer; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import org.jetbrains.jps.incremental.java.CopyResourcesUtil; - -import java.io.DataInput; -import java.io.File; -import java.io.IOException; -import java.net.URL; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.StringTokenizer; - -public final class Form2ByteCodeCompiler implements ClassInstrumentingCompiler { - private static final Logger LOG = Logger.getInstance("#com.intellij.uiDesigner.make.Form2ByteCodeCompiler"); - - @Override - @NotNull - public String getDescription() { - return UIDesignerBundle.message("component.gui.designer.form.to.bytecode.compiler"); - } - - @Override - public boolean validateConfiguration(CompileScope scope) { - return true; - } - - @NotNull - public static InstrumentationClassFinder createClassFinder(@NotNull final String classPath){ - final ArrayList urls = new ArrayList(); - for (StringTokenizer tokenizer = new StringTokenizer(classPath, File.pathSeparator); tokenizer.hasMoreTokens();) { - final String s = tokenizer.nextToken(); - try { - urls.add(new File(s).toURI().toURL()); - } - catch (Exception exc) { - throw new RuntimeException(exc); - } - } - return new InstrumentationClassFinder(urls.toArray(new URL[urls.size()])); - } - - @Override - @NotNull - public ProcessingItem[] getProcessingItems(final CompileContext context) { - final Project project = context.getProject(); - if (!GuiDesignerConfiguration.getInstance(project).INSTRUMENT_CLASSES) { - return ProcessingItem.EMPTY_ARRAY; - } - - final ArrayList items = new ArrayList(); - - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - final CompileScope scope = context.getCompileScope(); - final CompileScope projectScope = context.getProjectCompileScope(); - - final VirtualFile[] formFiles = projectScope.getFiles(StdFileTypes.GUI_DESIGNER_FORM, true); - if (formFiles.length==0) return; - final CompilerManager compilerManager = CompilerManager.getInstance(project); - final BindingsCache bindingsCache = new BindingsCache(project); - - final HashMap> module2formFiles = sortByModules(project, formFiles); - - try { - for (final Module module : module2formFiles.keySet()) { - final HashMap class2form = new HashMap(); - - final ArrayList list = module2formFiles.get(module); - for (final VirtualFile formFile : list) { - if (compilerManager.isExcludedFromCompilation(formFile)) { - continue; - } - - final String classToBind; - try { - classToBind = bindingsCache.getBoundClassName(formFile); - } - catch (AlienFormFileException e) { - // ignore non-IDEA forms - continue; - } - catch (Exception e) { - addMessage(context, UIDesignerBundle.message("error.cannot.process.form.file", e), formFile, CompilerMessageCategory.ERROR); - continue; - } - - if (classToBind == null) { - continue; - } - - final VirtualFile classFile = findFile(context, classToBind, module); - if (classFile == null) { - if (scope.belongs(formFile.getUrl())) { - addMessage(context, UIDesignerBundle.message("error.class.to.bind.does.not.exist", classToBind), formFile, - CompilerMessageCategory.ERROR); - } - continue; - } - - final VirtualFile alreadyProcessedForm = class2form.get(classToBind); - if (alreadyProcessedForm != null) { - if (belongsToCompileScope(context, formFile, classToBind)) { - addMessage( - context, - UIDesignerBundle.message("error.duplicate.bind", - classToBind, alreadyProcessedForm.getPresentableUrl()), - formFile, CompilerMessageCategory.ERROR); - } - continue; - } - class2form.put(classToBind, formFile); - - final ProcessingItem item = new MyInstrumentationItem(classFile, formFile, classToBind); - items.add(item); - } - } - } - finally { - bindingsCache.close(); - } - } - }); - - return items.toArray(new ProcessingItem[items.size()]); - } - - private static boolean belongsToCompileScope(final CompileContext context, final VirtualFile formFile, final String classToBind) { - final CompileScope compileScope = context.getCompileScope(); - if (compileScope.belongs(formFile.getUrl())) { - return true; - } - final VirtualFile sourceFile = findSourceFile(context, formFile, classToBind); - return sourceFile != null && compileScope.belongs(sourceFile.getUrl()); - } - - private static HashMap> sortByModules(final Project project, final VirtualFile[] formFiles) { - final HashMap> module2formFiles = new HashMap>(); - for (final VirtualFile formFile : formFiles) { - final Module module = ModuleUtil.findModuleForFile(formFile, project); - if (module != null) { - ArrayList list = module2formFiles.get(module); - if (list == null) { - list = new ArrayList(); - module2formFiles.put(module, list); - } - list.add(formFile); - } - else { - // todo[anton] handle somehow - } - } - return module2formFiles; - } - - private static HashMap> sortByModules(final Project project, final ProcessingItem[] items) { - final HashMap> module2formFiles = new HashMap>(); - for (ProcessingItem item1 : items) { - final MyInstrumentationItem item = (MyInstrumentationItem)item1; - final VirtualFile formFile = item.getFormFile(); - - final Module module = ModuleUtil.findModuleForFile(formFile, project); - if (module != null) { - ArrayList list = module2formFiles.get(module); - if (list == null) { - list = new ArrayList(); - module2formFiles.put(module, list); - } - list.add(item); - } - else { - // todo[anton] handle somehow - } - } - return module2formFiles; - } - - @Nullable - private static VirtualFile findFile(final CompileContext context, final String className, final Module module) { - /*for most cases (top-level classes) this will work*/ - VirtualFile file = findFileByRelativePath(context, module, className.replace('.', '/') + ".class"); - if (file == null) { - // getClassFileName() is much longer than simply conversion from dots into slashes, but works for inner classes - file = findFileByRelativePath(context, module, getClassFileName(className.replace('$', '.'), module) + ".class"); - } - return file; - } - - private static VirtualFile findFileByRelativePath(final CompileContext context, final Module module, final String relativepath) { - final VirtualFile output = context.getModuleOutputDirectory(module); - VirtualFile file = output != null? output.findFileByRelativePath(relativepath) : null; - if (file == null) { - final VirtualFile testsOutput = context.getModuleOutputDirectoryForTests(module); - if (testsOutput != null && !testsOutput.equals(output)) { - file = testsOutput.findFileByRelativePath(relativepath); - } - } - return file; - } - - private static String getClassFileName(final String _className, final Module module) { - final PsiClass aClass = JavaPsiFacade.getInstance(module.getProject()).findClass(_className, GlobalSearchScope.moduleScope(module)); - if (aClass == null) { - return _className.replace('.', '/'); - } - - PsiClass outerClass = aClass; - while (outerClass.getParent() instanceof PsiClass) { - outerClass = (PsiClass)outerClass.getParent(); - } - - final String outerQualifiedName = outerClass.getQualifiedName(); - - assert outerQualifiedName != null; - return outerQualifiedName.replace('.','/') + _className.substring(outerQualifiedName.length()).replace('.','$'); - } - - @Override - public ProcessingItem[] process(final CompileContext context, final ProcessingItem[] items) { - final ArrayList compiledItems = new ArrayList(); - - context.getProgressIndicator().pushState(); - context.getProgressIndicator().setText(UIDesignerBundle.message("progress.compiling.ui.forms")); - - final Project project = context.getProject(); - final HashMap> module2itemsList = sortByModules(project, items); - - List filesToRefresh = new ArrayList(); - for (final Module module : module2itemsList.keySet()) { - final String classPath = OrderEnumerator.orderEntries(module).recursively().getPathsList().getPathsString(); - final InstrumentationClassFinder finder = createClassFinder(classPath); - - try { - if (GuiDesignerConfiguration.getInstance(project).COPY_FORMS_RUNTIME_TO_OUTPUT) { - final String moduleOutputPath = CompilerPaths.getModuleOutputPath(module, false); - try { - if (moduleOutputPath != null) { - filesToRefresh.addAll(CopyResourcesUtil.copyFormsRuntime(moduleOutputPath, false)); - } - final String testsOutputPath = CompilerPaths.getModuleOutputPath(module, true); - if (testsOutputPath != null && !testsOutputPath.equals(moduleOutputPath)) { - filesToRefresh.addAll(CopyResourcesUtil.copyFormsRuntime(testsOutputPath, false)); - } - } - catch (IOException e) { - addMessage( - context, - UIDesignerBundle.message("error.cannot.copy.gui.designer.form.runtime", module.getName(), e.toString()), - null, CompilerMessageCategory.ERROR); - } - } - - final ArrayList list = module2itemsList.get(module); - - for (final MyInstrumentationItem item : list) { - //context.getProgressIndicator().setFraction((double)++formsProcessed / (double)items.length); - - final VirtualFile formFile = item.getFormFile(); - context.getProgressIndicator().setText2(formFile.getPresentableUrl()); - - final String text = ApplicationManager.getApplication().runReadAction(new Computable() { - @Override - public String compute() { - if (!belongsToCompileScope(context, formFile, item.getClassToBindFQname())) { - return null; - } - Document document = FileDocumentManager.getInstance().getDocument(formFile); - return document == null ? null : document.getText(); - } - }); - if (text == null) { - continue; // does not belong to current scope - } - - final LwRootContainer rootContainer; - try { - rootContainer = Utils.getRootContainer(text, new CompiledClassPropertiesProvider(finder.getLoader())); - } - catch (Exception e) { - addMessage(context, UIDesignerBundle.message("error.cannot.process.form.file", e), formFile, CompilerMessageCategory.ERROR); - continue; - } - - final File classFile = VfsUtil.virtualToIoFile(item.getFile()); - LOG.assertTrue(classFile.exists(), classFile.getPath()); - - final AsmCodeGenerator codeGenerator = new AsmCodeGenerator( - rootContainer, finder, new PsiNestedFormLoader(module), false, new PsiClassWriter(module) - ); - ApplicationManager.getApplication().runReadAction(new Runnable() { - @Override - public void run() { - codeGenerator.patchFile(classFile); - } - }); - final FormErrorInfo[] errors = codeGenerator.getErrors(); - final FormErrorInfo[] warnings = codeGenerator.getWarnings(); - for (FormErrorInfo warning : warnings) { - addMessage(context, warning, formFile, CompilerMessageCategory.WARNING); - } - for (FormErrorInfo error : errors) { - addMessage(context, error, formFile, CompilerMessageCategory.ERROR); - } - if (errors.length == 0) { - compiledItems.add(item); - } - } - } - finally { - finder.releaseResources(); - } - } - CompilerUtil.refreshIOFiles(filesToRefresh); - context.getProgressIndicator().popState(); - - return compiledItems.toArray(new ProcessingItem[compiledItems.size()]); - } - - private static void addMessage(final CompileContext context, - final String s, - final VirtualFile formFile, - final CompilerMessageCategory severity) { - addMessage(context, new FormErrorInfo(null, s), formFile, severity); - } - - private static void addMessage(final CompileContext context, - final FormErrorInfo e, - final VirtualFile formFile, - final CompilerMessageCategory severity) { - if (formFile != null) { - FormElementNavigatable navigatable = new FormElementNavigatable(context.getProject(), formFile, e.getComponentId()); - context.addMessage(severity, - formFile.getPresentableUrl() + ": " + e.getErrorMessage(), - formFile.getUrl(), -1, -1, navigatable); - } - else { - context.addMessage(severity, e.getErrorMessage(), null, -1, -1); - } - } - - @Override - public ValidityState createValidityState(final DataInput in) throws IOException { - return TimestampValidityState.load(in); - } - - public static VirtualFile findSourceFile(final CompileContext context, final VirtualFile formFile, final String className) { - final Module module = context.getModuleByFile(formFile); - if (module == null) { - return null; - } - final PsiClass aClass = FormEditingUtil.findClassToBind(module, className); - if (aClass == null) { - return null; - } - - final PsiFile containingFile = aClass.getContainingFile(); - if (containingFile == null){ - return null; - } - - return containingFile.getVirtualFile(); - } - - private static final class MyInstrumentationItem implements ProcessingItem { - private final VirtualFile myClassFile; - private final VirtualFile myFormFile; - private final String myClassToBindFQname; - private final TimestampValidityState myState; - - private MyInstrumentationItem(final VirtualFile classFile, final VirtualFile formFile, final String classToBindFQname) { - myClassFile = classFile; - myFormFile = formFile; - myClassToBindFQname = classToBindFQname; - myState = new TimestampValidityState(formFile.getTimeStamp()); - } - - @Override - @NotNull - public VirtualFile getFile() { - return myClassFile; - } - - public VirtualFile getFormFile() { - return myFormFile; - } - - public String getClassToBindFQname() { - return myClassToBindFQname; - } - - @Override - public ValidityState getValidityState() { - return myState; - } - } - -} 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 05ba5140707a..946bf5e1a11b 100644 --- a/plugins/ui-designer/src/com/intellij/uiDesigner/make/Form2SourceCompiler.java +++ b/plugins/ui-designer/src/com/intellij/uiDesigner/make/Form2SourceCompiler.java @@ -26,7 +26,10 @@ import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleUtilCore; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; +import com.intellij.psi.PsiClass; import com.intellij.psi.PsiDocumentManager; +import com.intellij.psi.PsiFile; +import com.intellij.uiDesigner.FormEditingUtil; import com.intellij.uiDesigner.GuiDesignerConfiguration; import com.intellij.uiDesigner.UIDesignerBundle; import com.intellij.uiDesigner.compiler.AlienFormFileException; @@ -44,6 +47,24 @@ import java.util.List; public final class Form2SourceCompiler implements SourceInstrumentingCompiler{ + private static VirtualFile findSourceFile(final CompileContext context, final VirtualFile formFile, final String className) { + final Module module = context.getModuleByFile(formFile); + if (module == null) { + return null; + } + final PsiClass aClass = FormEditingUtil.findClassToBind(module, className); + if (aClass == null) { + return null; + } + + final PsiFile containingFile = aClass.getContainingFile(); + if (containingFile == null){ + return null; + } + + return containingFile.getVirtualFile(); + } + @NotNull public String getDescription() { return UIDesignerBundle.message("component.gui.designer.form.to.source.compiler"); @@ -96,7 +117,7 @@ public final class Form2SourceCompiler implements SourceInstrumentingCompiler{ continue; } - final VirtualFile sourceFile = Form2ByteCodeCompiler.findSourceFile(context, formFile, classToBind); + final VirtualFile sourceFile = 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); diff --git a/plugins/ui-designer/testSrc/com/intellij/uiDesigner/make/UiDesignerExternalBuildTest.java b/plugins/ui-designer/testSrc/com/intellij/uiDesigner/make/UiDesignerExternalBuildTest.java index 091ed0b39649..4837b0e82c82 100644 --- a/plugins/ui-designer/testSrc/com/intellij/uiDesigner/make/UiDesignerExternalBuildTest.java +++ b/plugins/ui-designer/testSrc/com/intellij/uiDesigner/make/UiDesignerExternalBuildTest.java @@ -31,10 +31,6 @@ import java.io.IOException; * @author nik */ public class UiDesignerExternalBuildTest extends ArtifactCompilerTestCase { - @Override - protected boolean useExternalCompiler() { - return true; - } //IDEA-94779 public void testCopyFormsRuntimeToArtifact() throws IOException { diff --git a/resources-en/src/messages/CompilerBundle.properties b/resources-en/src/messages/CompilerBundle.properties index 27a33a6d02df..be7367512247 100644 --- a/resources-en/src/messages/CompilerBundle.properties +++ b/resources-en/src/messages/CompilerBundle.properties @@ -51,18 +51,11 @@ generated.ant.build.build.all.target.name=build all generated.ant.build.building.concrete.module.section.title=Module {0} compiler.error.exception=Error: {0} error.compiler.caches.corrupted=Compiler caches are corrupted. Starting rebuild... -error.caches.old.format=Compiler caches on disk have old format. Project rebuild is required. -error.previous.compilation.failed=Previous compilation did not terminate properly. Caches may have been corrupted. Starting rebuild... error.dependency.info.on.disk.corrupted=Compiler dependency information on disk is corrupted. Rebuild required. -error.vfs.was.rebuilt=File system caches were invalidated. Rebuild required. status.compilation.aborted=Compilation aborted status.all.up.to.date=All files are up-to-date -progress.saving.caches=Saving caches... -progress.clearing.output=Clearing output directories... compiler.error.failed.to.delete=Failed to delete {0} -progress.synchronizing.output.directory=Synchronizing output directory... progress.updating.caches=Updating caches... -progress.processing.outdated.files=Processing outdated files... compiler.content.name.compile=Compile compiler.content.name.make=Make status.compilation.completed.successfully.with.warnings=Compilation completed successfully with {0} {0,choice, 0#warnings|1#warning|2#warnings} @@ -73,25 +66,19 @@ progress.executing.postcompile.tasks=Executing post-compile tasks... error.failed.to.create.directory=Failed to create directory {0} error.chunk.modules.must.have.same.jdk=The following modules must have the same JDK assigned because of cyclic dependencies between them:\n{0}\nPlease update modules configuration error.chunk.modules.must.have.same.language.level=The following modules must have the same language level assigned because of cyclic dependencies between them:\n{0}\nPlease update modules configuration -error.annotation.processing.not.supported.for.module.cycles=Annotation processors running is not supported for module cycles. The following modules form a cycle:\n{0}\nPlease either update modules configuration or exclude these modules from annotation processing warning.sources.under.output.paths=Compiler option \"Clear output directory on rebuild\" is currently on.\nHowever, source files may exist in the following output paths:\n{0}\nCompilation will proceed without clearing output directories. action.compiler.properties.text=Compiler Properties actions.exclude.from.compile.text=Exclude from Compile -progress.deleting.temp.files=Deleting temp files... progress.checking.dependencies=Checking dependencies... progress.found.dependent.files=Found {0} dependent files error.compiler.internal.error=Compiler internal error. Process terminated with exit code {0} error.bad.class.file.format=Bad class file format:\n{0} java.compiler.description=Java Compiler -annotation.processing.compiler.description=Java Annotation Processing Compiler resource.compiler.description=Resource Compiler -progress.copying.resources=Copying resources... -progress.generating.rmi.stubs=Generating RMI stubs... rmi.compiler.description=RMI Compiler error.jdk.not.specified=Cannot start compiler: the SDK is not specified for {0,choice, 1#module|2#modules\n} {1}.\nSpecify the SDK at Project Structure dialog. error.output.not.specified=Cannot start compilation: the output path is not specified for {0,choice, 1#module|2#modules\n} {1}.\nSpecify the output path in Configure Project. error.project.output.not.specified=Cannot start compilation: some compilers require that project path is defined.\nSpecify project output path in Configure Project. -statistics.files.classes.module=Files: {0} - Classes: {1} - Module: {2} statistics.files.classes=Files: {0} - Classes: {1} compiler.javac.name=Javac javac.error.jdk.home.missing=Cannot find home directory ''{1}'' for JDK ''{0}''.\nUpdate JDK configuration. @@ -99,16 +86,8 @@ javac.error.vm.executable.missing=Cannot obtain path to VM executable for JDK {0 javac.error.tools.jar.missing=Cannot obtain path javac classes for JDK {0}.\nUpdate JDK configuration. javac.error.unknown.jdk.version=Cannot determine version for JDK {0}.\nUpdate JDK configuration. javac.error.1_0_compilation.not.supported=Compilation is not supported for JDK 1.0 -compiler.jikes.name=Jikes -jikes.error.path.to.compiler.unspecified=Cannot start Jikes compiler.\nThe path to compiler executable is not configured -jikes.error.path.to.compiler.missing=Cannot start Jikes compiler.\nThe file {0} not found. compiler.configurable.display.name=Compiler -label.option.honor.dependencies=Honor &dependencies on "Compile" command label.option.compile.in.background=C&ompile in background -label.option.deploy.ask=Ask -label.option.deploy.never=Never -label.option.deploy.always=Always -label.option.deploy.text=Deploy web applications to server after compilation: label.option.clear.output.directory.on.rebuild=C&lear output directory on rebuild label.option.resource.patterns.text=Resource patterns\: error.compiler.configurable.malformed.patterns=The following resource patterns are malformed:\n{0} @@ -121,8 +100,6 @@ java.compiler.option.generate.no.warnings=Generate no warnings java.compiler.option.generate.debugging.info=Generate debugging info java.compiler.option.report.deprecated=Report use of deprecated features javac.option.max.heap.size=Maximum heap size (MB): -jikes.option.path.to.executable=Path to Jikes executable: -jikes.options.group.title=Jikes Options javac.options.group.title=Javac Options rmic.option.generate.iiop.stubs=Generate IIOP stubs rmic.option.enable.rmi.stubs=Enable RMI stubs generation @@ -139,7 +116,6 @@ error.signature.parsing.expected.other.symbol=Symbol ''{0}'' expected: {1} error.compiler.process.not.started=Compiler not started: {0} add.notnull.assertions=Add @NotNull &assertions -eclipse.compiler.error.jar.not.found=Cannot start Eclipse compiler.\nThe file {0} not found. compiler.eclipse.name=Eclipse eclipse.options.group.title=Eclipse Options eclipse.compiler.parsing=Parsing {0} diff --git a/resources/src/idea/RichPlatformActions.xml b/resources/src/idea/RichPlatformActions.xml index 0822f3c29e6c..419eb2afcbfc 100644 --- a/resources/src/idea/RichPlatformActions.xml +++ b/resources/src/idea/RichPlatformActions.xml @@ -98,7 +98,6 @@ - @@ -177,13 +176,9 @@ - - - - @@ -209,7 +204,6 @@ - @@ -232,7 +226,6 @@ - @@ -256,7 +249,6 @@ - @@ -297,7 +289,6 @@ - @@ -337,7 +328,6 @@ - diff --git a/resources/src/idea/RichPlatformPlugin.xml b/resources/src/idea/RichPlatformPlugin.xml index 7b38db51ac53..2de194f6d4b8 100644 --- a/resources/src/idea/RichPlatformPlugin.xml +++ b/resources/src/idea/RichPlatformPlugin.xml @@ -35,9 +35,6 @@ - - @@ -47,9 +44,6 @@ - -