From 973c6f8d8590d335e69123d7c0f0e399291914ff Mon Sep 17 00:00:00 2001 From: "Pavel V. Talanov" Date: Wed, 4 Apr 2012 16:08:11 +0400 Subject: [PATCH 01/12] Read lib files for IDEA config from zip archive. --- .../k2js/test/config/TestConfig.java | 10 ++--- .../org/jetbrains/k2js/config/IDEAConfig.java | 45 ++++++++++++++++++- .../jetbrains/k2js/facade/K2JSTranslator.java | 8 ++-- 3 files changed, 52 insertions(+), 11 deletions(-) diff --git a/js/js.tests/test/org/jetbrains/k2js/test/config/TestConfig.java b/js/js.tests/test/org/jetbrains/k2js/test/config/TestConfig.java index e5e7c66d310..144fa6f49f5 100644 --- a/js/js.tests/test/org/jetbrains/k2js/test/config/TestConfig.java +++ b/js/js.tests/test/org/jetbrains/k2js/test/config/TestConfig.java @@ -25,7 +25,6 @@ import org.jetbrains.k2js.config.Config; import org.jetbrains.k2js.utils.JetFileUtils; import java.io.FileInputStream; -import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; @@ -57,15 +56,16 @@ public final class TestConfig extends Config { try { String text = FileUtil.loadTextAndClose(stream); file = JetFileUtils.createPsiFile(libFileName, text, project); - } catch (IOException e) { + } + catch (IOException e) { e.printStackTrace(); } libFiles.add(file); - } catch (FileNotFoundException e) { - //TODO: throw generic expception + } + catch (Exception e) { + //TODO: throw generic exception throw new IllegalStateException(e); } - } return libFiles; } diff --git a/js/js.translator/src/org/jetbrains/k2js/config/IDEAConfig.java b/js/js.translator/src/org/jetbrains/k2js/config/IDEAConfig.java index cec202f7b62..0b697af7aaa 100644 --- a/js/js.translator/src/org/jetbrains/k2js/config/IDEAConfig.java +++ b/js/js.translator/src/org/jetbrains/k2js/config/IDEAConfig.java @@ -16,25 +16,66 @@ package org.jetbrains.k2js.config; +import com.google.common.collect.Lists; import com.intellij.openapi.project.Project; +import com.intellij.openapi.util.io.FileUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.jet.lang.psi.JetFile; +import org.jetbrains.k2js.utils.JetFileUtils; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; import java.util.Collections; +import java.util.Enumeration; import java.util.List; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; /** * @author Pavel Talanov */ public final class IDEAConfig extends Config { - public IDEAConfig(@NotNull Project project) { + @NotNull + private final String pathToLibZip; + + public IDEAConfig(@NotNull Project project, @NotNull String pathToLibZip) { super(project); + this.pathToLibZip = pathToLibZip; } @NotNull @Override public List getLibFiles() { - return Collections.emptyList(); + try { + File file = new File(pathToLibZip); + ZipFile zipFile = new ZipFile(file); + try { + return traverseArchive(zipFile); + } + finally { + zipFile.close(); + } + } + catch (IOException e) { + return Collections.emptyList(); + } + } + + @NotNull + private List traverseArchive(@NotNull ZipFile file) throws IOException { + List result = Lists.newArrayList(); + Enumeration zipEntries = file.entries(); + while (zipEntries.hasMoreElements()) { + ZipEntry entry = zipEntries.nextElement(); + if (!entry.isDirectory()) { + InputStream stream = file.getInputStream(entry); + String text = FileUtil.loadTextAndClose(stream); + JetFile jetFile = JetFileUtils.createPsiFile(entry.getName(), text, getProject()); + result.add(jetFile); + } + } + return result; } } diff --git a/js/js.translator/src/org/jetbrains/k2js/facade/K2JSTranslator.java b/js/js.translator/src/org/jetbrains/k2js/facade/K2JSTranslator.java index 952aaeba759..a18f5e282be 100644 --- a/js/js.translator/src/org/jetbrains/k2js/facade/K2JSTranslator.java +++ b/js/js.translator/src/org/jetbrains/k2js/facade/K2JSTranslator.java @@ -52,7 +52,8 @@ public final class K2JSTranslator { public static void translateWithCallToMainAndSaveToFile(@NotNull List files, @NotNull String outputPath, @NotNull Project project) throws Exception { - K2JSTranslator translator = new K2JSTranslator(new IDEAConfig(project)); + K2JSTranslator translator = new K2JSTranslator(new IDEAConfig(project, + "C:\\Dev\\Projects\\Kotlin\\clean_jet\\js\\js.libraries\\src\\k2jslib.zip")); String programCode = translator.generateProgramCode(files) + "\n"; JetFile fileWithMain = JetMainDetector.getFileWithMain(files); if (fileWithMain == null) { @@ -62,7 +63,8 @@ public final class K2JSTranslator { FileWriter writer = new FileWriter(new File(outputPath)); try { writer.write(programCode + callToMain); - } finally { + } + finally { writer.close(); } } @@ -109,7 +111,6 @@ public final class K2JSTranslator { return Translation.generateAst(bindingContext, AnalyzerFacadeForJS.withJsLibAdded(filesToTranslate, config)); } - @NotNull public static String generateCallToMain(@NotNull JetFile file, @NotNull String argumentString) { String namespaceName = getNamespaceName(file); @@ -132,5 +133,4 @@ public final class K2JSTranslator { private Project getProject() { return config.getProject(); } - } From 766b4dc97559766a1d2a7a5982911cca4fac6759 Mon Sep 17 00:00:00 2001 From: "Pavel V. Talanov" Date: Wed, 4 Apr 2012 16:11:40 +0400 Subject: [PATCH 02/12] Move AnalyzerExhaust from frontend.java to frontend. --- .../jet/codegen/GenerationState.java | 31 +++-- .../jet/codegen/GenerationUtils.java | 9 +- .../jet/compiler/CompileSession.java | 35 +++-- .../resolve/java/AnalyzerFacadeForJVM.java | 102 ++++++++------- .../jet/analyzer}/AnalyzeExhaust.java | 5 +- .../jetbrains/jet/asJava/JetLightClass.java | 32 ++--- .../tests/org/jetbrains/jet/JetTestUtils.java | 120 +++++++++--------- .../jet/codegen/CodegenTestCase.java | 56 ++++---- .../jet/resolve/ExpectedResolveData.java | 66 +++++----- .../JetDefaultModalityModifiersTest.java | 44 ++++--- .../plugin/debugger/JetPositionManager.java | 27 ++-- .../codewindow/BytecodeToolwindow.java | 31 +++-- .../project/WholeProjectAnalyzerFacade.java | 9 +- 13 files changed, 316 insertions(+), 251 deletions(-) rename compiler/{frontend.java/src/org/jetbrains/jet/lang/resolve/java => frontend/src/org/jetbrains/jet/analyzer}/AnalyzeExhaust.java (93%) diff --git a/compiler/backend/src/org/jetbrains/jet/codegen/GenerationState.java b/compiler/backend/src/org/jetbrains/jet/codegen/GenerationState.java index 03bdc90036e..fdb550c11e7 100644 --- a/compiler/backend/src/org/jetbrains/jet/codegen/GenerationState.java +++ b/compiler/backend/src/org/jetbrains/jet/codegen/GenerationState.java @@ -25,6 +25,7 @@ import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Pair; import com.intellij.openapi.vfs.VirtualFile; import org.jetbrains.annotations.NotNull; +import org.jetbrains.jet.analyzer.AnalyzeExhaust; import org.jetbrains.jet.di.InjectorForJvmCodegen; import org.jetbrains.jet.lang.descriptors.ClassDescriptor; import org.jetbrains.jet.lang.descriptors.ConstructorDescriptor; @@ -34,7 +35,6 @@ import org.jetbrains.jet.lang.psi.JetFile; import org.jetbrains.jet.lang.psi.JetObjectDeclaration; import org.jetbrains.jet.lang.psi.JetObjectLiteralExpression; import org.jetbrains.jet.lang.resolve.BindingContext; -import org.jetbrains.jet.lang.resolve.java.AnalyzeExhaust; import org.jetbrains.jet.utils.Progress; import java.util.List; @@ -54,12 +54,18 @@ public class GenerationState { this(project, builderFactory, Progress.DEAF, analyzeExhaust, files); } - public GenerationState(Project project, ClassBuilderFactory builderFactory, Progress progress, @NotNull AnalyzeExhaust exhaust, @NotNull List files) { + public GenerationState(Project project, + ClassBuilderFactory builderFactory, + Progress progress, + @NotNull AnalyzeExhaust exhaust, + @NotNull List files) { this.project = project; this.progress = progress; this.analyzeExhaust = exhaust; this.files = files; - this.injector = new InjectorForJvmCodegen(analyzeExhaust.getStandardLibrary(), analyzeExhaust.getBindingContext(), this.files, project, this, builderFactory); + this.injector = + new InjectorForJvmCodegen(analyzeExhaust.getStandardLibrary(), analyzeExhaust.getBindingContext(), this.files, project, this, + builderFactory); } @NotNull @@ -84,11 +90,13 @@ public class GenerationState { } public ClassBuilder forClassImplementation(ClassDescriptor aClass) { - return getFactory().newVisitor(getInjector().getJetTypeMapper().mapType(aClass.getDefaultType(), OwnerKind.IMPLEMENTATION).getInternalName() + ".class"); + return getFactory().newVisitor( + getInjector().getJetTypeMapper().mapType(aClass.getDefaultType(), OwnerKind.IMPLEMENTATION).getInternalName() + ".class"); } public ClassBuilder forTraitImplementation(ClassDescriptor aClass) { - return getFactory().newVisitor(getInjector().getJetTypeMapper().mapType(aClass.getDefaultType(), OwnerKind.TRAIT_IMPL).getInternalName() + ".class"); + return getFactory().newVisitor( + getInjector().getJetTypeMapper().mapType(aClass.getDefaultType(), OwnerKind.TRAIT_IMPL).getInternalName() + ".class"); } public Pair forAnonymousSubclass(JetExpression expression) { @@ -134,14 +142,17 @@ public class GenerationState { closure.cv = nameAndVisitor.getSecond(); closure.name = nameAndVisitor.getFirst(); final CodegenContext objectContext = closure.context.intoAnonymousClass( - closure, analyzeExhaust.getBindingContext().get(BindingContext.CLASS, objectDeclaration), OwnerKind.IMPLEMENTATION, injector.getJetTypeMapper()); + closure, analyzeExhaust.getBindingContext().get(BindingContext.CLASS, objectDeclaration), OwnerKind.IMPLEMENTATION, + injector.getJetTypeMapper()); new ImplementationBodyCodegen(objectDeclaration, objectContext, nameAndVisitor.getSecond(), this).generate(); ConstructorDescriptor constructorDescriptor = analyzeExhaust.getBindingContext().get(BindingContext.CONSTRUCTOR, objectDeclaration); CallableMethod callableMethod = injector.getJetTypeMapper().mapToCallableMethod( - constructorDescriptor, OwnerKind.IMPLEMENTATION, injector.getJetTypeMapper().hasThis0(constructorDescriptor.getContainingDeclaration())); - return new GeneratedAnonymousClassDescriptor(nameAndVisitor.first, callableMethod.getSignature().getAsmMethod(), objectContext.outerWasUsed, null); + constructorDescriptor, OwnerKind.IMPLEMENTATION, + injector.getJetTypeMapper().hasThis0(constructorDescriptor.getContainingDeclaration())); + return new GeneratedAnonymousClassDescriptor(nameAndVisitor.first, callableMethod.getSignature().getAsmMethod(), + objectContext.outerWasUsed, null); } public String createText() { @@ -151,8 +162,8 @@ public class GenerationState { List files = factory.files(); for (String file : files) { // if (!file.startsWith("kotlin/")) { - answer.append("@").append(file).append('\n'); - answer.append(factory.asText(file)); + answer.append("@").append(file).append('\n'); + answer.append(factory.asText(file)); // } } diff --git a/compiler/backend/src/org/jetbrains/jet/codegen/GenerationUtils.java b/compiler/backend/src/org/jetbrains/jet/codegen/GenerationUtils.java index 22dd565a94e..b43db7ec503 100644 --- a/compiler/backend/src/org/jetbrains/jet/codegen/GenerationUtils.java +++ b/compiler/backend/src/org/jetbrains/jet/codegen/GenerationUtils.java @@ -17,9 +17,9 @@ package org.jetbrains.jet.codegen; import org.jetbrains.annotations.NotNull; +import org.jetbrains.jet.analyzer.AnalyzeExhaust; import org.jetbrains.jet.lang.cfg.pseudocode.JetControlFlowDataTraceFactory; import org.jetbrains.jet.lang.psi.JetFile; -import org.jetbrains.jet.lang.resolve.java.AnalyzeExhaust; import org.jetbrains.jet.lang.resolve.java.AnalyzerFacadeForJVM; import java.util.Collections; @@ -34,10 +34,11 @@ public class GenerationUtils { } public static GenerationState compileFileGetGenerationState(JetFile psiFile) { - final AnalyzeExhaust analyzeExhaust = AnalyzerFacadeForJVM.analyzeOneFileWithJavaIntegrationAndCheckForErrors(psiFile, JetControlFlowDataTraceFactory.EMPTY); - GenerationState state = new GenerationState(psiFile.getProject(), ClassBuilderFactories.binaries(false), analyzeExhaust, Collections.singletonList(psiFile)); + final AnalyzeExhaust analyzeExhaust = + AnalyzerFacadeForJVM.analyzeOneFileWithJavaIntegrationAndCheckForErrors(psiFile, JetControlFlowDataTraceFactory.EMPTY); + GenerationState state = new GenerationState(psiFile.getProject(), ClassBuilderFactories.binaries(false), analyzeExhaust, + Collections.singletonList(psiFile)); state.compileCorrectFiles(CompilationErrorHandler.THROW_EXCEPTION); return state; } - } diff --git a/compiler/cli/src/org/jetbrains/jet/compiler/CompileSession.java b/compiler/cli/src/org/jetbrains/jet/compiler/CompileSession.java index cc616bce02e..c5e5c378df8 100644 --- a/compiler/cli/src/org/jetbrains/jet/compiler/CompileSession.java +++ b/compiler/cli/src/org/jetbrains/jet/compiler/CompileSession.java @@ -26,6 +26,7 @@ import com.intellij.psi.PsiFile; import com.intellij.psi.PsiManager; import com.intellij.psi.PsiRecursiveElementWalkingVisitor; import org.jetbrains.annotations.NotNull; +import org.jetbrains.jet.analyzer.AnalyzeExhaust; import org.jetbrains.jet.codegen.ClassBuilderFactories; import org.jetbrains.jet.codegen.CompilationErrorHandler; import org.jetbrains.jet.codegen.GenerationState; @@ -41,7 +42,6 @@ import org.jetbrains.jet.lang.diagnostics.DiagnosticUtils; import org.jetbrains.jet.lang.diagnostics.Severity; import org.jetbrains.jet.lang.psi.JetFile; import org.jetbrains.jet.lang.resolve.BindingContext; -import org.jetbrains.jet.lang.resolve.java.AnalyzeExhaust; import org.jetbrains.jet.lang.resolve.java.AnalyzerFacadeForJVM; import org.jetbrains.jet.lang.resolve.java.CompilerSpecialMode; import org.jetbrains.jet.lang.resolve.java.JavaDescriptorResolver; @@ -71,7 +71,11 @@ public class CompileSession { private final CompilerSpecialMode compilerSpecialMode; private AnalyzeExhaust bindingContext; - public CompileSession(JetCoreEnvironment environment, MessageRenderer messageRenderer, PrintStream errorStream, boolean verbose, CompilerSpecialMode mode) { + public CompileSession(JetCoreEnvironment environment, + MessageRenderer messageRenderer, + PrintStream errorStream, + boolean verbose, + CompilerSpecialMode mode) { this.environment = environment; this.messageRenderer = messageRenderer; this.errorStream = errorStream; @@ -90,8 +94,9 @@ public class CompileSession { } public void addSources(String path) { - if(path == null) + if (path == null) { return; + } VirtualFile vFile = environment.getLocalFileSystem().findFileByPath(path); if (vFile == null) { @@ -107,7 +112,7 @@ public class CompileSession { } private void addSources(File file) { - if(file.isDirectory()) { + if (file.isDirectory()) { File[] files = file.listFiles(); if (files != null) { for (File child : files) { @@ -119,7 +124,7 @@ public class CompileSession { VirtualFile fileByPath = environment.getLocalFileSystem().findFileByPath(file.getAbsolutePath()); if (fileByPath != null) { PsiFile psiFile = PsiManager.getInstance(environment.getProject()).findFile(fileByPath); - if(psiFile instanceof JetFile) { + if (psiFile instanceof JetFile) { sourceFiles.add((JetFile)psiFile); } } @@ -127,7 +132,7 @@ public class CompileSession { } public void addSources(VirtualFile vFile) { - if (vFile.isDirectory()) { + if (vFile.isDirectory()) { for (VirtualFile virtualFile : vFile.getChildren()) { addSources(virtualFile); } @@ -161,22 +166,25 @@ public class CompileSession { /** * @see JetTypeMapper#getFQName(DeclarationDescriptor) - * TODO possibly duplicates DescriptorUtils#getFQName(DeclarationDescriptor) + * TODO possibly duplicates DescriptorUtils#getFQName(DeclarationDescriptor) */ private static String fqName(ClassOrNamespaceDescriptor descriptor) { DeclarationDescriptor containingDeclaration = descriptor.getContainingDeclaration(); - if (containingDeclaration == null || containingDeclaration instanceof ModuleDescriptor || containingDeclaration.getName().equals(JavaDescriptorResolver.JAVA_ROOT)) { + if (containingDeclaration == null || + containingDeclaration instanceof ModuleDescriptor || + containingDeclaration.getName().equals(JavaDescriptorResolver.JAVA_ROOT)) { return descriptor.getName(); - } else { - return fqName((ClassOrNamespaceDescriptor) containingDeclaration) + "." + descriptor.getName(); + } + else { + return fqName((ClassOrNamespaceDescriptor)containingDeclaration) + "." + descriptor.getName(); } } private void analyzeAndReportSemanticErrors() { Predicate filesToAnalyzeCompletely = - stubs ? Predicates.alwaysFalse() : Predicates.alwaysTrue(); + stubs ? Predicates.alwaysFalse() : Predicates.alwaysTrue(); bindingContext = AnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration( - environment.getProject(), sourceFiles, filesToAnalyzeCompletely, JetControlFlowDataTraceFactory.EMPTY, compilerSpecialMode); + environment.getProject(), sourceFiles, filesToAnalyzeCompletely, JetControlFlowDataTraceFactory.EMPTY, compilerSpecialMode); for (Diagnostic diagnostic : bindingContext.getBindingContext().getDiagnostics()) { reportDiagnostic(messageCollector, diagnostic); @@ -221,7 +229,8 @@ public class CompileSession { public GenerationState generate(boolean module) { Project project = environment.getProject(); GenerationState generationState = new GenerationState(project, ClassBuilderFactories.binaries(stubs), - isVerbose ? new BackendProgress() : Progress.DEAF, bindingContext, sourceFiles); + isVerbose ? new BackendProgress() : Progress.DEAF, bindingContext, + sourceFiles); generationState.compileCorrectFiles(CompilationErrorHandler.THROW_EXCEPTION); List plugins = environment.getCompilerPlugins(); diff --git a/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/AnalyzerFacadeForJVM.java b/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/AnalyzerFacadeForJVM.java index b3ea52401c4..5419632b5cc 100644 --- a/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/AnalyzerFacadeForJVM.java +++ b/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/AnalyzerFacadeForJVM.java @@ -29,6 +29,7 @@ import com.intellij.psi.util.CachedValuesManager; import com.intellij.psi.util.PsiModificationTracker; import com.intellij.util.Function; import org.jetbrains.annotations.NotNull; +import org.jetbrains.jet.analyzer.AnalyzeExhaust; import org.jetbrains.jet.di.InjectorForTopDownAnalyzerForJvm; import org.jetbrains.jet.lang.cfg.pseudocode.JetControlFlowDataTraceFactory; import org.jetbrains.jet.lang.descriptors.ModuleDescriptor; @@ -71,36 +72,38 @@ public class AnalyzerFacadeForJVM { * @param declarationProvider * @return */ - public static AnalyzeExhaust analyzeFileWithCache(@NotNull final JetFile file, @NotNull final Function> declarationProvider) { + public static AnalyzeExhaust analyzeFileWithCache(@NotNull final JetFile file, + @NotNull final Function> declarationProvider) { // Need lock for getValue(), because parallel threads can start evaluation of compute() simultaneously synchronized (lock) { CachedValue bindingContextCachedValue = file.getUserData(BINDING_CONTEXT); if (bindingContextCachedValue == null) { - bindingContextCachedValue = CachedValuesManager.getManager(file.getProject()).createCachedValue(new CachedValueProvider() { - @Override - public Result compute() { - try { - AnalyzeExhaust bindingContext = analyzeFilesWithJavaIntegration( + bindingContextCachedValue = + CachedValuesManager.getManager(file.getProject()).createCachedValue(new CachedValueProvider() { + @Override + public Result compute() { + try { + AnalyzeExhaust bindingContext = analyzeFilesWithJavaIntegration( file.getProject(), declarationProvider.fun(file), Predicates.equalTo(file), JetControlFlowDataTraceFactory.EMPTY, CompilerSpecialMode.REGULAR); - return new Result(bindingContext, PsiModificationTracker.MODIFICATION_COUNT); + return new Result(bindingContext, PsiModificationTracker.MODIFICATION_COUNT); + } + catch (ProcessCanceledException e) { + throw e; + } + catch (Throwable e) { + DiagnosticUtils.throwIfRunningOnServer(e); + LOG.error(e); + BindingTraceContext bindingTraceContext = new BindingTraceContext(); + bindingTraceContext.report(Errors.EXCEPTION_WHILE_ANALYZING.on(file, e)); + AnalyzeExhaust analyzeExhaust = new AnalyzeExhaust(bindingTraceContext.getBindingContext(), null); + return new Result(analyzeExhaust, PsiModificationTracker.MODIFICATION_COUNT); + } } - catch (ProcessCanceledException e) { - throw e; - } - catch (Throwable e) { - DiagnosticUtils.throwIfRunningOnServer(e); - LOG.error(e); - BindingTraceContext bindingTraceContext = new BindingTraceContext(); - bindingTraceContext.report(Errors.EXCEPTION_WHILE_ANALYZING.on(file, e)); - AnalyzeExhaust analyzeExhaust = new AnalyzeExhaust(bindingTraceContext.getBindingContext(), null); - return new Result(analyzeExhaust, PsiModificationTracker.MODIFICATION_COUNT); - } - } - }, false); + }, false); file.putUserData(BINDING_CONTEXT, bindingContextCachedValue); } return bindingContextCachedValue.getValue(); @@ -111,35 +114,36 @@ public class AnalyzerFacadeForJVM { * Analyze project with string cache for the whole project. All given files will be analyzed only for descriptors. */ public static AnalyzeExhaust analyzeProjectWithCache(@NotNull final Project project, - @NotNull final Collection files) { + @NotNull final Collection files) { // Need lock for getValue(), because parallel threads can start evaluation of compute() simultaneously synchronized (lock) { CachedValue bindingContextCachedValue = project.getUserData(BINDING_CONTEXT); if (bindingContextCachedValue == null) { - bindingContextCachedValue = CachedValuesManager.getManager(project).createCachedValue(new CachedValueProvider() { - @Override - public Result compute() { - try { - AnalyzeExhaust analyzeExhaust = analyzeFilesWithJavaIntegration( + bindingContextCachedValue = + CachedValuesManager.getManager(project).createCachedValue(new CachedValueProvider() { + @Override + public Result compute() { + try { + AnalyzeExhaust analyzeExhaust = analyzeFilesWithJavaIntegration( project, files, Predicates.alwaysFalse(), JetControlFlowDataTraceFactory.EMPTY, CompilerSpecialMode.REGULAR); - return new Result(analyzeExhaust, PsiModificationTracker.MODIFICATION_COUNT); + return new Result(analyzeExhaust, PsiModificationTracker.MODIFICATION_COUNT); + } + catch (ProcessCanceledException e) { + throw e; + } + catch (Throwable e) { + DiagnosticUtils.throwIfRunningOnServer(e); + LOG.error(e); + BindingTraceContext bindingTraceContext = new BindingTraceContext(); + AnalyzeExhaust analyzeExhaust = new AnalyzeExhaust(bindingTraceContext.getBindingContext(), null); + return new Result(analyzeExhaust, PsiModificationTracker.MODIFICATION_COUNT); + } } - catch (ProcessCanceledException e) { - throw e; - } - catch (Throwable e) { - DiagnosticUtils.throwIfRunningOnServer(e); - LOG.error(e); - BindingTraceContext bindingTraceContext = new BindingTraceContext(); - AnalyzeExhaust analyzeExhaust = new AnalyzeExhaust(bindingTraceContext.getBindingContext(), null); - return new Result(analyzeExhaust, PsiModificationTracker.MODIFICATION_COUNT); - } - } - }, false); + }, false); project.putUserData(BINDING_CONTEXT, bindingContextCachedValue); } return bindingContextCachedValue.getValue(); @@ -147,7 +151,7 @@ public class AnalyzerFacadeForJVM { } public static AnalyzeExhaust analyzeOneFileWithJavaIntegrationAndCheckForErrors( - JetFile file, JetControlFlowDataTraceFactory flowDataTraceFactory) { + JetFile file, JetControlFlowDataTraceFactory flowDataTraceFactory) { AnalyzingUtils.checkForSyntacticErrors(file); AnalyzeExhaust analyzeExhaust = analyzeOneFileWithJavaIntegration(file, flowDataTraceFactory); @@ -159,25 +163,25 @@ public class AnalyzerFacadeForJVM { public static AnalyzeExhaust analyzeOneFileWithJavaIntegration(JetFile file, JetControlFlowDataTraceFactory flowDataTraceFactory) { return analyzeFilesWithJavaIntegration(file.getProject(), Collections.singleton(file), - Predicates.alwaysTrue(), flowDataTraceFactory, CompilerSpecialMode.REGULAR); + Predicates.alwaysTrue(), flowDataTraceFactory, CompilerSpecialMode.REGULAR); } public static AnalyzeExhaust analyzeFilesWithJavaIntegration( - Project project, Collection files, Predicate filesToAnalyzeCompletely, - JetControlFlowDataTraceFactory flowDataTraceFactory, - CompilerSpecialMode compilerSpecialMode) { + Project project, Collection files, Predicate filesToAnalyzeCompletely, + JetControlFlowDataTraceFactory flowDataTraceFactory, + CompilerSpecialMode compilerSpecialMode) { BindingTraceContext bindingTraceContext = new BindingTraceContext(); final ModuleDescriptor owner = new ModuleDescriptor(""); TopDownAnalysisParameters topDownAnalysisParameters = new TopDownAnalysisParameters( - filesToAnalyzeCompletely, false, false); + filesToAnalyzeCompletely, false, false); InjectorForTopDownAnalyzerForJvm injector = new InjectorForTopDownAnalyzerForJvm( - project, topDownAnalysisParameters, - new ObservableBindingTrace(bindingTraceContext), owner, flowDataTraceFactory, - compilerSpecialMode); + project, topDownAnalysisParameters, + new ObservableBindingTrace(bindingTraceContext), owner, flowDataTraceFactory, + compilerSpecialMode); injector.getTopDownAnalyzer().analyzeFiles(files); @@ -190,6 +194,6 @@ public class AnalyzerFacadeForJVM { Project project = files.iterator().next().getProject(); return analyzeFilesWithJavaIntegration(project, files, Predicates.alwaysFalse(), - JetControlFlowDataTraceFactory.EMPTY, CompilerSpecialMode.REGULAR); + JetControlFlowDataTraceFactory.EMPTY, CompilerSpecialMode.REGULAR); } } diff --git a/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/AnalyzeExhaust.java b/compiler/frontend/src/org/jetbrains/jet/analyzer/AnalyzeExhaust.java similarity index 93% rename from compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/AnalyzeExhaust.java rename to compiler/frontend/src/org/jetbrains/jet/analyzer/AnalyzeExhaust.java index aed2724895c..3a2a9af1ef9 100644 --- a/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/AnalyzeExhaust.java +++ b/compiler/frontend/src/org/jetbrains/jet/analyzer/AnalyzeExhaust.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.jetbrains.jet.lang.resolve.java; +package org.jetbrains.jet.analyzer; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -35,7 +35,8 @@ public class AnalyzeExhaust { this.standardLibrary = standardLibrary; } - @NotNull public BindingContext getBindingContext() { + @NotNull + public BindingContext getBindingContext() { return bindingContext; } diff --git a/compiler/jet.as.java.psi/src/org/jetbrains/jet/asJava/JetLightClass.java b/compiler/jet.as.java.psi/src/org/jetbrains/jet/asJava/JetLightClass.java index ed3b3ed3888..9d7a7492f3d 100644 --- a/compiler/jet.as.java.psi/src/org/jetbrains/jet/asJava/JetLightClass.java +++ b/compiler/jet.as.java.psi/src/org/jetbrains/jet/asJava/JetLightClass.java @@ -41,6 +41,7 @@ import com.intellij.psi.util.CachedValuesManager; import com.intellij.psi.util.PsiModificationTracker; import com.intellij.util.containers.Stack; import org.jetbrains.annotations.NotNull; +import org.jetbrains.jet.analyzer.AnalyzeExhaust; import org.jetbrains.jet.codegen.ClassBuilder; import org.jetbrains.jet.codegen.ClassBuilderFactory; import org.jetbrains.jet.codegen.CompilationErrorHandler; @@ -48,7 +49,6 @@ import org.jetbrains.jet.codegen.GenerationState; import org.jetbrains.jet.lang.psi.JetFile; import org.jetbrains.jet.lang.psi.JetPsiUtil; import org.jetbrains.jet.lang.resolve.FqName; -import org.jetbrains.jet.lang.resolve.java.AnalyzeExhaust; import org.jetbrains.jet.lang.resolve.java.AnalyzerFacadeForJVM; import org.jetbrains.jet.lang.resolve.java.JetFilesProvider; import org.jetbrains.jet.lang.resolve.java.JetJavaMirrorMarker; @@ -100,8 +100,8 @@ public class JetLightClass extends AbstractLightClass implements JetJavaMirrorMa } private static PsiClass findClass(FqName fqn, StubElement stub) { - if (stub instanceof PsiClassStub && Comparing.equal(fqn.getFqName(), ((PsiClassStub) stub).getQualifiedName())) { - return (PsiClass) stub.getPsi(); + if (stub instanceof PsiClassStub && Comparing.equal(fqn.getFqName(), ((PsiClassStub)stub).getQualifiedName())) { + return (PsiClass)stub.getPsi(); } for (StubElement child : stub.getChildrenStubs()) { @@ -128,14 +128,14 @@ public class JetLightClass extends AbstractLightClass implements JetJavaMirrorMa }, false); file.putUserData(JAVA_API_STUB, answer); } - + return answer.getValue(); } - + private PsiJavaFileStub calcStub() { final PsiJavaFileStubImpl answer = new PsiJavaFileStubImpl(JetPsiUtil.getFQName(file).getFqName(), true); final Project project = getProject(); - + final Stack stubStack = new Stack(); final ClassBuilderFactory builderFactory = new ClassBuilderFactory() { @@ -168,13 +168,14 @@ public class JetLightClass extends AbstractLightClass implements JetJavaMirrorMa stubStack.push(answer); answer.setPsiFactory(new ClsWrapperStubPsiFactory()); - final ClsFileImpl fakeFile = new ClsFileImpl((PsiManagerImpl) manager, new ClassFileViewProvider(manager, file.getVirtualFile())) { - @NotNull - @Override - public PsiClassHolderFileStub getStub() { - return answer; - } - }; + final ClsFileImpl fakeFile = + new ClsFileImpl((PsiManagerImpl)manager, new ClassFileViewProvider(manager, file.getVirtualFile())) { + @NotNull + @Override + public PsiClassHolderFileStub getStub() { + return answer; + } + }; fakeFile.setPhysical(false); answer.setPsi(fakeFile); @@ -205,7 +206,7 @@ public class JetLightClass extends AbstractLightClass implements JetJavaMirrorMa @Override public boolean isEquivalentTo(PsiElement another) { - return another instanceof PsiClass && Comparing.equal(((PsiClass) another).getQualifiedName(), getQualifiedName()); + return another instanceof PsiClass && Comparing.equal(((PsiClass)another).getQualifiedName(), getQualifiedName()); } @Override @@ -217,7 +218,8 @@ public class JetLightClass extends AbstractLightClass implements JetJavaMirrorMa public String toString() { try { return JetLightClass.class.getSimpleName() + ":" + getQualifiedName(); - } catch (Throwable e) { + } + catch (Throwable e) { return JetLightClass.class.getSimpleName() + ":" + e.toString(); } } diff --git a/compiler/tests/org/jetbrains/jet/JetTestUtils.java b/compiler/tests/org/jetbrains/jet/JetTestUtils.java index b4a9f37face..95f2aa504ad 100644 --- a/compiler/tests/org/jetbrains/jet/JetTestUtils.java +++ b/compiler/tests/org/jetbrains/jet/JetTestUtils.java @@ -22,6 +22,7 @@ import com.intellij.openapi.util.ShutDownTracker; import com.intellij.openapi.util.io.FileUtil; import junit.framework.TestCase; import org.jetbrains.annotations.NotNull; +import org.jetbrains.jet.analyzer.AnalyzeExhaust; import org.jetbrains.jet.compiler.JetCoreEnvironment; import org.jetbrains.jet.lang.cfg.pseudocode.JetControlFlowDataTraceFactory; import org.jetbrains.jet.lang.diagnostics.Diagnostic; @@ -30,7 +31,6 @@ import org.jetbrains.jet.lang.diagnostics.UnresolvedReferenceDiagnostic; import org.jetbrains.jet.lang.psi.JetFile; import org.jetbrains.jet.lang.resolve.BindingContext; import org.jetbrains.jet.lang.resolve.BindingTrace; -import org.jetbrains.jet.lang.resolve.java.AnalyzeExhaust; import org.jetbrains.jet.lang.resolve.java.AnalyzerFacadeForJVM; import org.jetbrains.jet.util.slicedmap.ReadOnlySlice; import org.jetbrains.jet.util.slicedmap.SlicedMap; @@ -86,7 +86,7 @@ public class JetTestUtils { @Override public V get(ReadOnlySlice slice, K key) { - if (slice == BindingContext.PROCESSED) return (V) Boolean.FALSE; + if (slice == BindingContext.PROCESSED) return (V)Boolean.FALSE; return SlicedMap.DO_NOTHING.get(slice, key); } @@ -100,61 +100,61 @@ public class JetTestUtils { @Override public void report(@NotNull Diagnostic diagnostic) { if (diagnostic instanceof UnresolvedReferenceDiagnostic) { - UnresolvedReferenceDiagnostic unresolvedReferenceDiagnostic = (UnresolvedReferenceDiagnostic) diagnostic; + UnresolvedReferenceDiagnostic unresolvedReferenceDiagnostic = (UnresolvedReferenceDiagnostic)diagnostic; throw new IllegalStateException("Unresolved: " + unresolvedReferenceDiagnostic.getPsiElement().getText()); } } }; public static BindingTrace DUMMY_EXCEPTION_ON_ERROR_TRACE = new BindingTrace() { - @Override - public BindingContext getBindingContext() { - return new BindingContext() { - @Override - public Collection getDiagnostics() { - throw new UnsupportedOperationException(); - } + @Override + public BindingContext getBindingContext() { + return new BindingContext() { + @Override + public Collection getDiagnostics() { + throw new UnsupportedOperationException(); + } - @Override - public V get(ReadOnlySlice slice, K key) { - return DUMMY_EXCEPTION_ON_ERROR_TRACE.get(slice, key); - } + @Override + public V get(ReadOnlySlice slice, K key) { + return DUMMY_EXCEPTION_ON_ERROR_TRACE.get(slice, key); + } - @NotNull - @Override - public Collection getKeys(WritableSlice slice) { - return DUMMY_EXCEPTION_ON_ERROR_TRACE.getKeys(slice); - } - }; - } - - @Override - public void record(WritableSlice slice, K key, V value) { - } - - @Override - public void record(WritableSlice slice, K key) { - } - - @Override - public V get(ReadOnlySlice slice, K key) { - return null; - } - - @NotNull - @Override - public Collection getKeys(WritableSlice slice) { - assert slice.isCollective(); - return Collections.emptySet(); - } - - @Override - public void report(@NotNull Diagnostic diagnostic) { - if (diagnostic.getSeverity() == Severity.ERROR) { - throw new IllegalStateException(diagnostic.getMessage()); - } + @NotNull + @Override + public Collection getKeys(WritableSlice slice) { + return DUMMY_EXCEPTION_ON_ERROR_TRACE.getKeys(slice); } }; + } + + @Override + public void record(WritableSlice slice, K key, V value) { + } + + @Override + public void record(WritableSlice slice, K key) { + } + + @Override + public V get(ReadOnlySlice slice, K key) { + return null; + } + + @NotNull + @Override + public Collection getKeys(WritableSlice slice) { + assert slice.isCollective(); + return Collections.emptySet(); + } + + @Override + public void report(@NotNull Diagnostic diagnostic) { + if (diagnostic.getSeverity() == Severity.ERROR) { + throw new IllegalStateException(diagnostic.getMessage()); + } + } + }; public static AnalyzeExhaust analyzeFile(@NotNull JetFile namespace, @NotNull JetControlFlowDataTraceFactory flowDataTraceFactory) { return AnalyzerFacadeForJVM.analyzeOneFileWithJavaIntegration(namespace, flowDataTraceFactory); @@ -202,24 +202,25 @@ public class JetTestUtils { public static void deleteOnShutdown(File file) { if (filesToDelete.isEmpty()) { ShutDownTracker.getInstance().registerShutdownTask(new Runnable() { - @Override - public void run() { + @Override + public void run() { ShutDownTracker.invokeAndWait(true, true, new Runnable() { - @Override - public void run() { - for (File victim : filesToDelete) { - FileUtil.delete(victim); - } - } + @Override + public void run() { + for (File victim : filesToDelete) { + FileUtil.delete(victim); + } + } }); - } - }); + } + }); } filesToDelete.add(file); } public static final Pattern FILE_PATTERN = Pattern.compile("//\\s*FILE:\\s*(.*)$", Pattern.MULTILINE); + public interface TestFileFactory { F create(String fileName, String text); } @@ -254,7 +255,10 @@ public class JetTestUtils { if (!nextFileExists) break; } - assert processedChars == expectedText.length() : "Characters skipped from " + processedChars + " to " + (expectedText.length() - 1); + assert processedChars == expectedText.length() : "Characters skipped from " + + processedChars + + " to " + + (expectedText.length() - 1); } return testFileFiles; } diff --git a/compiler/tests/org/jetbrains/jet/codegen/CodegenTestCase.java b/compiler/tests/org/jetbrains/jet/codegen/CodegenTestCase.java index ed18d54693e..d82137e2a2f 100644 --- a/compiler/tests/org/jetbrains/jet/codegen/CodegenTestCase.java +++ b/compiler/tests/org/jetbrains/jet/codegen/CodegenTestCase.java @@ -19,11 +19,10 @@ package org.jetbrains.jet.codegen; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.jet.JetLiteFixture; +import org.jetbrains.jet.analyzer.AnalyzeExhaust; import org.jetbrains.jet.lang.cfg.pseudocode.JetControlFlowDataTraceFactory; import org.jetbrains.jet.lang.psi.JetFile; import org.jetbrains.jet.lang.psi.JetPsiUtil; -import org.jetbrains.jet.lang.resolve.AnalyzingUtils; -import org.jetbrains.jet.lang.resolve.java.AnalyzeExhaust; import org.jetbrains.jet.lang.resolve.java.AnalyzerFacadeForJVM; import org.jetbrains.jet.parsing.JetParsingTest; @@ -38,12 +37,13 @@ import java.util.Collections; */ public abstract class CodegenTestCase extends JetLiteFixture { - protected static void assertThrows(Method foo, Class exceptionClass, Object instance, Object... args) throws IllegalAccessException { + protected static void assertThrows(Method foo, Class exceptionClass, Object instance, Object... args) + throws IllegalAccessException { boolean caught = false; try { foo.invoke(instance, args); } - catch(InvocationTargetException ex) { + catch (InvocationTargetException ex) { caught = exceptionClass.isInstance(ex.getTargetException()); } assertTrue(caught); @@ -61,16 +61,17 @@ public abstract class CodegenTestCase extends JetLiteFixture { } protected void loadText(final String text) { - myFile = (JetFile) createFile("a.jet", text); + myFile = (JetFile)createFile("a.jet", text); } @Override protected String loadFile(final String name) { try { final String content = doLoadFile(JetParsingTest.getTestDataDir() + "/codegen/", name); - myFile = (JetFile) createFile(name, content); + myFile = (JetFile)createFile(name, content); return content; - } catch (IOException e) { + } + catch (IOException e) { throw new RuntimeException(e); } } @@ -88,10 +89,12 @@ public abstract class CodegenTestCase extends JetLiteFixture { String actual; try { actual = blackBox(); - } catch (NoClassDefFoundError e) { + } + catch (NoClassDefFoundError e) { System.out.println(generateToText()); throw e; - } catch (Throwable e) { + } + catch (Throwable e) { System.out.println(generateToText()); throw new RuntimeException(e); } @@ -109,9 +112,10 @@ public abstract class CodegenTestCase extends JetLiteFixture { String fqName = NamespaceCodegen.getJVMClassName(JetPsiUtil.getFQName(myFile), true).replace("/", "."); Class namespaceClass = loader.loadClass(fqName); Method method = namespaceClass.getMethod("box"); - return (String) method.invoke(null); - } finally { - loader.dispose(); + return (String)method.invoke(null); + } + finally { + loader.dispose(); } } @@ -124,7 +128,8 @@ public abstract class CodegenTestCase extends JetLiteFixture { } private GenerationState generateCommon(ClassBuilderFactory classBuilderFactory) { - final AnalyzeExhaust analyzeExhaust = AnalyzerFacadeForJVM.analyzeOneFileWithJavaIntegrationAndCheckForErrors(myFile, JetControlFlowDataTraceFactory.EMPTY); + final AnalyzeExhaust analyzeExhaust = + AnalyzerFacadeForJVM.analyzeOneFileWithJavaIntegrationAndCheckForErrors(myFile, JetControlFlowDataTraceFactory.EMPTY); GenerationState state = new GenerationState(getProject(), classBuilderFactory, analyzeExhaust, Collections.singletonList(myFile)); state.compileCorrectFiles(CompilationErrorHandler.THROW_EXCEPTION); return state; @@ -144,9 +149,11 @@ public abstract class CodegenTestCase extends JetLiteFixture { String fqName = NamespaceCodegen.getJVMClassName(JetPsiUtil.getFQName(myFile), true).replace("/", "."); try { return createClassLoader(state).loadClass(fqName); - } catch (ClassNotFoundException e) { + } + catch (ClassNotFoundException e) { e.printStackTrace(); - } catch (MalformedURLException e) { + } + catch (MalformedURLException e) { e.printStackTrace(); } return null; @@ -155,8 +162,10 @@ public abstract class CodegenTestCase extends JetLiteFixture { protected Class loadClass(String fqName, @NotNull ClassFileFactory state) { try { return createClassLoader(state).loadClass(fqName); - } catch (ClassNotFoundException e) { - } catch (MalformedURLException e) { + } + catch (ClassNotFoundException e) { + } + catch (MalformedURLException e) { } fail("No classfile was generated for: " + fqName); @@ -169,7 +178,8 @@ public abstract class CodegenTestCase extends JetLiteFixture { ClassBuilderFactory classBuilderFactory = ClassBuilderFactories.binaries(false); return generateCommon(classBuilderFactory).getFactory(); - } catch (RuntimeException e) { + } + catch (RuntimeException e) { System.out.println(generateToText()); throw e; } @@ -190,10 +200,12 @@ public abstract class CodegenTestCase extends JetLiteFixture { r = method; } - if (r == null) + if (r == null) { throw new AssertionError(); + } return r; - } catch (Error e) { + } + catch (Error e) { System.out.println(generateToText()); throw e; } @@ -221,11 +233,11 @@ public abstract class CodegenTestCase extends JetLiteFixture { protected static void assertIsCurrentTime(long returnValue) { long currentTime = System.currentTimeMillis(); long diff = Math.abs(returnValue - currentTime); - assertTrue("Difference with current time: " + diff + " (this test is a bad one: it may fail even if the generated code is correct)", diff <= 1L); + assertTrue("Difference with current time: " + diff + " (this test is a bad one: it may fail even if the generated code is correct)", + diff <= 1L); } protected Class loadImplementationClass(@NotNull ClassFileFactory codegens, final String name) { return loadClass(name, codegens); } - } diff --git a/compiler/tests/org/jetbrains/jet/resolve/ExpectedResolveData.java b/compiler/tests/org/jetbrains/jet/resolve/ExpectedResolveData.java index d1653ed6745..9a4acee5571 100644 --- a/compiler/tests/org/jetbrains/jet/resolve/ExpectedResolveData.java +++ b/compiler/tests/org/jetbrains/jet/resolve/ExpectedResolveData.java @@ -23,6 +23,7 @@ import com.intellij.openapi.project.Project; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.util.PsiTreeUtil; +import org.jetbrains.jet.analyzer.AnalyzeExhaust; import org.jetbrains.jet.lang.cfg.pseudocode.JetControlFlowDataTraceFactory; import org.jetbrains.jet.lang.descriptors.*; import org.jetbrains.jet.lang.diagnostics.Diagnostic; @@ -31,13 +32,12 @@ import org.jetbrains.jet.lang.diagnostics.UnresolvedReferenceDiagnostic; import org.jetbrains.jet.lang.psi.*; import org.jetbrains.jet.lang.resolve.BindingContext; import org.jetbrains.jet.lang.resolve.BindingContextUtils; -import org.jetbrains.jet.lang.resolve.java.AnalyzeExhaust; import org.jetbrains.jet.lang.resolve.java.AnalyzerFacadeForJVM; import org.jetbrains.jet.lang.resolve.java.CompilerSpecialMode; import org.jetbrains.jet.lang.types.ErrorUtils; -import org.jetbrains.jet.lang.types.lang.JetStandardLibrary; import org.jetbrains.jet.lang.types.JetType; import org.jetbrains.jet.lang.types.TypeConstructor; +import org.jetbrains.jet.lang.types.lang.JetStandardLibrary; import java.util.List; import java.util.Map; @@ -139,11 +139,13 @@ public abstract class ExpectedResolveData { JetStandardLibrary lib = JetStandardLibrary.getInstance(); AnalyzeExhaust analyzeExhaust = AnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration(project, files, - Predicates.alwaysTrue(), JetControlFlowDataTraceFactory.EMPTY, CompilerSpecialMode.REGULAR); + Predicates.alwaysTrue(), + JetControlFlowDataTraceFactory.EMPTY, + CompilerSpecialMode.REGULAR); BindingContext bindingContext = analyzeExhaust.getBindingContext(); for (Diagnostic diagnostic : bindingContext.getDiagnostics()) { if (diagnostic instanceof UnresolvedReferenceDiagnostic) { - UnresolvedReferenceDiagnostic unresolvedReferenceDiagnostic = (UnresolvedReferenceDiagnostic) diagnostic; + UnresolvedReferenceDiagnostic unresolvedReferenceDiagnostic = (UnresolvedReferenceDiagnostic)diagnostic; unresolvedReferences.add(unresolvedReferenceDiagnostic.getPsiElement()); } } @@ -174,35 +176,35 @@ public abstract class ExpectedResolveData { JetReferenceExpression referenceExpression = PsiTreeUtil.getParentOfType(element, JetReferenceExpression.class); if ("!".equals(name)) { assertTrue( - "Must have been unresolved: " + - renderReferenceInContext(referenceExpression) + - " but was resolved to " + DescriptorRenderer.TEXT.render(bindingContext.get(REFERENCE_TARGET, referenceExpression)), - unresolvedReferences.contains(referenceExpression)); + "Must have been unresolved: " + + renderReferenceInContext(referenceExpression) + + " but was resolved to " + DescriptorRenderer.TEXT.render(bindingContext.get(REFERENCE_TARGET, referenceExpression)), + unresolvedReferences.contains(referenceExpression)); continue; } if ("!!".equals(name)) { assertTrue( - "Must have been resolved to multiple descriptors: " + - renderReferenceInContext(referenceExpression) + - " but was resolved to " + DescriptorRenderer.TEXT.render(bindingContext.get(REFERENCE_TARGET, referenceExpression)), - bindingContext.get(AMBIGUOUS_REFERENCE_TARGET, referenceExpression) != null); + "Must have been resolved to multiple descriptors: " + + renderReferenceInContext(referenceExpression) + + " but was resolved to " + DescriptorRenderer.TEXT.render(bindingContext.get(REFERENCE_TARGET, referenceExpression)), + bindingContext.get(AMBIGUOUS_REFERENCE_TARGET, referenceExpression) != null); continue; } else if ("!null".equals(name)) { assertTrue( - "Must have been resolved to null: " + - renderReferenceInContext(referenceExpression) + - " but was resolved to " + DescriptorRenderer.TEXT.render(bindingContext.get(REFERENCE_TARGET, referenceExpression)), - bindingContext.get(REFERENCE_TARGET, referenceExpression) == null + "Must have been resolved to null: " + + renderReferenceInContext(referenceExpression) + + " but was resolved to " + DescriptorRenderer.TEXT.render(bindingContext.get(REFERENCE_TARGET, referenceExpression)), + bindingContext.get(REFERENCE_TARGET, referenceExpression) == null ); continue; } else if ("!error".equals(name)) { assertTrue( - "Must have been resolved to error: " + - renderReferenceInContext(referenceExpression) + - " but was resolved to " + DescriptorRenderer.TEXT.render(bindingContext.get(REFERENCE_TARGET, referenceExpression)), - ErrorUtils.isError(bindingContext.get(REFERENCE_TARGET, referenceExpression)) + "Must have been resolved to error: " + + renderReferenceInContext(referenceExpression) + + " but was resolved to " + DescriptorRenderer.TEXT.render(bindingContext.get(REFERENCE_TARGET, referenceExpression)), + ErrorUtils.isError(bindingContext.get(REFERENCE_TARGET, referenceExpression)) ); continue; } @@ -250,30 +252,30 @@ public abstract class ExpectedResolveData { if (expected instanceof JetParameter || actual instanceof JetParameter) { DeclarationDescriptor expectedDescriptor; if (name.startsWith("$")) { - expectedDescriptor = bindingContext.get(BindingContext.PRIMARY_CONSTRUCTOR_PARAMETER, (JetParameter) expected); + expectedDescriptor = bindingContext.get(BindingContext.PRIMARY_CONSTRUCTOR_PARAMETER, (JetParameter)expected); } else { expectedDescriptor = bindingContext.get(BindingContext.DECLARATION_TO_DESCRIPTOR, expected); if (expectedDescriptor == null) { - expectedDescriptor = bindingContext.get(BindingContext.CONSTRUCTOR, (JetElement) expected); + expectedDescriptor = bindingContext.get(BindingContext.CONSTRUCTOR, (JetElement)expected); } } DeclarationDescriptor actualDescriptor = bindingContext.get(REFERENCE_TARGET, reference); if (actualDescriptor instanceof VariableAsFunctionDescriptor) { - VariableAsFunctionDescriptor descriptor = (VariableAsFunctionDescriptor) actualDescriptor; + VariableAsFunctionDescriptor descriptor = (VariableAsFunctionDescriptor)actualDescriptor; actualDescriptor = descriptor.getVariableDescriptor(); } assertEquals( - "Reference `" + name + "`" + renderReferenceInContext(reference) + " is resolved into " + actualName + ".", - expectedDescriptor, actualDescriptor); + "Reference `" + name + "`" + renderReferenceInContext(reference) + " is resolved into " + actualName + ".", + expectedDescriptor, actualDescriptor); } else { assertEquals( - "Reference `" + name + "`" + renderReferenceInContext(reference) + " is resolved into " + actualName + ".", - expected, actual); + "Reference `" + name + "`" + renderReferenceInContext(reference) + " is resolved into " + actualName + ".", + expected, actual); } } @@ -305,7 +307,8 @@ public abstract class ExpectedResolveData { expectedTypeConstructor = classDescriptor.getTypeConstructor(); } else if (declaration instanceof JetTypeParameter) { - TypeParameterDescriptor typeParameterDescriptor = bindingContext.get(BindingContext.TYPE_PARAMETER, (JetTypeParameter) declaration); + TypeParameterDescriptor typeParameterDescriptor = + bindingContext.get(BindingContext.TYPE_PARAMETER, (JetTypeParameter)declaration); expectedTypeConstructor = typeParameterDescriptor.getTypeConstructor(); } else { @@ -325,14 +328,13 @@ public abstract class ExpectedResolveData { PsiElement parent = statement.getParent(); if (!(parent instanceof JetExpression)) break; if (parent instanceof JetBlockExpression) break; - statement = (JetExpression) parent; + statement = (JetExpression)parent; } JetDeclaration declaration = PsiTreeUtil.getParentOfType(referenceExpression, JetDeclaration.class); - return referenceExpression.getText() + " at " + DiagnosticUtils.atLocation(referenceExpression) + - " in " + statement.getText() + (declaration == null ? "" : " in " + declaration.getText()); + " in " + statement.getText() + (declaration == null ? "" : " in " + declaration.getText()); } private static T getAncestorOfType(Class type, PsiElement element) { @@ -340,7 +342,7 @@ public abstract class ExpectedResolveData { element = element.getParent(); } @SuppressWarnings({"unchecked", "UnnecessaryLocalVariable"}) - T result = (T) element; + T result = (T)element; return result; } } diff --git a/compiler/tests/org/jetbrains/jet/types/JetDefaultModalityModifiersTest.java b/compiler/tests/org/jetbrains/jet/types/JetDefaultModalityModifiersTest.java index 3d8a6fe4d30..2cb035ae555 100644 --- a/compiler/tests/org/jetbrains/jet/types/JetDefaultModalityModifiersTest.java +++ b/compiler/tests/org/jetbrains/jet/types/JetDefaultModalityModifiersTest.java @@ -18,12 +18,12 @@ package org.jetbrains.jet.types; import org.jetbrains.jet.JetLiteFixture; import org.jetbrains.jet.JetTestUtils; +import org.jetbrains.jet.analyzer.AnalyzeExhaust; import org.jetbrains.jet.di.InjectorForTests; import org.jetbrains.jet.lang.descriptors.*; import org.jetbrains.jet.lang.psi.*; import org.jetbrains.jet.lang.resolve.BindingContext; import org.jetbrains.jet.lang.resolve.DescriptorResolver; -import org.jetbrains.jet.lang.resolve.java.AnalyzeExhaust; import org.jetbrains.jet.lang.resolve.java.AnalyzerFacadeForJVM; import org.jetbrains.jet.lang.resolve.scopes.JetScope; import org.jetbrains.jet.lang.resolve.scopes.RedeclarationHandler; @@ -45,7 +45,7 @@ public class JetDefaultModalityModifiersTest extends JetLiteFixture { tc.setUp(); } - public class JetDefaultModalityModifiersTestCase { + public class JetDefaultModalityModifiersTestCase { private ModuleDescriptor root = new ModuleDescriptor("test_root"); private DescriptorResolver descriptorResolver; private JetScope scope; @@ -62,11 +62,13 @@ public class JetDefaultModalityModifiersTest extends JetLiteFixture { List declarations = file.getDeclarations(); JetDeclaration aClass = declarations.get(0); assert aClass instanceof JetClass; - AnalyzeExhaust bindingContext = AnalyzerFacadeForJVM.analyzeFileWithCache(file, AnalyzerFacadeForJVM.SINGLE_DECLARATION_PROVIDER); - DeclarationDescriptor classDescriptor = bindingContext.getBindingContext().get(BindingContext.DECLARATION_TO_DESCRIPTOR, aClass); + AnalyzeExhaust bindingContext = + AnalyzerFacadeForJVM.analyzeFileWithCache(file, AnalyzerFacadeForJVM.SINGLE_DECLARATION_PROVIDER); + DeclarationDescriptor classDescriptor = + bindingContext.getBindingContext().get(BindingContext.DECLARATION_TO_DESCRIPTOR, aClass); WritableScopeImpl scope = new WritableScopeImpl(libraryScope, root, RedeclarationHandler.DO_NOTHING); assert classDescriptor instanceof ClassifierDescriptor; - scope.addClassifierDescriptor((ClassifierDescriptor) classDescriptor); + scope.addClassifierDescriptor((ClassifierDescriptor)classDescriptor); scope.changeLockLevel(WritableScope.LockLevel.READING); return scope; } @@ -90,8 +92,9 @@ public class JetDefaultModalityModifiersTest extends JetLiteFixture { MutableClassDescriptor classDescriptor = createClassDescriptor(kind, aClass); List declarations = aClass.getDeclarations(); - JetNamedFunction function = (JetNamedFunction) declarations.get(0); - SimpleFunctionDescriptor functionDescriptor = descriptorResolver.resolveFunctionDescriptor(classDescriptor, scope, function, JetTestUtils.DUMMY_TRACE); + JetNamedFunction function = (JetNamedFunction)declarations.get(0); + SimpleFunctionDescriptor functionDescriptor = + descriptorResolver.resolveFunctionDescriptor(classDescriptor, scope, function, JetTestUtils.DUMMY_TRACE); assertEquals(expectedFunctionModality, functionDescriptor.getModality()); } @@ -101,20 +104,25 @@ public class JetDefaultModalityModifiersTest extends JetLiteFixture { MutableClassDescriptor classDescriptor = createClassDescriptor(kind, aClass); List declarations = aClass.getDeclarations(); - JetProperty property = (JetProperty) declarations.get(0); - PropertyDescriptor propertyDescriptor = descriptorResolver.resolvePropertyDescriptor(classDescriptor, scope, property, JetTestUtils.DUMMY_TRACE); + JetProperty property = (JetProperty)declarations.get(0); + PropertyDescriptor propertyDescriptor = + descriptorResolver.resolvePropertyDescriptor(classDescriptor, scope, property, JetTestUtils.DUMMY_TRACE); assertEquals(expectedPropertyModality, propertyDescriptor.getModality()); } - private void testPropertyAccessorModality(String classWithPropertyWithAccessor, ClassKind kind, Modality expectedPropertyAccessorModality, boolean isGetter) { + private void testPropertyAccessorModality(String classWithPropertyWithAccessor, + ClassKind kind, + Modality expectedPropertyAccessorModality, + boolean isGetter) { JetClass aClass = JetPsiFactory.createClass(getProject(), classWithPropertyWithAccessor); MutableClassDescriptor classDescriptor = createClassDescriptor(kind, aClass); List declarations = aClass.getDeclarations(); - JetProperty property = (JetProperty) declarations.get(0); - PropertyDescriptor propertyDescriptor = descriptorResolver.resolvePropertyDescriptor(classDescriptor, scope, property, JetTestUtils.DUMMY_TRACE); + JetProperty property = (JetProperty)declarations.get(0); + PropertyDescriptor propertyDescriptor = + descriptorResolver.resolvePropertyDescriptor(classDescriptor, scope, property, JetTestUtils.DUMMY_TRACE); PropertyAccessorDescriptor propertyAccessor = isGetter ? propertyDescriptor.getGetter() : propertyDescriptor.getSetter(); @@ -382,13 +390,15 @@ public class JetDefaultModalityModifiersTest extends JetLiteFixture { tc.testPropertyAccessorModalityInClass("open class A : C { open override val a: Int = 0; open get }", Modality.OPEN); tc.testPropertyAccessorModalityInClass("open class A : C { open override val a: Int = 0; final get }", Modality.FINAL); tc.testPropertyAccessorModalityInClass("open class A : C { open override val a: Int = 0; override get() = 2 }", Modality.OPEN); - tc.testPropertyAccessorModalityInClass("open class A : C { open override val a: Int = 0; final override get() = 2 }", Modality.FINAL); + tc.testPropertyAccessorModalityInClass("open class A : C { open override val a: Int = 0; final override get() = 2 }", + Modality.FINAL); tc.testPropertyAccessorModalityInClass("open class A : C { final override val a: Int = 0 }", Modality.FINAL); tc.testPropertyAccessorModalityInClass("open class A : C { final override val a: Int = 0; get }", Modality.FINAL); tc.testPropertyAccessorModalityInClass("open class A : C { final override val a: Int = 0; final get }", Modality.FINAL); tc.testPropertyAccessorModalityInClass("open class A : C { final override val a: Int = 0; override get() = 2 }", Modality.OPEN); - tc.testPropertyAccessorModalityInClass("open class A : C { final override val a: Int = 0; final override get() = 2 }", Modality.FINAL); + tc.testPropertyAccessorModalityInClass("open class A : C { final override val a: Int = 0; final override get() = 2 }", + Modality.FINAL); tc.testPropertyAccessorModalityInClass("abstract class A : C { abstract override val a: Int }", Modality.ABSTRACT); tc.testPropertyAccessorModalityInClass("abstract class A : C { abstract override val a: Int get }", Modality.ABSTRACT); @@ -401,10 +411,12 @@ public class JetDefaultModalityModifiersTest extends JetLiteFixture { tc.testPropertyAccessorModalityInClass("abstract class A : C { open abstract override val a: Int }", Modality.ABSTRACT); tc.testPropertyAccessorModalityInClass("abstract class A : C { open abstract override val a: Int get }", Modality.ABSTRACT); tc.testPropertyAccessorModalityInClass("abstract class A : C { open abstract override val a: Int open get }", Modality.ABSTRACT); - tc.testPropertyAccessorModalityInClass("abstract class A : C { open abstract override val a: Int abstract get }", Modality.ABSTRACT); + tc.testPropertyAccessorModalityInClass("abstract class A : C { open abstract override val a: Int abstract get }", + Modality.ABSTRACT); tc.testPropertyAccessorModalityInClass("abstract class A : C { open override val a: Int override get() = 10 }", Modality.OPEN); tc.testPropertyAccessorModalityInClass("abstract class A : C { open override val a: Int open override get() = 10 }", Modality.OPEN); - tc.testPropertyAccessorModalityInClass("abstract class A : C { open override val a: Int final override get() = 10 }", Modality.FINAL); + tc.testPropertyAccessorModalityInClass("abstract class A : C { open override val a: Int final override get() = 10 }", + Modality.FINAL); tc.testPropertyAccessorModalityInTrait("trait A : C { override val a: Int }", Modality.ABSTRACT); tc.testPropertyAccessorModalityInTrait("trait A : C { override val a: Int get }", Modality.ABSTRACT); diff --git a/idea/src/org/jetbrains/jet/plugin/debugger/JetPositionManager.java b/idea/src/org/jetbrains/jet/plugin/debugger/JetPositionManager.java index c17df603b19..7b53f454aa2 100644 --- a/idea/src/org/jetbrains/jet/plugin/debugger/JetPositionManager.java +++ b/idea/src/org/jetbrains/jet/plugin/debugger/JetPositionManager.java @@ -34,13 +34,13 @@ import com.sun.jdi.ReferenceType; import com.sun.jdi.request.ClassPrepareRequest; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import org.jetbrains.jet.analyzer.AnalyzeExhaust; import org.jetbrains.jet.codegen.JetTypeMapper; import org.jetbrains.jet.codegen.NamespaceCodegen; import org.jetbrains.jet.di.InjectorForJetTypeMapper; import org.jetbrains.jet.lang.psi.JetClassOrObject; import org.jetbrains.jet.lang.psi.JetFile; import org.jetbrains.jet.lang.psi.JetPsiUtil; -import org.jetbrains.jet.lang.resolve.java.AnalyzeExhaust; import org.jetbrains.jet.plugin.project.WholeProjectAnalyzerFacade; import java.util.*; @@ -67,7 +67,8 @@ public class JetPositionManager implements PositionManager { int lineNumber; try { lineNumber = location.lineNumber() - 1; - } catch (InternalError e) { + } + catch (InternalError e) { lineNumber = -1; } @@ -86,8 +87,8 @@ public class JetPositionManager implements PositionManager { if (files.length == 1 && files[0] instanceof JetFile) { return files[0]; } - - } catch (AbsentInformationException e) { + } + catch (AbsentInformationException e) { throw new NoDataException(); } @@ -126,7 +127,7 @@ public class JetPositionManager implements PositionManager { ApplicationManager.getApplication().runReadAction(new Runnable() { @Override public void run() { - final JetFile file = (JetFile) sourcePosition.getFile(); + final JetFile file = (JetFile)sourcePosition.getFile(); JetTypeMapper typeMapper = prepareTypeMapper(file); JetClassOrObject jetClass = PsiTreeUtil.getParentOfType(sourcePosition.getElementAt(), JetClassOrObject.class); @@ -155,7 +156,7 @@ public class JetPositionManager implements PositionManager { } final AnalyzeExhaust analyzeExhaust = WholeProjectAnalyzerFacade.analyzeProjectWithCacheOnAFile(file); JetTypeMapper typeMapper = new InjectorForJetTypeMapper( - analyzeExhaust.getStandardLibrary(), analyzeExhaust.getBindingContext(), Collections.singletonList(file)).getJetTypeMapper(); + analyzeExhaust.getStandardLibrary(), analyzeExhaust.getBindingContext(), Collections.singletonList(file)).getJetTypeMapper(); myTypeMappers.put(file, typeMapper); return typeMapper; } @@ -167,15 +168,15 @@ public class JetPositionManager implements PositionManager { throw new NoDataException(); } try { - int line = position.getLine() + 1; - List locations = myDebugProcess.getVirtualMachineProxy().versionHigher("1.4") - ? type.locationsOfLine(DebugProcess.JAVA_STRATUM, null, line) - : type.locationsOfLine(line); - if (locations == null || locations.isEmpty()) throw new NoDataException(); - return locations; + int line = position.getLine() + 1; + List locations = myDebugProcess.getVirtualMachineProxy().versionHigher("1.4") + ? type.locationsOfLine(DebugProcess.JAVA_STRATUM, null, line) + : type.locationsOfLine(line); + if (locations == null || locations.isEmpty()) throw new NoDataException(); + return locations; } catch (AbsentInformationException e) { - throw new NoDataException(); + throw new NoDataException(); } } diff --git a/idea/src/org/jetbrains/jet/plugin/internal/codewindow/BytecodeToolwindow.java b/idea/src/org/jetbrains/jet/plugin/internal/codewindow/BytecodeToolwindow.java index 42a7f9cfadc..b7bfe2551a2 100644 --- a/idea/src/org/jetbrains/jet/plugin/internal/codewindow/BytecodeToolwindow.java +++ b/idea/src/org/jetbrains/jet/plugin/internal/codewindow/BytecodeToolwindow.java @@ -36,12 +36,12 @@ import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiManager; import com.intellij.util.Alarm; +import org.jetbrains.jet.analyzer.AnalyzeExhaust; import org.jetbrains.jet.codegen.ClassBuilderFactories; import org.jetbrains.jet.codegen.ClassFileFactory; import org.jetbrains.jet.codegen.CompilationErrorHandler; import org.jetbrains.jet.codegen.GenerationState; import org.jetbrains.jet.lang.psi.JetFile; -import org.jetbrains.jet.lang.resolve.java.AnalyzeExhaust; import org.jetbrains.jet.plugin.project.WholeProjectAnalyzerFacade; import javax.swing.*; @@ -69,7 +69,8 @@ public class BytecodeToolwindow extends JPanel implements Disposable { public BytecodeToolwindow(Project project) { super(new BorderLayout()); myProject = project; - myEditor = EditorFactory.getInstance().createEditor(EditorFactory.getInstance().createDocument(""), project, JavaFileType.INSTANCE, true); + myEditor = + EditorFactory.getInstance().createEditor(EditorFactory.getInstance().createDocument(""), project, JavaFileType.INSTANCE, true); add(myEditor.getComponent()); myUpdateAlarm = new Alarm(Alarm.ThreadToUse.SWING_THREAD, this); myUpdateAlarm.addRequest(new Runnable() { @@ -92,7 +93,7 @@ public class BytecodeToolwindow extends JPanel implements Disposable { setText(DEFAULT_TEXT); } else { - VirtualFile vFile = ((EditorEx) editor).getVirtualFile(); + VirtualFile vFile = ((EditorEx)editor).getVirtualFile(); if (vFile == null) { setText(DEFAULT_TEXT); return; @@ -104,17 +105,21 @@ public class BytecodeToolwindow extends JPanel implements Disposable { return; } - if (oldLocation == null || !Comparing.equal(oldLocation.editor, location.editor) || oldLocation.modificationStamp != location.modificationStamp) { - setText(generateToText((JetFile) psiFile)); + if (oldLocation == null || + !Comparing.equal(oldLocation.editor, location.editor) || + oldLocation.modificationStamp != location.modificationStamp) { + setText(generateToText((JetFile)psiFile)); } Document document = editor.getDocument(); int startLine = document.getLineNumber(location.startOffset); int endLine = document.getLineNumber(location.endOffset); - if (endLine > startLine && location.endOffset > 0 && document.getCharsSequence().charAt(location.endOffset - 1) == '\n') endLine--; + if (endLine > startLine && location.endOffset > 0 && document.getCharsSequence().charAt(location.endOffset - 1) == '\n') { + endLine--; + } Document byteCodeDocument = myEditor.getDocument(); - + Pair linesRange = mapLines(byteCodeDocument.getText(), startLine, endLine); int endSelectionLineIndex = Math.min(linesRange.second + 1, byteCodeDocument.getLineCount()); @@ -152,7 +157,7 @@ public class BytecodeToolwindow extends JPanel implements Disposable { break; } } - + for (String line : text.split("\n")) { line = line.trim(); @@ -163,7 +168,7 @@ public class BytecodeToolwindow extends JPanel implements Disposable { byteCodeStartLine = byteCodeLine; } - if (byteCodeStartLine > 0&& ktLineNum > endLine) { + if (byteCodeStartLine > 0 && ktLineNum > endLine) { byteCodeEndLine = byteCodeLine - 1; break; } @@ -179,14 +184,12 @@ public class BytecodeToolwindow extends JPanel implements Disposable { } - if (byteCodeStartLine == -1 || byteCodeEndLine == -1) { return new Pair(0, 0); } else { return new Pair(byteCodeStartLine, byteCodeEndLine); } - } private void setText(final String text) { @@ -269,7 +272,7 @@ public class BytecodeToolwindow extends JPanel implements Disposable { if (this == o) return true; if (!(o instanceof Location)) return false; - Location location = (Location) o; + Location location = (Location)o; if (endOffset != location.endOffset) return false; if (modificationStamp != location.modificationStamp) return false; @@ -282,10 +285,10 @@ public class BytecodeToolwindow extends JPanel implements Disposable { @Override public int hashCode() { int result = editor != null ? editor.hashCode() : 0; - result = 31 * result + (int) (modificationStamp ^ (modificationStamp >>> 32)); + result = 31 * result + (int)(modificationStamp ^ (modificationStamp >>> 32)); result = 31 * result + startOffset; result = 31 * result + endOffset; return result; } - } + } } diff --git a/idea/src/org/jetbrains/jet/plugin/project/WholeProjectAnalyzerFacade.java b/idea/src/org/jetbrains/jet/plugin/project/WholeProjectAnalyzerFacade.java index 1fb82439458..88d478585c1 100644 --- a/idea/src/org/jetbrains/jet/plugin/project/WholeProjectAnalyzerFacade.java +++ b/idea/src/org/jetbrains/jet/plugin/project/WholeProjectAnalyzerFacade.java @@ -19,8 +19,8 @@ package org.jetbrains.jet.plugin.project; import com.intellij.openapi.project.Project; import com.intellij.psi.search.GlobalSearchScope; import org.jetbrains.annotations.NotNull; +import org.jetbrains.jet.analyzer.AnalyzeExhaust; import org.jetbrains.jet.lang.psi.JetFile; -import org.jetbrains.jet.lang.resolve.java.AnalyzeExhaust; import org.jetbrains.jet.lang.resolve.java.AnalyzerFacadeForJVM; import org.jetbrains.jet.lang.resolve.java.JetFilesProvider; @@ -29,8 +29,11 @@ import org.jetbrains.jet.lang.resolve.java.JetFilesProvider; */ public final class WholeProjectAnalyzerFacade { - /** Forbid creating */ - private WholeProjectAnalyzerFacade() {} + /** + * Forbid creating + */ + private WholeProjectAnalyzerFacade() { + } @NotNull From 1ad12b29fa81f6008bf6a92e03198984657889e6 Mon Sep 17 00:00:00 2001 From: "Pavel V. Talanov" Date: Wed, 4 Apr 2012 17:20:27 +0400 Subject: [PATCH 03/12] Extract AnalyzerFacade interface. Extract AnalyzerFacadeWithCache decorator for AnalyzerFacade. --- .../resolve/java/AnalyzerFacadeForJVM.java | 126 +---- .../jet/analyzer/AnalyzerFacade.java | 38 ++ .../jet/analyzer/AnalyzerFacadeWithCache.java | 171 +++++++ .../JetDefaultModalityModifiersTest.java | 3 +- .../libraries/JetSourceNavigationHelper.java | 128 +++--- .../JetFunctionParameterInfoHandler.java | 144 +++--- .../quickfix/ChangeVariableMutabilityFix.java | 14 +- .../plugin/quickfix/ImportInsertHelper.java | 7 +- .../jet/plugin/quickfix/QuickFixUtil.java | 9 +- .../plugin/refactoring/JetNameSuggester.java | 104 +++-- .../refactoring/JetRefactoringUtil.java | 62 +-- .../JetIntroduceVariableHandler.java | 432 ++++++++++-------- 12 files changed, 745 insertions(+), 493 deletions(-) create mode 100644 compiler/frontend/src/org/jetbrains/jet/analyzer/AnalyzerFacade.java create mode 100644 compiler/frontend/src/org/jetbrains/jet/analyzer/AnalyzerFacadeWithCache.java diff --git a/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/AnalyzerFacadeForJVM.java b/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/AnalyzerFacadeForJVM.java index 5419632b5cc..53f2c2aac59 100644 --- a/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/AnalyzerFacadeForJVM.java +++ b/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/AnalyzerFacadeForJVM.java @@ -18,23 +18,16 @@ package org.jetbrains.jet.lang.resolve.java; import com.google.common.base.Predicate; import com.google.common.base.Predicates; -import com.intellij.openapi.diagnostic.Logger; -import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.project.Project; -import com.intellij.openapi.util.Key; import com.intellij.psi.PsiFile; -import com.intellij.psi.util.CachedValue; -import com.intellij.psi.util.CachedValueProvider; -import com.intellij.psi.util.CachedValuesManager; -import com.intellij.psi.util.PsiModificationTracker; import com.intellij.util.Function; import org.jetbrains.annotations.NotNull; import org.jetbrains.jet.analyzer.AnalyzeExhaust; +import org.jetbrains.jet.analyzer.AnalyzerFacade; +import org.jetbrains.jet.analyzer.AnalyzerFacadeWithCache; import org.jetbrains.jet.di.InjectorForTopDownAnalyzerForJvm; import org.jetbrains.jet.lang.cfg.pseudocode.JetControlFlowDataTraceFactory; import org.jetbrains.jet.lang.descriptors.ModuleDescriptor; -import org.jetbrains.jet.lang.diagnostics.DiagnosticUtils; -import org.jetbrains.jet.lang.diagnostics.Errors; import org.jetbrains.jet.lang.psi.JetFile; import org.jetbrains.jet.lang.resolve.AnalyzingUtils; import org.jetbrains.jet.lang.resolve.BindingTraceContext; @@ -48,106 +41,20 @@ import java.util.Collections; /** * @author abreslav */ -public class AnalyzerFacadeForJVM { +public enum AnalyzerFacadeForJVM implements AnalyzerFacade { - private static final Logger LOG = Logger.getInstance("org.jetbrains.jet.lang.resolve.java.AnalyzerFacadeForJVM"); - - public static final Function> SINGLE_DECLARATION_PROVIDER = new Function>() { - @Override - public Collection fun(JetFile file) { - return Collections.singleton(file); - } - }; - - private final static Key> BINDING_CONTEXT = Key.create("BINDING_CONTEXT"); - private static final Object lock = new Object(); + INSTANCE; private AnalyzerFacadeForJVM() { } - /** - * Analyze project with string cache for given file. Given file will be fully analyzed. - * - * @param file - * @param declarationProvider - * @return - */ - public static AnalyzeExhaust analyzeFileWithCache(@NotNull final JetFile file, - @NotNull final Function> declarationProvider) { - // Need lock for getValue(), because parallel threads can start evaluation of compute() simultaneously - synchronized (lock) { - CachedValue bindingContextCachedValue = file.getUserData(BINDING_CONTEXT); - if (bindingContextCachedValue == null) { - bindingContextCachedValue = - CachedValuesManager.getManager(file.getProject()).createCachedValue(new CachedValueProvider() { - @Override - public Result compute() { - try { - AnalyzeExhaust bindingContext = analyzeFilesWithJavaIntegration( - file.getProject(), - declarationProvider.fun(file), - Predicates.equalTo(file), - JetControlFlowDataTraceFactory.EMPTY, - CompilerSpecialMode.REGULAR); - return new Result(bindingContext, PsiModificationTracker.MODIFICATION_COUNT); - } - catch (ProcessCanceledException e) { - throw e; - } - catch (Throwable e) { - DiagnosticUtils.throwIfRunningOnServer(e); - LOG.error(e); - BindingTraceContext bindingTraceContext = new BindingTraceContext(); - bindingTraceContext.report(Errors.EXCEPTION_WHILE_ANALYZING.on(file, e)); - AnalyzeExhaust analyzeExhaust = new AnalyzeExhaust(bindingTraceContext.getBindingContext(), null); - return new Result(analyzeExhaust, PsiModificationTracker.MODIFICATION_COUNT); - } - } - }, false); - file.putUserData(BINDING_CONTEXT, bindingContextCachedValue); - } - return bindingContextCachedValue.getValue(); - } - } - - /** - * Analyze project with string cache for the whole project. All given files will be analyzed only for descriptors. - */ - public static AnalyzeExhaust analyzeProjectWithCache(@NotNull final Project project, - @NotNull final Collection files) { - // Need lock for getValue(), because parallel threads can start evaluation of compute() simultaneously - synchronized (lock) { - CachedValue bindingContextCachedValue = project.getUserData(BINDING_CONTEXT); - if (bindingContextCachedValue == null) { - bindingContextCachedValue = - CachedValuesManager.getManager(project).createCachedValue(new CachedValueProvider() { - @Override - public Result compute() { - try { - AnalyzeExhaust analyzeExhaust = analyzeFilesWithJavaIntegration( - project, - files, - Predicates.alwaysFalse(), - JetControlFlowDataTraceFactory.EMPTY, - CompilerSpecialMode.REGULAR); - return new Result(analyzeExhaust, PsiModificationTracker.MODIFICATION_COUNT); - } - catch (ProcessCanceledException e) { - throw e; - } - catch (Throwable e) { - DiagnosticUtils.throwIfRunningOnServer(e); - LOG.error(e); - BindingTraceContext bindingTraceContext = new BindingTraceContext(); - AnalyzeExhaust analyzeExhaust = new AnalyzeExhaust(bindingTraceContext.getBindingContext(), null); - return new Result(analyzeExhaust, PsiModificationTracker.MODIFICATION_COUNT); - } - } - }, false); - project.putUserData(BINDING_CONTEXT, bindingContextCachedValue); - } - return bindingContextCachedValue.getValue(); - } + @Override + @NotNull + public AnalyzeExhaust analyzeFiles(@NotNull Project project, + @NotNull Collection files, + @NotNull Predicate filesToAnalyzeCompletely, + @NotNull JetControlFlowDataTraceFactory flowDataTraceFactory) { + return analyzeFilesWithJavaIntegration(project, files, filesToAnalyzeCompletely, flowDataTraceFactory, CompilerSpecialMode.REGULAR); } public static AnalyzeExhaust analyzeOneFileWithJavaIntegrationAndCheckForErrors( @@ -196,4 +103,15 @@ public class AnalyzerFacadeForJVM { return analyzeFilesWithJavaIntegration(project, files, Predicates.alwaysFalse(), JetControlFlowDataTraceFactory.EMPTY, CompilerSpecialMode.REGULAR); } + + @NotNull + public static AnalyzeExhaust analyzeFileWithCache(@NotNull final JetFile file, + @NotNull final Function> declarationProvider) { + return AnalyzerFacadeWithCache.getInstance(INSTANCE).analyzeFileWithCache(file, declarationProvider); + } + + @NotNull + public static AnalyzeExhaust analyzeProjectWithCache(@NotNull final Project project, @NotNull final Collection files) { + return AnalyzerFacadeWithCache.getInstance(INSTANCE).analyzeProjectWithCache(project, files); + } } diff --git a/compiler/frontend/src/org/jetbrains/jet/analyzer/AnalyzerFacade.java b/compiler/frontend/src/org/jetbrains/jet/analyzer/AnalyzerFacade.java new file mode 100644 index 00000000000..7e31fee0773 --- /dev/null +++ b/compiler/frontend/src/org/jetbrains/jet/analyzer/AnalyzerFacade.java @@ -0,0 +1,38 @@ +/* + * Copyright 2010-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jetbrains.jet.analyzer; + +import com.google.common.base.Predicate; +import com.intellij.openapi.project.Project; +import com.intellij.psi.PsiFile; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.jet.lang.cfg.pseudocode.JetControlFlowDataTraceFactory; +import org.jetbrains.jet.lang.psi.JetFile; + +import java.util.Collection; + +/** + * @author Pavel Talanov + */ +public interface AnalyzerFacade { + + @NotNull + AnalyzeExhaust analyzeFiles(@NotNull Project project, + @NotNull Collection files, + @NotNull Predicate filesToAnalyzeCompletely, + @NotNull JetControlFlowDataTraceFactory flowDataTraceFactory); +} diff --git a/compiler/frontend/src/org/jetbrains/jet/analyzer/AnalyzerFacadeWithCache.java b/compiler/frontend/src/org/jetbrains/jet/analyzer/AnalyzerFacadeWithCache.java new file mode 100644 index 00000000000..aee6ea5e4c8 --- /dev/null +++ b/compiler/frontend/src/org/jetbrains/jet/analyzer/AnalyzerFacadeWithCache.java @@ -0,0 +1,171 @@ +/* + * Copyright 2010-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jetbrains.jet.analyzer; + +import com.google.common.base.Predicate; +import com.google.common.base.Predicates; +import com.intellij.openapi.diagnostic.Logger; +import com.intellij.openapi.progress.ProcessCanceledException; +import com.intellij.openapi.project.Project; +import com.intellij.openapi.util.Key; +import com.intellij.psi.PsiFile; +import com.intellij.psi.util.CachedValue; +import com.intellij.psi.util.CachedValueProvider; +import com.intellij.psi.util.CachedValuesManager; +import com.intellij.psi.util.PsiModificationTracker; +import com.intellij.util.Function; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.jet.lang.cfg.pseudocode.JetControlFlowDataTraceFactory; +import org.jetbrains.jet.lang.diagnostics.DiagnosticUtils; +import org.jetbrains.jet.lang.diagnostics.Errors; +import org.jetbrains.jet.lang.psi.JetFile; +import org.jetbrains.jet.lang.resolve.BindingTraceContext; + +import java.util.Collection; +import java.util.Collections; + +/** + * @author Pavel Talanov + */ +public class AnalyzerFacadeWithCache implements AnalyzerFacade { + + private static final Logger LOG = Logger.getInstance("org.jetbrains.jet.analyzer.AnalyzerFacadeWithCache"); + + private final static Key> ANALYZE_EXHAUST = Key.create("ANALYZE_EXHAUST"); + private static final Object lock = new Object(); + public static final Function> SINGLE_DECLARATION_PROVIDER = new Function>() { + @Override + public Collection fun(JetFile file) { + return Collections.singleton(file); + } + }; + + public static AnalyzerFacadeWithCache getInstance(@NotNull AnalyzerFacade facade) { + return new AnalyzerFacadeWithCache(facade); + } + + @NotNull + private final AnalyzerFacade facade; + + private AnalyzerFacadeWithCache(@NotNull AnalyzerFacade facade) { + this.facade = facade; + } + + /** + * Analyze project with string cache for given file. Given file will be fully analyzed. + * + * @param file + * @param declarationProvider + * @return + */ + @NotNull + public AnalyzeExhaust analyzeFileWithCache(@NotNull final JetFile file, + @NotNull final Function> declarationProvider) { + // Need lock for getValue(), because parallel threads can start evaluation of compute() simultaneously + synchronized (lock) { + CachedValue bindingContextCachedValue = file.getUserData(ANALYZE_EXHAUST); + if (bindingContextCachedValue == null) { + bindingContextCachedValue = + CachedValuesManager.getManager(file.getProject()).createCachedValue(new CachedValueProvider() { + @Override + public Result compute() { + try { + AnalyzeExhaust exhaust = facade.analyzeFiles(file.getProject(), + declarationProvider.fun(file), + Predicates.equalTo(file), + JetControlFlowDataTraceFactory.EMPTY); + return new Result(exhaust, PsiModificationTracker.MODIFICATION_COUNT); + } + catch (ProcessCanceledException e) { + throw e; + } + catch (Throwable e) { + handleError(e); + return emptyExhaustWithDiagnosticOnFile(e); + } + } + + @NotNull + private Result emptyExhaustWithDiagnosticOnFile(Throwable e) { + BindingTraceContext bindingTraceContext = new BindingTraceContext(); + bindingTraceContext.report(Errors.EXCEPTION_WHILE_ANALYZING.on(file, e)); + AnalyzeExhaust analyzeExhaust = new AnalyzeExhaust(bindingTraceContext.getBindingContext(), null); + return new Result(analyzeExhaust, PsiModificationTracker.MODIFICATION_COUNT); + } + }, false); + file.putUserData(ANALYZE_EXHAUST, bindingContextCachedValue); + } + return bindingContextCachedValue.getValue(); + } + } + + private static void handleError(@NotNull Throwable e) { + DiagnosticUtils.throwIfRunningOnServer(e); + LOG.error(e); + } + + /** + * Analyze project with string cache for the whole project. All given files will be analyzed only for descriptors. + */ + @NotNull + public AnalyzeExhaust analyzeProjectWithCache(@NotNull final Project project, @NotNull final Collection files) { + // Need lock for getValue(), because parallel threads can start evaluation of compute() simultaneously + synchronized (lock) { + CachedValue bindingContextCachedValue = project.getUserData(ANALYZE_EXHAUST); + if (bindingContextCachedValue == null) { + bindingContextCachedValue = + CachedValuesManager.getManager(project).createCachedValue(new CachedValueProvider() { + @Override + public Result compute() { + try { + AnalyzeExhaust analyzeExhaust = facade.analyzeFiles(project, + files, + Predicates.alwaysFalse(), + JetControlFlowDataTraceFactory.EMPTY); + return new Result(analyzeExhaust, PsiModificationTracker.MODIFICATION_COUNT); + } + catch (ProcessCanceledException e) { + throw e; + } + catch (Throwable e) { + handleError(e); + return emptyExhaust(); + } + } + + @NotNull + private Result emptyExhaust() { + BindingTraceContext bindingTraceContext = new BindingTraceContext(); + AnalyzeExhaust analyzeExhaust = new AnalyzeExhaust(bindingTraceContext.getBindingContext(), null); + return new Result(analyzeExhaust, PsiModificationTracker.MODIFICATION_COUNT); + } + }, false); + project.putUserData(ANALYZE_EXHAUST, bindingContextCachedValue); + } + return bindingContextCachedValue.getValue(); + } + } + + @NotNull + @Override + public AnalyzeExhaust analyzeFiles(@NotNull Project project, + @NotNull Collection files, + @NotNull Predicate filesToAnalyzeCompletely, + @NotNull JetControlFlowDataTraceFactory flowDataTraceFactory) { + return facade.analyzeFiles(project, files, filesToAnalyzeCompletely, flowDataTraceFactory); + } +} diff --git a/compiler/tests/org/jetbrains/jet/types/JetDefaultModalityModifiersTest.java b/compiler/tests/org/jetbrains/jet/types/JetDefaultModalityModifiersTest.java index 2cb035ae555..763e0dd1dc0 100644 --- a/compiler/tests/org/jetbrains/jet/types/JetDefaultModalityModifiersTest.java +++ b/compiler/tests/org/jetbrains/jet/types/JetDefaultModalityModifiersTest.java @@ -19,6 +19,7 @@ package org.jetbrains.jet.types; import org.jetbrains.jet.JetLiteFixture; import org.jetbrains.jet.JetTestUtils; import org.jetbrains.jet.analyzer.AnalyzeExhaust; +import org.jetbrains.jet.analyzer.AnalyzerFacadeWithCache; import org.jetbrains.jet.di.InjectorForTests; import org.jetbrains.jet.lang.descriptors.*; import org.jetbrains.jet.lang.psi.*; @@ -63,7 +64,7 @@ public class JetDefaultModalityModifiersTest extends JetLiteFixture { JetDeclaration aClass = declarations.get(0); assert aClass instanceof JetClass; AnalyzeExhaust bindingContext = - AnalyzerFacadeForJVM.analyzeFileWithCache(file, AnalyzerFacadeForJVM.SINGLE_DECLARATION_PROVIDER); + AnalyzerFacadeForJVM.analyzeFileWithCache(file, AnalyzerFacadeWithCache.SINGLE_DECLARATION_PROVIDER); DeclarationDescriptor classDescriptor = bindingContext.getBindingContext().get(BindingContext.DECLARATION_TO_DESCRIPTOR, aClass); WritableScopeImpl scope = new WritableScopeImpl(libraryScope, root, RedeclarationHandler.DO_NOTHING); diff --git a/idea/src/org/jetbrains/jet/plugin/libraries/JetSourceNavigationHelper.java b/idea/src/org/jetbrains/jet/plugin/libraries/JetSourceNavigationHelper.java index 5dcb490153e..8b8ee42afa7 100644 --- a/idea/src/org/jetbrains/jet/plugin/libraries/JetSourceNavigationHelper.java +++ b/idea/src/org/jetbrains/jet/plugin/libraries/JetSourceNavigationHelper.java @@ -32,6 +32,7 @@ import com.intellij.psi.util.PsiTreeUtil; import jet.Tuple2; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import org.jetbrains.jet.analyzer.AnalyzerFacadeWithCache; import org.jetbrains.jet.lang.descriptors.*; import org.jetbrains.jet.lang.psi.*; import org.jetbrains.jet.lang.resolve.BindingContext; @@ -57,18 +58,18 @@ public class JetSourceNavigationHelper { } @Nullable - private static Tuple2 - getBindingContextAndClassOrNamespaceDescriptor(@NotNull WritableSlice slice, - @NotNull JetDeclaration declaration, - @Nullable FqName fqName) { + private static Tuple2 + getBindingContextAndClassOrNamespaceDescriptor(@NotNull WritableSlice slice, + @NotNull JetDeclaration declaration, + @Nullable FqName fqName) { if (fqName == null || DumbService.isDumb(declaration.getProject())) { return null; } final List libraryFiles = findAllSourceFilesWhichContainIdentifier(declaration); for (JetFile libraryFile : libraryFiles) { BindingContext bindingContext = AnalyzerFacadeForJVM.analyzeFileWithCache(libraryFile, - AnalyzerFacadeForJVM.SINGLE_DECLARATION_PROVIDER) - .getBindingContext(); + AnalyzerFacadeWithCache.SINGLE_DECLARATION_PROVIDER) + .getBindingContext(); D descriptor = bindingContext.get(slice, fqName); if (descriptor != null) { return new Tuple2(bindingContext, descriptor); @@ -79,22 +80,25 @@ public class JetSourceNavigationHelper { @Nullable private static Tuple2 getBindingContextAndClassDescriptor(@NotNull JetClass decompiledClass) { - return getBindingContextAndClassOrNamespaceDescriptor(BindingContext.FQNAME_TO_CLASS_DESCRIPTOR, decompiledClass, JetPsiUtil.getFQName(decompiledClass)); + return getBindingContextAndClassOrNamespaceDescriptor(BindingContext.FQNAME_TO_CLASS_DESCRIPTOR, decompiledClass, + JetPsiUtil.getFQName(decompiledClass)); } @Nullable private static Tuple2 getBindingContextAndNamespaceDescriptor(@NotNull JetDeclaration declaration) { - JetFile file = (JetFile) declaration.getContainingFile(); - return getBindingContextAndClassOrNamespaceDescriptor(BindingContext.FQNAME_TO_NAMESPACE_DESCRIPTOR, declaration, JetPsiUtil.getFQName(file)); + JetFile file = (JetFile)declaration.getContainingFile(); + return getBindingContextAndClassOrNamespaceDescriptor(BindingContext.FQNAME_TO_NAMESPACE_DESCRIPTOR, declaration, + JetPsiUtil.getFQName(file)); } @Nullable public static JetClass getSourceClass(@NotNull JetClass decompiledClass) { Tuple2 bindingContextAndClassDescriptor = getBindingContextAndClassDescriptor(decompiledClass); if (bindingContextAndClassDescriptor == null) return null; - PsiElement declaration = bindingContextAndClassDescriptor._1.get(BindingContext.DESCRIPTOR_TO_DECLARATION, bindingContextAndClassDescriptor._2); + PsiElement declaration = + bindingContextAndClassDescriptor._1.get(BindingContext.DESCRIPTOR_TO_DECLARATION, bindingContextAndClassDescriptor._2); assert declaration instanceof JetClass; - return (JetClass) declaration; + return (JetClass)declaration; } @NotNull @@ -119,12 +123,13 @@ public class JetSourceNavigationHelper { Project project = jetDeclaration.getProject(); CacheManager cacheManager = CacheManager.SERVICE.getInstance(project); PsiFile[] filesWithWord = cacheManager.getFilesWithWord(name, - UsageSearchContext.IN_CODE, createLibrarySourcesScopeForFile(libraryFile, project), + UsageSearchContext.IN_CODE, + createLibrarySourcesScopeForFile(libraryFile, project), true); List jetFiles = new ArrayList(); for (PsiFile psiFile : filesWithWord) { if (psiFile instanceof JetFile) { - jetFiles.add((JetFile) psiFile); + jetFiles.add((JetFile)psiFile); } } return jetFiles; @@ -132,9 +137,9 @@ public class JetSourceNavigationHelper { @Nullable private static JetDeclaration - getSourcePropertyOrFunction(final @NotNull Decl decompiledDeclaration, - JetTypeReference receiverType, - Matcher matcher) { + getSourcePropertyOrFunction(final @NotNull Decl decompiledDeclaration, + JetTypeReference receiverType, + Matcher matcher) { String entityName = decompiledDeclaration.getName(); if (entityName == null) { return null; @@ -142,7 +147,8 @@ public class JetSourceNavigationHelper { PsiElement declarationContainer = decompiledDeclaration.getParent(); if (declarationContainer instanceof JetFile) { - Tuple2 bindingContextAndNamespaceDescriptor = getBindingContextAndNamespaceDescriptor(decompiledDeclaration); + Tuple2 bindingContextAndNamespaceDescriptor = + getBindingContextAndNamespaceDescriptor(decompiledDeclaration); if (bindingContextAndNamespaceDescriptor == null) return null; BindingContext bindingContext = bindingContextAndNamespaceDescriptor._1; NamespaceDescriptor namespaceDescriptor = bindingContextAndNamespaceDescriptor._2; @@ -151,11 +157,12 @@ public class JetSourceNavigationHelper { for (Descr candidate : matcher.getCandidatesFromScope(namespaceDescriptor.getMemberScope(), entityName)) { if (candidate.getReceiverParameter() == ReceiverDescriptor.NO_RECEIVER) { if (matcher.areSame(decompiledDeclaration, candidate)) { - return (JetDeclaration) bindingContext.get(BindingContext.DESCRIPTOR_TO_DECLARATION, candidate); + return (JetDeclaration)bindingContext.get(BindingContext.DESCRIPTOR_TO_DECLARATION, candidate); } } } - } else { + } + else { // extension property String expectedTypeString = receiverType.getText(); for (Descr candidate : matcher.getCandidatesFromScope(namespaceDescriptor.getMemberScope(), entityName)) { @@ -163,7 +170,7 @@ public class JetSourceNavigationHelper { String thisReceiverType = DescriptorRenderer.TEXT.renderType(candidate.getReceiverParameter().getType()); if (expectedTypeString.equals(thisReceiverType)) { if (matcher.areSame(decompiledDeclaration, candidate)) { - return (JetDeclaration) bindingContext.get(BindingContext.DESCRIPTOR_TO_DECLARATION, candidate); + return (JetDeclaration)bindingContext.get(BindingContext.DESCRIPTOR_TO_DECLARATION, candidate); } } } @@ -194,7 +201,7 @@ public class JetSourceNavigationHelper { ClassDescriptor expectedContainer = isClassObject ? classDescriptor.getClassObjectDescriptor() : classDescriptor; for (Descr candidate : matcher.getCandidatesFromScope(memberScope, entityName)) { if (candidate.getContainingDeclaration() == expectedContainer) { - JetDeclaration property = (JetDeclaration) bindingContext.get(BindingContext.DESCRIPTOR_TO_DECLARATION, candidate); + JetDeclaration property = (JetDeclaration)bindingContext.get(BindingContext.DESCRIPTOR_TO_DECLARATION, candidate); if (property != null) { return property; } @@ -207,51 +214,54 @@ public class JetSourceNavigationHelper { @Nullable public static JetDeclaration getSourceProperty(final @NotNull JetProperty decompiledProperty) { - return getSourcePropertyOrFunction(decompiledProperty, decompiledProperty.getReceiverTypeRef(), new Matcher() { - @Override - public boolean areSame(JetProperty declaration, VariableDescriptor descriptor) { - return true; - } + return getSourcePropertyOrFunction(decompiledProperty, decompiledProperty.getReceiverTypeRef(), + new Matcher() { + @Override + public boolean areSame(JetProperty declaration, VariableDescriptor descriptor) { + return true; + } - @Override - public Set getCandidatesFromScope(JetScope scope, String name) { - return scope.getProperties(name); - } - }); + @Override + public Set getCandidatesFromScope(JetScope scope, String name) { + return scope.getProperties(name); + } + }); } @Nullable public static JetDeclaration getSourceFunction(final @NotNull JetFunction decompiledFunction) { - return getSourcePropertyOrFunction(decompiledFunction, decompiledFunction.getReceiverTypeRef(), new Matcher() { - @Override - public boolean areSame(JetFunction declaration, FunctionDescriptor descriptor) { - List declarationParameters = declaration.getValueParameters(); - List descriptorParameters = descriptor.getValueParameters(); - if (descriptorParameters.size() != declarationParameters.size()) { - return false; - } + return getSourcePropertyOrFunction(decompiledFunction, decompiledFunction.getReceiverTypeRef(), + new Matcher() { + @Override + public boolean areSame(JetFunction declaration, FunctionDescriptor descriptor) { + List declarationParameters = declaration.getValueParameters(); + List descriptorParameters = descriptor.getValueParameters(); + if (descriptorParameters.size() != declarationParameters.size()) { + return false; + } - for (int i = 0; i < descriptorParameters.size(); i++) { - ValueParameterDescriptor descriptorParameter = descriptorParameters.get(i); - JetParameter declarationParameter = declarationParameters.get(i); - JetTypeReference typeReference = declarationParameter.getTypeReference(); - if (typeReference == null) { - return false; - } - String declarationTypeText = typeReference.getText(); - String descriptorParameterText = DescriptorRenderer.TEXT.renderType(descriptorParameter.getType()); - if (!declarationTypeText.equals(descriptorParameterText)) { - return false; - } - } - return true; - } + for (int i = 0; i < descriptorParameters.size(); i++) { + ValueParameterDescriptor descriptorParameter = descriptorParameters.get(i); + JetParameter declarationParameter = declarationParameters.get(i); + JetTypeReference typeReference = declarationParameter.getTypeReference(); + if (typeReference == null) { + return false; + } + String declarationTypeText = typeReference.getText(); + String descriptorParameterText = + DescriptorRenderer.TEXT.renderType(descriptorParameter.getType()); + if (!declarationTypeText.equals(descriptorParameterText)) { + return false; + } + } + return true; + } - @Override - public Set getCandidatesFromScope(JetScope scope, String name) { - return scope.getFunctions(name); - } - }); + @Override + public Set getCandidatesFromScope(JetScope scope, String name) { + return scope.getFunctions(name); + } + }); } private interface Matcher { diff --git a/idea/src/org/jetbrains/jet/plugin/parameterInfo/JetFunctionParameterInfoHandler.java b/idea/src/org/jetbrains/jet/plugin/parameterInfo/JetFunctionParameterInfoHandler.java index 04896e14f59..78dc31c3e2b 100644 --- a/idea/src/org/jetbrains/jet/plugin/parameterInfo/JetFunctionParameterInfoHandler.java +++ b/idea/src/org/jetbrains/jet/plugin/parameterInfo/JetFunctionParameterInfoHandler.java @@ -26,6 +26,7 @@ import com.intellij.psi.PsiReference; import com.intellij.psi.tree.IElementType; import com.intellij.util.ArrayUtil; import org.jetbrains.annotations.NotNull; +import org.jetbrains.jet.analyzer.AnalyzerFacadeWithCache; import org.jetbrains.jet.compiler.TipsManager; import org.jetbrains.jet.lang.descriptors.*; import org.jetbrains.jet.lang.psi.*; @@ -47,7 +48,7 @@ import java.util.List; * Date: 17.01.12 */ public class JetFunctionParameterInfoHandler implements - ParameterInfoHandlerWithTabActionSupport { + ParameterInfoHandlerWithTabActionSupport { public final static Color GREEN_BACKGROUND = new Color(231, 254, 234); @NotNull @@ -72,7 +73,7 @@ public class JetFunctionParameterInfoHandler implements @NotNull @Override public Set getArgumentListAllowedParentClasses() { - return Collections.singleton((Class) JetCallElement.class); + return Collections.singleton((Class)JetCallElement.class); } @NotNull @@ -139,7 +140,7 @@ public class JetFunctionParameterInfoHandler implements public boolean tracksParameterIndex() { return true; } - + private static String renderParameter(ValueParameterDescriptor descriptor, boolean named, BindingContext bindingContext) { StringBuilder builder = new StringBuilder(); if (named) builder.append("["); @@ -147,21 +148,27 @@ public class JetFunctionParameterInfoHandler implements builder.append("vararg "); } builder.append(descriptor.getName()).append(": "). - append(DescriptorRenderer.TEXT.renderType(getActualParameterType(descriptor))); + append(DescriptorRenderer.TEXT.renderType(getActualParameterType(descriptor))); if (descriptor.hasDefaultValue()) { PsiElement element = bindingContext.get(BindingContext.DESCRIPTOR_TO_DECLARATION, descriptor); String defaultExpression = "?"; if (element instanceof JetParameter) { - JetParameter parameter = (JetParameter) element; + JetParameter parameter = (JetParameter)element; JetExpression defaultValue = parameter.getDefaultValue(); if (defaultValue != null) { if (defaultValue instanceof JetConstantExpression) { - JetConstantExpression constantExpression = (JetConstantExpression) defaultValue; + JetConstantExpression constantExpression = (JetConstantExpression)defaultValue; defaultExpression = constantExpression.getText(); if (defaultExpression.length() > 10) { - if (defaultExpression.startsWith("\"")) defaultExpression = "\"...\""; - else if (defaultExpression.startsWith("\'")) defaultExpression = "\'...\'"; - else defaultExpression = defaultExpression.substring(0, 7) + "..."; + if (defaultExpression.startsWith("\"")) { + defaultExpression = "\"...\""; + } + else if (defaultExpression.startsWith("\'")) { + defaultExpression = "\'...\'"; + } + else { + defaultExpression = defaultExpression.substring(0, 7) + "..."; + } } } } @@ -171,7 +178,7 @@ public class JetFunctionParameterInfoHandler implements if (named) builder.append("]"); return builder.toString(); } - + private static JetType getActualParameterType(ValueParameterDescriptor descriptor) { JetType paramType = descriptor.getType(); if (descriptor.getVarargElementType() != null) paramType = descriptor.getVarargElementType(); @@ -186,13 +193,13 @@ public class JetFunctionParameterInfoHandler implements } PsiElement parameterOwner = context.getParameterOwner(); if (parameterOwner instanceof JetValueArgumentList) { - JetValueArgumentList argumentList = (JetValueArgumentList) parameterOwner; + JetValueArgumentList argumentList = (JetValueArgumentList)parameterOwner; if (descriptor instanceof FunctionDescriptor) { - JetFile file = (JetFile) argumentList.getContainingFile(); + JetFile file = (JetFile)argumentList.getContainingFile(); BindingContext bindingContext = - AnalyzerFacadeForJVM.analyzeFileWithCache(file, AnalyzerFacadeForJVM.SINGLE_DECLARATION_PROVIDER) - .getBindingContext(); - FunctionDescriptor functionDescriptor = (FunctionDescriptor) descriptor; + AnalyzerFacadeForJVM.analyzeFileWithCache(file, AnalyzerFacadeWithCache.SINGLE_DECLARATION_PROVIDER) + .getBindingContext(); + FunctionDescriptor functionDescriptor = (FunctionDescriptor)descriptor; StringBuilder builder = new StringBuilder(); List valueParameters = functionDescriptor.getValueParameters(); List valueArguments = argumentList.getArguments(); @@ -204,27 +211,28 @@ public class JetFunctionParameterInfoHandler implements Color color = context.getDefaultParameterColor(); PsiElement parent = argumentList.getParent(); if (parent instanceof JetCallElement) { - JetCallElement callExpression = (JetCallElement) parent; + JetCallElement callExpression = (JetCallElement)parent; JetExpression calleeExpression = callExpression.getCalleeExpression(); JetSimpleNameExpression refExpression = null; if (calleeExpression instanceof JetSimpleNameExpression) { - refExpression = (JetSimpleNameExpression) calleeExpression; - } else if (calleeExpression instanceof JetConstructorCalleeExpression) { - JetConstructorCalleeExpression constructorCalleeExpression = (JetConstructorCalleeExpression) calleeExpression; + refExpression = (JetSimpleNameExpression)calleeExpression; + } + else if (calleeExpression instanceof JetConstructorCalleeExpression) { + JetConstructorCalleeExpression constructorCalleeExpression = (JetConstructorCalleeExpression)calleeExpression; if (constructorCalleeExpression.getConstructorReferenceExpression() instanceof JetSimpleNameExpression) { - refExpression = (JetSimpleNameExpression) constructorCalleeExpression.getConstructorReferenceExpression(); + refExpression = (JetSimpleNameExpression)constructorCalleeExpression.getConstructorReferenceExpression(); } } if (refExpression != null) { DeclarationDescriptor declarationDescriptor = bindingContext.get(BindingContext.REFERENCE_TARGET, refExpression); if (declarationDescriptor != null) { if (declarationDescriptor == functionDescriptor) { - color = GREEN_BACKGROUND; + color = GREEN_BACKGROUND; } } } } - + boolean[] usedIndexes = new boolean[valueParameters.size()]; boolean namedMode = false; Arrays.fill(usedIndexes, false); @@ -236,35 +244,40 @@ public class JetFunctionParameterInfoHandler implements if (valueParameters.size() == 0) builder.append(CodeInsightBundle.message("parameter.info.no.parameters")); for (int i = 0; i < valueParameters.size(); ++i) { if (i != 0) builder.append(", "); - boolean highlightParameter = - i == currentParameterIndex || (!namedMode && i < currentParameterIndex && - valueParameters.get(valueParameters.size() - 1). - getVarargElementType() != null); + boolean highlightParameter = + i == currentParameterIndex || (!namedMode && i < currentParameterIndex && + valueParameters.get(valueParameters.size() - 1). + getVarargElementType() != null); if (highlightParameter) boldStartOffset = builder.length(); if (!namedMode) { if (valueArguments.size() > i) { JetValueArgument argument = valueArguments.get(i); if (argument.isNamed()) { namedMode = true; - } else { + } + else { ValueParameterDescriptor param = valueParameters.get(i); builder.append(renderParameter(param, false, bindingContext)); if (i < currentParameterIndex) { if (argument.getArgumentExpression() != null) { //check type JetType paramType = getActualParameterType(param); - JetType exprType = bindingContext.get(BindingContext.EXPRESSION_TYPE, argument.getArgumentExpression()); + JetType exprType = + bindingContext.get(BindingContext.EXPRESSION_TYPE, argument.getArgumentExpression()); if (exprType != null && !JetTypeChecker.INSTANCE.isSubtypeOf(exprType, paramType)) isGrey = true; } - else isGrey = true; + else { + isGrey = true; + } } usedIndexes[i] = true; } - } else { + } + else { ValueParameterDescriptor param = valueParameters.get(i); builder.append(renderParameter(param, false, bindingContext)); } - } + } if (namedMode) { boolean takeAnyArgument = true; if (valueArguments.size() > i) { @@ -282,20 +295,25 @@ public class JetFunctionParameterInfoHandler implements if (argument.getArgumentExpression() != null) { //check type JetType paramType = getActualParameterType(param); - JetType exprType = bindingContext.get(BindingContext.EXPRESSION_TYPE, argument.getArgumentExpression()); - if (exprType != null && !JetTypeChecker.INSTANCE.isSubtypeOf(exprType, paramType)) isGrey = true; + JetType exprType = + bindingContext.get(BindingContext.EXPRESSION_TYPE, argument.getArgumentExpression()); + if (exprType != null && !JetTypeChecker.INSTANCE.isSubtypeOf(exprType, paramType)) { + isGrey = true; + } + } + else { + isGrey = true; } - else isGrey = true; } break; } } } } - + if (takeAnyArgument) { if (i < currentParameterIndex) isGrey = true; - + for (int j = 0; j < valueParameters.size(); ++j) { ValueParameterDescriptor param = valueParameters.get(j); if (!usedIndexes[j]) { @@ -308,10 +326,17 @@ public class JetFunctionParameterInfoHandler implements } if (highlightParameter) boldEndOffset = builder.length(); } - if (builder.toString().isEmpty()) context.setUIComponentEnabled(false); - else context.setupUIComponentPresentation(builder.toString(), boldStartOffset, boldEndOffset, isGrey, - isDeprecated, false, color); - } else context.setUIComponentEnabled(false); + if (builder.toString().isEmpty()) { + context.setUIComponentEnabled(false); + } + else { + context.setupUIComponentPresentation(builder.toString(), boldStartOffset, boldEndOffset, isGrey, + isDeprecated, false, color); + } + } + else { + context.setUIComponentEnabled(false); + } } } @@ -324,24 +349,28 @@ public class JetFunctionParameterInfoHandler implements element = element.getParent(); } if (element == null) return null; - JetValueArgumentList argumentList = (JetValueArgumentList) element; + JetValueArgumentList argumentList = (JetValueArgumentList)element; JetCallElement callExpression; if (element.getParent() instanceof JetCallElement) { - callExpression = (JetCallElement) element.getParent(); - } else return null; + callExpression = (JetCallElement)element.getParent(); + } + else { + return null; + } BindingContext bindingContext = AnalyzerFacadeForJVM.analyzeFileWithCache( - (JetFile) file, - AnalyzerFacadeForJVM.SINGLE_DECLARATION_PROVIDER) - .getBindingContext(); + (JetFile)file, + AnalyzerFacadeWithCache.SINGLE_DECLARATION_PROVIDER) + .getBindingContext(); JetExpression calleeExpression = callExpression.getCalleeExpression(); if (calleeExpression == null) return null; JetSimpleNameExpression refExpression = null; if (calleeExpression instanceof JetSimpleNameExpression) { - refExpression = (JetSimpleNameExpression) calleeExpression; - } else if (calleeExpression instanceof JetConstructorCalleeExpression) { - JetConstructorCalleeExpression constructorCalleeExpression = (JetConstructorCalleeExpression) calleeExpression; + refExpression = (JetSimpleNameExpression)calleeExpression; + } + else if (calleeExpression instanceof JetConstructorCalleeExpression) { + JetConstructorCalleeExpression constructorCalleeExpression = (JetConstructorCalleeExpression)calleeExpression; if (constructorCalleeExpression.getConstructorReferenceExpression() instanceof JetSimpleNameExpression) { - refExpression = (JetSimpleNameExpression) constructorCalleeExpression.getConstructorReferenceExpression(); + refExpression = (JetSimpleNameExpression)constructorCalleeExpression.getConstructorReferenceExpression(); } } if (refExpression != null) { @@ -357,18 +386,21 @@ public class JetFunctionParameterInfoHandler implements ArrayList itemsToShow = new ArrayList(); for (DeclarationDescriptor variant : variants) { if (variant instanceof FunctionDescriptor) { - FunctionDescriptor functionDescriptor = (FunctionDescriptor) variant; + FunctionDescriptor functionDescriptor = (FunctionDescriptor)variant; if (functionDescriptor.getName().equals(refName)) { //todo: renamed functions? if (placeDescriptor != null && !JetVisibilityChecker.isVisible(placeDescriptor, functionDescriptor)) continue; itemsToShow.add(functionDescriptor); } - } else if (variant instanceof ClassDescriptor) { - ClassDescriptor classDescriptor = (ClassDescriptor) variant; + } + else if (variant instanceof ClassDescriptor) { + ClassDescriptor classDescriptor = (ClassDescriptor)variant; if (classDescriptor.getName().equals(refName)) { //todo: renamed classes? for (ConstructorDescriptor constructorDescriptor : classDescriptor.getConstructors()) { - if (placeDescriptor != null && !JetVisibilityChecker.isVisible(placeDescriptor, constructorDescriptor)) continue; + if (placeDescriptor != null && !JetVisibilityChecker.isVisible(placeDescriptor, constructorDescriptor)) { + continue; + } itemsToShow.add(constructorDescriptor); } } @@ -390,9 +422,9 @@ public class JetFunctionParameterInfoHandler implements parent = parent.getParent(); } if (parent == null) return null; - JetValueArgumentList argumentList = (JetValueArgumentList) parent; + JetValueArgumentList argumentList = (JetValueArgumentList)parent; if (element instanceof JetValueArgument) { - JetValueArgument arg = (JetValueArgument) element; + JetValueArgument arg = (JetValueArgument)element; int i = argumentList.getArguments().indexOf(arg); context.setCurrentParameter(i); context.setHighlightedParameter(arg); diff --git a/idea/src/org/jetbrains/jet/plugin/quickfix/ChangeVariableMutabilityFix.java b/idea/src/org/jetbrains/jet/plugin/quickfix/ChangeVariableMutabilityFix.java index 5e95c71da6b..96f36499b34 100644 --- a/idea/src/org/jetbrains/jet/plugin/quickfix/ChangeVariableMutabilityFix.java +++ b/idea/src/org/jetbrains/jet/plugin/quickfix/ChangeVariableMutabilityFix.java @@ -24,6 +24,7 @@ import com.intellij.psi.PsiFile; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.IncorrectOperationException; import org.jetbrains.annotations.NotNull; +import org.jetbrains.jet.analyzer.AnalyzerFacadeWithCache; import org.jetbrains.jet.lang.descriptors.VariableDescriptor; import org.jetbrains.jet.lang.psi.JetFile; import org.jetbrains.jet.lang.psi.JetProperty; @@ -39,7 +40,7 @@ import org.jetbrains.jet.plugin.JetBundle; */ public class ChangeVariableMutabilityFix implements IntentionAction { private boolean isVar; - + public ChangeVariableMutabilityFix(boolean isVar) { this.isVar = isVar; } @@ -47,7 +48,7 @@ public class ChangeVariableMutabilityFix implements IntentionAction { public ChangeVariableMutabilityFix() { this(false); } - + @NotNull @Override public String getText() { @@ -63,7 +64,7 @@ public class ChangeVariableMutabilityFix implements IntentionAction { @Override public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) { if (!(file instanceof JetFile)) return false; - JetProperty property = getCorrespondingProperty(editor, (JetFile) file); + JetProperty property = getCorrespondingProperty(editor, (JetFile)file); return property != null && !property.isVar(); } @@ -73,13 +74,14 @@ public class ChangeVariableMutabilityFix implements IntentionAction { if (property != null) return property; JetSimpleNameExpression simpleNameExpression = PsiTreeUtil.getParentOfType(elementAtCaret, JetSimpleNameExpression.class); if (simpleNameExpression != null) { - BindingContext bindingContext = AnalyzerFacadeForJVM.analyzeFileWithCache(file, AnalyzerFacadeForJVM.SINGLE_DECLARATION_PROVIDER) + BindingContext bindingContext = + AnalyzerFacadeForJVM.analyzeFileWithCache(file, AnalyzerFacadeWithCache.SINGLE_DECLARATION_PROVIDER) .getBindingContext(); VariableDescriptor descriptor = BindingContextUtils.extractVariableDescriptorIfAny(bindingContext, simpleNameExpression, true); if (descriptor != null) { PsiElement declaration = bindingContext.get(BindingContext.DESCRIPTOR_TO_DECLARATION, descriptor); if (declaration instanceof JetProperty) { - return (JetProperty) declaration; + return (JetProperty)declaration; } } } @@ -92,7 +94,7 @@ public class ChangeVariableMutabilityFix implements IntentionAction { assert property != null && !property.isVar(); JetProperty newElement = JetPsiFactory.createProperty(project, property.getText().replaceFirst( - property.isVar() ? "var" : "val", property.isVar() ? "val" : "var")); + property.isVar() ? "var" : "val", property.isVar() ? "val" : "var")); property.replace(newElement); } diff --git a/idea/src/org/jetbrains/jet/plugin/quickfix/ImportInsertHelper.java b/idea/src/org/jetbrains/jet/plugin/quickfix/ImportInsertHelper.java index a6b5a2a3a4f..ed321599c54 100644 --- a/idea/src/org/jetbrains/jet/plugin/quickfix/ImportInsertHelper.java +++ b/idea/src/org/jetbrains/jet/plugin/quickfix/ImportInsertHelper.java @@ -19,6 +19,7 @@ package org.jetbrains.jet.plugin.quickfix; import com.intellij.psi.PsiElement; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import org.jetbrains.jet.analyzer.AnalyzerFacadeWithCache; import org.jetbrains.jet.lang.DefaultModuleConfiguration; import org.jetbrains.jet.lang.psi.JetFile; import org.jetbrains.jet.lang.psi.JetImportDirective; @@ -54,8 +55,8 @@ public class ImportInsertHelper { if (JetPluginUtil.checkTypeIsStandard(type, file.getProject()) || ErrorUtils.isErrorType(type)) { return; } - BindingContext bindingContext = AnalyzerFacadeForJVM.analyzeFileWithCache(file, AnalyzerFacadeForJVM.SINGLE_DECLARATION_PROVIDER) - .getBindingContext(); + BindingContext bindingContext = AnalyzerFacadeForJVM.analyzeFileWithCache(file, AnalyzerFacadeWithCache.SINGLE_DECLARATION_PROVIDER) + .getBindingContext(); PsiElement element = bindingContext.get(BindingContext.DESCRIPTOR_TO_DECLARATION, type.getMemberScope().getContainingDeclaration()); if (element != null && element.getContainingFile() == file) { //declaration is in the same file, so no import is needed return; @@ -67,7 +68,7 @@ public class ImportInsertHelper { * Add import directive into the PSI tree for the given namespace. * * @param importFqn full name of the import - * @param file File where directive should be added. + * @param file File where directive should be added. */ public static void addImportDirective(@NotNull FqName importFqn, @NotNull JetFile file) { addImportDirective(new ImportPath(importFqn, false), null, file); diff --git a/idea/src/org/jetbrains/jet/plugin/quickfix/QuickFixUtil.java b/idea/src/org/jetbrains/jet/plugin/quickfix/QuickFixUtil.java index 6559be36c8e..169e9617d54 100644 --- a/idea/src/org/jetbrains/jet/plugin/quickfix/QuickFixUtil.java +++ b/idea/src/org/jetbrains/jet/plugin/quickfix/QuickFixUtil.java @@ -16,13 +16,13 @@ package org.jetbrains.jet.plugin.quickfix; -import com.intellij.codeInsight.intention.IntentionAction; import com.intellij.extapi.psi.ASTDelegatePsiElement; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiWhiteSpace; import com.intellij.psi.util.PsiTreeUtil; import org.jetbrains.annotations.Nullable; +import org.jetbrains.jet.analyzer.AnalyzerFacadeWithCache; import org.jetbrains.jet.lang.descriptors.CallableDescriptor; import org.jetbrains.jet.lang.descriptors.DeclarationDescriptor; import org.jetbrains.jet.lang.diagnostics.Diagnostic; @@ -57,13 +57,14 @@ public class QuickFixUtil { public static JetType getDeclarationReturnType(JetNamedDeclaration declaration) { PsiFile file = declaration.getContainingFile(); if (!(file instanceof JetFile)) return null; - BindingContext bindingContext = AnalyzerFacadeForJVM.analyzeFileWithCache((JetFile) file, AnalyzerFacadeForJVM.SINGLE_DECLARATION_PROVIDER) + BindingContext bindingContext = + AnalyzerFacadeForJVM.analyzeFileWithCache((JetFile)file, AnalyzerFacadeWithCache.SINGLE_DECLARATION_PROVIDER) .getBindingContext(); DeclarationDescriptor descriptor = bindingContext.get(BindingContext.DECLARATION_TO_DESCRIPTOR, declaration); if (!(descriptor instanceof CallableDescriptor)) return null; - JetType type = ((CallableDescriptor) descriptor).getReturnType(); + JetType type = ((CallableDescriptor)descriptor).getReturnType(); if (type instanceof DeferredType) { - type = ((DeferredType) type).getActualType(); + type = ((DeferredType)type).getActualType(); } return type; } diff --git a/idea/src/org/jetbrains/jet/plugin/refactoring/JetNameSuggester.java b/idea/src/org/jetbrains/jet/plugin/refactoring/JetNameSuggester.java index 58d84b77067..b45fee942a8 100644 --- a/idea/src/org/jetbrains/jet/plugin/refactoring/JetNameSuggester.java +++ b/idea/src/org/jetbrains/jet/plugin/refactoring/JetNameSuggester.java @@ -19,15 +19,16 @@ package org.jetbrains.jet.plugin.refactoring; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.ArrayUtil; +import org.jetbrains.jet.analyzer.AnalyzerFacadeWithCache; import org.jetbrains.jet.lang.descriptors.ClassDescriptor; import org.jetbrains.jet.lang.psi.*; import org.jetbrains.jet.lang.resolve.BindingContext; import org.jetbrains.jet.lang.resolve.java.AnalyzerFacadeForJVM; import org.jetbrains.jet.lang.types.ErrorUtils; -import org.jetbrains.jet.lang.types.lang.JetStandardLibrary; import org.jetbrains.jet.lang.types.JetType; import org.jetbrains.jet.lang.types.TypeUtils; import org.jetbrains.jet.lang.types.checker.JetTypeChecker; +import org.jetbrains.jet.lang.types.lang.JetStandardLibrary; import org.jetbrains.jet.lexer.JetLexer; import org.jetbrains.jet.lexer.JetTokens; @@ -59,16 +60,17 @@ public class JetNameSuggester { * 1c. Arrays => arrayOfInnerType * 2. Reference expressions according to reference name camel humps * 3. Method call expression according to method callee expression + * * @param expression to suggest name for variable - * @param validator to check scope for such names + * @param validator to check scope for such names * @return possible names */ public static String[] suggestNames(JetExpression expression, JetNameValidator validator) { ArrayList result = new ArrayList(); - BindingContext bindingContext = AnalyzerFacadeForJVM.analyzeFileWithCache((JetFile) expression.getContainingFile(), - AnalyzerFacadeForJVM.SINGLE_DECLARATION_PROVIDER) - .getBindingContext(); + BindingContext bindingContext = AnalyzerFacadeForJVM.analyzeFileWithCache((JetFile)expression.getContainingFile(), + AnalyzerFacadeWithCache.SINGLE_DECLARATION_PROVIDER) + .getBindingContext(); JetType jetType = bindingContext.get(BindingContext.EXPRESSION_TYPE, expression); if (jetType != null) { addNamesForType(result, jetType, validator); @@ -78,67 +80,85 @@ public class JetNameSuggester { if (result.isEmpty()) addName(result, "value", validator); return ArrayUtil.toStringArray(result); } - + private static void addNamesForType(ArrayList result, JetType jetType, JetNameValidator validator) { JetStandardLibrary standardLibrary = JetStandardLibrary.getInstance(); JetTypeChecker typeChecker = JetTypeChecker.INSTANCE; if (ErrorUtils.containsErrorType(jetType)) return; if (typeChecker.equalTypes(standardLibrary.getBooleanType(), jetType)) { addName(result, "b", validator); - } else if (typeChecker.equalTypes(standardLibrary.getIntType(), jetType)) { + } + else if (typeChecker.equalTypes(standardLibrary.getIntType(), jetType)) { addName(result, "i", validator); - } else if (typeChecker.equalTypes(standardLibrary.getByteType(), jetType)) { + } + else if (typeChecker.equalTypes(standardLibrary.getByteType(), jetType)) { addName(result, "byte", validator); - } else if (typeChecker.equalTypes(standardLibrary.getLongType(), jetType)) { + } + else if (typeChecker.equalTypes(standardLibrary.getLongType(), jetType)) { addName(result, "l", validator); - } else if (typeChecker.equalTypes(standardLibrary.getFloatType(), jetType)) { + } + else if (typeChecker.equalTypes(standardLibrary.getFloatType(), jetType)) { addName(result, "fl", validator); - } else if (typeChecker.equalTypes(standardLibrary.getDoubleType(), jetType)) { + } + else if (typeChecker.equalTypes(standardLibrary.getDoubleType(), jetType)) { addName(result, "d", validator); - } else if (typeChecker.equalTypes(standardLibrary.getShortType(), jetType)) { + } + else if (typeChecker.equalTypes(standardLibrary.getShortType(), jetType)) { addName(result, "sh", validator); - } else if (typeChecker.equalTypes(standardLibrary.getCharType(), jetType)) { + } + else if (typeChecker.equalTypes(standardLibrary.getCharType(), jetType)) { addName(result, "c", validator); - } else if (typeChecker.equalTypes(standardLibrary.getStringType(), jetType)) { + } + else if (typeChecker.equalTypes(standardLibrary.getStringType(), jetType)) { addName(result, "s", validator); - } else { + } + else { if (jetType.getArguments().size() == 1) { JetType argument = jetType.getArguments().get(0).getType(); if (typeChecker.equalTypes(standardLibrary.getArrayType(argument), jetType)) { if (typeChecker.equalTypes(standardLibrary.getBooleanType(), argument)) { addName(result, "booleans", validator); - } else if (typeChecker.equalTypes(standardLibrary.getIntType(), argument)) { + } + else if (typeChecker.equalTypes(standardLibrary.getIntType(), argument)) { addName(result, "ints", validator); - } else if (typeChecker.equalTypes(standardLibrary.getByteType(), argument)) { + } + else if (typeChecker.equalTypes(standardLibrary.getByteType(), argument)) { addName(result, "bytes", validator); - } else if (typeChecker.equalTypes(standardLibrary.getLongType(), argument)) { + } + else if (typeChecker.equalTypes(standardLibrary.getLongType(), argument)) { addName(result, "longs", validator); - } else if (typeChecker.equalTypes(standardLibrary.getFloatType(), argument)) { + } + else if (typeChecker.equalTypes(standardLibrary.getFloatType(), argument)) { addName(result, "floats", validator); - } else if (typeChecker.equalTypes(standardLibrary.getDoubleType(), argument)) { + } + else if (typeChecker.equalTypes(standardLibrary.getDoubleType(), argument)) { addName(result, "doubles", validator); - } else if (typeChecker.equalTypes(standardLibrary.getShortType(), argument)) { + } + else if (typeChecker.equalTypes(standardLibrary.getShortType(), argument)) { addName(result, "shorts", validator); - } else if (typeChecker.equalTypes(standardLibrary.getCharType(), argument)) { + } + else if (typeChecker.equalTypes(standardLibrary.getCharType(), argument)) { addName(result, "chars", validator); - } else if (typeChecker.equalTypes(standardLibrary.getStringType(), argument)) { + } + else if (typeChecker.equalTypes(standardLibrary.getStringType(), argument)) { addName(result, "strings", validator); - } else { + } + else { ClassDescriptor classDescriptor = TypeUtils.getClassDescriptor(argument); if (classDescriptor != null) { String className = classDescriptor.getName(); addName(result, "arrayOf" + StringUtil.capitalize(className) + "s", validator); } } - } else { + } + else { addForClassType(result, jetType, validator); } - } else { + } + else { addForClassType(result, jetType, validator); } } - - } private static void addForClassType(ArrayList result, JetType jetType, JetNameValidator validator) { @@ -152,42 +172,48 @@ public class JetNameSuggester { private static void addCamelNames(ArrayList result, String name, JetNameValidator validator) { if (name == "") return; String s = deleteNonLetterFromString(name); - if (s.startsWith("get") || s.startsWith("set")) s = s.substring(0, 3); + if (s.startsWith("get") || s.startsWith("set")) { + s = s.substring(0, 3); + } else if (s.startsWith("is")) s = s.substring(0, 2); for (int i = 0; i < s.length(); ++i) { if (i == 0) { addName(result, StringUtil.decapitalize(s), validator); - } else if (s.charAt(i) >= 'A' && s.charAt(i) <= 'Z') { + } + else if (s.charAt(i) >= 'A' && s.charAt(i) <= 'Z') { addName(result, StringUtil.decapitalize(s.substring(i)), validator); } } } - + private static String deleteNonLetterFromString(String s) { Pattern pattern = Pattern.compile("[^a-zA-Z]"); Matcher matcher = pattern.matcher(s); return matcher.replaceAll(""); } - + private static void addNamesForExpression(ArrayList result, JetExpression expression, JetNameValidator validator) { if (expression instanceof JetQualifiedExpression) { - JetQualifiedExpression qualifiedExpression = (JetQualifiedExpression) expression; + JetQualifiedExpression qualifiedExpression = (JetQualifiedExpression)expression; addNamesForExpression(result, qualifiedExpression.getSelectorExpression(), validator); - } else if (expression instanceof JetSimpleNameExpression) { - JetSimpleNameExpression reference = (JetSimpleNameExpression) expression; + } + else if (expression instanceof JetSimpleNameExpression) { + JetSimpleNameExpression reference = (JetSimpleNameExpression)expression; String referenceName = reference.getReferencedName(); if (referenceName == null) return; if (referenceName.equals(referenceName.toUpperCase())) { addName(result, referenceName, validator); - } else { + } + else { addCamelNames(result, referenceName, validator); } - } else if (expression instanceof JetCallExpression) { - JetCallExpression call = (JetCallExpression) expression; + } + else if (expression instanceof JetCallExpression) { + JetCallExpression call = (JetCallExpression)expression; addNamesForExpression(result, call.getCalleeExpression(), validator); } } - + public static boolean isIdentifier(String name) { ApplicationManager.getApplication().assertReadAccessAllowed(); if (name == null || name.isEmpty()) return false; diff --git a/idea/src/org/jetbrains/jet/plugin/refactoring/JetRefactoringUtil.java b/idea/src/org/jetbrains/jet/plugin/refactoring/JetRefactoringUtil.java index ae1352e8b6b..246e57711db 100644 --- a/idea/src/org/jetbrains/jet/plugin/refactoring/JetRefactoringUtil.java +++ b/idea/src/org/jetbrains/jet/plugin/refactoring/JetRefactoringUtil.java @@ -28,13 +28,14 @@ import com.intellij.psi.util.PsiTreeUtil; import com.intellij.ui.components.JBList; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import org.jetbrains.jet.analyzer.AnalyzerFacadeWithCache; import org.jetbrains.jet.lang.psi.*; import org.jetbrains.jet.lang.resolve.BindingContext; import org.jetbrains.jet.lang.resolve.java.AnalyzerFacadeForJVM; -import org.jetbrains.jet.lang.types.lang.JetStandardLibrary; import org.jetbrains.jet.lang.types.JetType; import org.jetbrains.jet.lang.types.NamespaceType; import org.jetbrains.jet.lang.types.checker.JetTypeChecker; +import org.jetbrains.jet.lang.types.lang.JetStandardLibrary; import javax.swing.*; import javax.swing.event.ListSelectionEvent; @@ -66,15 +67,16 @@ public class JetRefactoringUtil { while (selectionStart < selectionEnd && Character.isSpaceChar(text.charAt(selectionStart))) ++selectionStart; while (selectionStart < selectionEnd && Character.isSpaceChar(text.charAt(selectionEnd - 1))) --selectionEnd; callback.run(findExpression(editor, file, selectionStart, selectionEnd)); - } else { + } + else { int offset = editor.getCaretModel().getOffset(); smartSelectExpression(editor, file, offset, callback); } } private static void smartSelectExpression(@NotNull Editor editor, @NotNull PsiFile file, int offset, - @NotNull final SelectExpressionCallback callback) - throws IntroduceRefactoringException { + @NotNull final SelectExpressionCallback callback) + throws IntroduceRefactoringException { if (offset < 0) throw new IntroduceRefactoringException(JetRefactoringBundle.message("cannot.refactor.not.expression")); PsiElement element = file.findElementAt(offset); if (element == null) throw new IntroduceRefactoringException(JetRefactoringBundle.message("cannot.refactor.not.expression")); @@ -88,34 +90,38 @@ public class JetRefactoringUtil { if (element instanceof JetExpression && !(element instanceof JetStatementExpression)) { boolean addExpression = true; if (element.getParent() instanceof JetQualifiedExpression) { - JetQualifiedExpression qualifiedExpression = (JetQualifiedExpression) element.getParent(); + JetQualifiedExpression qualifiedExpression = (JetQualifiedExpression)element.getParent(); if (qualifiedExpression.getReceiverExpression() != element) { addExpression = false; } - } else if (element.getParent() instanceof JetCallElement) { + } + else if (element.getParent() instanceof JetCallElement) { addExpression = false; - } else if (element.getParent() instanceof JetOperationExpression) { - JetOperationExpression operationExpression = (JetOperationExpression) element.getParent(); + } + else if (element.getParent() instanceof JetOperationExpression) { + JetOperationExpression operationExpression = (JetOperationExpression)element.getParent(); if (operationExpression.getOperationReference() == element) { addExpression = false; } } if (addExpression) { - JetExpression expression = (JetExpression) element; - BindingContext bindingContext = AnalyzerFacadeForJVM.analyzeFileWithCache((JetFile) expression.getContainingFile(), - AnalyzerFacadeForJVM.SINGLE_DECLARATION_PROVIDER) - .getBindingContext(); + JetExpression expression = (JetExpression)element; + BindingContext bindingContext = AnalyzerFacadeForJVM.analyzeFileWithCache((JetFile)expression.getContainingFile(), + AnalyzerFacadeWithCache.SINGLE_DECLARATION_PROVIDER) + .getBindingContext(); JetType expressionType = bindingContext.get(BindingContext.EXPRESSION_TYPE, expression); if (expressionType == null || !(expressionType instanceof NamespaceType) && !JetTypeChecker.INSTANCE.equalTypes(JetStandardLibrary. - getInstance().getTuple0Type(), expressionType)) { + getInstance().getTuple0Type(), expressionType)) { expressions.add(expression); } } } element = element.getParent(); } - if (expressions.size() == 0) throw new IntroduceRefactoringException(JetRefactoringBundle.message("cannot.refactor.not.expression")); + if (expressions.size() == 0) { + throw new IntroduceRefactoringException(JetRefactoringBundle.message("cannot.refactor.not.expression")); + } final DefaultListModel model = new DefaultListModel(); for (JetExpression expression : expressions) { @@ -125,13 +131,13 @@ public class JetRefactoringUtil { final ScopeHighlighter highlighter = new ScopeHighlighter(editor); final JList list = new JBList(model); - + list.setCellRenderer(new DefaultListCellRenderer() { @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { Component rendererComponent = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); StringBuilder buffer = new StringBuilder(); - JetExpression element = (JetExpression) value; + JetExpression element = (JetExpression)value; if (element.isValid()) { setText(getExpressionShortText(element)); } @@ -145,7 +151,7 @@ public class JetRefactoringUtil { highlighter.dropHighlight(); int selectedIndex = list.getSelectedIndex(); if (selectedIndex < 0) return; - JetExpression expression = (JetExpression) model.get(selectedIndex); + JetExpression expression = (JetExpression)model.get(selectedIndex); ArrayList toExtract = new ArrayList(); toExtract.add(expression); highlighter.highlight(expression, toExtract); @@ -153,11 +159,11 @@ public class JetRefactoringUtil { }); JBPopupFactory.getInstance().createListPopupBuilder(list). - setTitle(JetRefactoringBundle.message("expressions.title")).setMovable(false).setResizable(false). - setRequestFocus(true).setItemChoosenCallback(new Runnable() { + setTitle(JetRefactoringBundle.message("expressions.title")).setMovable(false).setResizable(false). + setRequestFocus(true).setItemChoosenCallback(new Runnable() { @Override public void run() { - callback.run((JetExpression) list.getSelectedValue()); + callback.run((JetExpression)list.getSelectedValue()); } }).addListener(new JBPopupAdapter() { @Override @@ -165,7 +171,6 @@ public class JetRefactoringUtil { highlighter.dropHighlight(); } }).createPopup().showInBestPositionFor(editor); - } public static String getExpressionShortText(@NotNull JetExpression expression) { //todo: write appropriate implementation @@ -178,24 +183,26 @@ public class JetRefactoringUtil { @Nullable private static JetExpression findExpression(@NotNull Editor editor, @NotNull PsiFile file, - int startOffset, int endOffset) throws IntroduceRefactoringException{ + int startOffset, int endOffset) throws IntroduceRefactoringException { PsiElement element = PsiTreeUtil.findElementOfClassAtRange(file, startOffset, endOffset, JetExpression.class); if (element == null || element.getTextRange().getStartOffset() != startOffset || element.getTextRange().getEndOffset() != endOffset) { //todo: if it's infix expression => add (), then commit document then return new created expression throw new IntroduceRefactoringException(JetRefactoringBundle.message("cannot.refactor.not.expression")); - } else if (!(element instanceof JetExpression)) { + } + else if (!(element instanceof JetExpression)) { throw new IntroduceRefactoringException(JetRefactoringBundle.message("cannot.refactor.not.expression")); - } else if (element instanceof JetBlockExpression) { - List statements = ((JetBlockExpression) element).getStatements(); + } + else if (element instanceof JetBlockExpression) { + List statements = ((JetBlockExpression)element).getStatements(); if (statements.size() == 1) { JetElement elem = statements.get(0); if (elem.getText().equals(element.getText()) && elem instanceof JetExpression) { - return (JetExpression) elem; + return (JetExpression)elem; } } } - return (JetExpression) element; + return (JetExpression)element; } public static class IntroduceRefactoringException extends Exception { @@ -209,5 +216,4 @@ public class JetRefactoringUtil { return myMessage; } } - } diff --git a/idea/src/org/jetbrains/jet/plugin/refactoring/introduceVariable/JetIntroduceVariableHandler.java b/idea/src/org/jetbrains/jet/plugin/refactoring/introduceVariable/JetIntroduceVariableHandler.java index 0469eaa0675..7305fa72482 100644 --- a/idea/src/org/jetbrains/jet/plugin/refactoring/introduceVariable/JetIntroduceVariableHandler.java +++ b/idea/src/org/jetbrains/jet/plugin/refactoring/introduceVariable/JetIntroduceVariableHandler.java @@ -34,14 +34,15 @@ import com.intellij.refactoring.introduce.inplace.OccurrencesChooser; import com.intellij.refactoring.util.CommonRefactoringUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import org.jetbrains.jet.analyzer.AnalyzerFacadeWithCache; import org.jetbrains.jet.lang.descriptors.DeclarationDescriptor; import org.jetbrains.jet.lang.psi.*; import org.jetbrains.jet.lang.resolve.BindingContext; import org.jetbrains.jet.lang.resolve.java.AnalyzerFacadeForJVM; -import org.jetbrains.jet.lang.types.lang.JetStandardLibrary; import org.jetbrains.jet.lang.types.JetType; import org.jetbrains.jet.lang.types.NamespaceType; import org.jetbrains.jet.lang.types.checker.JetTypeChecker; +import org.jetbrains.jet.lang.types.lang.JetStandardLibrary; import org.jetbrains.jet.lexer.JetTokens; import org.jetbrains.jet.plugin.refactoring.*; @@ -65,7 +66,8 @@ public class JetIntroduceVariableHandler extends JetIntroduceHandlerBase { }; try { JetRefactoringUtil.selectExpression(editor, file, callback); - } catch (JetRefactoringUtil.IntroduceRefactoringException e) { + } + catch (JetRefactoringUtil.IntroduceRefactoringException e) { showErrorHint(project, editor, e.getMessage()); } } @@ -76,34 +78,37 @@ public class JetIntroduceVariableHandler extends JetIntroduceHandlerBase { return; } if (_expression.getParent() instanceof JetParenthesizedExpression) { - _expression = (JetExpression) _expression.getParent(); + _expression = (JetExpression)_expression.getParent(); } final JetExpression expression = _expression; if (expression.getParent() instanceof JetQualifiedExpression) { - JetQualifiedExpression qualifiedExpression = (JetQualifiedExpression) expression.getParent(); + JetQualifiedExpression qualifiedExpression = (JetQualifiedExpression)expression.getParent(); if (qualifiedExpression.getReceiverExpression() != expression) { showErrorHint(project, editor, JetRefactoringBundle.message("cannot.refactor.no.expression")); return; } - } else if (expression.getParent() instanceof JetCallElement || expression instanceof JetStatementExpression) { + } + else if (expression.getParent() instanceof JetCallElement || expression instanceof JetStatementExpression) { showErrorHint(project, editor, JetRefactoringBundle.message("cannot.refactor.no.expression")); return; - } else if (expression.getParent() instanceof JetOperationExpression) { - JetOperationExpression operationExpression = (JetOperationExpression) expression.getParent(); + } + else if (expression.getParent() instanceof JetOperationExpression) { + JetOperationExpression operationExpression = (JetOperationExpression)expression.getParent(); if (operationExpression.getOperationReference() == expression) { showErrorHint(project, editor, JetRefactoringBundle.message("cannot.refactor.no.expression")); return; } } - BindingContext bindingContext = AnalyzerFacadeForJVM.analyzeFileWithCache((JetFile) expression.getContainingFile(), - AnalyzerFacadeForJVM.SINGLE_DECLARATION_PROVIDER) - .getBindingContext(); + BindingContext bindingContext = AnalyzerFacadeForJVM.analyzeFileWithCache((JetFile)expression.getContainingFile(), + AnalyzerFacadeWithCache.SINGLE_DECLARATION_PROVIDER) + .getBindingContext(); final JetType expressionType = bindingContext.get(BindingContext.EXPRESSION_TYPE, expression); //can be null or error type if (expressionType instanceof NamespaceType) { showErrorHint(project, editor, JetRefactoringBundle.message("cannot.refactor.namespace.expression")); return; - } if (expressionType != null && - JetTypeChecker.INSTANCE.equalTypes(JetStandardLibrary.getInstance().getTuple0Type(), expressionType)) { + } + if (expressionType != null && + JetTypeChecker.INSTANCE.equalTypes(JetStandardLibrary.getInstance().getTuple0Type(), expressionType)) { showErrorHint(project, editor, JetRefactoringBundle.message("cannot.refactor.expression.has.unit.type")); return; } @@ -114,8 +119,8 @@ public class JetIntroduceVariableHandler extends JetIntroduceHandlerBase { return; } final boolean isInplaceAvailableOnDataContext = - editor.getSettings().isVariableInplaceRenameEnabled() && - !ApplicationManager.getApplication().isUnitTestMode(); + editor.getSettings().isVariableInplaceRenameEnabled() && + !ApplicationManager.getApplication().isUnitTestMode(); final ArrayList allOccurrences = findOccurrences(occurrenceContainer, expression); Pass callback = new Pass() { @Override @@ -125,10 +130,11 @@ public class JetIntroduceVariableHandler extends JetIntroduceHandlerBase { if (OccurrencesChooser.ReplaceChoice.ALL == replaceChoice) { if (allOccurrences.size() > 1) replaceOccurrence = true; allReplaces = allOccurrences; - } else { + } + else { allReplaces = Collections.singletonList(expression); } - + PsiElement commonParent = PsiTreeUtil.findCommonParent(allReplaces); PsiElement commonContainer = getContainer(commonParent); JetNameValidatorImpl validator = new JetNameValidatorImpl(commonContainer, @@ -142,8 +148,8 @@ public class JetIntroduceVariableHandler extends JetIntroduceHandlerBase { final ArrayList references = new ArrayList(); final Ref reference = new Ref(); final Runnable introduceRunnable = introduceVariable(project, expression, suggestedNames, allReplaces, commonContainer, - commonParent, replaceOccurrence, propertyRef, references, - reference); + commonParent, replaceOccurrence, propertyRef, references, + reference); final boolean finalReplaceOccurrence = replaceOccurrence; CommandProcessor.getInstance().executeCommand(project, new Runnable() { @Override @@ -156,13 +162,13 @@ public class JetIntroduceVariableHandler extends JetIntroduceHandlerBase { if (isInplaceAvailableOnDataContext) { PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument()); PsiDocumentManager.getInstance(project). - doPostponedOperationsAndUnblockDocument(editor.getDocument()); + doPostponedOperationsAndUnblockDocument(editor.getDocument()); JetInplaceVariableIntroducer variableIntroducer = - new JetInplaceVariableIntroducer(property, editor, project, INTRODUCE_VARIABLE, - references.toArray(new JetExpression[references.size()]), - reference.get(), finalReplaceOccurrence, - property, /*todo*/false, /*todo*/false, - expressionType); + new JetInplaceVariableIntroducer(property, editor, project, INTRODUCE_VARIABLE, + references.toArray(new JetExpression[references.size()]), + reference.get(), finalReplaceOccurrence, + property, /*todo*/false, /*todo*/false, + expressionType); variableIntroducer.performInplaceRefactoring(suggestedNamesSet); } } @@ -172,147 +178,163 @@ public class JetIntroduceVariableHandler extends JetIntroduceHandlerBase { }; if (isInplaceAvailableOnDataContext) { OccurrencesChooser.simpleChooser(editor). - showChooser(expression, allOccurrences, callback); - } else { + showChooser(expression, allOccurrences, callback); + } + else { callback.pass(OccurrencesChooser.ReplaceChoice.ALL); } } - - private static Runnable introduceVariable(final @NotNull Project project, final JetExpression expression, + + private static Runnable introduceVariable(final @NotNull Project project, final JetExpression expression, final String[] suggestedNames, final List allReplaces, final PsiElement commonContainer, final PsiElement commonParent, final boolean replaceOccurrence, final Ref propertyRef, - final ArrayList references, + final ArrayList references, final Ref reference) { - return new Runnable() { - @Override - public void run() { - String variableText = "val " + suggestedNames[0] + " = "; - if (expression instanceof JetParenthesizedExpression) { - JetParenthesizedExpression parenthesizedExpression = (JetParenthesizedExpression) expression; - JetExpression innerExpression = parenthesizedExpression.getExpression(); - if (innerExpression != null) variableText += innerExpression.getText(); - else variableText += expression.getText(); - } else variableText += expression.getText(); - JetProperty property = JetPsiFactory.createProperty(project, variableText); - if (property == null) return; - PsiElement anchor = calculateAnchor(commonParent, commonContainer, allReplaces); - if (anchor == null) return; - boolean needBraces = !(commonContainer instanceof JetBlockExpression || - commonContainer instanceof JetClassBody || - commonContainer instanceof JetClassInitializer); - if (!needBraces) { - property = (JetProperty) commonContainer.addBefore(property, anchor); - commonContainer.addBefore(JetPsiFactory.createWhiteSpace(project, "\n"), anchor); - } else { - JetExpression emptyBody = JetPsiFactory.createEmptyBody(project); - PsiElement firstChild = emptyBody.getFirstChild(); - emptyBody.addAfter(JetPsiFactory.createWhiteSpace(project, "\n"), firstChild); - if (replaceOccurrence && commonContainer != null) { - for (JetExpression replace : allReplaces) { - boolean isActualExpression = expression == replace; - JetExpression element = (JetExpression) replace.replace(JetPsiFactory.createExpression(project, suggestedNames[0])); - if (isActualExpression) reference.set(element); - } - PsiElement oldElement = commonContainer; - if (commonContainer instanceof JetWhenEntry) { - JetExpression body = ((JetWhenEntry) commonContainer).getExpression(); - if (body != null) { - oldElement = body; - } - } else if (commonContainer instanceof JetNamedFunction) { - JetExpression body = ((JetNamedFunction) commonContainer).getBodyExpression(); - if (body != null) { - oldElement = body; - } - } else if (commonContainer instanceof JetSecondaryConstructor) { - JetExpression body = ((JetSecondaryConstructor) commonContainer).getBodyExpression(); - if (body != null) { - oldElement = body; - } - } else if (commonContainer instanceof JetContainerNode) { - JetContainerNode container = (JetContainerNode) commonContainer; - PsiElement[] children = container.getChildren(); - for (PsiElement child : children) { - if (child instanceof JetExpression) { - oldElement = child; - } - } - } - //ugly logic to make sure we are working with right actual expression - JetExpression actualExpression = reference.get(); - int diff = actualExpression.getTextRange().getStartOffset() - oldElement.getTextRange().getStartOffset(); - String actualExpressionText = actualExpression.getText(); - PsiElement newElement = emptyBody.addAfter(oldElement, firstChild); - PsiElement elem = newElement.findElementAt(diff); - while (elem != null && !(elem instanceof JetExpression && - actualExpressionText.equals(elem.getText()))) { - elem = elem.getParent(); - } - if (elem != null) { - reference.set((JetExpression) elem); - } - emptyBody.addAfter(JetPsiFactory.createWhiteSpace(project, "\n"), firstChild); - property = (JetProperty) emptyBody.addAfter(property, firstChild); - emptyBody.addAfter(JetPsiFactory.createWhiteSpace(project, "\n"), firstChild); - actualExpression = reference.get(); - diff = actualExpression.getTextRange().getStartOffset() - emptyBody.getTextRange().getStartOffset(); - actualExpressionText = actualExpression.getText(); - emptyBody = (JetExpression) anchor.replace(emptyBody); - elem = emptyBody.findElementAt(diff); - while (elem != null && !(elem instanceof JetExpression && - actualExpressionText.equals(elem.getText()))) { - elem = elem.getParent(); - } - if (elem != null) { - reference.set((JetExpression) elem); - } - } else { - property = (JetProperty) emptyBody.addAfter(property, firstChild); - emptyBody.addAfter(JetPsiFactory.createWhiteSpace(project, "\n"), firstChild); - emptyBody = (JetExpression) anchor.replace(emptyBody); - } - for (PsiElement child : emptyBody.getChildren()) { - if (child instanceof JetProperty) { - property = (JetProperty) child; - } - } - if (commonContainer instanceof JetNamedFunction) { - //we should remove equals sign - JetNamedFunction function = (JetNamedFunction) commonContainer; - if (!function.hasDeclaredReturnType()) { - //todo: add return type - } - function.getEqualsToken().delete(); - } else if (commonContainer instanceof JetContainerNode) { - JetContainerNode node = (JetContainerNode) commonContainer; - if (node.getParent() instanceof JetIfExpression) { - PsiElement next = node.getNextSibling(); - if (next != null) { - PsiElement nextnext = next.getNextSibling(); - if (nextnext != null && nextnext.getNode().getElementType() == JetTokens.ELSE_KEYWORD) { - if (next instanceof PsiWhiteSpace) { - next.replace(JetPsiFactory.createWhiteSpace(project, " ")) ; - } - } - } - } - } - } - for (JetExpression replace : allReplaces) { - if (replaceOccurrence && !needBraces) { - boolean isActualExpression = expression == replace; - JetExpression element = (JetExpression) replace.replace(JetPsiFactory.createExpression(project, suggestedNames[0])); - references.add(element); - if (isActualExpression) reference.set(element); - } else if (!needBraces) { - replace.delete(); - } - } - propertyRef.set(property); - } - }; + return new Runnable() { + @Override + public void run() { + String variableText = "val " + suggestedNames[0] + " = "; + if (expression instanceof JetParenthesizedExpression) { + JetParenthesizedExpression parenthesizedExpression = (JetParenthesizedExpression)expression; + JetExpression innerExpression = parenthesizedExpression.getExpression(); + if (innerExpression != null) { + variableText += innerExpression.getText(); + } + else { + variableText += expression.getText(); + } + } + else { + variableText += expression.getText(); + } + JetProperty property = JetPsiFactory.createProperty(project, variableText); + if (property == null) return; + PsiElement anchor = calculateAnchor(commonParent, commonContainer, allReplaces); + if (anchor == null) return; + boolean needBraces = !(commonContainer instanceof JetBlockExpression || + commonContainer instanceof JetClassBody || + commonContainer instanceof JetClassInitializer); + if (!needBraces) { + property = (JetProperty)commonContainer.addBefore(property, anchor); + commonContainer.addBefore(JetPsiFactory.createWhiteSpace(project, "\n"), anchor); + } + else { + JetExpression emptyBody = JetPsiFactory.createEmptyBody(project); + PsiElement firstChild = emptyBody.getFirstChild(); + emptyBody.addAfter(JetPsiFactory.createWhiteSpace(project, "\n"), firstChild); + if (replaceOccurrence && commonContainer != null) { + for (JetExpression replace : allReplaces) { + boolean isActualExpression = expression == replace; + JetExpression element = + (JetExpression)replace.replace(JetPsiFactory.createExpression(project, suggestedNames[0])); + if (isActualExpression) reference.set(element); + } + PsiElement oldElement = commonContainer; + if (commonContainer instanceof JetWhenEntry) { + JetExpression body = ((JetWhenEntry)commonContainer).getExpression(); + if (body != null) { + oldElement = body; + } + } + else if (commonContainer instanceof JetNamedFunction) { + JetExpression body = ((JetNamedFunction)commonContainer).getBodyExpression(); + if (body != null) { + oldElement = body; + } + } + else if (commonContainer instanceof JetSecondaryConstructor) { + JetExpression body = ((JetSecondaryConstructor)commonContainer).getBodyExpression(); + if (body != null) { + oldElement = body; + } + } + else if (commonContainer instanceof JetContainerNode) { + JetContainerNode container = (JetContainerNode)commonContainer; + PsiElement[] children = container.getChildren(); + for (PsiElement child : children) { + if (child instanceof JetExpression) { + oldElement = child; + } + } + } + //ugly logic to make sure we are working with right actual expression + JetExpression actualExpression = reference.get(); + int diff = actualExpression.getTextRange().getStartOffset() - oldElement.getTextRange().getStartOffset(); + String actualExpressionText = actualExpression.getText(); + PsiElement newElement = emptyBody.addAfter(oldElement, firstChild); + PsiElement elem = newElement.findElementAt(diff); + while (elem != null && !(elem instanceof JetExpression && + actualExpressionText.equals(elem.getText()))) { + elem = elem.getParent(); + } + if (elem != null) { + reference.set((JetExpression)elem); + } + emptyBody.addAfter(JetPsiFactory.createWhiteSpace(project, "\n"), firstChild); + property = (JetProperty)emptyBody.addAfter(property, firstChild); + emptyBody.addAfter(JetPsiFactory.createWhiteSpace(project, "\n"), firstChild); + actualExpression = reference.get(); + diff = actualExpression.getTextRange().getStartOffset() - emptyBody.getTextRange().getStartOffset(); + actualExpressionText = actualExpression.getText(); + emptyBody = (JetExpression)anchor.replace(emptyBody); + elem = emptyBody.findElementAt(diff); + while (elem != null && !(elem instanceof JetExpression && + actualExpressionText.equals(elem.getText()))) { + elem = elem.getParent(); + } + if (elem != null) { + reference.set((JetExpression)elem); + } + } + else { + property = (JetProperty)emptyBody.addAfter(property, firstChild); + emptyBody.addAfter(JetPsiFactory.createWhiteSpace(project, "\n"), firstChild); + emptyBody = (JetExpression)anchor.replace(emptyBody); + } + for (PsiElement child : emptyBody.getChildren()) { + if (child instanceof JetProperty) { + property = (JetProperty)child; + } + } + if (commonContainer instanceof JetNamedFunction) { + //we should remove equals sign + JetNamedFunction function = (JetNamedFunction)commonContainer; + if (!function.hasDeclaredReturnType()) { + //todo: add return type + } + function.getEqualsToken().delete(); + } + else if (commonContainer instanceof JetContainerNode) { + JetContainerNode node = (JetContainerNode)commonContainer; + if (node.getParent() instanceof JetIfExpression) { + PsiElement next = node.getNextSibling(); + if (next != null) { + PsiElement nextnext = next.getNextSibling(); + if (nextnext != null && nextnext.getNode().getElementType() == JetTokens.ELSE_KEYWORD) { + if (next instanceof PsiWhiteSpace) { + next.replace(JetPsiFactory.createWhiteSpace(project, " ")); + } + } + } + } + } + } + for (JetExpression replace : allReplaces) { + if (replaceOccurrence && !needBraces) { + boolean isActualExpression = expression == replace; + JetExpression element = (JetExpression)replace.replace(JetPsiFactory.createExpression(project, suggestedNames[0])); + references.add(element); + if (isActualExpression) reference.set(element); + } + else if (!needBraces) { + replace.delete(); + } + } + propertyRef.set(property); + } + }; } private static PsiElement calculateAnchor(PsiElement commonParent, PsiElement commonContainer, @@ -322,7 +344,8 @@ public class JetIntroduceVariableHandler extends JetIntroduceHandlerBase { while (anchor.getParent() != commonContainer) { anchor = anchor.getParent(); } - } else { + } + else { anchor = commonContainer.getFirstChild(); int startOffset = commonContainer.getTextRange().getEndOffset(); for (JetExpression expr : allReplaces) { @@ -339,7 +362,7 @@ public class JetIntroduceVariableHandler extends JetIntroduceHandlerBase { private static ArrayList findOccurrences(PsiElement occurrenceContainer, @NotNull JetExpression expression) { if (expression instanceof JetParenthesizedExpression) { - JetParenthesizedExpression parenthesizedExpression = (JetParenthesizedExpression) expression; + JetParenthesizedExpression parenthesizedExpression = (JetParenthesizedExpression)expression; JetExpression innerExpression = parenthesizedExpression.getExpression(); if (innerExpression != null) { expression = innerExpression; @@ -349,9 +372,9 @@ public class JetIntroduceVariableHandler extends JetIntroduceHandlerBase { final ArrayList result = new ArrayList(); - final BindingContext bindingContext = AnalyzerFacadeForJVM.analyzeFileWithCache((JetFile) expression.getContainingFile(), - AnalyzerFacadeForJVM.SINGLE_DECLARATION_PROVIDER) - .getBindingContext(); + final BindingContext bindingContext = AnalyzerFacadeForJVM.analyzeFileWithCache((JetFile)expression.getContainingFile(), + AnalyzerFacadeWithCache.SINGLE_DECLARATION_PROVIDER) + .getBindingContext(); JetVisitorVoid visitor = new JetVisitorVoid() { @Override @@ -368,26 +391,36 @@ public class JetIntroduceVariableHandler extends JetIntroduceHandlerBase { if (element1.getNode().getElementType() == JetTokens.IDENTIFIER && element2.getNode().getElementType() == JetTokens.IDENTIFIER) { if (element1.getParent() instanceof JetSimpleNameExpression && - element2.getParent() instanceof JetSimpleNameExpression) { - JetSimpleNameExpression expr1 = (JetSimpleNameExpression) element1.getParent(); - JetSimpleNameExpression expr2 = (JetSimpleNameExpression) element2.getParent(); + element2.getParent() instanceof JetSimpleNameExpression) { + JetSimpleNameExpression expr1 = (JetSimpleNameExpression)element1.getParent(); + JetSimpleNameExpression expr2 = (JetSimpleNameExpression)element2.getParent(); DeclarationDescriptor descr1 = bindingContext.get(BindingContext.REFERENCE_TARGET, expr1); DeclarationDescriptor descr2 = bindingContext.get(BindingContext.REFERENCE_TARGET, expr2); - if (descr1 != descr2) return 1; - else return 0; + if (descr1 != descr2) { + return 1; + } + else { + return 0; + } } } - if (!element1.textMatches(element2)) return 1; - else return 0; + if (!element1.textMatches(element2)) { + return 1; + } + else { + return 0; + } } }, null, false)) { PsiElement parent = expression.getParent(); if (parent instanceof JetParenthesizedExpression) { - result.add((JetParenthesizedExpression) parent); - } else { + result.add((JetParenthesizedExpression)parent); + } + else { result.add(expression); } - } else { + } + else { super.visitExpression(expression); } } @@ -399,25 +432,28 @@ public class JetIntroduceVariableHandler extends JetIntroduceHandlerBase { @Nullable private static PsiElement getContainer(PsiElement place) { if (place instanceof JetBlockExpression || place instanceof JetClassBody || - place instanceof JetClassInitializer) { + place instanceof JetClassInitializer) { return place; } while (place != null) { PsiElement parent = place.getParent(); if (parent instanceof JetContainerNode) { - if (!isBadContainerNode((JetContainerNode) parent, place)) { + if (!isBadContainerNode((JetContainerNode)parent, place)) { return parent; } - } if (parent instanceof JetBlockExpression || parent instanceof JetWhenEntry || + } + if (parent instanceof JetBlockExpression || parent instanceof JetWhenEntry || parent instanceof JetClassBody || parent instanceof JetClassInitializer) { return parent; - } else if (parent instanceof JetNamedFunction) { - JetNamedFunction function = (JetNamedFunction) parent; + } + else if (parent instanceof JetNamedFunction) { + JetNamedFunction function = (JetNamedFunction)parent; if (function.getBodyExpression() == place) { return parent; } - } else if (parent instanceof JetSecondaryConstructor) { - JetSecondaryConstructor secondaryConstructor = (JetSecondaryConstructor) parent; + } + else if (parent instanceof JetSecondaryConstructor) { + JetSecondaryConstructor secondaryConstructor = (JetSecondaryConstructor)parent; if (secondaryConstructor.getBodyExpression() == place) { return parent; } @@ -426,13 +462,14 @@ public class JetIntroduceVariableHandler extends JetIntroduceHandlerBase { } return null; } - + private static boolean isBadContainerNode(JetContainerNode parent, PsiElement place) { if (parent.getParent() instanceof JetIfExpression && - ((JetIfExpression) parent.getParent()).getCondition() == place) { + ((JetIfExpression)parent.getParent()).getCondition() == place) { return true; - } else if (parent.getParent() instanceof JetLoopExpression && - ((JetLoopExpression) parent.getParent()).getBody() != place) { + } + else if (parent.getParent() instanceof JetLoopExpression && + ((JetLoopExpression)parent.getParent()).getBody() != place) { return true; } return false; @@ -444,27 +481,36 @@ public class JetIntroduceVariableHandler extends JetIntroduceHandlerBase { while (place != null) { PsiElement parent = place.getParent(); if (parent instanceof JetContainerNode) { - if (!(place instanceof JetBlockExpression) && !isBadContainerNode((JetContainerNode) parent, place)) { + if (!(place instanceof JetBlockExpression) && !isBadContainerNode((JetContainerNode)parent, place)) { result = parent; } - } else if (parent instanceof JetClassBody || parent instanceof JetFile || parent instanceof JetClassInitializer) { - if (result == null) return parent; - else return result; - } else if (parent instanceof JetBlockExpression) { + } + else if (parent instanceof JetClassBody || parent instanceof JetFile || parent instanceof JetClassInitializer) { + if (result == null) { + return parent; + } + else { + return result; + } + } + else if (parent instanceof JetBlockExpression) { result = parent; - } else if (parent instanceof JetWhenEntry ) { + } + else if (parent instanceof JetWhenEntry) { if (!(place instanceof JetBlockExpression)) { result = parent; } - } else if (parent instanceof JetNamedFunction) { - JetNamedFunction function = (JetNamedFunction) parent; + } + else if (parent instanceof JetNamedFunction) { + JetNamedFunction function = (JetNamedFunction)parent; if (function.getBodyExpression() == place) { if (!(place instanceof JetBlockExpression)) { result = parent; } } - } else if (parent instanceof JetSecondaryConstructor) { - JetSecondaryConstructor secondaryConstructor = (JetSecondaryConstructor) parent; + } + else if (parent instanceof JetSecondaryConstructor) { + JetSecondaryConstructor secondaryConstructor = (JetSecondaryConstructor)parent; if (secondaryConstructor.getBodyExpression() == place) { if (!(place instanceof JetBlockExpression)) { result = parent; From 1eb38baa28431c7816270e1e9e666d5d69b08ff5 Mon Sep 17 00:00:00 2001 From: "Pavel V. Talanov" Date: Wed, 4 Apr 2012 17:43:31 +0400 Subject: [PATCH 04/12] Introduce AnalyzerFacadeProvider --- .../project/AnalyzerFacadeProvider.java | 53 +++++++++++++++++++ .../project/WholeProjectAnalyzerFacade.java | 8 +-- 2 files changed, 57 insertions(+), 4 deletions(-) create mode 100644 idea/src/org/jetbrains/jet/plugin/project/AnalyzerFacadeProvider.java diff --git a/idea/src/org/jetbrains/jet/plugin/project/AnalyzerFacadeProvider.java b/idea/src/org/jetbrains/jet/plugin/project/AnalyzerFacadeProvider.java new file mode 100644 index 00000000000..e1b1f54f8ea --- /dev/null +++ b/idea/src/org/jetbrains/jet/plugin/project/AnalyzerFacadeProvider.java @@ -0,0 +1,53 @@ +/* + * Copyright 2010-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jetbrains.jet.plugin.project; + +import com.intellij.openapi.project.Project; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.jet.analyzer.AnalyzerFacade; +import org.jetbrains.jet.analyzer.AnalyzerFacadeWithCache; +import org.jetbrains.jet.lang.psi.JetFile; +import org.jetbrains.jet.lang.resolve.java.AnalyzerFacadeForJVM; + +/** + * @author Pavel Talanov + */ +public final class AnalyzerFacadeProvider { + + private AnalyzerFacadeProvider() { + } + + @NotNull + public static AnalyzerFacade getAnalyzerFacadeForFile(@NotNull JetFile file) { + return AnalyzerFacadeForJVM.INSTANCE; + } + + @NotNull + public static AnalyzerFacadeWithCache getAnalyzerFacadeWithCacheForFile(@NotNull JetFile file) { + return AnalyzerFacadeWithCache.getInstance(getAnalyzerFacadeForFile(file)); + } + + @NotNull + public static AnalyzerFacade getAnalyzerFacadeForProject(@NotNull Project project) { + return AnalyzerFacadeForJVM.INSTANCE; + } + + @NotNull + public static AnalyzerFacadeWithCache getAnalyzerFacadeWithCacheForProject(@NotNull Project project) { + return AnalyzerFacadeWithCache.getInstance(getAnalyzerFacadeForProject(project)); + } +} diff --git a/idea/src/org/jetbrains/jet/plugin/project/WholeProjectAnalyzerFacade.java b/idea/src/org/jetbrains/jet/plugin/project/WholeProjectAnalyzerFacade.java index 88d478585c1..51288c1ad41 100644 --- a/idea/src/org/jetbrains/jet/plugin/project/WholeProjectAnalyzerFacade.java +++ b/idea/src/org/jetbrains/jet/plugin/project/WholeProjectAnalyzerFacade.java @@ -21,7 +21,6 @@ import com.intellij.psi.search.GlobalSearchScope; import org.jetbrains.annotations.NotNull; import org.jetbrains.jet.analyzer.AnalyzeExhaust; import org.jetbrains.jet.lang.psi.JetFile; -import org.jetbrains.jet.lang.resolve.java.AnalyzerFacadeForJVM; import org.jetbrains.jet.lang.resolve.java.JetFilesProvider; /** @@ -35,14 +34,15 @@ public final class WholeProjectAnalyzerFacade { private WholeProjectAnalyzerFacade() { } - @NotNull public static AnalyzeExhaust analyzeProjectWithCacheOnAFile(@NotNull JetFile file) { - return AnalyzerFacadeForJVM.analyzeFileWithCache(file, JetFilesProvider.getInstance(file.getProject()).sampleToAllFilesInModule()); + return AnalyzerFacadeProvider.getAnalyzerFacadeWithCacheForFile(file) + .analyzeFileWithCache(file, JetFilesProvider.getInstance(file.getProject()).sampleToAllFilesInModule()); } @NotNull public static AnalyzeExhaust analyzeProjectWithCache(@NotNull Project project, @NotNull GlobalSearchScope scope) { - return AnalyzerFacadeForJVM.analyzeProjectWithCache(project, JetFilesProvider.getInstance(project).allInScope(scope)); + return AnalyzerFacadeProvider.getAnalyzerFacadeWithCacheForProject(project) + .analyzeProjectWithCache(project, JetFilesProvider.getInstance(project).allInScope(scope)); } } From 3c9c7e6ede8e21c54fc6ec4b6823cc051857d28b Mon Sep 17 00:00:00 2001 From: "Pavel V. Talanov" Date: Wed, 4 Apr 2012 19:25:30 +0400 Subject: [PATCH 05/12] Introduce AnalyzeSingleFileUtil. --- .../libraries/JetSourceNavigationHelper.java | 7 +-- .../JetFunctionParameterInfoHandler.java | 10 ++--- .../plugin/project/AnalyzeSingleFileUtil.java | 43 +++++++++++++++++++ .../quickfix/ChangeVariableMutabilityFix.java | 7 +-- .../plugin/quickfix/ImportInsertHelper.java | 6 ++- .../jet/plugin/quickfix/QuickFixUtil.java | 6 +-- .../plugin/refactoring/JetNameSuggester.java | 6 +-- .../refactoring/JetRefactoringUtil.java | 6 +-- .../JetIntroduceVariableHandler.java | 10 ++--- 9 files changed, 69 insertions(+), 32 deletions(-) create mode 100644 idea/src/org/jetbrains/jet/plugin/project/AnalyzeSingleFileUtil.java diff --git a/idea/src/org/jetbrains/jet/plugin/libraries/JetSourceNavigationHelper.java b/idea/src/org/jetbrains/jet/plugin/libraries/JetSourceNavigationHelper.java index 8b8ee42afa7..fe7b2426437 100644 --- a/idea/src/org/jetbrains/jet/plugin/libraries/JetSourceNavigationHelper.java +++ b/idea/src/org/jetbrains/jet/plugin/libraries/JetSourceNavigationHelper.java @@ -32,15 +32,14 @@ import com.intellij.psi.util.PsiTreeUtil; import jet.Tuple2; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.jetbrains.jet.analyzer.AnalyzerFacadeWithCache; import org.jetbrains.jet.lang.descriptors.*; import org.jetbrains.jet.lang.psi.*; import org.jetbrains.jet.lang.resolve.BindingContext; import org.jetbrains.jet.lang.resolve.FqName; -import org.jetbrains.jet.lang.resolve.java.AnalyzerFacadeForJVM; import org.jetbrains.jet.lang.resolve.scopes.JetScope; import org.jetbrains.jet.lang.resolve.scopes.receivers.ReceiverDescriptor; import org.jetbrains.jet.lang.types.JetType; +import org.jetbrains.jet.plugin.project.AnalyzeSingleFileUtil; import org.jetbrains.jet.resolve.DescriptorRenderer; import org.jetbrains.jet.util.slicedmap.WritableSlice; @@ -67,9 +66,7 @@ public class JetSourceNavigationHelper { } final List libraryFiles = findAllSourceFilesWhichContainIdentifier(declaration); for (JetFile libraryFile : libraryFiles) { - BindingContext bindingContext = AnalyzerFacadeForJVM.analyzeFileWithCache(libraryFile, - AnalyzerFacadeWithCache.SINGLE_DECLARATION_PROVIDER) - .getBindingContext(); + BindingContext bindingContext = AnalyzeSingleFileUtil.analyzeSingleFileWithCache(libraryFile).getBindingContext(); D descriptor = bindingContext.get(slice, fqName); if (descriptor != null) { return new Tuple2(bindingContext, descriptor); diff --git a/idea/src/org/jetbrains/jet/plugin/parameterInfo/JetFunctionParameterInfoHandler.java b/idea/src/org/jetbrains/jet/plugin/parameterInfo/JetFunctionParameterInfoHandler.java index 78dc31c3e2b..4e903726007 100644 --- a/idea/src/org/jetbrains/jet/plugin/parameterInfo/JetFunctionParameterInfoHandler.java +++ b/idea/src/org/jetbrains/jet/plugin/parameterInfo/JetFunctionParameterInfoHandler.java @@ -37,6 +37,7 @@ import org.jetbrains.jet.lang.resolve.scopes.JetScope; import org.jetbrains.jet.lang.types.JetType; import org.jetbrains.jet.lang.types.checker.JetTypeChecker; import org.jetbrains.jet.lexer.JetTokens; +import org.jetbrains.jet.plugin.project.AnalyzeSingleFileUtil; import org.jetbrains.jet.resolve.DescriptorRenderer; import java.awt.*; @@ -196,9 +197,7 @@ public class JetFunctionParameterInfoHandler implements JetValueArgumentList argumentList = (JetValueArgumentList)parameterOwner; if (descriptor instanceof FunctionDescriptor) { JetFile file = (JetFile)argumentList.getContainingFile(); - BindingContext bindingContext = - AnalyzerFacadeForJVM.analyzeFileWithCache(file, AnalyzerFacadeWithCache.SINGLE_DECLARATION_PROVIDER) - .getBindingContext(); + BindingContext bindingContext = AnalyzeSingleFileUtil.getContextForSingleFile(file); FunctionDescriptor functionDescriptor = (FunctionDescriptor)descriptor; StringBuilder builder = new StringBuilder(); List valueParameters = functionDescriptor.getValueParameters(); @@ -357,10 +356,7 @@ public class JetFunctionParameterInfoHandler implements else { return null; } - BindingContext bindingContext = AnalyzerFacadeForJVM.analyzeFileWithCache( - (JetFile)file, - AnalyzerFacadeWithCache.SINGLE_DECLARATION_PROVIDER) - .getBindingContext(); + BindingContext bindingContext = AnalyzeSingleFileUtil.getContextForSingleFile((JetFile)file); JetExpression calleeExpression = callExpression.getCalleeExpression(); if (calleeExpression == null) return null; JetSimpleNameExpression refExpression = null; diff --git a/idea/src/org/jetbrains/jet/plugin/project/AnalyzeSingleFileUtil.java b/idea/src/org/jetbrains/jet/plugin/project/AnalyzeSingleFileUtil.java new file mode 100644 index 00000000000..eb982ea2ca6 --- /dev/null +++ b/idea/src/org/jetbrains/jet/plugin/project/AnalyzeSingleFileUtil.java @@ -0,0 +1,43 @@ +/* + * Copyright 2010-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jetbrains.jet.plugin.project; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.jet.analyzer.AnalyzeExhaust; +import org.jetbrains.jet.analyzer.AnalyzerFacadeWithCache; +import org.jetbrains.jet.lang.psi.JetFile; +import org.jetbrains.jet.lang.resolve.BindingContext; + +/** + * @author Pavel Talanov + */ +public final class AnalyzeSingleFileUtil { + + private AnalyzeSingleFileUtil() { + } + + @NotNull + public static AnalyzeExhaust analyzeSingleFileWithCache(@NotNull JetFile file) { + return AnalyzerFacadeProvider.getAnalyzerFacadeWithCacheForFile(file) + .analyzeFileWithCache(file, AnalyzerFacadeWithCache.SINGLE_DECLARATION_PROVIDER); + } + + @NotNull + public static BindingContext getContextForSingleFile(@NotNull JetFile file) { + return analyzeSingleFileWithCache(file).getBindingContext(); + } +} diff --git a/idea/src/org/jetbrains/jet/plugin/quickfix/ChangeVariableMutabilityFix.java b/idea/src/org/jetbrains/jet/plugin/quickfix/ChangeVariableMutabilityFix.java index 96f36499b34..208c71b7934 100644 --- a/idea/src/org/jetbrains/jet/plugin/quickfix/ChangeVariableMutabilityFix.java +++ b/idea/src/org/jetbrains/jet/plugin/quickfix/ChangeVariableMutabilityFix.java @@ -34,6 +34,9 @@ import org.jetbrains.jet.lang.resolve.BindingContext; import org.jetbrains.jet.lang.resolve.BindingContextUtils; import org.jetbrains.jet.lang.resolve.java.AnalyzerFacadeForJVM; import org.jetbrains.jet.plugin.JetBundle; +import org.jetbrains.jet.plugin.project.AnalyzeSingleFileUtil; + +import static org.jetbrains.jet.plugin.project.AnalyzeSingleFileUtil.getContextForSingleFile; /** * @author svtk @@ -74,9 +77,7 @@ public class ChangeVariableMutabilityFix implements IntentionAction { if (property != null) return property; JetSimpleNameExpression simpleNameExpression = PsiTreeUtil.getParentOfType(elementAtCaret, JetSimpleNameExpression.class); if (simpleNameExpression != null) { - BindingContext bindingContext = - AnalyzerFacadeForJVM.analyzeFileWithCache(file, AnalyzerFacadeWithCache.SINGLE_DECLARATION_PROVIDER) - .getBindingContext(); + BindingContext bindingContext = getContextForSingleFile(file); VariableDescriptor descriptor = BindingContextUtils.extractVariableDescriptorIfAny(bindingContext, simpleNameExpression, true); if (descriptor != null) { PsiElement declaration = bindingContext.get(BindingContext.DESCRIPTOR_TO_DECLARATION, descriptor); diff --git a/idea/src/org/jetbrains/jet/plugin/quickfix/ImportInsertHelper.java b/idea/src/org/jetbrains/jet/plugin/quickfix/ImportInsertHelper.java index ed321599c54..1b3f90342d2 100644 --- a/idea/src/org/jetbrains/jet/plugin/quickfix/ImportInsertHelper.java +++ b/idea/src/org/jetbrains/jet/plugin/quickfix/ImportInsertHelper.java @@ -34,10 +34,13 @@ import org.jetbrains.jet.lang.resolve.java.JavaDescriptorResolver; import org.jetbrains.jet.lang.types.ErrorUtils; import org.jetbrains.jet.lang.types.JetType; import org.jetbrains.jet.plugin.JetPluginUtil; +import org.jetbrains.jet.plugin.project.AnalyzeSingleFileUtil; import org.jetbrains.jet.util.QualifiedNamesUtil; import java.util.List; +import static org.jetbrains.jet.plugin.project.AnalyzeSingleFileUtil.getContextForSingleFile; + /** * @author svtk */ @@ -55,8 +58,7 @@ public class ImportInsertHelper { if (JetPluginUtil.checkTypeIsStandard(type, file.getProject()) || ErrorUtils.isErrorType(type)) { return; } - BindingContext bindingContext = AnalyzerFacadeForJVM.analyzeFileWithCache(file, AnalyzerFacadeWithCache.SINGLE_DECLARATION_PROVIDER) - .getBindingContext(); + BindingContext bindingContext = getContextForSingleFile(file); PsiElement element = bindingContext.get(BindingContext.DESCRIPTOR_TO_DECLARATION, type.getMemberScope().getContainingDeclaration()); if (element != null && element.getContainingFile() == file) { //declaration is in the same file, so no import is needed return; diff --git a/idea/src/org/jetbrains/jet/plugin/quickfix/QuickFixUtil.java b/idea/src/org/jetbrains/jet/plugin/quickfix/QuickFixUtil.java index 169e9617d54..5ddf98566e1 100644 --- a/idea/src/org/jetbrains/jet/plugin/quickfix/QuickFixUtil.java +++ b/idea/src/org/jetbrains/jet/plugin/quickfix/QuickFixUtil.java @@ -33,6 +33,8 @@ import org.jetbrains.jet.lang.resolve.java.AnalyzerFacadeForJVM; import org.jetbrains.jet.lang.types.DeferredType; import org.jetbrains.jet.lang.types.JetType; +import static org.jetbrains.jet.plugin.project.AnalyzeSingleFileUtil.getContextForSingleFile; + /** * @author svtk */ @@ -57,9 +59,7 @@ public class QuickFixUtil { public static JetType getDeclarationReturnType(JetNamedDeclaration declaration) { PsiFile file = declaration.getContainingFile(); if (!(file instanceof JetFile)) return null; - BindingContext bindingContext = - AnalyzerFacadeForJVM.analyzeFileWithCache((JetFile)file, AnalyzerFacadeWithCache.SINGLE_DECLARATION_PROVIDER) - .getBindingContext(); + BindingContext bindingContext = getContextForSingleFile((JetFile) file); DeclarationDescriptor descriptor = bindingContext.get(BindingContext.DECLARATION_TO_DESCRIPTOR, declaration); if (!(descriptor instanceof CallableDescriptor)) return null; JetType type = ((CallableDescriptor)descriptor).getReturnType(); diff --git a/idea/src/org/jetbrains/jet/plugin/refactoring/JetNameSuggester.java b/idea/src/org/jetbrains/jet/plugin/refactoring/JetNameSuggester.java index b45fee942a8..2b4f44ec40c 100644 --- a/idea/src/org/jetbrains/jet/plugin/refactoring/JetNameSuggester.java +++ b/idea/src/org/jetbrains/jet/plugin/refactoring/JetNameSuggester.java @@ -36,6 +36,8 @@ import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; +import static org.jetbrains.jet.plugin.project.AnalyzeSingleFileUtil.getContextForSingleFile; + /** * User: Alefas * Date: 31.01.12 @@ -68,9 +70,7 @@ public class JetNameSuggester { public static String[] suggestNames(JetExpression expression, JetNameValidator validator) { ArrayList result = new ArrayList(); - BindingContext bindingContext = AnalyzerFacadeForJVM.analyzeFileWithCache((JetFile)expression.getContainingFile(), - AnalyzerFacadeWithCache.SINGLE_DECLARATION_PROVIDER) - .getBindingContext(); + BindingContext bindingContext = getContextForSingleFile((JetFile) expression.getContainingFile()); JetType jetType = bindingContext.get(BindingContext.EXPRESSION_TYPE, expression); if (jetType != null) { addNamesForType(result, jetType, validator); diff --git a/idea/src/org/jetbrains/jet/plugin/refactoring/JetRefactoringUtil.java b/idea/src/org/jetbrains/jet/plugin/refactoring/JetRefactoringUtil.java index 246e57711db..549f0c171d8 100644 --- a/idea/src/org/jetbrains/jet/plugin/refactoring/JetRefactoringUtil.java +++ b/idea/src/org/jetbrains/jet/plugin/refactoring/JetRefactoringUtil.java @@ -44,6 +44,8 @@ import java.awt.*; import java.util.ArrayList; import java.util.List; +import static org.jetbrains.jet.plugin.project.AnalyzeSingleFileUtil.getContextForSingleFile; + /** * User: Alefas * Date: 25.01.12 @@ -106,9 +108,7 @@ public class JetRefactoringUtil { } if (addExpression) { JetExpression expression = (JetExpression)element; - BindingContext bindingContext = AnalyzerFacadeForJVM.analyzeFileWithCache((JetFile)expression.getContainingFile(), - AnalyzerFacadeWithCache.SINGLE_DECLARATION_PROVIDER) - .getBindingContext(); + BindingContext bindingContext = getContextForSingleFile((JetFile)expression.getContainingFile()); JetType expressionType = bindingContext.get(BindingContext.EXPRESSION_TYPE, expression); if (expressionType == null || !(expressionType instanceof NamespaceType) && !JetTypeChecker.INSTANCE.equalTypes(JetStandardLibrary. diff --git a/idea/src/org/jetbrains/jet/plugin/refactoring/introduceVariable/JetIntroduceVariableHandler.java b/idea/src/org/jetbrains/jet/plugin/refactoring/introduceVariable/JetIntroduceVariableHandler.java index 7305fa72482..07583a8c957 100644 --- a/idea/src/org/jetbrains/jet/plugin/refactoring/introduceVariable/JetIntroduceVariableHandler.java +++ b/idea/src/org/jetbrains/jet/plugin/refactoring/introduceVariable/JetIntroduceVariableHandler.java @@ -48,6 +48,8 @@ import org.jetbrains.jet.plugin.refactoring.*; import java.util.*; +import static org.jetbrains.jet.plugin.project.AnalyzeSingleFileUtil.getContextForSingleFile; + /** * User: Alefas * Date: 25.01.12 @@ -99,9 +101,7 @@ public class JetIntroduceVariableHandler extends JetIntroduceHandlerBase { return; } } - BindingContext bindingContext = AnalyzerFacadeForJVM.analyzeFileWithCache((JetFile)expression.getContainingFile(), - AnalyzerFacadeWithCache.SINGLE_DECLARATION_PROVIDER) - .getBindingContext(); + BindingContext bindingContext = getContextForSingleFile((JetFile)expression.getContainingFile()); final JetType expressionType = bindingContext.get(BindingContext.EXPRESSION_TYPE, expression); //can be null or error type if (expressionType instanceof NamespaceType) { showErrorHint(project, editor, JetRefactoringBundle.message("cannot.refactor.namespace.expression")); @@ -372,9 +372,7 @@ public class JetIntroduceVariableHandler extends JetIntroduceHandlerBase { final ArrayList result = new ArrayList(); - final BindingContext bindingContext = AnalyzerFacadeForJVM.analyzeFileWithCache((JetFile)expression.getContainingFile(), - AnalyzerFacadeWithCache.SINGLE_DECLARATION_PROVIDER) - .getBindingContext(); + final BindingContext bindingContext = getContextForSingleFile((JetFile)expression.getContainingFile()); JetVisitorVoid visitor = new JetVisitorVoid() { @Override From 2150789502c24391f7c3794f8837f3fda91f4395 Mon Sep 17 00:00:00 2001 From: "Pavel V. Talanov" Date: Fri, 6 Apr 2012 17:39:24 +0400 Subject: [PATCH 06/12] AnalyzerFacadeForJS implements interface AnalyzerFacade. Delete analyzer*WithCache methods from AnalyzerFacadeForJVM. Introduce JsModuleDetector. Move AnalyzerFacadeWithCache to idea module. Make it static, make it acquire facade through AnalyzerFacadeProvider. --- .../resolve/java/AnalyzerFacadeForJVM.java | 13 ----- .../JetDefaultModalityModifiersTest.java | 5 +- .../JetFunctionParameterInfoHandler.java | 2 - .../plugin/project/AnalyzeSingleFileUtil.java | 4 +- .../project/AnalyzerFacadeProvider.java | 18 +++---- .../project}/AnalyzerFacadeWithCache.java | 50 +++++++---------- .../jet/plugin/project/JsModuleDetector.java | 54 +++++++++++++++++++ .../project/WholeProjectAnalyzerFacade.java | 8 +-- .../quickfix/ChangeVariableMutabilityFix.java | 3 -- .../plugin/quickfix/ImportInsertHelper.java | 3 -- .../jet/plugin/quickfix/QuickFixUtil.java | 4 +- .../plugin/refactoring/JetNameSuggester.java | 4 +- .../refactoring/JetRefactoringUtil.java | 2 - .../JetIntroduceVariableHandler.java | 2 - .../k2js/analyze/AnalyzerFacadeForJS.java | 26 +++++++-- .../org/jetbrains/k2js/config/IDEAConfig.java | 5 ++ .../jetbrains/k2js/facade/K2JSTranslator.java | 9 ++-- 17 files changed, 119 insertions(+), 93 deletions(-) rename {compiler/frontend/src/org/jetbrains/jet/analyzer => idea/src/org/jetbrains/jet/plugin/project}/AnalyzerFacadeWithCache.java (75%) create mode 100644 idea/src/org/jetbrains/jet/plugin/project/JsModuleDetector.java diff --git a/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/AnalyzerFacadeForJVM.java b/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/AnalyzerFacadeForJVM.java index 53f2c2aac59..f867ab0dc3e 100644 --- a/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/AnalyzerFacadeForJVM.java +++ b/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/AnalyzerFacadeForJVM.java @@ -20,11 +20,9 @@ import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiFile; -import com.intellij.util.Function; import org.jetbrains.annotations.NotNull; import org.jetbrains.jet.analyzer.AnalyzeExhaust; import org.jetbrains.jet.analyzer.AnalyzerFacade; -import org.jetbrains.jet.analyzer.AnalyzerFacadeWithCache; import org.jetbrains.jet.di.InjectorForTopDownAnalyzerForJvm; import org.jetbrains.jet.lang.cfg.pseudocode.JetControlFlowDataTraceFactory; import org.jetbrains.jet.lang.descriptors.ModuleDescriptor; @@ -103,15 +101,4 @@ public enum AnalyzerFacadeForJVM implements AnalyzerFacade { return analyzeFilesWithJavaIntegration(project, files, Predicates.alwaysFalse(), JetControlFlowDataTraceFactory.EMPTY, CompilerSpecialMode.REGULAR); } - - @NotNull - public static AnalyzeExhaust analyzeFileWithCache(@NotNull final JetFile file, - @NotNull final Function> declarationProvider) { - return AnalyzerFacadeWithCache.getInstance(INSTANCE).analyzeFileWithCache(file, declarationProvider); - } - - @NotNull - public static AnalyzeExhaust analyzeProjectWithCache(@NotNull final Project project, @NotNull final Collection files) { - return AnalyzerFacadeWithCache.getInstance(INSTANCE).analyzeProjectWithCache(project, files); - } } diff --git a/compiler/tests/org/jetbrains/jet/types/JetDefaultModalityModifiersTest.java b/compiler/tests/org/jetbrains/jet/types/JetDefaultModalityModifiersTest.java index 763e0dd1dc0..d8df9c689c0 100644 --- a/compiler/tests/org/jetbrains/jet/types/JetDefaultModalityModifiersTest.java +++ b/compiler/tests/org/jetbrains/jet/types/JetDefaultModalityModifiersTest.java @@ -19,8 +19,8 @@ package org.jetbrains.jet.types; import org.jetbrains.jet.JetLiteFixture; import org.jetbrains.jet.JetTestUtils; import org.jetbrains.jet.analyzer.AnalyzeExhaust; -import org.jetbrains.jet.analyzer.AnalyzerFacadeWithCache; import org.jetbrains.jet.di.InjectorForTests; +import org.jetbrains.jet.lang.cfg.pseudocode.JetControlFlowDataTraceFactory; import org.jetbrains.jet.lang.descriptors.*; import org.jetbrains.jet.lang.psi.*; import org.jetbrains.jet.lang.resolve.BindingContext; @@ -63,8 +63,7 @@ public class JetDefaultModalityModifiersTest extends JetLiteFixture { List declarations = file.getDeclarations(); JetDeclaration aClass = declarations.get(0); assert aClass instanceof JetClass; - AnalyzeExhaust bindingContext = - AnalyzerFacadeForJVM.analyzeFileWithCache(file, AnalyzerFacadeWithCache.SINGLE_DECLARATION_PROVIDER); + AnalyzeExhaust bindingContext = AnalyzerFacadeForJVM.analyzeOneFileWithJavaIntegration(file, JetControlFlowDataTraceFactory.EMPTY); DeclarationDescriptor classDescriptor = bindingContext.getBindingContext().get(BindingContext.DECLARATION_TO_DESCRIPTOR, aClass); WritableScopeImpl scope = new WritableScopeImpl(libraryScope, root, RedeclarationHandler.DO_NOTHING); diff --git a/idea/src/org/jetbrains/jet/plugin/parameterInfo/JetFunctionParameterInfoHandler.java b/idea/src/org/jetbrains/jet/plugin/parameterInfo/JetFunctionParameterInfoHandler.java index 4e903726007..bf076cf3a07 100644 --- a/idea/src/org/jetbrains/jet/plugin/parameterInfo/JetFunctionParameterInfoHandler.java +++ b/idea/src/org/jetbrains/jet/plugin/parameterInfo/JetFunctionParameterInfoHandler.java @@ -26,13 +26,11 @@ import com.intellij.psi.PsiReference; import com.intellij.psi.tree.IElementType; import com.intellij.util.ArrayUtil; import org.jetbrains.annotations.NotNull; -import org.jetbrains.jet.analyzer.AnalyzerFacadeWithCache; import org.jetbrains.jet.compiler.TipsManager; import org.jetbrains.jet.lang.descriptors.*; import org.jetbrains.jet.lang.psi.*; import org.jetbrains.jet.lang.resolve.BindingContext; import org.jetbrains.jet.lang.resolve.JetVisibilityChecker; -import org.jetbrains.jet.lang.resolve.java.AnalyzerFacadeForJVM; import org.jetbrains.jet.lang.resolve.scopes.JetScope; import org.jetbrains.jet.lang.types.JetType; import org.jetbrains.jet.lang.types.checker.JetTypeChecker; diff --git a/idea/src/org/jetbrains/jet/plugin/project/AnalyzeSingleFileUtil.java b/idea/src/org/jetbrains/jet/plugin/project/AnalyzeSingleFileUtil.java index eb982ea2ca6..21d2fdb097e 100644 --- a/idea/src/org/jetbrains/jet/plugin/project/AnalyzeSingleFileUtil.java +++ b/idea/src/org/jetbrains/jet/plugin/project/AnalyzeSingleFileUtil.java @@ -18,7 +18,6 @@ package org.jetbrains.jet.plugin.project; import org.jetbrains.annotations.NotNull; import org.jetbrains.jet.analyzer.AnalyzeExhaust; -import org.jetbrains.jet.analyzer.AnalyzerFacadeWithCache; import org.jetbrains.jet.lang.psi.JetFile; import org.jetbrains.jet.lang.resolve.BindingContext; @@ -32,8 +31,7 @@ public final class AnalyzeSingleFileUtil { @NotNull public static AnalyzeExhaust analyzeSingleFileWithCache(@NotNull JetFile file) { - return AnalyzerFacadeProvider.getAnalyzerFacadeWithCacheForFile(file) - .analyzeFileWithCache(file, AnalyzerFacadeWithCache.SINGLE_DECLARATION_PROVIDER); + return AnalyzerFacadeWithCache.analyzeFileWithCache(file, AnalyzerFacadeWithCache.SINGLE_DECLARATION_PROVIDER); } @NotNull diff --git a/idea/src/org/jetbrains/jet/plugin/project/AnalyzerFacadeProvider.java b/idea/src/org/jetbrains/jet/plugin/project/AnalyzerFacadeProvider.java index e1b1f54f8ea..c6a6dd4d2c1 100644 --- a/idea/src/org/jetbrains/jet/plugin/project/AnalyzerFacadeProvider.java +++ b/idea/src/org/jetbrains/jet/plugin/project/AnalyzerFacadeProvider.java @@ -19,9 +19,9 @@ package org.jetbrains.jet.plugin.project; import com.intellij.openapi.project.Project; import org.jetbrains.annotations.NotNull; import org.jetbrains.jet.analyzer.AnalyzerFacade; -import org.jetbrains.jet.analyzer.AnalyzerFacadeWithCache; import org.jetbrains.jet.lang.psi.JetFile; import org.jetbrains.jet.lang.resolve.java.AnalyzerFacadeForJVM; +import org.jetbrains.k2js.analyze.AnalyzerFacadeForJS; /** * @author Pavel Talanov @@ -33,21 +33,17 @@ public final class AnalyzerFacadeProvider { @NotNull public static AnalyzerFacade getAnalyzerFacadeForFile(@NotNull JetFile file) { + if (JsModuleDetector.isJsProject(file.getProject())) { + return AnalyzerFacadeForJS.INSTANCE; + } return AnalyzerFacadeForJVM.INSTANCE; } - @NotNull - public static AnalyzerFacadeWithCache getAnalyzerFacadeWithCacheForFile(@NotNull JetFile file) { - return AnalyzerFacadeWithCache.getInstance(getAnalyzerFacadeForFile(file)); - } - @NotNull public static AnalyzerFacade getAnalyzerFacadeForProject(@NotNull Project project) { + if (JsModuleDetector.isJsProject(project)) { + return AnalyzerFacadeForJS.INSTANCE; + } return AnalyzerFacadeForJVM.INSTANCE; } - - @NotNull - public static AnalyzerFacadeWithCache getAnalyzerFacadeWithCacheForProject(@NotNull Project project) { - return AnalyzerFacadeWithCache.getInstance(getAnalyzerFacadeForProject(project)); - } } diff --git a/compiler/frontend/src/org/jetbrains/jet/analyzer/AnalyzerFacadeWithCache.java b/idea/src/org/jetbrains/jet/plugin/project/AnalyzerFacadeWithCache.java similarity index 75% rename from compiler/frontend/src/org/jetbrains/jet/analyzer/AnalyzerFacadeWithCache.java rename to idea/src/org/jetbrains/jet/plugin/project/AnalyzerFacadeWithCache.java index aee6ea5e4c8..3a8458faf4b 100644 --- a/compiler/frontend/src/org/jetbrains/jet/analyzer/AnalyzerFacadeWithCache.java +++ b/idea/src/org/jetbrains/jet/plugin/project/AnalyzerFacadeWithCache.java @@ -14,9 +14,8 @@ * limitations under the License. */ -package org.jetbrains.jet.analyzer; +package org.jetbrains.jet.plugin.project; -import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.progress.ProcessCanceledException; @@ -29,6 +28,7 @@ import com.intellij.psi.util.CachedValuesManager; import com.intellij.psi.util.PsiModificationTracker; import com.intellij.util.Function; import org.jetbrains.annotations.NotNull; +import org.jetbrains.jet.analyzer.AnalyzeExhaust; import org.jetbrains.jet.lang.cfg.pseudocode.JetControlFlowDataTraceFactory; import org.jetbrains.jet.lang.diagnostics.DiagnosticUtils; import org.jetbrains.jet.lang.diagnostics.Errors; @@ -41,9 +41,9 @@ import java.util.Collections; /** * @author Pavel Talanov */ -public class AnalyzerFacadeWithCache implements AnalyzerFacade { +public final class AnalyzerFacadeWithCache { - private static final Logger LOG = Logger.getInstance("org.jetbrains.jet.analyzer.AnalyzerFacadeWithCache"); + private static final Logger LOG = Logger.getInstance("org.jetbrains.jet.plugin.project.AnalyzerFacadeWithCache"); private final static Key> ANALYZE_EXHAUST = Key.create("ANALYZE_EXHAUST"); private static final Object lock = new Object(); @@ -54,16 +54,9 @@ public class AnalyzerFacadeWithCache implements AnalyzerFacade { } }; - public static AnalyzerFacadeWithCache getInstance(@NotNull AnalyzerFacade facade) { - return new AnalyzerFacadeWithCache(facade); + private AnalyzerFacadeWithCache() { } - @NotNull - private final AnalyzerFacade facade; - - private AnalyzerFacadeWithCache(@NotNull AnalyzerFacade facade) { - this.facade = facade; - } /** * Analyze project with string cache for given file. Given file will be fully analyzed. @@ -73,8 +66,8 @@ public class AnalyzerFacadeWithCache implements AnalyzerFacade { * @return */ @NotNull - public AnalyzeExhaust analyzeFileWithCache(@NotNull final JetFile file, - @NotNull final Function> declarationProvider) { + public static AnalyzeExhaust analyzeFileWithCache(@NotNull final JetFile file, + @NotNull final Function> declarationProvider) { // Need lock for getValue(), because parallel threads can start evaluation of compute() simultaneously synchronized (lock) { CachedValue bindingContextCachedValue = file.getUserData(ANALYZE_EXHAUST); @@ -84,10 +77,11 @@ public class AnalyzerFacadeWithCache implements AnalyzerFacade { @Override public Result compute() { try { - AnalyzeExhaust exhaust = facade.analyzeFiles(file.getProject(), - declarationProvider.fun(file), - Predicates.equalTo(file), - JetControlFlowDataTraceFactory.EMPTY); + AnalyzeExhaust exhaust = AnalyzerFacadeProvider.getAnalyzerFacadeForFile(file) + .analyzeFiles(file.getProject(), + declarationProvider.fun(file), + Predicates.equalTo(file), + JetControlFlowDataTraceFactory.EMPTY); return new Result(exhaust, PsiModificationTracker.MODIFICATION_COUNT); } catch (ProcessCanceledException e) { @@ -122,7 +116,7 @@ public class AnalyzerFacadeWithCache implements AnalyzerFacade { * Analyze project with string cache for the whole project. All given files will be analyzed only for descriptors. */ @NotNull - public AnalyzeExhaust analyzeProjectWithCache(@NotNull final Project project, @NotNull final Collection files) { + public static AnalyzeExhaust analyzeProjectWithCache(@NotNull final Project project, @NotNull final Collection files) { // Need lock for getValue(), because parallel threads can start evaluation of compute() simultaneously synchronized (lock) { CachedValue bindingContextCachedValue = project.getUserData(ANALYZE_EXHAUST); @@ -132,10 +126,11 @@ public class AnalyzerFacadeWithCache implements AnalyzerFacade { @Override public Result compute() { try { - AnalyzeExhaust analyzeExhaust = facade.analyzeFiles(project, - files, - Predicates.alwaysFalse(), - JetControlFlowDataTraceFactory.EMPTY); + AnalyzeExhaust analyzeExhaust = AnalyzerFacadeProvider.getAnalyzerFacadeForProject(project) + .analyzeFiles(project, + files, + Predicates.alwaysFalse(), + JetControlFlowDataTraceFactory.EMPTY); return new Result(analyzeExhaust, PsiModificationTracker.MODIFICATION_COUNT); } catch (ProcessCanceledException e) { @@ -159,13 +154,4 @@ public class AnalyzerFacadeWithCache implements AnalyzerFacade { return bindingContextCachedValue.getValue(); } } - - @NotNull - @Override - public AnalyzeExhaust analyzeFiles(@NotNull Project project, - @NotNull Collection files, - @NotNull Predicate filesToAnalyzeCompletely, - @NotNull JetControlFlowDataTraceFactory flowDataTraceFactory) { - return facade.analyzeFiles(project, files, filesToAnalyzeCompletely, flowDataTraceFactory); - } } diff --git a/idea/src/org/jetbrains/jet/plugin/project/JsModuleDetector.java b/idea/src/org/jetbrains/jet/plugin/project/JsModuleDetector.java new file mode 100644 index 00000000000..a5547ccdd5a --- /dev/null +++ b/idea/src/org/jetbrains/jet/plugin/project/JsModuleDetector.java @@ -0,0 +1,54 @@ +/* + * Copyright 2010-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jetbrains.jet.plugin.project; + +import com.intellij.openapi.fileTypes.FileTypes; +import com.intellij.openapi.project.Project; +import com.intellij.openapi.roots.ProjectRootManager; +import com.intellij.openapi.vfs.VirtualFile; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +/** + * @author Pavel Talanov + * + * This class has utility functions to determine whether the project (or module) is js project. + */ +public final class JsModuleDetector { + + public static final String INDICATION_FILE_NAME = "k2js.txt"; + + private JsModuleDetector() { + } + + public static boolean isJsProject(@NotNull Project project) { + return findIndicationFileInContextRoots(project) != null; + } + + @Nullable + public static VirtualFile findIndicationFileInContextRoots(@NotNull Project project) { + VirtualFile[] roots = ProjectRootManager.getInstance(project).getContentRoots(); + for (VirtualFile root : roots) { + for (VirtualFile child : root.getChildren()) { + if (child.getFileType().equals(FileTypes.PLAIN_TEXT) && child.getName().equals(INDICATION_FILE_NAME)) { + return child; + } + } + } + return null; + } +} diff --git a/idea/src/org/jetbrains/jet/plugin/project/WholeProjectAnalyzerFacade.java b/idea/src/org/jetbrains/jet/plugin/project/WholeProjectAnalyzerFacade.java index 51288c1ad41..4e979856d71 100644 --- a/idea/src/org/jetbrains/jet/plugin/project/WholeProjectAnalyzerFacade.java +++ b/idea/src/org/jetbrains/jet/plugin/project/WholeProjectAnalyzerFacade.java @@ -23,6 +23,8 @@ import org.jetbrains.jet.analyzer.AnalyzeExhaust; import org.jetbrains.jet.lang.psi.JetFile; import org.jetbrains.jet.lang.resolve.java.JetFilesProvider; +import static org.jetbrains.jet.plugin.project.AnalyzerFacadeWithCache.analyzeFileWithCache; + /** * @author abreslav */ @@ -36,13 +38,11 @@ public final class WholeProjectAnalyzerFacade { @NotNull public static AnalyzeExhaust analyzeProjectWithCacheOnAFile(@NotNull JetFile file) { - return AnalyzerFacadeProvider.getAnalyzerFacadeWithCacheForFile(file) - .analyzeFileWithCache(file, JetFilesProvider.getInstance(file.getProject()).sampleToAllFilesInModule()); + return analyzeFileWithCache(file, JetFilesProvider.getInstance(file.getProject()).sampleToAllFilesInModule()); } @NotNull public static AnalyzeExhaust analyzeProjectWithCache(@NotNull Project project, @NotNull GlobalSearchScope scope) { - return AnalyzerFacadeProvider.getAnalyzerFacadeWithCacheForProject(project) - .analyzeProjectWithCache(project, JetFilesProvider.getInstance(project).allInScope(scope)); + return AnalyzerFacadeWithCache.analyzeProjectWithCache(project, JetFilesProvider.getInstance(project).allInScope(scope)); } } diff --git a/idea/src/org/jetbrains/jet/plugin/quickfix/ChangeVariableMutabilityFix.java b/idea/src/org/jetbrains/jet/plugin/quickfix/ChangeVariableMutabilityFix.java index 208c71b7934..8d40279ccfb 100644 --- a/idea/src/org/jetbrains/jet/plugin/quickfix/ChangeVariableMutabilityFix.java +++ b/idea/src/org/jetbrains/jet/plugin/quickfix/ChangeVariableMutabilityFix.java @@ -24,7 +24,6 @@ import com.intellij.psi.PsiFile; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.IncorrectOperationException; import org.jetbrains.annotations.NotNull; -import org.jetbrains.jet.analyzer.AnalyzerFacadeWithCache; import org.jetbrains.jet.lang.descriptors.VariableDescriptor; import org.jetbrains.jet.lang.psi.JetFile; import org.jetbrains.jet.lang.psi.JetProperty; @@ -32,9 +31,7 @@ import org.jetbrains.jet.lang.psi.JetPsiFactory; import org.jetbrains.jet.lang.psi.JetSimpleNameExpression; import org.jetbrains.jet.lang.resolve.BindingContext; import org.jetbrains.jet.lang.resolve.BindingContextUtils; -import org.jetbrains.jet.lang.resolve.java.AnalyzerFacadeForJVM; import org.jetbrains.jet.plugin.JetBundle; -import org.jetbrains.jet.plugin.project.AnalyzeSingleFileUtil; import static org.jetbrains.jet.plugin.project.AnalyzeSingleFileUtil.getContextForSingleFile; diff --git a/idea/src/org/jetbrains/jet/plugin/quickfix/ImportInsertHelper.java b/idea/src/org/jetbrains/jet/plugin/quickfix/ImportInsertHelper.java index 1b3f90342d2..40513366a91 100644 --- a/idea/src/org/jetbrains/jet/plugin/quickfix/ImportInsertHelper.java +++ b/idea/src/org/jetbrains/jet/plugin/quickfix/ImportInsertHelper.java @@ -19,7 +19,6 @@ package org.jetbrains.jet.plugin.quickfix; import com.intellij.psi.PsiElement; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.jetbrains.jet.analyzer.AnalyzerFacadeWithCache; import org.jetbrains.jet.lang.DefaultModuleConfiguration; import org.jetbrains.jet.lang.psi.JetFile; import org.jetbrains.jet.lang.psi.JetImportDirective; @@ -28,13 +27,11 @@ import org.jetbrains.jet.lang.psi.JetPsiUtil; import org.jetbrains.jet.lang.resolve.BindingContext; import org.jetbrains.jet.lang.resolve.FqName; import org.jetbrains.jet.lang.resolve.ImportPath; -import org.jetbrains.jet.lang.resolve.java.AnalyzerFacadeForJVM; import org.jetbrains.jet.lang.resolve.java.JavaBridgeConfiguration; import org.jetbrains.jet.lang.resolve.java.JavaDescriptorResolver; import org.jetbrains.jet.lang.types.ErrorUtils; import org.jetbrains.jet.lang.types.JetType; import org.jetbrains.jet.plugin.JetPluginUtil; -import org.jetbrains.jet.plugin.project.AnalyzeSingleFileUtil; import org.jetbrains.jet.util.QualifiedNamesUtil; import java.util.List; diff --git a/idea/src/org/jetbrains/jet/plugin/quickfix/QuickFixUtil.java b/idea/src/org/jetbrains/jet/plugin/quickfix/QuickFixUtil.java index 5ddf98566e1..16ab5a3c924 100644 --- a/idea/src/org/jetbrains/jet/plugin/quickfix/QuickFixUtil.java +++ b/idea/src/org/jetbrains/jet/plugin/quickfix/QuickFixUtil.java @@ -22,14 +22,12 @@ import com.intellij.psi.PsiFile; import com.intellij.psi.PsiWhiteSpace; import com.intellij.psi.util.PsiTreeUtil; import org.jetbrains.annotations.Nullable; -import org.jetbrains.jet.analyzer.AnalyzerFacadeWithCache; import org.jetbrains.jet.lang.descriptors.CallableDescriptor; import org.jetbrains.jet.lang.descriptors.DeclarationDescriptor; import org.jetbrains.jet.lang.diagnostics.Diagnostic; import org.jetbrains.jet.lang.psi.JetFile; import org.jetbrains.jet.lang.psi.JetNamedDeclaration; import org.jetbrains.jet.lang.resolve.BindingContext; -import org.jetbrains.jet.lang.resolve.java.AnalyzerFacadeForJVM; import org.jetbrains.jet.lang.types.DeferredType; import org.jetbrains.jet.lang.types.JetType; @@ -59,7 +57,7 @@ public class QuickFixUtil { public static JetType getDeclarationReturnType(JetNamedDeclaration declaration) { PsiFile file = declaration.getContainingFile(); if (!(file instanceof JetFile)) return null; - BindingContext bindingContext = getContextForSingleFile((JetFile) file); + BindingContext bindingContext = getContextForSingleFile((JetFile)file); DeclarationDescriptor descriptor = bindingContext.get(BindingContext.DECLARATION_TO_DESCRIPTOR, declaration); if (!(descriptor instanceof CallableDescriptor)) return null; JetType type = ((CallableDescriptor)descriptor).getReturnType(); diff --git a/idea/src/org/jetbrains/jet/plugin/refactoring/JetNameSuggester.java b/idea/src/org/jetbrains/jet/plugin/refactoring/JetNameSuggester.java index 2b4f44ec40c..64fa206b6e8 100644 --- a/idea/src/org/jetbrains/jet/plugin/refactoring/JetNameSuggester.java +++ b/idea/src/org/jetbrains/jet/plugin/refactoring/JetNameSuggester.java @@ -19,11 +19,9 @@ package org.jetbrains.jet.plugin.refactoring; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.ArrayUtil; -import org.jetbrains.jet.analyzer.AnalyzerFacadeWithCache; import org.jetbrains.jet.lang.descriptors.ClassDescriptor; import org.jetbrains.jet.lang.psi.*; import org.jetbrains.jet.lang.resolve.BindingContext; -import org.jetbrains.jet.lang.resolve.java.AnalyzerFacadeForJVM; import org.jetbrains.jet.lang.types.ErrorUtils; import org.jetbrains.jet.lang.types.JetType; import org.jetbrains.jet.lang.types.TypeUtils; @@ -70,7 +68,7 @@ public class JetNameSuggester { public static String[] suggestNames(JetExpression expression, JetNameValidator validator) { ArrayList result = new ArrayList(); - BindingContext bindingContext = getContextForSingleFile((JetFile) expression.getContainingFile()); + BindingContext bindingContext = getContextForSingleFile((JetFile)expression.getContainingFile()); JetType jetType = bindingContext.get(BindingContext.EXPRESSION_TYPE, expression); if (jetType != null) { addNamesForType(result, jetType, validator); diff --git a/idea/src/org/jetbrains/jet/plugin/refactoring/JetRefactoringUtil.java b/idea/src/org/jetbrains/jet/plugin/refactoring/JetRefactoringUtil.java index 549f0c171d8..29857eefe72 100644 --- a/idea/src/org/jetbrains/jet/plugin/refactoring/JetRefactoringUtil.java +++ b/idea/src/org/jetbrains/jet/plugin/refactoring/JetRefactoringUtil.java @@ -28,10 +28,8 @@ import com.intellij.psi.util.PsiTreeUtil; import com.intellij.ui.components.JBList; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.jetbrains.jet.analyzer.AnalyzerFacadeWithCache; import org.jetbrains.jet.lang.psi.*; import org.jetbrains.jet.lang.resolve.BindingContext; -import org.jetbrains.jet.lang.resolve.java.AnalyzerFacadeForJVM; import org.jetbrains.jet.lang.types.JetType; import org.jetbrains.jet.lang.types.NamespaceType; import org.jetbrains.jet.lang.types.checker.JetTypeChecker; diff --git a/idea/src/org/jetbrains/jet/plugin/refactoring/introduceVariable/JetIntroduceVariableHandler.java b/idea/src/org/jetbrains/jet/plugin/refactoring/introduceVariable/JetIntroduceVariableHandler.java index 07583a8c957..31e05ec33dc 100644 --- a/idea/src/org/jetbrains/jet/plugin/refactoring/introduceVariable/JetIntroduceVariableHandler.java +++ b/idea/src/org/jetbrains/jet/plugin/refactoring/introduceVariable/JetIntroduceVariableHandler.java @@ -34,11 +34,9 @@ import com.intellij.refactoring.introduce.inplace.OccurrencesChooser; import com.intellij.refactoring.util.CommonRefactoringUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.jetbrains.jet.analyzer.AnalyzerFacadeWithCache; import org.jetbrains.jet.lang.descriptors.DeclarationDescriptor; import org.jetbrains.jet.lang.psi.*; import org.jetbrains.jet.lang.resolve.BindingContext; -import org.jetbrains.jet.lang.resolve.java.AnalyzerFacadeForJVM; import org.jetbrains.jet.lang.types.JetType; import org.jetbrains.jet.lang.types.NamespaceType; import org.jetbrains.jet.lang.types.checker.JetTypeChecker; diff --git a/js/js.translator/src/org/jetbrains/k2js/analyze/AnalyzerFacadeForJS.java b/js/js.translator/src/org/jetbrains/k2js/analyze/AnalyzerFacadeForJS.java index ace8c2fc424..525919411e7 100644 --- a/js/js.translator/src/org/jetbrains/k2js/analyze/AnalyzerFacadeForJS.java +++ b/js/js.translator/src/org/jetbrains/k2js/analyze/AnalyzerFacadeForJS.java @@ -22,6 +22,8 @@ import com.intellij.openapi.project.Project; import com.intellij.psi.PsiFile; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import org.jetbrains.jet.analyzer.AnalyzeExhaust; +import org.jetbrains.jet.analyzer.AnalyzerFacade; import org.jetbrains.jet.di.InjectorForTopDownAnalyzerForJs; import org.jetbrains.jet.lang.DefaultModuleConfiguration; import org.jetbrains.jet.lang.ModuleConfiguration; @@ -34,7 +36,9 @@ import org.jetbrains.jet.lang.psi.JetPsiFactory; import org.jetbrains.jet.lang.resolve.*; import org.jetbrains.jet.lang.resolve.scopes.WritableScope; import org.jetbrains.jet.lang.types.lang.JetStandardClasses; +import org.jetbrains.jet.lang.types.lang.JetStandardLibrary; import org.jetbrains.k2js.config.Config; +import org.jetbrains.k2js.config.IDEAConfig; import java.util.ArrayList; import java.util.Collection; @@ -44,11 +48,23 @@ import java.util.List; /** * @author Pavel Talanov */ -public final class AnalyzerFacadeForJS { +public enum AnalyzerFacadeForJS implements AnalyzerFacade { + + INSTANCE; private AnalyzerFacadeForJS() { } + @NotNull + @Override + public AnalyzeExhaust analyzeFiles(@NotNull Project project, + @NotNull Collection files, + @NotNull Predicate filesToAnalyzeCompletely, + @NotNull JetControlFlowDataTraceFactory flowDataTraceFactory) { + BindingContext context = analyzeFiles(files, new IDEAConfig(project)); + return new AnalyzeExhaust(context, JetStandardLibrary.getInstance()); + } + @NotNull public static BindingContext analyzeFilesAndCheckErrors(@NotNull List files, @NotNull Config config) { @@ -58,7 +74,7 @@ public final class AnalyzerFacadeForJS { } @NotNull - public static BindingContext analyzeFiles(@NotNull List files, + public static BindingContext analyzeFiles(@NotNull Collection files, @NotNull Config config) { Project project = config.getProject(); BindingTraceContext bindingTraceContext = new BindingTraceContext(); @@ -76,7 +92,7 @@ public final class AnalyzerFacadeForJS { return bindingTraceContext.getBindingContext(); } - private static void checkForErrors(@NotNull List allFiles, @NotNull BindingContext bindingContext) { + private static void checkForErrors(@NotNull Collection allFiles, @NotNull BindingContext bindingContext) { AnalyzingUtils.throwExceptionOnErrors(bindingContext); for (JetFile file : allFiles) { AnalyzingUtils.checkForSyntacticErrors(file); @@ -84,7 +100,7 @@ public final class AnalyzerFacadeForJS { } @NotNull - public static List withJsLibAdded(@NotNull List files, @NotNull Config config) { + public static Collection withJsLibAdded(@NotNull Collection files, @NotNull Config config) { List allFiles = new ArrayList(); allFiles.addAll(files); allFiles.addAll(config.getLibFiles()); @@ -103,6 +119,8 @@ public final class AnalyzerFacadeForJS { }; } + //TODO: exclude? + @NotNull public static BindingContext analyzeNamespace(@NotNull JetFile file) { BindingTraceContext bindingTraceContext = new BindingTraceContext(); Project project = file.getProject(); diff --git a/js/js.translator/src/org/jetbrains/k2js/config/IDEAConfig.java b/js/js.translator/src/org/jetbrains/k2js/config/IDEAConfig.java index 0b697af7aaa..6518839da61 100644 --- a/js/js.translator/src/org/jetbrains/k2js/config/IDEAConfig.java +++ b/js/js.translator/src/org/jetbrains/k2js/config/IDEAConfig.java @@ -45,6 +45,11 @@ public final class IDEAConfig extends Config { this.pathToLibZip = pathToLibZip; } + public IDEAConfig(@NotNull Project project) { + //TODO: testing purposes. Should not get anywhere near production + this(project, "C:\\Dev\\Projects\\Kotlin\\clean_jet\\js\\js.libraries\\src\\k2jslib.zip"); + } + @NotNull @Override public List getLibFiles() { diff --git a/js/js.translator/src/org/jetbrains/k2js/facade/K2JSTranslator.java b/js/js.translator/src/org/jetbrains/k2js/facade/K2JSTranslator.java index a18f5e282be..abd649410bb 100644 --- a/js/js.translator/src/org/jetbrains/k2js/facade/K2JSTranslator.java +++ b/js/js.translator/src/org/jetbrains/k2js/facade/K2JSTranslator.java @@ -16,6 +16,7 @@ package org.jetbrains.k2js.facade; +import com.google.common.collect.Lists; import com.google.dart.compiler.backend.js.ast.JsProgram; import com.intellij.openapi.project.Project; import org.jetbrains.annotations.NotNull; @@ -33,10 +34,7 @@ import org.jetbrains.k2js.utils.JetFileUtils; import java.io.File; import java.io.FileWriter; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.StringTokenizer; +import java.util.*; import static org.jetbrains.k2js.translate.utils.PsiUtils.getNamespaceName; @@ -108,7 +106,8 @@ public final class K2JSTranslator { public JsProgram generateProgram(@NotNull List filesToTranslate) { JetStandardLibrary.initialize(config.getProject()); BindingContext bindingContext = AnalyzerFacadeForJS.analyzeFilesAndCheckErrors(filesToTranslate, config); - return Translation.generateAst(bindingContext, AnalyzerFacadeForJS.withJsLibAdded(filesToTranslate, config)); + Collection files = AnalyzerFacadeForJS.withJsLibAdded(filesToTranslate, config); + return Translation.generateAst(bindingContext, Lists.newArrayList(files)); } @NotNull From f94823c5924d7fa7c33b9544dc90ac0f34102601 Mon Sep 17 00:00:00 2001 From: "Pavel V. Talanov" Date: Fri, 6 Apr 2012 17:40:05 +0400 Subject: [PATCH 07/12] Remove "Setup kotlin runtime" notification for js modules. --- .../quickfix/ConfigureKotlinLibraryNotificationProvider.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/idea/src/org/jetbrains/jet/plugin/quickfix/ConfigureKotlinLibraryNotificationProvider.java b/idea/src/org/jetbrains/jet/plugin/quickfix/ConfigureKotlinLibraryNotificationProvider.java index 94d2d6e6c4a..096a5fb9f25 100644 --- a/idea/src/org/jetbrains/jet/plugin/quickfix/ConfigureKotlinLibraryNotificationProvider.java +++ b/idea/src/org/jetbrains/jet/plugin/quickfix/ConfigureKotlinLibraryNotificationProvider.java @@ -50,12 +50,15 @@ import com.intellij.ui.EditorNotificationPanel; import com.intellij.ui.EditorNotifications; import org.jetbrains.annotations.NotNull; import org.jetbrains.jet.plugin.JetFileType; +import org.jetbrains.jet.plugin.project.JsModuleDetector; import org.jetbrains.jet.utils.PathUtil; import javax.swing.*; import java.io.File; import java.io.IOException; +import static org.jetbrains.jet.plugin.project.JsModuleDetector.*; + public class ConfigureKotlinLibraryNotificationProvider implements EditorNotifications.Provider { private static final Key KEY = Key.create("configure.kotlin.library"); private final Project myProject; @@ -82,6 +85,8 @@ public class ConfigureKotlinLibraryNotificationProvider implements EditorNotific if (isMavenModule(module)) return null; + if (isJsProject(myProject)) return null; + GlobalSearchScope scope = module.getModuleWithDependenciesAndLibrariesScope(false); if (JavaPsiFacade.getInstance(myProject).findClass("jet.JetObject", scope) == null) { return createNotificationPanel(module); From 6cf51fb20ac00ecae51adc4a8a98c72488de9e43 Mon Sep 17 00:00:00 2001 From: "Pavel V. Talanov" Date: Fri, 6 Apr 2012 19:55:21 +0400 Subject: [PATCH 08/12] IDEAConfig move to idea module (circular dependency). Slightly modify Config class. --- .../jet/plugin/project}/IDEAConfig.java | 65 +++++++++++++++---- .../k2js/test/config/TestConfig.java | 2 +- js/js.translator/js.translator.iml | 1 + .../k2js/analyze/AnalyzerFacadeForJS.java | 26 +++++--- .../src/org/jetbrains/k2js/config/Config.java | 13 +++- .../jetbrains/k2js/facade/K2JSTranslator.java | 5 +- 6 files changed, 87 insertions(+), 25 deletions(-) rename {js/js.translator/src/org/jetbrains/k2js/config => idea/src/org/jetbrains/jet/plugin/project}/IDEAConfig.java (55%) diff --git a/js/js.translator/src/org/jetbrains/k2js/config/IDEAConfig.java b/idea/src/org/jetbrains/jet/plugin/project/IDEAConfig.java similarity index 55% rename from js/js.translator/src/org/jetbrains/k2js/config/IDEAConfig.java rename to idea/src/org/jetbrains/jet/plugin/project/IDEAConfig.java index 6518839da61..16f4caee2cc 100644 --- a/js/js.translator/src/org/jetbrains/k2js/config/IDEAConfig.java +++ b/idea/src/org/jetbrains/jet/plugin/project/IDEAConfig.java @@ -14,18 +14,21 @@ * limitations under the License. */ -package org.jetbrains.k2js.config; +package org.jetbrains.jet.plugin.project; import com.google.common.collect.Lists; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.io.FileUtil; +import com.intellij.openapi.vfs.VirtualFile; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import org.jetbrains.jet.lang.psi.JetFile; +import org.jetbrains.k2js.config.Config; import org.jetbrains.k2js.utils.JetFileUtils; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; +import java.io.*; +import java.net.URI; +import java.net.URISyntaxException; import java.util.Collections; import java.util.Enumeration; import java.util.List; @@ -37,22 +40,62 @@ import java.util.zip.ZipFile; */ public final class IDEAConfig extends Config { - @NotNull + @Nullable private final String pathToLibZip; - public IDEAConfig(@NotNull Project project, @NotNull String pathToLibZip) { + public IDEAConfig(@NotNull Project project) { super(project); - this.pathToLibZip = pathToLibZip; + this.pathToLibZip = getLibLocationForProject(project); } - public IDEAConfig(@NotNull Project project) { - //TODO: testing purposes. Should not get anywhere near production - this(project, "C:\\Dev\\Projects\\Kotlin\\clean_jet\\js\\js.libraries\\src\\k2jslib.zip"); + //TODO: refactor + @Nullable + private static String getLibLocationForProject(@NotNull Project project) { + VirtualFile indicationFile = JsModuleDetector.findIndicationFileInContextRoots(project); + if (indicationFile == null) { + return null; + } + try { + InputStream stream = indicationFile.getInputStream(); + String path = FileUtil.loadTextAndClose(stream); + String pathToLibFile = getFirstLine(path); + if (pathToLibFile == null) { + return null; + } + try { + URI pathToLibFileUri = new URI(pathToLibFile); + URI pathToIndicationFileUri = new URI(indicationFile.getPath()); + return pathToIndicationFileUri.resolve(pathToLibFileUri).toString(); + } + catch (URISyntaxException e) { + e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. + return null; + } + } + catch (IOException e) { + return null; + } + } + + //TODO: util + @Nullable + private static String getFirstLine(@NotNull String path) throws IOException { + BufferedReader reader = new BufferedReader(new StringReader(path)); + try { + return reader.readLine(); + } + + finally { + reader.close(); + } } @NotNull @Override - public List getLibFiles() { + public List generateLibFiles() { + if (pathToLibZip == null) { + return Collections.emptyList(); + } try { File file = new File(pathToLibZip); ZipFile zipFile = new ZipFile(file); diff --git a/js/js.tests/test/org/jetbrains/k2js/test/config/TestConfig.java b/js/js.tests/test/org/jetbrains/k2js/test/config/TestConfig.java index 144fa6f49f5..cb830ee2d56 100644 --- a/js/js.tests/test/org/jetbrains/k2js/test/config/TestConfig.java +++ b/js/js.tests/test/org/jetbrains/k2js/test/config/TestConfig.java @@ -71,7 +71,7 @@ public final class TestConfig extends Config { } @NotNull - public List getLibFiles() { + public List generateLibFiles() { if (jsLibFiles == null) { jsLibFiles = initLibFiles(getProject()); } diff --git a/js/js.translator/js.translator.iml b/js/js.translator/js.translator.iml index a827f7758ae..f877327f1c0 100644 --- a/js/js.translator/js.translator.iml +++ b/js/js.translator/js.translator.iml @@ -10,6 +10,7 @@ + diff --git a/js/js.translator/src/org/jetbrains/k2js/analyze/AnalyzerFacadeForJS.java b/js/js.translator/src/org/jetbrains/k2js/analyze/AnalyzerFacadeForJS.java index 525919411e7..354ead5cd2f 100644 --- a/js/js.translator/src/org/jetbrains/k2js/analyze/AnalyzerFacadeForJS.java +++ b/js/js.translator/src/org/jetbrains/k2js/analyze/AnalyzerFacadeForJS.java @@ -18,6 +18,8 @@ package org.jetbrains.k2js.analyze; import com.google.common.base.Predicate; import com.google.common.base.Predicates; +import com.google.common.collect.Lists; +import com.google.common.collect.Sets; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiFile; import org.jetbrains.annotations.NotNull; @@ -37,13 +39,10 @@ import org.jetbrains.jet.lang.resolve.*; import org.jetbrains.jet.lang.resolve.scopes.WritableScope; import org.jetbrains.jet.lang.types.lang.JetStandardClasses; import org.jetbrains.jet.lang.types.lang.JetStandardLibrary; +import org.jetbrains.jet.plugin.project.IDEAConfig; import org.jetbrains.k2js.config.Config; -import org.jetbrains.k2js.config.IDEAConfig; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.List; +import java.util.*; /** * @author Pavel Talanov @@ -101,9 +100,9 @@ public enum AnalyzerFacadeForJS implements AnalyzerFacade { @NotNull public static Collection withJsLibAdded(@NotNull Collection files, @NotNull Config config) { - List allFiles = new ArrayList(); - allFiles.addAll(files); - allFiles.addAll(config.getLibFiles()); + Set allFiles = Sets.newHashSet(); + allFiles.addAll(toOriginal(files)); + allFiles.addAll(toOriginal(config.getLibFiles())); return allFiles; } @@ -113,12 +112,21 @@ public enum AnalyzerFacadeForJS implements AnalyzerFacade { @Override public boolean apply(@Nullable PsiFile file) { assert file instanceof JetFile; - @SuppressWarnings("UnnecessaryLocalVariable") boolean notLibFile = !jsLibFiles.contains(file); + @SuppressWarnings("UnnecessaryLocalVariable") boolean notLibFile = !jsLibFiles.contains(file.getOriginalFile()); return notLibFile; } }; } + @NotNull + private static Collection toOriginal(@NotNull Collection files) { + Collection result = Lists.newArrayList(); + for (JetFile file : files) { + result.add(file); + } + return result; + } + //TODO: exclude? @NotNull public static BindingContext analyzeNamespace(@NotNull JetFile file) { diff --git a/js/js.translator/src/org/jetbrains/k2js/config/Config.java b/js/js.translator/src/org/jetbrains/k2js/config/Config.java index af75c6d253e..0be12f4fef0 100644 --- a/js/js.translator/src/org/jetbrains/k2js/config/Config.java +++ b/js/js.translator/src/org/jetbrains/k2js/config/Config.java @@ -18,6 +18,7 @@ package org.jetbrains.k2js.config; import com.intellij.openapi.project.Project; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import org.jetbrains.jet.lang.psi.JetFile; import java.util.Arrays; @@ -52,6 +53,8 @@ public abstract class Config { @NotNull private final Project project; + @Nullable + private List libFiles = null; public Config(@NotNull Project project) { this.project = project; @@ -63,5 +66,13 @@ public abstract class Config { } @NotNull - public abstract List getLibFiles(); + protected abstract List generateLibFiles(); + + @NotNull + public final List getLibFiles() { + if (libFiles == null) { + libFiles = generateLibFiles(); + } + return libFiles; + } } diff --git a/js/js.translator/src/org/jetbrains/k2js/facade/K2JSTranslator.java b/js/js.translator/src/org/jetbrains/k2js/facade/K2JSTranslator.java index abd649410bb..d0cd2b05334 100644 --- a/js/js.translator/src/org/jetbrains/k2js/facade/K2JSTranslator.java +++ b/js/js.translator/src/org/jetbrains/k2js/facade/K2JSTranslator.java @@ -24,9 +24,9 @@ import org.jetbrains.jet.lang.psi.JetFile; import org.jetbrains.jet.lang.resolve.BindingContext; import org.jetbrains.jet.lang.types.lang.JetStandardLibrary; import org.jetbrains.jet.plugin.JetMainDetector; +import org.jetbrains.jet.plugin.project.IDEAConfig; import org.jetbrains.k2js.analyze.AnalyzerFacadeForJS; import org.jetbrains.k2js.config.Config; -import org.jetbrains.k2js.config.IDEAConfig; import org.jetbrains.k2js.generate.CodeGenerator; import org.jetbrains.k2js.translate.general.Translation; import org.jetbrains.k2js.utils.GenerationUtils; @@ -50,8 +50,7 @@ public final class K2JSTranslator { public static void translateWithCallToMainAndSaveToFile(@NotNull List files, @NotNull String outputPath, @NotNull Project project) throws Exception { - K2JSTranslator translator = new K2JSTranslator(new IDEAConfig(project, - "C:\\Dev\\Projects\\Kotlin\\clean_jet\\js\\js.libraries\\src\\k2jslib.zip")); + K2JSTranslator translator = new K2JSTranslator(new IDEAConfig(project)); String programCode = translator.generateProgramCode(files) + "\n"; JetFile fileWithMain = JetMainDetector.getFileWithMain(files); if (fileWithMain == null) { From 06ab0d7a55426e22b90af2b7b0ba0e60445832ec Mon Sep 17 00:00:00 2001 From: "Pavel V. Talanov" Date: Fri, 6 Apr 2012 20:03:43 +0400 Subject: [PATCH 09/12] Remove debug output from IDEAConfig class. --- idea/src/org/jetbrains/jet/plugin/project/IDEAConfig.java | 1 - 1 file changed, 1 deletion(-) diff --git a/idea/src/org/jetbrains/jet/plugin/project/IDEAConfig.java b/idea/src/org/jetbrains/jet/plugin/project/IDEAConfig.java index 16f4caee2cc..4ba93444e1f 100644 --- a/idea/src/org/jetbrains/jet/plugin/project/IDEAConfig.java +++ b/idea/src/org/jetbrains/jet/plugin/project/IDEAConfig.java @@ -68,7 +68,6 @@ public final class IDEAConfig extends Config { return pathToIndicationFileUri.resolve(pathToLibFileUri).toString(); } catch (URISyntaxException e) { - e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. return null; } } From 0f44771447e38dd5811d2cabda17c239d5626c9f Mon Sep 17 00:00:00 2001 From: "Pavel V. Talanov" Date: Mon, 9 Apr 2012 13:50:48 +0400 Subject: [PATCH 10/12] Resolve circular dependency. Introduce JsAnalyzerFacadeForIDEA. --- .../jet/plugin/k2jsrun/K2JSRunnerUtils.java | 2 + .../project/AnalyzerFacadeProvider.java | 7 +-- .../project/JSAnalyzerFacadeForIDEA.java | 52 +++++++++++++++++++ js/js.translator/js.translator.iml | 1 - .../k2js/analyze/AnalyzerFacadeForJS.java | 25 +++------ .../jetbrains/k2js/facade/K2JSTranslator.java | 4 +- 6 files changed, 64 insertions(+), 27 deletions(-) create mode 100644 idea/src/org/jetbrains/jet/plugin/project/JSAnalyzerFacadeForIDEA.java diff --git a/idea/src/org/jetbrains/jet/plugin/k2jsrun/K2JSRunnerUtils.java b/idea/src/org/jetbrains/jet/plugin/k2jsrun/K2JSRunnerUtils.java index f6d87889364..f508cc8f9c9 100644 --- a/idea/src/org/jetbrains/jet/plugin/k2jsrun/K2JSRunnerUtils.java +++ b/idea/src/org/jetbrains/jet/plugin/k2jsrun/K2JSRunnerUtils.java @@ -30,6 +30,7 @@ import com.intellij.psi.PsiFile; import com.intellij.psi.PsiManager; import org.jetbrains.annotations.NotNull; import org.jetbrains.jet.lang.psi.JetFile; +import org.jetbrains.jet.plugin.project.IDEAConfig; import org.jetbrains.k2js.facade.K2JSTranslator; import java.util.Collection; @@ -64,6 +65,7 @@ public final class K2JSRunnerUtils { String outputFilePath = constructPathToGeneratedFile(project, outputDirPath); K2JSTranslator.translateWithCallToMainAndSaveToFile(kotlinFiles, outputFilePath, + new IDEAConfig(project), project); notifySuccess(outputDirPath); } diff --git a/idea/src/org/jetbrains/jet/plugin/project/AnalyzerFacadeProvider.java b/idea/src/org/jetbrains/jet/plugin/project/AnalyzerFacadeProvider.java index c6a6dd4d2c1..84ec04b4ce5 100644 --- a/idea/src/org/jetbrains/jet/plugin/project/AnalyzerFacadeProvider.java +++ b/idea/src/org/jetbrains/jet/plugin/project/AnalyzerFacadeProvider.java @@ -33,16 +33,13 @@ public final class AnalyzerFacadeProvider { @NotNull public static AnalyzerFacade getAnalyzerFacadeForFile(@NotNull JetFile file) { - if (JsModuleDetector.isJsProject(file.getProject())) { - return AnalyzerFacadeForJS.INSTANCE; - } - return AnalyzerFacadeForJVM.INSTANCE; + return getAnalyzerFacadeForProject(file.getProject()); } @NotNull public static AnalyzerFacade getAnalyzerFacadeForProject(@NotNull Project project) { if (JsModuleDetector.isJsProject(project)) { - return AnalyzerFacadeForJS.INSTANCE; + return JSAnalyzerFacadeForIDEA.INSTANCE; } return AnalyzerFacadeForJVM.INSTANCE; } diff --git a/idea/src/org/jetbrains/jet/plugin/project/JSAnalyzerFacadeForIDEA.java b/idea/src/org/jetbrains/jet/plugin/project/JSAnalyzerFacadeForIDEA.java new file mode 100644 index 00000000000..a9b0292b39f --- /dev/null +++ b/idea/src/org/jetbrains/jet/plugin/project/JSAnalyzerFacadeForIDEA.java @@ -0,0 +1,52 @@ +/* + * Copyright 2010-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jetbrains.jet.plugin.project; + +import com.google.common.base.Predicate; +import com.intellij.openapi.project.Project; +import com.intellij.psi.PsiFile; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.jet.analyzer.AnalyzeExhaust; +import org.jetbrains.jet.analyzer.AnalyzerFacade; +import org.jetbrains.jet.lang.cfg.pseudocode.JetControlFlowDataTraceFactory; +import org.jetbrains.jet.lang.psi.JetFile; +import org.jetbrains.jet.lang.resolve.BindingContext; +import org.jetbrains.jet.lang.types.lang.JetStandardLibrary; +import org.jetbrains.k2js.analyze.AnalyzerFacadeForJS; + +import java.util.Collection; + +/** + * @author Pavel Talanov + */ +public enum JSAnalyzerFacadeForIDEA implements AnalyzerFacade { + + INSTANCE; + + private JSAnalyzerFacadeForIDEA() { + } + + @NotNull + @Override + public AnalyzeExhaust analyzeFiles(@NotNull Project project, + @NotNull Collection files, + @NotNull Predicate filesToAnalyzeCompletely, + @NotNull JetControlFlowDataTraceFactory flowDataTraceFactory) { + BindingContext context = AnalyzerFacadeForJS.analyzeFiles(files, new IDEAConfig(project)); + return new AnalyzeExhaust(context, JetStandardLibrary.getInstance()); + } +} \ No newline at end of file diff --git a/js/js.translator/js.translator.iml b/js/js.translator/js.translator.iml index f877327f1c0..a827f7758ae 100644 --- a/js/js.translator/js.translator.iml +++ b/js/js.translator/js.translator.iml @@ -10,7 +10,6 @@ - diff --git a/js/js.translator/src/org/jetbrains/k2js/analyze/AnalyzerFacadeForJS.java b/js/js.translator/src/org/jetbrains/k2js/analyze/AnalyzerFacadeForJS.java index 354ead5cd2f..cb202551495 100644 --- a/js/js.translator/src/org/jetbrains/k2js/analyze/AnalyzerFacadeForJS.java +++ b/js/js.translator/src/org/jetbrains/k2js/analyze/AnalyzerFacadeForJS.java @@ -24,8 +24,6 @@ import com.intellij.openapi.project.Project; import com.intellij.psi.PsiFile; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.jetbrains.jet.analyzer.AnalyzeExhaust; -import org.jetbrains.jet.analyzer.AnalyzerFacade; import org.jetbrains.jet.di.InjectorForTopDownAnalyzerForJs; import org.jetbrains.jet.lang.DefaultModuleConfiguration; import org.jetbrains.jet.lang.ModuleConfiguration; @@ -38,32 +36,21 @@ import org.jetbrains.jet.lang.psi.JetPsiFactory; import org.jetbrains.jet.lang.resolve.*; import org.jetbrains.jet.lang.resolve.scopes.WritableScope; import org.jetbrains.jet.lang.types.lang.JetStandardClasses; -import org.jetbrains.jet.lang.types.lang.JetStandardLibrary; -import org.jetbrains.jet.plugin.project.IDEAConfig; import org.jetbrains.k2js.config.Config; -import java.util.*; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Set; /** * @author Pavel Talanov */ -public enum AnalyzerFacadeForJS implements AnalyzerFacade { - - INSTANCE; +public final class AnalyzerFacadeForJS { private AnalyzerFacadeForJS() { } - @NotNull - @Override - public AnalyzeExhaust analyzeFiles(@NotNull Project project, - @NotNull Collection files, - @NotNull Predicate filesToAnalyzeCompletely, - @NotNull JetControlFlowDataTraceFactory flowDataTraceFactory) { - BindingContext context = analyzeFiles(files, new IDEAConfig(project)); - return new AnalyzeExhaust(context, JetStandardLibrary.getInstance()); - } - @NotNull public static BindingContext analyzeFilesAndCheckErrors(@NotNull List files, @NotNull Config config) { @@ -112,7 +99,7 @@ public enum AnalyzerFacadeForJS implements AnalyzerFacade { @Override public boolean apply(@Nullable PsiFile file) { assert file instanceof JetFile; - @SuppressWarnings("UnnecessaryLocalVariable") boolean notLibFile = !jsLibFiles.contains(file.getOriginalFile()); + @SuppressWarnings("UnnecessaryLocalVariable") boolean notLibFile = !jsLibFiles.contains(file); return notLibFile; } }; diff --git a/js/js.translator/src/org/jetbrains/k2js/facade/K2JSTranslator.java b/js/js.translator/src/org/jetbrains/k2js/facade/K2JSTranslator.java index d0cd2b05334..0ef6e9b4f54 100644 --- a/js/js.translator/src/org/jetbrains/k2js/facade/K2JSTranslator.java +++ b/js/js.translator/src/org/jetbrains/k2js/facade/K2JSTranslator.java @@ -24,7 +24,6 @@ import org.jetbrains.jet.lang.psi.JetFile; import org.jetbrains.jet.lang.resolve.BindingContext; import org.jetbrains.jet.lang.types.lang.JetStandardLibrary; import org.jetbrains.jet.plugin.JetMainDetector; -import org.jetbrains.jet.plugin.project.IDEAConfig; import org.jetbrains.k2js.analyze.AnalyzerFacadeForJS; import org.jetbrains.k2js.config.Config; import org.jetbrains.k2js.generate.CodeGenerator; @@ -49,8 +48,9 @@ public final class K2JSTranslator { public static void translateWithCallToMainAndSaveToFile(@NotNull List files, @NotNull String outputPath, + @NotNull Config config, @NotNull Project project) throws Exception { - K2JSTranslator translator = new K2JSTranslator(new IDEAConfig(project)); + K2JSTranslator translator = new K2JSTranslator(config); String programCode = translator.generateProgramCode(files) + "\n"; JetFile fileWithMain = JetMainDetector.getFileWithMain(files); if (fileWithMain == null) { From 62efa952117b536e41ce40ba6e2f12681d2f3d5d Mon Sep 17 00:00:00 2001 From: "Pavel V. Talanov" Date: Mon, 9 Apr 2012 14:20:08 +0400 Subject: [PATCH 11/12] Change indication filename to ".kotlin-js" --- idea/src/org/jetbrains/jet/plugin/project/JsModuleDetector.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/idea/src/org/jetbrains/jet/plugin/project/JsModuleDetector.java b/idea/src/org/jetbrains/jet/plugin/project/JsModuleDetector.java index a5547ccdd5a..9d3df9bc1e3 100644 --- a/idea/src/org/jetbrains/jet/plugin/project/JsModuleDetector.java +++ b/idea/src/org/jetbrains/jet/plugin/project/JsModuleDetector.java @@ -30,7 +30,7 @@ import org.jetbrains.annotations.Nullable; */ public final class JsModuleDetector { - public static final String INDICATION_FILE_NAME = "k2js.txt"; + public static final String INDICATION_FILE_NAME = ".kotlin-js"; private JsModuleDetector() { } From 652be4ed9517a59a3d408974b2fc6c22c15184db Mon Sep 17 00:00:00 2001 From: "Pavel V. Talanov" Date: Mon, 9 Apr 2012 15:04:27 +0400 Subject: [PATCH 12/12] Revert misleading whitespace changes. --- .../jet/codegen/GenerationState.java | 29 +++------ .../jet/codegen/GenerationUtils.java | 8 +-- .../jet/codegen/CodegenTestCase.java | 53 ++++++--------- .../jet/resolve/ExpectedResolveData.java | 64 +++++++++---------- .../libraries/JetSourceNavigationHelper.java | 3 +- .../plugin/refactoring/JetNameSuggester.java | 6 +- .../JetIntroduceVariableHandler.java | 8 +-- 7 files changed, 73 insertions(+), 98 deletions(-) diff --git a/compiler/backend/src/org/jetbrains/jet/codegen/GenerationState.java b/compiler/backend/src/org/jetbrains/jet/codegen/GenerationState.java index fdb550c11e7..eac7e779fa5 100644 --- a/compiler/backend/src/org/jetbrains/jet/codegen/GenerationState.java +++ b/compiler/backend/src/org/jetbrains/jet/codegen/GenerationState.java @@ -54,18 +54,12 @@ public class GenerationState { this(project, builderFactory, Progress.DEAF, analyzeExhaust, files); } - public GenerationState(Project project, - ClassBuilderFactory builderFactory, - Progress progress, - @NotNull AnalyzeExhaust exhaust, - @NotNull List files) { + public GenerationState(Project project, ClassBuilderFactory builderFactory, Progress progress, @NotNull AnalyzeExhaust exhaust, @NotNull List files) { this.project = project; this.progress = progress; this.analyzeExhaust = exhaust; this.files = files; - this.injector = - new InjectorForJvmCodegen(analyzeExhaust.getStandardLibrary(), analyzeExhaust.getBindingContext(), this.files, project, this, - builderFactory); + this.injector = new InjectorForJvmCodegen(analyzeExhaust.getStandardLibrary(), analyzeExhaust.getBindingContext(), this.files, project, this, builderFactory); } @NotNull @@ -90,13 +84,11 @@ public class GenerationState { } public ClassBuilder forClassImplementation(ClassDescriptor aClass) { - return getFactory().newVisitor( - getInjector().getJetTypeMapper().mapType(aClass.getDefaultType(), OwnerKind.IMPLEMENTATION).getInternalName() + ".class"); + return getFactory().newVisitor(getInjector().getJetTypeMapper().mapType(aClass.getDefaultType(), OwnerKind.IMPLEMENTATION).getInternalName() + ".class"); } public ClassBuilder forTraitImplementation(ClassDescriptor aClass) { - return getFactory().newVisitor( - getInjector().getJetTypeMapper().mapType(aClass.getDefaultType(), OwnerKind.TRAIT_IMPL).getInternalName() + ".class"); + return getFactory().newVisitor(getInjector().getJetTypeMapper().mapType(aClass.getDefaultType(), OwnerKind.TRAIT_IMPL).getInternalName() + ".class"); } public Pair forAnonymousSubclass(JetExpression expression) { @@ -142,17 +134,14 @@ public class GenerationState { closure.cv = nameAndVisitor.getSecond(); closure.name = nameAndVisitor.getFirst(); final CodegenContext objectContext = closure.context.intoAnonymousClass( - closure, analyzeExhaust.getBindingContext().get(BindingContext.CLASS, objectDeclaration), OwnerKind.IMPLEMENTATION, - injector.getJetTypeMapper()); + closure, analyzeExhaust.getBindingContext().get(BindingContext.CLASS, objectDeclaration), OwnerKind.IMPLEMENTATION, injector.getJetTypeMapper()); new ImplementationBodyCodegen(objectDeclaration, objectContext, nameAndVisitor.getSecond(), this).generate(); ConstructorDescriptor constructorDescriptor = analyzeExhaust.getBindingContext().get(BindingContext.CONSTRUCTOR, objectDeclaration); CallableMethod callableMethod = injector.getJetTypeMapper().mapToCallableMethod( - constructorDescriptor, OwnerKind.IMPLEMENTATION, - injector.getJetTypeMapper().hasThis0(constructorDescriptor.getContainingDeclaration())); - return new GeneratedAnonymousClassDescriptor(nameAndVisitor.first, callableMethod.getSignature().getAsmMethod(), - objectContext.outerWasUsed, null); + constructorDescriptor, OwnerKind.IMPLEMENTATION, injector.getJetTypeMapper().hasThis0(constructorDescriptor.getContainingDeclaration())); + return new GeneratedAnonymousClassDescriptor(nameAndVisitor.first, callableMethod.getSignature().getAsmMethod(), objectContext.outerWasUsed, null); } public String createText() { @@ -162,8 +151,8 @@ public class GenerationState { List files = factory.files(); for (String file : files) { // if (!file.startsWith("kotlin/")) { - answer.append("@").append(file).append('\n'); - answer.append(factory.asText(file)); + answer.append("@").append(file).append('\n'); + answer.append(factory.asText(file)); // } } diff --git a/compiler/backend/src/org/jetbrains/jet/codegen/GenerationUtils.java b/compiler/backend/src/org/jetbrains/jet/codegen/GenerationUtils.java index b43db7ec503..82a8fb25b57 100644 --- a/compiler/backend/src/org/jetbrains/jet/codegen/GenerationUtils.java +++ b/compiler/backend/src/org/jetbrains/jet/codegen/GenerationUtils.java @@ -34,11 +34,11 @@ public class GenerationUtils { } public static GenerationState compileFileGetGenerationState(JetFile psiFile) { - final AnalyzeExhaust analyzeExhaust = - AnalyzerFacadeForJVM.analyzeOneFileWithJavaIntegrationAndCheckForErrors(psiFile, JetControlFlowDataTraceFactory.EMPTY); - GenerationState state = new GenerationState(psiFile.getProject(), ClassBuilderFactories.binaries(false), analyzeExhaust, - Collections.singletonList(psiFile)); + final AnalyzeExhaust analyzeExhaust = AnalyzerFacadeForJVM.analyzeOneFileWithJavaIntegrationAndCheckForErrors(psiFile, JetControlFlowDataTraceFactory.EMPTY); + GenerationState state = new GenerationState(psiFile.getProject(), ClassBuilderFactories.binaries(false), + analyzeExhaust, Collections.singletonList(psiFile)); state.compileCorrectFiles(CompilationErrorHandler.THROW_EXCEPTION); return state; } + } diff --git a/compiler/tests/org/jetbrains/jet/codegen/CodegenTestCase.java b/compiler/tests/org/jetbrains/jet/codegen/CodegenTestCase.java index d82137e2a2f..93d6c3027b9 100644 --- a/compiler/tests/org/jetbrains/jet/codegen/CodegenTestCase.java +++ b/compiler/tests/org/jetbrains/jet/codegen/CodegenTestCase.java @@ -37,13 +37,12 @@ import java.util.Collections; */ public abstract class CodegenTestCase extends JetLiteFixture { - protected static void assertThrows(Method foo, Class exceptionClass, Object instance, Object... args) - throws IllegalAccessException { + protected static void assertThrows(Method foo, Class exceptionClass, Object instance, Object... args) throws IllegalAccessException { boolean caught = false; try { foo.invoke(instance, args); } - catch (InvocationTargetException ex) { + catch(InvocationTargetException ex) { caught = exceptionClass.isInstance(ex.getTargetException()); } assertTrue(caught); @@ -61,17 +60,16 @@ public abstract class CodegenTestCase extends JetLiteFixture { } protected void loadText(final String text) { - myFile = (JetFile)createFile("a.jet", text); + myFile = (JetFile) createFile("a.jet", text); } @Override protected String loadFile(final String name) { try { final String content = doLoadFile(JetParsingTest.getTestDataDir() + "/codegen/", name); - myFile = (JetFile)createFile(name, content); + myFile = (JetFile) createFile(name, content); return content; - } - catch (IOException e) { + } catch (IOException e) { throw new RuntimeException(e); } } @@ -89,12 +87,10 @@ public abstract class CodegenTestCase extends JetLiteFixture { String actual; try { actual = blackBox(); - } - catch (NoClassDefFoundError e) { + } catch (NoClassDefFoundError e) { System.out.println(generateToText()); throw e; - } - catch (Throwable e) { + } catch (Throwable e) { System.out.println(generateToText()); throw new RuntimeException(e); } @@ -112,10 +108,9 @@ public abstract class CodegenTestCase extends JetLiteFixture { String fqName = NamespaceCodegen.getJVMClassName(JetPsiUtil.getFQName(myFile), true).replace("/", "."); Class namespaceClass = loader.loadClass(fqName); Method method = namespaceClass.getMethod("box"); - return (String)method.invoke(null); - } - finally { - loader.dispose(); + return (String) method.invoke(null); + } finally { + loader.dispose(); } } @@ -128,8 +123,7 @@ public abstract class CodegenTestCase extends JetLiteFixture { } private GenerationState generateCommon(ClassBuilderFactory classBuilderFactory) { - final AnalyzeExhaust analyzeExhaust = - AnalyzerFacadeForJVM.analyzeOneFileWithJavaIntegrationAndCheckForErrors(myFile, JetControlFlowDataTraceFactory.EMPTY); + final AnalyzeExhaust analyzeExhaust = AnalyzerFacadeForJVM.analyzeOneFileWithJavaIntegrationAndCheckForErrors(myFile, JetControlFlowDataTraceFactory.EMPTY); GenerationState state = new GenerationState(getProject(), classBuilderFactory, analyzeExhaust, Collections.singletonList(myFile)); state.compileCorrectFiles(CompilationErrorHandler.THROW_EXCEPTION); return state; @@ -149,11 +143,9 @@ public abstract class CodegenTestCase extends JetLiteFixture { String fqName = NamespaceCodegen.getJVMClassName(JetPsiUtil.getFQName(myFile), true).replace("/", "."); try { return createClassLoader(state).loadClass(fqName); - } - catch (ClassNotFoundException e) { + } catch (ClassNotFoundException e) { e.printStackTrace(); - } - catch (MalformedURLException e) { + } catch (MalformedURLException e) { e.printStackTrace(); } return null; @@ -162,10 +154,8 @@ public abstract class CodegenTestCase extends JetLiteFixture { protected Class loadClass(String fqName, @NotNull ClassFileFactory state) { try { return createClassLoader(state).loadClass(fqName); - } - catch (ClassNotFoundException e) { - } - catch (MalformedURLException e) { + } catch (ClassNotFoundException e) { + } catch (MalformedURLException e) { } fail("No classfile was generated for: " + fqName); @@ -178,8 +168,7 @@ public abstract class CodegenTestCase extends JetLiteFixture { ClassBuilderFactory classBuilderFactory = ClassBuilderFactories.binaries(false); return generateCommon(classBuilderFactory).getFactory(); - } - catch (RuntimeException e) { + } catch (RuntimeException e) { System.out.println(generateToText()); throw e; } @@ -200,12 +189,10 @@ public abstract class CodegenTestCase extends JetLiteFixture { r = method; } - if (r == null) { + if (r == null) throw new AssertionError(); - } return r; - } - catch (Error e) { + } catch (Error e) { System.out.println(generateToText()); throw e; } @@ -233,11 +220,11 @@ public abstract class CodegenTestCase extends JetLiteFixture { protected static void assertIsCurrentTime(long returnValue) { long currentTime = System.currentTimeMillis(); long diff = Math.abs(returnValue - currentTime); - assertTrue("Difference with current time: " + diff + " (this test is a bad one: it may fail even if the generated code is correct)", - diff <= 1L); + assertTrue("Difference with current time: " + diff + " (this test is a bad one: it may fail even if the generated code is correct)", diff <= 1L); } protected Class loadImplementationClass(@NotNull ClassFileFactory codegens, final String name) { return loadClass(name, codegens); } + } diff --git a/compiler/tests/org/jetbrains/jet/resolve/ExpectedResolveData.java b/compiler/tests/org/jetbrains/jet/resolve/ExpectedResolveData.java index 9a4acee5571..6a858859df8 100644 --- a/compiler/tests/org/jetbrains/jet/resolve/ExpectedResolveData.java +++ b/compiler/tests/org/jetbrains/jet/resolve/ExpectedResolveData.java @@ -35,9 +35,9 @@ import org.jetbrains.jet.lang.resolve.BindingContextUtils; import org.jetbrains.jet.lang.resolve.java.AnalyzerFacadeForJVM; import org.jetbrains.jet.lang.resolve.java.CompilerSpecialMode; import org.jetbrains.jet.lang.types.ErrorUtils; +import org.jetbrains.jet.lang.types.lang.JetStandardLibrary; import org.jetbrains.jet.lang.types.JetType; import org.jetbrains.jet.lang.types.TypeConstructor; -import org.jetbrains.jet.lang.types.lang.JetStandardLibrary; import java.util.List; import java.util.Map; @@ -139,13 +139,11 @@ public abstract class ExpectedResolveData { JetStandardLibrary lib = JetStandardLibrary.getInstance(); AnalyzeExhaust analyzeExhaust = AnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration(project, files, - Predicates.alwaysTrue(), - JetControlFlowDataTraceFactory.EMPTY, - CompilerSpecialMode.REGULAR); + Predicates.alwaysTrue(), JetControlFlowDataTraceFactory.EMPTY, CompilerSpecialMode.REGULAR); BindingContext bindingContext = analyzeExhaust.getBindingContext(); for (Diagnostic diagnostic : bindingContext.getDiagnostics()) { if (diagnostic instanceof UnresolvedReferenceDiagnostic) { - UnresolvedReferenceDiagnostic unresolvedReferenceDiagnostic = (UnresolvedReferenceDiagnostic)diagnostic; + UnresolvedReferenceDiagnostic unresolvedReferenceDiagnostic = (UnresolvedReferenceDiagnostic) diagnostic; unresolvedReferences.add(unresolvedReferenceDiagnostic.getPsiElement()); } } @@ -176,35 +174,35 @@ public abstract class ExpectedResolveData { JetReferenceExpression referenceExpression = PsiTreeUtil.getParentOfType(element, JetReferenceExpression.class); if ("!".equals(name)) { assertTrue( - "Must have been unresolved: " + - renderReferenceInContext(referenceExpression) + - " but was resolved to " + DescriptorRenderer.TEXT.render(bindingContext.get(REFERENCE_TARGET, referenceExpression)), - unresolvedReferences.contains(referenceExpression)); + "Must have been unresolved: " + + renderReferenceInContext(referenceExpression) + + " but was resolved to " + DescriptorRenderer.TEXT.render(bindingContext.get(REFERENCE_TARGET, referenceExpression)), + unresolvedReferences.contains(referenceExpression)); continue; } if ("!!".equals(name)) { assertTrue( - "Must have been resolved to multiple descriptors: " + - renderReferenceInContext(referenceExpression) + - " but was resolved to " + DescriptorRenderer.TEXT.render(bindingContext.get(REFERENCE_TARGET, referenceExpression)), - bindingContext.get(AMBIGUOUS_REFERENCE_TARGET, referenceExpression) != null); + "Must have been resolved to multiple descriptors: " + + renderReferenceInContext(referenceExpression) + + " but was resolved to " + DescriptorRenderer.TEXT.render(bindingContext.get(REFERENCE_TARGET, referenceExpression)), + bindingContext.get(AMBIGUOUS_REFERENCE_TARGET, referenceExpression) != null); continue; } else if ("!null".equals(name)) { assertTrue( - "Must have been resolved to null: " + - renderReferenceInContext(referenceExpression) + - " but was resolved to " + DescriptorRenderer.TEXT.render(bindingContext.get(REFERENCE_TARGET, referenceExpression)), - bindingContext.get(REFERENCE_TARGET, referenceExpression) == null + "Must have been resolved to null: " + + renderReferenceInContext(referenceExpression) + + " but was resolved to " + DescriptorRenderer.TEXT.render(bindingContext.get(REFERENCE_TARGET, referenceExpression)), + bindingContext.get(REFERENCE_TARGET, referenceExpression) == null ); continue; } else if ("!error".equals(name)) { assertTrue( - "Must have been resolved to error: " + - renderReferenceInContext(referenceExpression) + - " but was resolved to " + DescriptorRenderer.TEXT.render(bindingContext.get(REFERENCE_TARGET, referenceExpression)), - ErrorUtils.isError(bindingContext.get(REFERENCE_TARGET, referenceExpression)) + "Must have been resolved to error: " + + renderReferenceInContext(referenceExpression) + + " but was resolved to " + DescriptorRenderer.TEXT.render(bindingContext.get(REFERENCE_TARGET, referenceExpression)), + ErrorUtils.isError(bindingContext.get(REFERENCE_TARGET, referenceExpression)) ); continue; } @@ -252,30 +250,30 @@ public abstract class ExpectedResolveData { if (expected instanceof JetParameter || actual instanceof JetParameter) { DeclarationDescriptor expectedDescriptor; if (name.startsWith("$")) { - expectedDescriptor = bindingContext.get(BindingContext.PRIMARY_CONSTRUCTOR_PARAMETER, (JetParameter)expected); + expectedDescriptor = bindingContext.get(BindingContext.PRIMARY_CONSTRUCTOR_PARAMETER, (JetParameter) expected); } else { expectedDescriptor = bindingContext.get(BindingContext.DECLARATION_TO_DESCRIPTOR, expected); if (expectedDescriptor == null) { - expectedDescriptor = bindingContext.get(BindingContext.CONSTRUCTOR, (JetElement)expected); + expectedDescriptor = bindingContext.get(BindingContext.CONSTRUCTOR, (JetElement) expected); } } DeclarationDescriptor actualDescriptor = bindingContext.get(REFERENCE_TARGET, reference); if (actualDescriptor instanceof VariableAsFunctionDescriptor) { - VariableAsFunctionDescriptor descriptor = (VariableAsFunctionDescriptor)actualDescriptor; + VariableAsFunctionDescriptor descriptor = (VariableAsFunctionDescriptor) actualDescriptor; actualDescriptor = descriptor.getVariableDescriptor(); } assertEquals( - "Reference `" + name + "`" + renderReferenceInContext(reference) + " is resolved into " + actualName + ".", - expectedDescriptor, actualDescriptor); + "Reference `" + name + "`" + renderReferenceInContext(reference) + " is resolved into " + actualName + ".", + expectedDescriptor, actualDescriptor); } else { assertEquals( - "Reference `" + name + "`" + renderReferenceInContext(reference) + " is resolved into " + actualName + ".", - expected, actual); + "Reference `" + name + "`" + renderReferenceInContext(reference) + " is resolved into " + actualName + ".", + expected, actual); } } @@ -307,8 +305,7 @@ public abstract class ExpectedResolveData { expectedTypeConstructor = classDescriptor.getTypeConstructor(); } else if (declaration instanceof JetTypeParameter) { - TypeParameterDescriptor typeParameterDescriptor = - bindingContext.get(BindingContext.TYPE_PARAMETER, (JetTypeParameter)declaration); + TypeParameterDescriptor typeParameterDescriptor = bindingContext.get(BindingContext.TYPE_PARAMETER, (JetTypeParameter) declaration); expectedTypeConstructor = typeParameterDescriptor.getTypeConstructor(); } else { @@ -328,13 +325,14 @@ public abstract class ExpectedResolveData { PsiElement parent = statement.getParent(); if (!(parent instanceof JetExpression)) break; if (parent instanceof JetBlockExpression) break; - statement = (JetExpression)parent; + statement = (JetExpression) parent; } JetDeclaration declaration = PsiTreeUtil.getParentOfType(referenceExpression, JetDeclaration.class); + return referenceExpression.getText() + " at " + DiagnosticUtils.atLocation(referenceExpression) + - " in " + statement.getText() + (declaration == null ? "" : " in " + declaration.getText()); + " in " + statement.getText() + (declaration == null ? "" : " in " + declaration.getText()); } private static T getAncestorOfType(Class type, PsiElement element) { @@ -342,7 +340,7 @@ public abstract class ExpectedResolveData { element = element.getParent(); } @SuppressWarnings({"unchecked", "UnnecessaryLocalVariable"}) - T result = (T)element; + T result = (T) element; return result; } } diff --git a/idea/src/org/jetbrains/jet/plugin/libraries/JetSourceNavigationHelper.java b/idea/src/org/jetbrains/jet/plugin/libraries/JetSourceNavigationHelper.java index fe7b2426437..c3f9a525934 100644 --- a/idea/src/org/jetbrains/jet/plugin/libraries/JetSourceNavigationHelper.java +++ b/idea/src/org/jetbrains/jet/plugin/libraries/JetSourceNavigationHelper.java @@ -36,6 +36,7 @@ import org.jetbrains.jet.lang.descriptors.*; import org.jetbrains.jet.lang.psi.*; import org.jetbrains.jet.lang.resolve.BindingContext; import org.jetbrains.jet.lang.resolve.FqName; +import org.jetbrains.jet.lang.resolve.java.AnalyzerFacadeForJVM; import org.jetbrains.jet.lang.resolve.scopes.JetScope; import org.jetbrains.jet.lang.resolve.scopes.receivers.ReceiverDescriptor; import org.jetbrains.jet.lang.types.JetType; @@ -66,7 +67,7 @@ public class JetSourceNavigationHelper { } final List libraryFiles = findAllSourceFilesWhichContainIdentifier(declaration); for (JetFile libraryFile : libraryFiles) { - BindingContext bindingContext = AnalyzeSingleFileUtil.analyzeSingleFileWithCache(libraryFile).getBindingContext(); + BindingContext bindingContext = AnalyzeSingleFileUtil.getContextForSingleFile(libraryFile); D descriptor = bindingContext.get(slice, fqName); if (descriptor != null) { return new Tuple2(bindingContext, descriptor); diff --git a/idea/src/org/jetbrains/jet/plugin/refactoring/JetNameSuggester.java b/idea/src/org/jetbrains/jet/plugin/refactoring/JetNameSuggester.java index 64fa206b6e8..9e19dd86523 100644 --- a/idea/src/org/jetbrains/jet/plugin/refactoring/JetNameSuggester.java +++ b/idea/src/org/jetbrains/jet/plugin/refactoring/JetNameSuggester.java @@ -22,6 +22,7 @@ import com.intellij.util.ArrayUtil; import org.jetbrains.jet.lang.descriptors.ClassDescriptor; import org.jetbrains.jet.lang.psi.*; import org.jetbrains.jet.lang.resolve.BindingContext; +import org.jetbrains.jet.lang.resolve.java.AnalyzerFacadeForJVM; import org.jetbrains.jet.lang.types.ErrorUtils; import org.jetbrains.jet.lang.types.JetType; import org.jetbrains.jet.lang.types.TypeUtils; @@ -29,13 +30,12 @@ import org.jetbrains.jet.lang.types.checker.JetTypeChecker; import org.jetbrains.jet.lang.types.lang.JetStandardLibrary; import org.jetbrains.jet.lexer.JetLexer; import org.jetbrains.jet.lexer.JetTokens; +import org.jetbrains.jet.plugin.project.AnalyzeSingleFileUtil; import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; -import static org.jetbrains.jet.plugin.project.AnalyzeSingleFileUtil.getContextForSingleFile; - /** * User: Alefas * Date: 31.01.12 @@ -68,7 +68,7 @@ public class JetNameSuggester { public static String[] suggestNames(JetExpression expression, JetNameValidator validator) { ArrayList result = new ArrayList(); - BindingContext bindingContext = getContextForSingleFile((JetFile)expression.getContainingFile()); + BindingContext bindingContext = AnalyzeSingleFileUtil.getContextForSingleFile((JetFile)expression.getContainingFile()); JetType jetType = bindingContext.get(BindingContext.EXPRESSION_TYPE, expression); if (jetType != null) { addNamesForType(result, jetType, validator); diff --git a/idea/src/org/jetbrains/jet/plugin/refactoring/introduceVariable/JetIntroduceVariableHandler.java b/idea/src/org/jetbrains/jet/plugin/refactoring/introduceVariable/JetIntroduceVariableHandler.java index 31e05ec33dc..1a7828ca375 100644 --- a/idea/src/org/jetbrains/jet/plugin/refactoring/introduceVariable/JetIntroduceVariableHandler.java +++ b/idea/src/org/jetbrains/jet/plugin/refactoring/introduceVariable/JetIntroduceVariableHandler.java @@ -37,17 +37,17 @@ import org.jetbrains.annotations.Nullable; import org.jetbrains.jet.lang.descriptors.DeclarationDescriptor; import org.jetbrains.jet.lang.psi.*; import org.jetbrains.jet.lang.resolve.BindingContext; +import org.jetbrains.jet.lang.resolve.java.AnalyzerFacadeForJVM; import org.jetbrains.jet.lang.types.JetType; import org.jetbrains.jet.lang.types.NamespaceType; import org.jetbrains.jet.lang.types.checker.JetTypeChecker; import org.jetbrains.jet.lang.types.lang.JetStandardLibrary; import org.jetbrains.jet.lexer.JetTokens; +import org.jetbrains.jet.plugin.project.AnalyzeSingleFileUtil; import org.jetbrains.jet.plugin.refactoring.*; import java.util.*; -import static org.jetbrains.jet.plugin.project.AnalyzeSingleFileUtil.getContextForSingleFile; - /** * User: Alefas * Date: 25.01.12 @@ -99,7 +99,7 @@ public class JetIntroduceVariableHandler extends JetIntroduceHandlerBase { return; } } - BindingContext bindingContext = getContextForSingleFile((JetFile)expression.getContainingFile()); + BindingContext bindingContext = AnalyzeSingleFileUtil.getContextForSingleFile((JetFile)expression.getContainingFile()); final JetType expressionType = bindingContext.get(BindingContext.EXPRESSION_TYPE, expression); //can be null or error type if (expressionType instanceof NamespaceType) { showErrorHint(project, editor, JetRefactoringBundle.message("cannot.refactor.namespace.expression")); @@ -370,7 +370,7 @@ public class JetIntroduceVariableHandler extends JetIntroduceHandlerBase { final ArrayList result = new ArrayList(); - final BindingContext bindingContext = getContextForSingleFile((JetFile)expression.getContainingFile()); + final BindingContext bindingContext = AnalyzeSingleFileUtil.getContextForSingleFile((JetFile)expression.getContainingFile()); JetVisitorVoid visitor = new JetVisitorVoid() { @Override