diff --git a/compiler/backend/src/org/jetbrains/jet/codegen/GenerationState.java b/compiler/backend/src/org/jetbrains/jet/codegen/GenerationState.java index 92a7ce90742..eac7e779fa5 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,8 +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.lang.resolve.java.CompilerSpecialMode; import org.jetbrains.jet.utils.Progress; import java.util.List; @@ -52,18 +51,15 @@ public class GenerationState { public GenerationState(Project project, ClassBuilderFactory builderFactory, AnalyzeExhaust analyzeExhaust, List files) { - this(project, builderFactory, Progress.DEAF, analyzeExhaust, files, CompilerSpecialMode.REGULAR); + this(project, builderFactory, Progress.DEAF, analyzeExhaust, files); } - public GenerationState(Project project, ClassBuilderFactory builderFactory, Progress progress, - @NotNull AnalyzeExhaust exhaust, @NotNull List files, @NotNull CompilerSpecialMode compilerSpecialMode) { + 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, compilerSpecialMode, this, builderFactory); + this.injector = new InjectorForJvmCodegen(analyzeExhaust.getStandardLibrary(), analyzeExhaust.getBindingContext(), this.files, project, this, builderFactory); } @NotNull @@ -88,11 +84,11 @@ public class GenerationState { } public ClassBuilder forClassImplementation(ClassDescriptor aClass) { - return getFactory().newVisitor(getInjector().getJetTypeMapper().mapType(aClass.getDefaultType(), MapTypeMode.IMPL).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(), MapTypeMode.TRAIT_IMPL).getInternalName() + ".class"); + return getFactory().newVisitor(getInjector().getJetTypeMapper().mapType(aClass.getDefaultType(), OwnerKind.TRAIT_IMPL).getInternalName() + ".class"); } public Pair forAnonymousSubclass(JetExpression expression) { diff --git a/compiler/cli/src/org/jetbrains/jet/compiler/CompileSession.java b/compiler/cli/src/org/jetbrains/jet/compiler/CompileSession.java index 55b7d08a788..c6b35cd90e3 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.CompilerDependencies; import org.jetbrains.jet.lang.resolve.java.JavaDescriptorResolver; @@ -71,8 +71,11 @@ public class CompileSession { private final CompilerDependencies compilerDependencies; private AnalyzeExhaust bindingContext; - public CompileSession(JetCoreEnvironment environment, MessageRenderer messageRenderer, PrintStream errorStream, boolean verbose, - @NotNull CompilerDependencies compilerDependencies) { + public CompileSession(JetCoreEnvironment environment, + MessageRenderer messageRenderer, + PrintStream errorStream, + boolean verbose, + CompilerSpecialMode mode) { this.environment = environment; this.messageRenderer = messageRenderer; this.errorStream = errorStream; @@ -177,8 +180,7 @@ public class CompileSession { Predicate filesToAnalyzeCompletely = stubs ? Predicates.alwaysFalse() : Predicates.alwaysTrue(); bindingContext = AnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration( - environment.getProject(), sourceFiles, filesToAnalyzeCompletely, JetControlFlowDataTraceFactory.EMPTY, - compilerDependencies); + environment.getProject(), sourceFiles, filesToAnalyzeCompletely, JetControlFlowDataTraceFactory.EMPTY, compilerSpecialMode); for (Diagnostic diagnostic : bindingContext.getBindingContext().getDiagnostics()) { reportDiagnostic(messageCollector, diagnostic); 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 e43cee00569..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 @@ -18,22 +18,14 @@ 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.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; @@ -47,158 +39,66 @@ 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, - @NotNull final CompilerSpecialMode compilerSpecialMode, @NotNull final CompilerDependencies compilerDependencies) { - // 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; - bindingContext = analyzeFilesWithJavaIntegration( - file.getProject(), - declarationProvider.fun(file), - Predicates.equalTo(file), - JetControlFlowDataTraceFactory.EMPTY, - compilerDependencies); - 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, - @NotNull final CompilerSpecialMode compilerSpecialMode, - @NotNull final CompilerDependencies compilerDependencies) { - // 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, - compilerDependencies); - 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( - JetFile file, JetControlFlowDataTraceFactory flowDataTraceFactory, - @NotNull CompilerSpecialMode compilerSpecialMode, @NotNull CompilerDependencies compilerDependencies) { + JetFile file, JetControlFlowDataTraceFactory flowDataTraceFactory) { AnalyzingUtils.checkForSyntacticErrors(file); - AnalyzeExhaust analyzeExhaust = analyzeOneFileWithJavaIntegration(file, flowDataTraceFactory, compilerDependencies); + AnalyzeExhaust analyzeExhaust = analyzeOneFileWithJavaIntegration(file, flowDataTraceFactory); AnalyzingUtils.throwExceptionOnErrors(analyzeExhaust.getBindingContext()); return analyzeExhaust; } - public static AnalyzeExhaust analyzeOneFileWithJavaIntegration( - JetFile file, JetControlFlowDataTraceFactory flowDataTraceFactory, - @NotNull CompilerDependencies compilerDependencies) { + public static AnalyzeExhaust analyzeOneFileWithJavaIntegration(JetFile file, JetControlFlowDataTraceFactory flowDataTraceFactory) { return analyzeFilesWithJavaIntegration(file.getProject(), Collections.singleton(file), - Predicates.alwaysTrue(), flowDataTraceFactory, compilerDependencies); + Predicates.alwaysTrue(), flowDataTraceFactory, CompilerSpecialMode.REGULAR); } public static AnalyzeExhaust analyzeFilesWithJavaIntegration( - Project project, Collection files, Predicate filesToAnalyzeCompletely, - JetControlFlowDataTraceFactory flowDataTraceFactory, - @NotNull CompilerDependencies compilerDependencies) { + 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, - compilerDependencies); + project, topDownAnalysisParameters, + new ObservableBindingTrace(bindingTraceContext), owner, flowDataTraceFactory, + compilerSpecialMode); injector.getTopDownAnalyzer().analyzeFiles(files); return new AnalyzeExhaust(bindingTraceContext.getBindingContext(), JetStandardLibrary.getInstance()); } - public static AnalyzeExhaust shallowAnalyzeFiles(Collection files, - @NotNull CompilerSpecialMode compilerSpecialMode, @NotNull CompilerDependencies compilerDependencies) { + public static AnalyzeExhaust shallowAnalyzeFiles(Collection files) { assert files.size() > 0; Project project = files.iterator().next().getProject(); return analyzeFilesWithJavaIntegration(project, files, Predicates.alwaysFalse(), - JetControlFlowDataTraceFactory.EMPTY, compilerDependencies); + 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/js/js.translator/src/org/jetbrains/k2js/config/IDEAConfig.java b/compiler/frontend/src/org/jetbrains/jet/analyzer/AnalyzerFacade.java similarity index 58% rename from js/js.translator/src/org/jetbrains/k2js/config/IDEAConfig.java rename to compiler/frontend/src/org/jetbrains/jet/analyzer/AnalyzerFacade.java index cec202f7b62..7e31fee0773 100644 --- a/js/js.translator/src/org/jetbrains/k2js/config/IDEAConfig.java +++ b/compiler/frontend/src/org/jetbrains/jet/analyzer/AnalyzerFacade.java @@ -14,27 +14,25 @@ * limitations under the License. */ -package org.jetbrains.k2js.config; +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.Collections; -import java.util.List; +import java.util.Collection; /** * @author Pavel Talanov */ -public final class IDEAConfig extends Config { - - public IDEAConfig(@NotNull Project project) { - super(project); - } +public interface AnalyzerFacade { @NotNull - @Override - public List getLibFiles() { - return Collections.emptyList(); - } + AnalyzeExhaust analyzeFiles(@NotNull Project project, + @NotNull Collection files, + @NotNull Predicate filesToAnalyzeCompletely, + @NotNull JetControlFlowDataTraceFactory flowDataTraceFactory); } 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 3d8e50eb30f..9fe97e20b42 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.CompilerDependencies; import org.jetbrains.jet.lang.resolve.java.CompilerSpecialMode; @@ -102,8 +102,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()) { @@ -130,14 +130,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() { @@ -172,13 +172,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); @@ -209,7 +210,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 @@ -221,7 +222,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 aa5eae1781f..98079588d7b 100644 --- a/compiler/tests/org/jetbrains/jet/JetTestUtils.java +++ b/compiler/tests/org/jetbrains/jet/JetTestUtils.java @@ -23,6 +23,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; @@ -31,7 +32,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.lang.resolve.java.CompilerSpecialMode; import org.jetbrains.jet.util.slicedmap.ReadOnlySlice; @@ -88,7 +88,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); } @@ -102,61 +102,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, @@ -205,24 +205,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); } @@ -257,7 +258,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 b76603539b7..c3a420b6a97 100644 --- a/compiler/tests/org/jetbrains/jet/codegen/CodegenTestCase.java +++ b/compiler/tests/org/jetbrains/jet/codegen/CodegenTestCase.java @@ -20,11 +20,10 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.jet.CompileCompilerDependenciesTest; 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.lang.resolve.java.CompilerSpecialMode; import org.jetbrains.jet.parsing.JetParsingTest; diff --git a/compiler/tests/org/jetbrains/jet/codegen/GenerationUtils.java b/compiler/tests/org/jetbrains/jet/codegen/GenerationUtils.java index d5e3ff9cefb..31b26827bb5 100644 --- a/compiler/tests/org/jetbrains/jet/codegen/GenerationUtils.java +++ b/compiler/tests/org/jetbrains/jet/codegen/GenerationUtils.java @@ -17,10 +17,9 @@ package org.jetbrains.jet.codegen; import org.jetbrains.annotations.NotNull; -import org.jetbrains.jet.CompileCompilerDependenciesTest; +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 org.jetbrains.jet.lang.resolve.java.CompilerSpecialMode; diff --git a/compiler/tests/org/jetbrains/jet/resolve/ExpectedResolveData.java b/compiler/tests/org/jetbrains/jet/resolve/ExpectedResolveData.java index b7766e30d8f..e97b0d3084e 100644 --- a/compiler/tests/org/jetbrains/jet/resolve/ExpectedResolveData.java +++ b/compiler/tests/org/jetbrains/jet/resolve/ExpectedResolveData.java @@ -23,7 +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.CompileCompilerDependenciesTest; +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; @@ -32,7 +32,6 @@ 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; @@ -246,9 +245,6 @@ public abstract class ExpectedResolveData { assert expected != null : "No declaration for " + name; PsiElement actual = BindingContextUtils.resolveToDeclarationPsiElement(bindingContext, reference); - if (actual instanceof JetSimpleNameExpression) { - actual = ((JetSimpleNameExpression)actual).getIdentifier(); - } String actualName = null; if (actual != null) { diff --git a/compiler/tests/org/jetbrains/jet/types/JetDefaultModalityModifiersTest.java b/compiler/tests/org/jetbrains/jet/types/JetDefaultModalityModifiersTest.java index c38cc9db853..f0492160150 100644 --- a/compiler/tests/org/jetbrains/jet/types/JetDefaultModalityModifiersTest.java +++ b/compiler/tests/org/jetbrains/jet/types/JetDefaultModalityModifiersTest.java @@ -16,17 +16,16 @@ package org.jetbrains.jet.types; -import org.jetbrains.jet.CompileCompilerDependenciesTest; 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.cfg.pseudocode.JetControlFlowDataTraceFactory; 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.java.CompilerSpecialMode; import org.jetbrains.jet.lang.resolve.scopes.JetScope; import org.jetbrains.jet.lang.resolve.scopes.RedeclarationHandler; import org.jetbrains.jet.lang.resolve.scopes.WritableScope; @@ -64,10 +63,9 @@ 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, - CompilerSpecialMode.REGULAR, CompileCompilerDependenciesTest.compilerDependenciesForTests(CompilerSpecialMode.REGULAR)); - DeclarationDescriptor classDescriptor = bindingContext.getBindingContext().get(BindingContext.DECLARATION_TO_DESCRIPTOR, aClass); + 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); assert classDescriptor instanceof ClassifierDescriptor; scope.addClassifierDescriptor((ClassifierDescriptor) classDescriptor); 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/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/libraries/JetSourceNavigationHelper.java b/idea/src/org/jetbrains/jet/plugin/libraries/JetSourceNavigationHelper.java index 791f6a60c89..cb6c883ad75 100644 --- a/idea/src/org/jetbrains/jet/plugin/libraries/JetSourceNavigationHelper.java +++ b/idea/src/org/jetbrains/jet/plugin/libraries/JetSourceNavigationHelper.java @@ -16,7 +16,6 @@ package org.jetbrains.jet.plugin.libraries; -import com.google.common.base.Predicates; import com.intellij.openapi.project.DumbService; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.OrderEntry; @@ -33,19 +32,17 @@ import com.intellij.psi.util.PsiTreeUtil; import jet.Tuple2; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -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; import org.jetbrains.jet.lang.resolve.FqName; import org.jetbrains.jet.lang.resolve.java.AnalyzerFacadeForJVM; -import org.jetbrains.jet.lang.resolve.java.CompilerDependencies; -import org.jetbrains.jet.lang.resolve.java.CompilerSpecialMode; 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.ReadOnlySlice; +import org.jetbrains.jet.util.slicedmap.WritableSlice; import java.util.ArrayList; import java.util.Collections; @@ -62,23 +59,19 @@ public class JetSourceNavigationHelper { @Nullable private static Tuple2 - getBindingContextAndClassOrNamespaceDescriptor(@NotNull ReadOnlySlice slice, + getBindingContextAndClassOrNamespaceDescriptor(@NotNull WritableSlice slice, @NotNull JetDeclaration declaration, @Nullable FqName fqName) { if (fqName == null || DumbService.isDumb(declaration.getProject())) { return null; } - final Project project = declaration.getProject(); final List libraryFiles = findAllSourceFilesWhichContainIdentifier(declaration); - BindingContext bindingContext = AnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration( - project, - libraryFiles, - Predicates.alwaysTrue(), - JetControlFlowDataTraceFactory.EMPTY, - CompilerDependencies.compilerDependenciesForProduction(CompilerSpecialMode.REGULAR)).getBindingContext(); - D descriptor = bindingContext.get(slice, fqName); - if (descriptor != null) { - return new Tuple2(bindingContext, descriptor); + for (JetFile libraryFile : libraryFiles) { + BindingContext bindingContext = AnalyzeSingleFileUtil.getContextForSingleFile(libraryFile); + D descriptor = bindingContext.get(slice, fqName); + if (descriptor != null) { + return new Tuple2(bindingContext, descriptor); + } } return null; } diff --git a/idea/src/org/jetbrains/jet/plugin/parameterInfo/JetFunctionParameterInfoHandler.java b/idea/src/org/jetbrains/jet/plugin/parameterInfo/JetFunctionParameterInfoHandler.java index 55599a04cb2..e0b7e14ea34 100644 --- a/idea/src/org/jetbrains/jet/plugin/parameterInfo/JetFunctionParameterInfoHandler.java +++ b/idea/src/org/jetbrains/jet/plugin/parameterInfo/JetFunctionParameterInfoHandler.java @@ -31,13 +31,11 @@ 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.java.CompilerDependencies; -import org.jetbrains.jet.lang.resolve.java.CompilerSpecialMode; 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.*; @@ -190,12 +188,9 @@ public class JetFunctionParameterInfoHandler implements if (parameterOwner instanceof JetValueArgumentList) { JetValueArgumentList argumentList = (JetValueArgumentList) parameterOwner; if (descriptor instanceof FunctionDescriptor) { - JetFile file = (JetFile) argumentList.getContainingFile(); - BindingContext bindingContext = - AnalyzerFacadeForJVM.analyzeFileWithCache(file, AnalyzerFacadeForJVM.SINGLE_DECLARATION_PROVIDER, - CompilerSpecialMode.REGULAR, CompilerDependencies.compilerDependenciesForProduction(CompilerSpecialMode.REGULAR)) - .getBindingContext(); - FunctionDescriptor functionDescriptor = (FunctionDescriptor) descriptor; + JetFile file = (JetFile)argumentList.getContainingFile(); + BindingContext bindingContext = AnalyzeSingleFileUtil.getContextForSingleFile(file); + FunctionDescriptor functionDescriptor = (FunctionDescriptor)descriptor; StringBuilder builder = new StringBuilder(); List valueParameters = functionDescriptor.getValueParameters(); List valueArguments = argumentList.getArguments(); @@ -330,12 +325,12 @@ public class JetFunctionParameterInfoHandler implements JetValueArgumentList argumentList = (JetValueArgumentList) element; JetCallElement callExpression; if (element.getParent() instanceof JetCallElement) { - callExpression = (JetCallElement) element.getParent(); - } else return null; - BindingContext bindingContext = AnalyzerFacadeForJVM.analyzeFileWithCache( - (JetFile) file, - AnalyzerFacadeForJVM.SINGLE_DECLARATION_PROVIDER, CompilerSpecialMode.REGULAR, CompilerDependencies.compilerDependenciesForProduction(CompilerSpecialMode.REGULAR)) - .getBindingContext(); + callExpression = (JetCallElement)element.getParent(); + } + else { + return null; + } + 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..21d2fdb097e --- /dev/null +++ b/idea/src/org/jetbrains/jet/plugin/project/AnalyzeSingleFileUtil.java @@ -0,0 +1,41 @@ +/* + * 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.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 AnalyzerFacadeWithCache.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/project/AnalyzerFacadeProvider.java b/idea/src/org/jetbrains/jet/plugin/project/AnalyzerFacadeProvider.java new file mode 100644 index 00000000000..84ec04b4ce5 --- /dev/null +++ b/idea/src/org/jetbrains/jet/plugin/project/AnalyzerFacadeProvider.java @@ -0,0 +1,46 @@ +/* + * 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.lang.psi.JetFile; +import org.jetbrains.jet.lang.resolve.java.AnalyzerFacadeForJVM; +import org.jetbrains.k2js.analyze.AnalyzerFacadeForJS; + +/** + * @author Pavel Talanov + */ +public final class AnalyzerFacadeProvider { + + private AnalyzerFacadeProvider() { + } + + @NotNull + public static AnalyzerFacade getAnalyzerFacadeForFile(@NotNull JetFile file) { + return getAnalyzerFacadeForProject(file.getProject()); + } + + @NotNull + public static AnalyzerFacade getAnalyzerFacadeForProject(@NotNull Project project) { + if (JsModuleDetector.isJsProject(project)) { + return JSAnalyzerFacadeForIDEA.INSTANCE; + } + return AnalyzerFacadeForJVM.INSTANCE; + } +} diff --git a/idea/src/org/jetbrains/jet/plugin/project/AnalyzerFacadeWithCache.java b/idea/src/org/jetbrains/jet/plugin/project/AnalyzerFacadeWithCache.java new file mode 100644 index 00000000000..3a8458faf4b --- /dev/null +++ b/idea/src/org/jetbrains/jet/plugin/project/AnalyzerFacadeWithCache.java @@ -0,0 +1,157 @@ +/* + * 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.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.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 final class 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(); + public static final Function> SINGLE_DECLARATION_PROVIDER = new Function>() { + @Override + public Collection fun(JetFile file) { + return Collections.singleton(file); + } + }; + + private AnalyzerFacadeWithCache() { + } + + + /** + * Analyze project with string cache for given file. Given file will be fully analyzed. + * + * @param file + * @param declarationProvider + * @return + */ + @NotNull + 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); + if (bindingContextCachedValue == null) { + bindingContextCachedValue = + CachedValuesManager.getManager(file.getProject()).createCachedValue(new CachedValueProvider() { + @Override + public Result compute() { + try { + 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) { + 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 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); + if (bindingContextCachedValue == null) { + bindingContextCachedValue = + CachedValuesManager.getManager(project).createCachedValue(new CachedValueProvider() { + @Override + public Result compute() { + try { + AnalyzeExhaust analyzeExhaust = AnalyzerFacadeProvider.getAnalyzerFacadeForProject(project) + .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(); + } + } +} diff --git a/idea/src/org/jetbrains/jet/plugin/project/IDEAConfig.java b/idea/src/org/jetbrains/jet/plugin/project/IDEAConfig.java new file mode 100644 index 00000000000..4ba93444e1f --- /dev/null +++ b/idea/src/org/jetbrains/jet/plugin/project/IDEAConfig.java @@ -0,0 +1,128 @@ +/* + * 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.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.*; +import java.net.URI; +import java.net.URISyntaxException; +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 { + + @Nullable + private final String pathToLibZip; + + public IDEAConfig(@NotNull Project project) { + super(project); + this.pathToLibZip = getLibLocationForProject(project); + } + + //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) { + 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 generateLibFiles() { + if (pathToLibZip == null) { + 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/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/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..9d3df9bc1e3 --- /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 = ".kotlin-js"; + + 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 5e3d3a27b42..4e979856d71 100644 --- a/idea/src/org/jetbrains/jet/plugin/project/WholeProjectAnalyzerFacade.java +++ b/idea/src/org/jetbrains/jet/plugin/project/WholeProjectAnalyzerFacade.java @@ -19,31 +19,30 @@ 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.CompilerDependencies; -import org.jetbrains.jet.lang.resolve.java.CompilerSpecialMode; import org.jetbrains.jet.lang.resolve.java.JetFilesProvider; +import static org.jetbrains.jet.plugin.project.AnalyzerFacadeWithCache.analyzeFileWithCache; + /** * @author abreslav */ public final class WholeProjectAnalyzerFacade { - /** Forbid creating */ - private WholeProjectAnalyzerFacade() {} - + /** + * Forbid creating + */ + private WholeProjectAnalyzerFacade() { + } @NotNull public static AnalyzeExhaust analyzeProjectWithCacheOnAFile(@NotNull JetFile file) { - return AnalyzerFacadeForJVM.analyzeFileWithCache(file, JetFilesProvider.getInstance(file.getProject()).sampleToAllFilesInModule(), - CompilerSpecialMode.REGULAR, CompilerDependencies.compilerDependenciesForProduction(CompilerSpecialMode.REGULAR)); + return 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), - CompilerSpecialMode.REGULAR, CompilerDependencies.compilerDependenciesForProduction(CompilerSpecialMode.REGULAR)); + 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 461ec3a29ce..b9a425ff4df 100644 --- a/idea/src/org/jetbrains/jet/plugin/quickfix/ChangeVariableMutabilityFix.java +++ b/idea/src/org/jetbrains/jet/plugin/quickfix/ChangeVariableMutabilityFix.java @@ -31,11 +31,10 @@ 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.lang.resolve.java.CompilerDependencies; -import org.jetbrains.jet.lang.resolve.java.CompilerSpecialMode; import org.jetbrains.jet.plugin.JetBundle; +import static org.jetbrains.jet.plugin.project.AnalyzeSingleFileUtil.getContextForSingleFile; + /** * @author svtk */ @@ -75,10 +74,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, AnalyzerFacadeForJVM.SINGLE_DECLARATION_PROVIDER, - CompilerSpecialMode.REGULAR, CompilerDependencies.compilerDependenciesForProduction(CompilerSpecialMode.REGULAR)) - .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/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); diff --git a/idea/src/org/jetbrains/jet/plugin/quickfix/ImportInsertHelper.java b/idea/src/org/jetbrains/jet/plugin/quickfix/ImportInsertHelper.java index 7aef95fed4b..edb36519fb7 100644 --- a/idea/src/org/jetbrains/jet/plugin/quickfix/ImportInsertHelper.java +++ b/idea/src/org/jetbrains/jet/plugin/quickfix/ImportInsertHelper.java @@ -27,9 +27,6 @@ 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.CompilerDependencies; -import org.jetbrains.jet.lang.resolve.java.CompilerSpecialMode; import org.jetbrains.jet.lang.resolve.java.JavaBridgeConfiguration; import org.jetbrains.jet.lang.resolve.java.JavaDescriptorResolver; import org.jetbrains.jet.lang.types.ErrorUtils; @@ -39,6 +36,8 @@ import org.jetbrains.jet.util.QualifiedNamesUtil; import java.util.List; +import static org.jetbrains.jet.plugin.project.AnalyzeSingleFileUtil.getContextForSingleFile; + /** * @author svtk */ @@ -56,10 +55,7 @@ public class ImportInsertHelper { if (JetPluginUtil.checkTypeIsStandard(type, file.getProject()) || ErrorUtils.isErrorType(type)) { return; } - BindingContext bindingContext = AnalyzerFacadeForJVM.analyzeFileWithCache( - file, AnalyzerFacadeForJVM.SINGLE_DECLARATION_PROVIDER, - CompilerSpecialMode.REGULAR, CompilerDependencies.compilerDependenciesForProduction(CompilerSpecialMode.REGULAR)) - .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 75cad141c11..e053b04e873 100644 --- a/idea/src/org/jetbrains/jet/plugin/quickfix/QuickFixUtil.java +++ b/idea/src/org/jetbrains/jet/plugin/quickfix/QuickFixUtil.java @@ -16,7 +16,6 @@ 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; @@ -29,12 +28,11 @@ 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.resolve.java.CompilerDependencies; -import org.jetbrains.jet.lang.resolve.java.CompilerSpecialMode; 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 */ @@ -59,10 +57,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, AnalyzerFacadeForJVM.SINGLE_DECLARATION_PROVIDER, - CompilerSpecialMode.REGULAR, CompilerDependencies.compilerDependenciesForProduction(CompilerSpecialMode.REGULAR)) - .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 979b95df8f0..9a7e66cf0d5 100644 --- a/idea/src/org/jetbrains/jet/plugin/refactoring/JetNameSuggester.java +++ b/idea/src/org/jetbrains/jet/plugin/refactoring/JetNameSuggester.java @@ -26,12 +26,13 @@ import org.jetbrains.jet.lang.resolve.java.AnalyzerFacadeForJVM; import org.jetbrains.jet.lang.resolve.java.CompilerDependencies; 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.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; +import org.jetbrains.jet.plugin.project.AnalyzeSingleFileUtil; import java.util.ArrayList; import java.util.regex.Matcher; @@ -68,10 +69,7 @@ public class JetNameSuggester { public static String[] suggestNames(JetExpression expression, JetNameValidator validator) { ArrayList result = new ArrayList(); - BindingContext bindingContext = AnalyzerFacadeForJVM.analyzeFileWithCache((JetFile) expression.getContainingFile(), - AnalyzerFacadeForJVM.SINGLE_DECLARATION_PROVIDER, - CompilerSpecialMode.REGULAR, CompilerDependencies.compilerDependenciesForProduction(CompilerSpecialMode.REGULAR)) - .getBindingContext(); + BindingContext bindingContext = AnalyzeSingleFileUtil.getContextForSingleFile((JetFile)expression.getContainingFile()); JetType jetType = bindingContext.get(BindingContext.EXPRESSION_TYPE, expression); if (jetType != null) { addNamesForType(result, jetType, validator); @@ -155,8 +153,8 @@ 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(3); - else if (s.startsWith("is")) s = s.substring(2); + 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); diff --git a/idea/src/org/jetbrains/jet/plugin/refactoring/JetRefactoringUtil.java b/idea/src/org/jetbrains/jet/plugin/refactoring/JetRefactoringUtil.java index 0a3d4e72621..4dad2b185f6 100644 --- a/idea/src/org/jetbrains/jet/plugin/refactoring/JetRefactoringUtil.java +++ b/idea/src/org/jetbrains/jet/plugin/refactoring/JetRefactoringUtil.java @@ -30,13 +30,10 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; 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.resolve.java.CompilerDependencies; -import org.jetbrains.jet.lang.resolve.java.CompilerSpecialMode; -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; @@ -45,6 +42,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 @@ -103,11 +102,8 @@ public class JetRefactoringUtil { } } if (addExpression) { - JetExpression expression = (JetExpression) element; - BindingContext bindingContext = AnalyzerFacadeForJVM.analyzeFileWithCache((JetFile) expression.getContainingFile(), - AnalyzerFacadeForJVM.SINGLE_DECLARATION_PROVIDER, CompilerSpecialMode.REGULAR, - CompilerDependencies.compilerDependenciesForProduction(CompilerSpecialMode.REGULAR)) - .getBindingContext(); + JetExpression expression = (JetExpression)element; + 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 5a17d347615..1a7828ca375 100644 --- a/idea/src/org/jetbrains/jet/plugin/refactoring/introduceVariable/JetIntroduceVariableHandler.java +++ b/idea/src/org/jetbrains/jet/plugin/refactoring/introduceVariable/JetIntroduceVariableHandler.java @@ -38,13 +38,12 @@ 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.resolve.java.CompilerDependencies; -import org.jetbrains.jet.lang.resolve.java.CompilerSpecialMode; -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.project.AnalyzeSingleFileUtil; import org.jetbrains.jet.plugin.refactoring.*; import java.util.*; @@ -67,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()); } } @@ -78,34 +78,35 @@ 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, CompilerSpecialMode.REGULAR, CompilerDependencies.compilerDependenciesForProduction(CompilerSpecialMode.REGULAR)) - .getBindingContext(); + 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")); 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; } @@ -116,8 +117,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 @@ -127,10 +128,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, @@ -144,8 +146,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 @@ -158,13 +160,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); } } @@ -174,147 +176,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, @@ -324,7 +342,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) { @@ -341,7 +360,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; @@ -351,9 +370,7 @@ public class JetIntroduceVariableHandler extends JetIntroduceHandlerBase { final ArrayList result = new ArrayList(); - final BindingContext bindingContext = AnalyzerFacadeForJVM.analyzeFileWithCache((JetFile) expression.getContainingFile(), - AnalyzerFacadeForJVM.SINGLE_DECLARATION_PROVIDER, CompilerSpecialMode.REGULAR, CompilerDependencies.compilerDependenciesForProduction(CompilerSpecialMode.REGULAR)) - .getBindingContext(); + final BindingContext bindingContext = AnalyzeSingleFileUtil.getContextForSingleFile((JetFile)expression.getContainingFile()); JetVisitorVoid visitor = new JetVisitorVoid() { @Override @@ -370,26 +387,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); } } @@ -401,25 +428,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; } @@ -428,13 +458,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; @@ -446,27 +477,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; 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..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 @@ -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,21 +56,22 @@ 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; } @NotNull - public List getLibFiles() { + public List generateLibFiles() { if (jsLibFiles == null) { jsLibFiles = initLibFiles(getProject()); } 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..cb202551495 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; @@ -36,10 +38,10 @@ import org.jetbrains.jet.lang.resolve.scopes.WritableScope; import org.jetbrains.jet.lang.types.lang.JetStandardClasses; import org.jetbrains.k2js.config.Config; -import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; +import java.util.Set; /** * @author Pavel Talanov @@ -58,7 +60,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 +78,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,10 +86,10 @@ public final class AnalyzerFacadeForJS { } @NotNull - public static List withJsLibAdded(@NotNull List files, @NotNull Config config) { - List allFiles = new ArrayList(); - allFiles.addAll(files); - allFiles.addAll(config.getLibFiles()); + public static Collection withJsLibAdded(@NotNull Collection files, @NotNull Config config) { + Set allFiles = Sets.newHashSet(); + allFiles.addAll(toOriginal(files)); + allFiles.addAll(toOriginal(config.getLibFiles())); return allFiles; } @@ -103,6 +105,17 @@ public final class AnalyzerFacadeForJS { }; } + @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) { BindingTraceContext bindingTraceContext = new BindingTraceContext(); Project project = file.getProject(); 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 8f2f41d8c37..1d182c5d729 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 952aaeba759..0ef6e9b4f54 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; @@ -25,7 +26,6 @@ import org.jetbrains.jet.lang.types.lang.JetStandardLibrary; import org.jetbrains.jet.plugin.JetMainDetector; 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; @@ -33,10 +33,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; @@ -51,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) { @@ -62,7 +60,8 @@ public final class K2JSTranslator { FileWriter writer = new FileWriter(new File(outputPath)); try { writer.write(programCode + callToMain); - } finally { + } + finally { writer.close(); } } @@ -106,10 +105,10 @@ 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 public static String generateCallToMain(@NotNull JetFile file, @NotNull String argumentString) { String namespaceName = getNamespaceName(file); @@ -132,5 +131,4 @@ public final class K2JSTranslator { private Project getProject() { return config.getProject(); } - }