Merge from brahch analyzeJS.

Conflicts:
	compiler/backend/src/org/jetbrains/jet/codegen/GenerationState.java
	compiler/cli/src/org/jetbrains/jet/compiler/CompileSession.java
	compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/AnalyzerFacadeForJVM.java
	compiler/tests/org/jetbrains/jet/codegen/GenerationUtils.java
	compiler/tests/org/jetbrains/jet/resolve/ExpectedResolveData.java
	compiler/tests/org/jetbrains/jet/types/JetDefaultModalityModifiersTest.java
	idea/src/org/jetbrains/jet/plugin/libraries/JetSourceNavigationHelper.java
	idea/src/org/jetbrains/jet/plugin/parameterInfo/JetFunctionParameterInfoHandler.java
	idea/src/org/jetbrains/jet/plugin/project/WholeProjectAnalyzerFacade.java
	idea/src/org/jetbrains/jet/plugin/quickfix/ChangeVariableMutabilityFix.java
	idea/src/org/jetbrains/jet/plugin/quickfix/ImportInsertHelper.java
	idea/src/org/jetbrains/jet/plugin/quickfix/QuickFixUtil.java
	idea/src/org/jetbrains/jet/plugin/refactoring/JetNameSuggester.java
	idea/src/org/jetbrains/jet/plugin/refactoring/JetRefactoringUtil.java
	idea/src/org/jetbrains/jet/plugin/refactoring/introduceVariable/JetIntroduceVariableHandler.java
This commit is contained in:
Pavel V. Talanov
2012-04-09 17:06:56 +04:00
34 changed files with 982 additions and 568 deletions
@@ -25,6 +25,7 @@ import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.Pair;
import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.jet.analyzer.AnalyzeExhaust;
import org.jetbrains.jet.di.InjectorForJvmCodegen; import org.jetbrains.jet.di.InjectorForJvmCodegen;
import org.jetbrains.jet.lang.descriptors.ClassDescriptor; import org.jetbrains.jet.lang.descriptors.ClassDescriptor;
import org.jetbrains.jet.lang.descriptors.ConstructorDescriptor; 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.JetObjectDeclaration;
import org.jetbrains.jet.lang.psi.JetObjectLiteralExpression; import org.jetbrains.jet.lang.psi.JetObjectLiteralExpression;
import org.jetbrains.jet.lang.resolve.BindingContext; 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 org.jetbrains.jet.utils.Progress;
import java.util.List; import java.util.List;
@@ -52,18 +51,15 @@ public class GenerationState {
public GenerationState(Project project, ClassBuilderFactory builderFactory, AnalyzeExhaust analyzeExhaust, List<JetFile> files) { public GenerationState(Project project, ClassBuilderFactory builderFactory, AnalyzeExhaust analyzeExhaust, List<JetFile> 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, public GenerationState(Project project, ClassBuilderFactory builderFactory, Progress progress, @NotNull AnalyzeExhaust exhaust, @NotNull List<JetFile> files) {
@NotNull AnalyzeExhaust exhaust, @NotNull List<JetFile> files, @NotNull CompilerSpecialMode compilerSpecialMode) {
this.project = project; this.project = project;
this.progress = progress; this.progress = progress;
this.analyzeExhaust = exhaust; this.analyzeExhaust = exhaust;
this.files = files; this.files = files;
this.injector = new InjectorForJvmCodegen( this.injector = new InjectorForJvmCodegen(analyzeExhaust.getStandardLibrary(), analyzeExhaust.getBindingContext(), this.files, project, this, builderFactory);
analyzeExhaust.getStandardLibrary(), analyzeExhaust.getBindingContext(),
this.files, project, compilerSpecialMode, this, builderFactory);
} }
@NotNull @NotNull
@@ -88,11 +84,11 @@ public class GenerationState {
} }
public ClassBuilder forClassImplementation(ClassDescriptor aClass) { 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) { 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<String, ClassBuilder> forAnonymousSubclass(JetExpression expression) { public Pair<String, ClassBuilder> forAnonymousSubclass(JetExpression expression) {
@@ -26,6 +26,7 @@ import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager; import com.intellij.psi.PsiManager;
import com.intellij.psi.PsiRecursiveElementWalkingVisitor; import com.intellij.psi.PsiRecursiveElementWalkingVisitor;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.jet.analyzer.AnalyzeExhaust;
import org.jetbrains.jet.codegen.ClassBuilderFactories; import org.jetbrains.jet.codegen.ClassBuilderFactories;
import org.jetbrains.jet.codegen.CompilationErrorHandler; import org.jetbrains.jet.codegen.CompilationErrorHandler;
import org.jetbrains.jet.codegen.GenerationState; 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.diagnostics.Severity;
import org.jetbrains.jet.lang.psi.JetFile; import org.jetbrains.jet.lang.psi.JetFile;
import org.jetbrains.jet.lang.resolve.BindingContext; 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.AnalyzerFacadeForJVM;
import org.jetbrains.jet.lang.resolve.java.CompilerDependencies; import org.jetbrains.jet.lang.resolve.java.CompilerDependencies;
import org.jetbrains.jet.lang.resolve.java.JavaDescriptorResolver; import org.jetbrains.jet.lang.resolve.java.JavaDescriptorResolver;
@@ -71,8 +71,11 @@ public class CompileSession {
private final CompilerDependencies compilerDependencies; private final CompilerDependencies compilerDependencies;
private AnalyzeExhaust bindingContext; private AnalyzeExhaust bindingContext;
public CompileSession(JetCoreEnvironment environment, MessageRenderer messageRenderer, PrintStream errorStream, boolean verbose, public CompileSession(JetCoreEnvironment environment,
@NotNull CompilerDependencies compilerDependencies) { MessageRenderer messageRenderer,
PrintStream errorStream,
boolean verbose,
CompilerSpecialMode mode) {
this.environment = environment; this.environment = environment;
this.messageRenderer = messageRenderer; this.messageRenderer = messageRenderer;
this.errorStream = errorStream; this.errorStream = errorStream;
@@ -177,8 +180,7 @@ public class CompileSession {
Predicate<PsiFile> filesToAnalyzeCompletely = Predicate<PsiFile> filesToAnalyzeCompletely =
stubs ? Predicates.<PsiFile>alwaysFalse() : Predicates.<PsiFile>alwaysTrue(); stubs ? Predicates.<PsiFile>alwaysFalse() : Predicates.<PsiFile>alwaysTrue();
bindingContext = AnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration( bindingContext = AnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration(
environment.getProject(), sourceFiles, filesToAnalyzeCompletely, JetControlFlowDataTraceFactory.EMPTY, environment.getProject(), sourceFiles, filesToAnalyzeCompletely, JetControlFlowDataTraceFactory.EMPTY, compilerSpecialMode);
compilerDependencies);
for (Diagnostic diagnostic : bindingContext.getBindingContext().getDiagnostics()) { for (Diagnostic diagnostic : bindingContext.getBindingContext().getDiagnostics()) {
reportDiagnostic(messageCollector, diagnostic); reportDiagnostic(messageCollector, diagnostic);
@@ -18,22 +18,14 @@ package org.jetbrains.jet.lang.resolve.java;
import com.google.common.base.Predicate; import com.google.common.base.Predicate;
import com.google.common.base.Predicates; 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.project.Project;
import com.intellij.openapi.util.Key;
import com.intellij.psi.PsiFile; 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.annotations.NotNull;
import org.jetbrains.jet.analyzer.AnalyzeExhaust;
import org.jetbrains.jet.analyzer.AnalyzerFacade;
import org.jetbrains.jet.di.InjectorForTopDownAnalyzerForJvm; import org.jetbrains.jet.di.InjectorForTopDownAnalyzerForJvm;
import org.jetbrains.jet.lang.cfg.pseudocode.JetControlFlowDataTraceFactory; import org.jetbrains.jet.lang.cfg.pseudocode.JetControlFlowDataTraceFactory;
import org.jetbrains.jet.lang.descriptors.ModuleDescriptor; 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.psi.JetFile;
import org.jetbrains.jet.lang.resolve.AnalyzingUtils; import org.jetbrains.jet.lang.resolve.AnalyzingUtils;
import org.jetbrains.jet.lang.resolve.BindingTraceContext; import org.jetbrains.jet.lang.resolve.BindingTraceContext;
@@ -47,158 +39,66 @@ import java.util.Collections;
/** /**
* @author abreslav * @author abreslav
*/ */
public class AnalyzerFacadeForJVM { public enum AnalyzerFacadeForJVM implements AnalyzerFacade {
private static final Logger LOG = Logger.getInstance("org.jetbrains.jet.lang.resolve.java.AnalyzerFacadeForJVM"); INSTANCE;
public static final Function<JetFile, Collection<JetFile>> SINGLE_DECLARATION_PROVIDER = new Function<JetFile, Collection<JetFile>>() {
@Override
public Collection<JetFile> fun(JetFile file) {
return Collections.singleton(file);
}
};
private final static Key<CachedValue<AnalyzeExhaust>> BINDING_CONTEXT = Key.create("BINDING_CONTEXT");
private static final Object lock = new Object();
private AnalyzerFacadeForJVM() { private AnalyzerFacadeForJVM() {
} }
/** @Override
* Analyze project with string cache for given file. Given file will be fully analyzed. @NotNull
* public AnalyzeExhaust analyzeFiles(@NotNull Project project,
* @param file @NotNull Collection<JetFile> files,
* @param declarationProvider @NotNull Predicate<PsiFile> filesToAnalyzeCompletely,
* @return @NotNull JetControlFlowDataTraceFactory flowDataTraceFactory) {
*/ return analyzeFilesWithJavaIntegration(project, files, filesToAnalyzeCompletely, flowDataTraceFactory, CompilerSpecialMode.REGULAR);
public static AnalyzeExhaust analyzeFileWithCache(@NotNull final JetFile file,
@NotNull final Function<JetFile, Collection<JetFile>> 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<AnalyzeExhaust> bindingContextCachedValue = file.getUserData(BINDING_CONTEXT);
if (bindingContextCachedValue == null) {
bindingContextCachedValue = CachedValuesManager.getManager(file.getProject()).createCachedValue(new CachedValueProvider<AnalyzeExhaust>() {
@Override
public Result<AnalyzeExhaust> compute() {
try {
AnalyzeExhaust bindingContext;
bindingContext = analyzeFilesWithJavaIntegration(
file.getProject(),
declarationProvider.fun(file),
Predicates.<PsiFile>equalTo(file),
JetControlFlowDataTraceFactory.EMPTY,
compilerDependencies);
return new Result<AnalyzeExhaust>(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>(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<JetFile> 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<AnalyzeExhaust> bindingContextCachedValue = project.getUserData(BINDING_CONTEXT);
if (bindingContextCachedValue == null) {
bindingContextCachedValue = CachedValuesManager.getManager(project).createCachedValue(new CachedValueProvider<AnalyzeExhaust>() {
@Override
public Result<AnalyzeExhaust> compute() {
try {
AnalyzeExhaust analyzeExhaust = analyzeFilesWithJavaIntegration(
project,
files,
Predicates.<PsiFile>alwaysFalse(),
JetControlFlowDataTraceFactory.EMPTY,
compilerDependencies);
return new Result<AnalyzeExhaust>(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>(analyzeExhaust, PsiModificationTracker.MODIFICATION_COUNT);
}
}
}, false);
project.putUserData(BINDING_CONTEXT, bindingContextCachedValue);
}
return bindingContextCachedValue.getValue();
}
} }
public static AnalyzeExhaust analyzeOneFileWithJavaIntegrationAndCheckForErrors( public static AnalyzeExhaust analyzeOneFileWithJavaIntegrationAndCheckForErrors(
JetFile file, JetControlFlowDataTraceFactory flowDataTraceFactory, JetFile file, JetControlFlowDataTraceFactory flowDataTraceFactory) {
@NotNull CompilerSpecialMode compilerSpecialMode, @NotNull CompilerDependencies compilerDependencies) {
AnalyzingUtils.checkForSyntacticErrors(file); AnalyzingUtils.checkForSyntacticErrors(file);
AnalyzeExhaust analyzeExhaust = analyzeOneFileWithJavaIntegration(file, flowDataTraceFactory, compilerDependencies); AnalyzeExhaust analyzeExhaust = analyzeOneFileWithJavaIntegration(file, flowDataTraceFactory);
AnalyzingUtils.throwExceptionOnErrors(analyzeExhaust.getBindingContext()); AnalyzingUtils.throwExceptionOnErrors(analyzeExhaust.getBindingContext());
return analyzeExhaust; return analyzeExhaust;
} }
public static AnalyzeExhaust analyzeOneFileWithJavaIntegration( public static AnalyzeExhaust analyzeOneFileWithJavaIntegration(JetFile file, JetControlFlowDataTraceFactory flowDataTraceFactory) {
JetFile file, JetControlFlowDataTraceFactory flowDataTraceFactory,
@NotNull CompilerDependencies compilerDependencies) {
return analyzeFilesWithJavaIntegration(file.getProject(), Collections.singleton(file), return analyzeFilesWithJavaIntegration(file.getProject(), Collections.singleton(file),
Predicates.<PsiFile>alwaysTrue(), flowDataTraceFactory, compilerDependencies); Predicates.<PsiFile>alwaysTrue(), flowDataTraceFactory, CompilerSpecialMode.REGULAR);
} }
public static AnalyzeExhaust analyzeFilesWithJavaIntegration( public static AnalyzeExhaust analyzeFilesWithJavaIntegration(
Project project, Collection<JetFile> files, Predicate<PsiFile> filesToAnalyzeCompletely, Project project, Collection<JetFile> files, Predicate<PsiFile> filesToAnalyzeCompletely,
JetControlFlowDataTraceFactory flowDataTraceFactory, JetControlFlowDataTraceFactory flowDataTraceFactory,
@NotNull CompilerDependencies compilerDependencies) { CompilerSpecialMode compilerSpecialMode) {
BindingTraceContext bindingTraceContext = new BindingTraceContext(); BindingTraceContext bindingTraceContext = new BindingTraceContext();
final ModuleDescriptor owner = new ModuleDescriptor("<module>"); final ModuleDescriptor owner = new ModuleDescriptor("<module>");
TopDownAnalysisParameters topDownAnalysisParameters = new TopDownAnalysisParameters( TopDownAnalysisParameters topDownAnalysisParameters = new TopDownAnalysisParameters(
filesToAnalyzeCompletely, false, false); filesToAnalyzeCompletely, false, false);
InjectorForTopDownAnalyzerForJvm injector = new InjectorForTopDownAnalyzerForJvm( InjectorForTopDownAnalyzerForJvm injector = new InjectorForTopDownAnalyzerForJvm(
project, topDownAnalysisParameters, project, topDownAnalysisParameters,
new ObservableBindingTrace(bindingTraceContext), owner, flowDataTraceFactory, new ObservableBindingTrace(bindingTraceContext), owner, flowDataTraceFactory,
compilerDependencies); compilerSpecialMode);
injector.getTopDownAnalyzer().analyzeFiles(files); injector.getTopDownAnalyzer().analyzeFiles(files);
return new AnalyzeExhaust(bindingTraceContext.getBindingContext(), JetStandardLibrary.getInstance()); return new AnalyzeExhaust(bindingTraceContext.getBindingContext(), JetStandardLibrary.getInstance());
} }
public static AnalyzeExhaust shallowAnalyzeFiles(Collection<JetFile> files, public static AnalyzeExhaust shallowAnalyzeFiles(Collection<JetFile> files) {
@NotNull CompilerSpecialMode compilerSpecialMode, @NotNull CompilerDependencies compilerDependencies) {
assert files.size() > 0; assert files.size() > 0;
Project project = files.iterator().next().getProject(); Project project = files.iterator().next().getProject();
return analyzeFilesWithJavaIntegration(project, files, Predicates.<PsiFile>alwaysFalse(), return analyzeFilesWithJavaIntegration(project, files, Predicates.<PsiFile>alwaysFalse(),
JetControlFlowDataTraceFactory.EMPTY, compilerDependencies); JetControlFlowDataTraceFactory.EMPTY, CompilerSpecialMode.REGULAR);
} }
} }
@@ -14,7 +14,7 @@
* limitations under the License. * 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.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
@@ -35,7 +35,8 @@ public class AnalyzeExhaust {
this.standardLibrary = standardLibrary; this.standardLibrary = standardLibrary;
} }
@NotNull public BindingContext getBindingContext() { @NotNull
public BindingContext getBindingContext() {
return bindingContext; return bindingContext;
} }
@@ -14,27 +14,25 @@
* limitations under the License. * 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.openapi.project.Project;
import com.intellij.psi.PsiFile;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.jet.lang.cfg.pseudocode.JetControlFlowDataTraceFactory;
import org.jetbrains.jet.lang.psi.JetFile; import org.jetbrains.jet.lang.psi.JetFile;
import java.util.Collections; import java.util.Collection;
import java.util.List;
/** /**
* @author Pavel Talanov * @author Pavel Talanov
*/ */
public final class IDEAConfig extends Config { public interface AnalyzerFacade {
public IDEAConfig(@NotNull Project project) {
super(project);
}
@NotNull @NotNull
@Override AnalyzeExhaust analyzeFiles(@NotNull Project project,
public List<JetFile> getLibFiles() { @NotNull Collection<JetFile> files,
return Collections.emptyList(); @NotNull Predicate<PsiFile> filesToAnalyzeCompletely,
} @NotNull JetControlFlowDataTraceFactory flowDataTraceFactory);
} }
@@ -41,6 +41,7 @@ import com.intellij.psi.util.CachedValuesManager;
import com.intellij.psi.util.PsiModificationTracker; import com.intellij.psi.util.PsiModificationTracker;
import com.intellij.util.containers.Stack; import com.intellij.util.containers.Stack;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.jet.analyzer.AnalyzeExhaust;
import org.jetbrains.jet.codegen.ClassBuilder; import org.jetbrains.jet.codegen.ClassBuilder;
import org.jetbrains.jet.codegen.ClassBuilderFactory; import org.jetbrains.jet.codegen.ClassBuilderFactory;
import org.jetbrains.jet.codegen.CompilationErrorHandler; 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.JetFile;
import org.jetbrains.jet.lang.psi.JetPsiUtil; import org.jetbrains.jet.lang.psi.JetPsiUtil;
import org.jetbrains.jet.lang.resolve.FqName; 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.AnalyzerFacadeForJVM;
import org.jetbrains.jet.lang.resolve.java.CompilerDependencies; import org.jetbrains.jet.lang.resolve.java.CompilerDependencies;
import org.jetbrains.jet.lang.resolve.java.CompilerSpecialMode; 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) { private static PsiClass findClass(FqName fqn, StubElement<?> stub) {
if (stub instanceof PsiClassStub && Comparing.equal(fqn.getFqName(), ((PsiClassStub) stub).getQualifiedName())) { if (stub instanceof PsiClassStub && Comparing.equal(fqn.getFqName(), ((PsiClassStub)stub).getQualifiedName())) {
return (PsiClass) stub.getPsi(); return (PsiClass)stub.getPsi();
} }
for (StubElement child : stub.getChildrenStubs()) { for (StubElement child : stub.getChildrenStubs()) {
@@ -172,13 +172,14 @@ public class JetLightClass extends AbstractLightClass implements JetJavaMirrorMa
stubStack.push(answer); stubStack.push(answer);
answer.setPsiFactory(new ClsWrapperStubPsiFactory()); answer.setPsiFactory(new ClsWrapperStubPsiFactory());
final ClsFileImpl fakeFile = new ClsFileImpl((PsiManagerImpl) manager, new ClassFileViewProvider(manager, file.getVirtualFile())) { final ClsFileImpl fakeFile =
@NotNull new ClsFileImpl((PsiManagerImpl)manager, new ClassFileViewProvider(manager, file.getVirtualFile())) {
@Override @NotNull
public PsiClassHolderFileStub getStub() { @Override
return answer; public PsiClassHolderFileStub getStub() {
} return answer;
}; }
};
fakeFile.setPhysical(false); fakeFile.setPhysical(false);
answer.setPsi(fakeFile); answer.setPsi(fakeFile);
@@ -209,7 +210,7 @@ public class JetLightClass extends AbstractLightClass implements JetJavaMirrorMa
@Override @Override
public boolean isEquivalentTo(PsiElement another) { 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 @Override
@@ -221,7 +222,8 @@ public class JetLightClass extends AbstractLightClass implements JetJavaMirrorMa
public String toString() { public String toString() {
try { try {
return JetLightClass.class.getSimpleName() + ":" + getQualifiedName(); return JetLightClass.class.getSimpleName() + ":" + getQualifiedName();
} catch (Throwable e) { }
catch (Throwable e) {
return JetLightClass.class.getSimpleName() + ":" + e.toString(); return JetLightClass.class.getSimpleName() + ":" + e.toString();
} }
} }
@@ -23,6 +23,7 @@ import com.intellij.openapi.util.ShutDownTracker;
import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.io.FileUtil;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.jet.analyzer.AnalyzeExhaust;
import org.jetbrains.jet.compiler.JetCoreEnvironment; import org.jetbrains.jet.compiler.JetCoreEnvironment;
import org.jetbrains.jet.lang.cfg.pseudocode.JetControlFlowDataTraceFactory; import org.jetbrains.jet.lang.cfg.pseudocode.JetControlFlowDataTraceFactory;
import org.jetbrains.jet.lang.diagnostics.Diagnostic; 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.psi.JetFile;
import org.jetbrains.jet.lang.resolve.BindingContext; import org.jetbrains.jet.lang.resolve.BindingContext;
import org.jetbrains.jet.lang.resolve.BindingTrace; 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.AnalyzerFacadeForJVM;
import org.jetbrains.jet.lang.resolve.java.CompilerSpecialMode; import org.jetbrains.jet.lang.resolve.java.CompilerSpecialMode;
import org.jetbrains.jet.util.slicedmap.ReadOnlySlice; import org.jetbrains.jet.util.slicedmap.ReadOnlySlice;
@@ -88,7 +88,7 @@ public class JetTestUtils {
@Override @Override
public <K, V> V get(ReadOnlySlice<K, V> slice, K key) { public <K, V> V get(ReadOnlySlice<K, V> 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); return SlicedMap.DO_NOTHING.get(slice, key);
} }
@@ -102,61 +102,61 @@ public class JetTestUtils {
@Override @Override
public void report(@NotNull Diagnostic diagnostic) { public void report(@NotNull Diagnostic diagnostic) {
if (diagnostic instanceof UnresolvedReferenceDiagnostic) { if (diagnostic instanceof UnresolvedReferenceDiagnostic) {
UnresolvedReferenceDiagnostic unresolvedReferenceDiagnostic = (UnresolvedReferenceDiagnostic) diagnostic; UnresolvedReferenceDiagnostic unresolvedReferenceDiagnostic = (UnresolvedReferenceDiagnostic)diagnostic;
throw new IllegalStateException("Unresolved: " + unresolvedReferenceDiagnostic.getPsiElement().getText()); throw new IllegalStateException("Unresolved: " + unresolvedReferenceDiagnostic.getPsiElement().getText());
} }
} }
}; };
public static BindingTrace DUMMY_EXCEPTION_ON_ERROR_TRACE = new BindingTrace() { public static BindingTrace DUMMY_EXCEPTION_ON_ERROR_TRACE = new BindingTrace() {
@Override @Override
public BindingContext getBindingContext() { public BindingContext getBindingContext() {
return new BindingContext() { return new BindingContext() {
@Override @Override
public Collection<Diagnostic> getDiagnostics() { public Collection<Diagnostic> getDiagnostics() {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
@Override @Override
public <K, V> V get(ReadOnlySlice<K, V> slice, K key) { public <K, V> V get(ReadOnlySlice<K, V> slice, K key) {
return DUMMY_EXCEPTION_ON_ERROR_TRACE.get(slice, key); return DUMMY_EXCEPTION_ON_ERROR_TRACE.get(slice, key);
} }
@NotNull @NotNull
@Override @Override
public <K, V> Collection<K> getKeys(WritableSlice<K, V> slice) { public <K, V> Collection<K> getKeys(WritableSlice<K, V> slice) {
return DUMMY_EXCEPTION_ON_ERROR_TRACE.getKeys(slice); return DUMMY_EXCEPTION_ON_ERROR_TRACE.getKeys(slice);
}
};
}
@Override
public <K, V> void record(WritableSlice<K, V> slice, K key, V value) {
}
@Override
public <K> void record(WritableSlice<K, Boolean> slice, K key) {
}
@Override
public <K, V> V get(ReadOnlySlice<K, V> slice, K key) {
return null;
}
@NotNull
@Override
public <K, V> Collection<K> getKeys(WritableSlice<K, V> slice) {
assert slice.isCollective();
return Collections.emptySet();
}
@Override
public void report(@NotNull Diagnostic diagnostic) {
if (diagnostic.getSeverity() == Severity.ERROR) {
throw new IllegalStateException(diagnostic.getMessage());
}
} }
}; };
}
@Override
public <K, V> void record(WritableSlice<K, V> slice, K key, V value) {
}
@Override
public <K> void record(WritableSlice<K, Boolean> slice, K key) {
}
@Override
public <K, V> V get(ReadOnlySlice<K, V> slice, K key) {
return null;
}
@NotNull
@Override
public <K, V> Collection<K> getKeys(WritableSlice<K, V> 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) { public static AnalyzeExhaust analyzeFile(@NotNull JetFile namespace, @NotNull JetControlFlowDataTraceFactory flowDataTraceFactory) {
return AnalyzerFacadeForJVM.analyzeOneFileWithJavaIntegration(namespace, flowDataTraceFactory, return AnalyzerFacadeForJVM.analyzeOneFileWithJavaIntegration(namespace, flowDataTraceFactory,
@@ -205,24 +205,25 @@ public class JetTestUtils {
public static void deleteOnShutdown(File file) { public static void deleteOnShutdown(File file) {
if (filesToDelete.isEmpty()) { if (filesToDelete.isEmpty()) {
ShutDownTracker.getInstance().registerShutdownTask(new Runnable() { ShutDownTracker.getInstance().registerShutdownTask(new Runnable() {
@Override @Override
public void run() { public void run() {
ShutDownTracker.invokeAndWait(true, true, new Runnable() { ShutDownTracker.invokeAndWait(true, true, new Runnable() {
@Override @Override
public void run() { public void run() {
for (File victim : filesToDelete) { for (File victim : filesToDelete) {
FileUtil.delete(victim); FileUtil.delete(victim);
} }
} }
}); });
} }
}); });
} }
filesToDelete.add(file); filesToDelete.add(file);
} }
public static final Pattern FILE_PATTERN = Pattern.compile("//\\s*FILE:\\s*(.*)$", Pattern.MULTILINE); public static final Pattern FILE_PATTERN = Pattern.compile("//\\s*FILE:\\s*(.*)$", Pattern.MULTILINE);
public interface TestFileFactory<F> { public interface TestFileFactory<F> {
F create(String fileName, String text); F create(String fileName, String text);
} }
@@ -257,7 +258,10 @@ public class JetTestUtils {
if (!nextFileExists) break; 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; return testFileFiles;
} }
@@ -20,11 +20,10 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.jetbrains.jet.CompileCompilerDependenciesTest; import org.jetbrains.jet.CompileCompilerDependenciesTest;
import org.jetbrains.jet.JetLiteFixture; import org.jetbrains.jet.JetLiteFixture;
import org.jetbrains.jet.analyzer.AnalyzeExhaust;
import org.jetbrains.jet.lang.cfg.pseudocode.JetControlFlowDataTraceFactory; import org.jetbrains.jet.lang.cfg.pseudocode.JetControlFlowDataTraceFactory;
import org.jetbrains.jet.lang.psi.JetFile; import org.jetbrains.jet.lang.psi.JetFile;
import org.jetbrains.jet.lang.psi.JetPsiUtil; 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.AnalyzerFacadeForJVM;
import org.jetbrains.jet.lang.resolve.java.CompilerSpecialMode; import org.jetbrains.jet.lang.resolve.java.CompilerSpecialMode;
import org.jetbrains.jet.parsing.JetParsingTest; import org.jetbrains.jet.parsing.JetParsingTest;
@@ -17,10 +17,9 @@
package org.jetbrains.jet.codegen; package org.jetbrains.jet.codegen;
import org.jetbrains.annotations.NotNull; 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.cfg.pseudocode.JetControlFlowDataTraceFactory;
import org.jetbrains.jet.lang.psi.JetFile; 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.AnalyzerFacadeForJVM;
import org.jetbrains.jet.lang.resolve.java.CompilerSpecialMode; import org.jetbrains.jet.lang.resolve.java.CompilerSpecialMode;
@@ -23,7 +23,7 @@ import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile; import com.intellij.psi.PsiFile;
import com.intellij.psi.util.PsiTreeUtil; 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.cfg.pseudocode.JetControlFlowDataTraceFactory;
import org.jetbrains.jet.lang.descriptors.*; import org.jetbrains.jet.lang.descriptors.*;
import org.jetbrains.jet.lang.diagnostics.Diagnostic; 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.psi.*;
import org.jetbrains.jet.lang.resolve.BindingContext; import org.jetbrains.jet.lang.resolve.BindingContext;
import org.jetbrains.jet.lang.resolve.BindingContextUtils; 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.AnalyzerFacadeForJVM;
import org.jetbrains.jet.lang.resolve.java.CompilerSpecialMode; import org.jetbrains.jet.lang.resolve.java.CompilerSpecialMode;
import org.jetbrains.jet.lang.types.ErrorUtils; import org.jetbrains.jet.lang.types.ErrorUtils;
@@ -246,9 +245,6 @@ public abstract class ExpectedResolveData {
assert expected != null : "No declaration for " + name; assert expected != null : "No declaration for " + name;
PsiElement actual = BindingContextUtils.resolveToDeclarationPsiElement(bindingContext, reference); PsiElement actual = BindingContextUtils.resolveToDeclarationPsiElement(bindingContext, reference);
if (actual instanceof JetSimpleNameExpression) {
actual = ((JetSimpleNameExpression)actual).getIdentifier();
}
String actualName = null; String actualName = null;
if (actual != null) { if (actual != null) {
@@ -16,17 +16,16 @@
package org.jetbrains.jet.types; package org.jetbrains.jet.types;
import org.jetbrains.jet.CompileCompilerDependenciesTest;
import org.jetbrains.jet.JetLiteFixture; import org.jetbrains.jet.JetLiteFixture;
import org.jetbrains.jet.JetTestUtils; import org.jetbrains.jet.JetTestUtils;
import org.jetbrains.jet.analyzer.AnalyzeExhaust;
import org.jetbrains.jet.di.InjectorForTests; 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.descriptors.*;
import org.jetbrains.jet.lang.psi.*; import org.jetbrains.jet.lang.psi.*;
import org.jetbrains.jet.lang.resolve.BindingContext; import org.jetbrains.jet.lang.resolve.BindingContext;
import org.jetbrains.jet.lang.resolve.DescriptorResolver; 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.AnalyzerFacadeForJVM;
import org.jetbrains.jet.lang.resolve.java.CompilerSpecialMode;
import org.jetbrains.jet.lang.resolve.scopes.JetScope; import org.jetbrains.jet.lang.resolve.scopes.JetScope;
import org.jetbrains.jet.lang.resolve.scopes.RedeclarationHandler; import org.jetbrains.jet.lang.resolve.scopes.RedeclarationHandler;
import org.jetbrains.jet.lang.resolve.scopes.WritableScope; import org.jetbrains.jet.lang.resolve.scopes.WritableScope;
@@ -64,10 +63,9 @@ public class JetDefaultModalityModifiersTest extends JetLiteFixture {
List<JetDeclaration> declarations = file.getDeclarations(); List<JetDeclaration> declarations = file.getDeclarations();
JetDeclaration aClass = declarations.get(0); JetDeclaration aClass = declarations.get(0);
assert aClass instanceof JetClass; assert aClass instanceof JetClass;
AnalyzeExhaust bindingContext = AnalyzerFacadeForJVM.analyzeFileWithCache( AnalyzeExhaust bindingContext = AnalyzerFacadeForJVM.analyzeOneFileWithJavaIntegration(file, JetControlFlowDataTraceFactory.EMPTY);
file, AnalyzerFacadeForJVM.SINGLE_DECLARATION_PROVIDER, DeclarationDescriptor classDescriptor =
CompilerSpecialMode.REGULAR, CompileCompilerDependenciesTest.compilerDependenciesForTests(CompilerSpecialMode.REGULAR)); bindingContext.getBindingContext().get(BindingContext.DECLARATION_TO_DESCRIPTOR, aClass);
DeclarationDescriptor classDescriptor = bindingContext.getBindingContext().get(BindingContext.DECLARATION_TO_DESCRIPTOR, aClass);
WritableScopeImpl scope = new WritableScopeImpl(libraryScope, root, RedeclarationHandler.DO_NOTHING); WritableScopeImpl scope = new WritableScopeImpl(libraryScope, root, RedeclarationHandler.DO_NOTHING);
assert classDescriptor instanceof ClassifierDescriptor; assert classDescriptor instanceof ClassifierDescriptor;
scope.addClassifierDescriptor((ClassifierDescriptor) classDescriptor); scope.addClassifierDescriptor((ClassifierDescriptor) classDescriptor);
@@ -34,13 +34,13 @@ import com.sun.jdi.ReferenceType;
import com.sun.jdi.request.ClassPrepareRequest; import com.sun.jdi.request.ClassPrepareRequest;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.jetbrains.jet.analyzer.AnalyzeExhaust;
import org.jetbrains.jet.codegen.JetTypeMapper; import org.jetbrains.jet.codegen.JetTypeMapper;
import org.jetbrains.jet.codegen.NamespaceCodegen; import org.jetbrains.jet.codegen.NamespaceCodegen;
import org.jetbrains.jet.di.InjectorForJetTypeMapper; import org.jetbrains.jet.di.InjectorForJetTypeMapper;
import org.jetbrains.jet.lang.psi.JetClassOrObject; import org.jetbrains.jet.lang.psi.JetClassOrObject;
import org.jetbrains.jet.lang.psi.JetFile; import org.jetbrains.jet.lang.psi.JetFile;
import org.jetbrains.jet.lang.psi.JetPsiUtil; import org.jetbrains.jet.lang.psi.JetPsiUtil;
import org.jetbrains.jet.lang.resolve.java.AnalyzeExhaust;
import org.jetbrains.jet.plugin.project.WholeProjectAnalyzerFacade; import org.jetbrains.jet.plugin.project.WholeProjectAnalyzerFacade;
import java.util.*; import java.util.*;
@@ -67,7 +67,8 @@ public class JetPositionManager implements PositionManager {
int lineNumber; int lineNumber;
try { try {
lineNumber = location.lineNumber() - 1; lineNumber = location.lineNumber() - 1;
} catch (InternalError e) { }
catch (InternalError e) {
lineNumber = -1; lineNumber = -1;
} }
@@ -86,8 +87,8 @@ public class JetPositionManager implements PositionManager {
if (files.length == 1 && files[0] instanceof JetFile) { if (files.length == 1 && files[0] instanceof JetFile) {
return files[0]; return files[0];
} }
}
} catch (AbsentInformationException e) { catch (AbsentInformationException e) {
throw new NoDataException(); throw new NoDataException();
} }
@@ -126,7 +127,7 @@ public class JetPositionManager implements PositionManager {
ApplicationManager.getApplication().runReadAction(new Runnable() { ApplicationManager.getApplication().runReadAction(new Runnable() {
@Override @Override
public void run() { public void run() {
final JetFile file = (JetFile) sourcePosition.getFile(); final JetFile file = (JetFile)sourcePosition.getFile();
JetTypeMapper typeMapper = prepareTypeMapper(file); JetTypeMapper typeMapper = prepareTypeMapper(file);
JetClassOrObject jetClass = PsiTreeUtil.getParentOfType(sourcePosition.getElementAt(), JetClassOrObject.class); JetClassOrObject jetClass = PsiTreeUtil.getParentOfType(sourcePosition.getElementAt(), JetClassOrObject.class);
@@ -155,7 +156,7 @@ public class JetPositionManager implements PositionManager {
} }
final AnalyzeExhaust analyzeExhaust = WholeProjectAnalyzerFacade.analyzeProjectWithCacheOnAFile(file); final AnalyzeExhaust analyzeExhaust = WholeProjectAnalyzerFacade.analyzeProjectWithCacheOnAFile(file);
JetTypeMapper typeMapper = new InjectorForJetTypeMapper( JetTypeMapper typeMapper = new InjectorForJetTypeMapper(
analyzeExhaust.getStandardLibrary(), analyzeExhaust.getBindingContext(), Collections.singletonList(file)).getJetTypeMapper(); analyzeExhaust.getStandardLibrary(), analyzeExhaust.getBindingContext(), Collections.singletonList(file)).getJetTypeMapper();
myTypeMappers.put(file, typeMapper); myTypeMappers.put(file, typeMapper);
return typeMapper; return typeMapper;
} }
@@ -167,15 +168,15 @@ public class JetPositionManager implements PositionManager {
throw new NoDataException(); throw new NoDataException();
} }
try { try {
int line = position.getLine() + 1; int line = position.getLine() + 1;
List<Location> locations = myDebugProcess.getVirtualMachineProxy().versionHigher("1.4") List<Location> locations = myDebugProcess.getVirtualMachineProxy().versionHigher("1.4")
? type.locationsOfLine(DebugProcess.JAVA_STRATUM, null, line) ? type.locationsOfLine(DebugProcess.JAVA_STRATUM, null, line)
: type.locationsOfLine(line); : type.locationsOfLine(line);
if (locations == null || locations.isEmpty()) throw new NoDataException(); if (locations == null || locations.isEmpty()) throw new NoDataException();
return locations; return locations;
} }
catch (AbsentInformationException e) { catch (AbsentInformationException e) {
throw new NoDataException(); throw new NoDataException();
} }
} }
@@ -36,12 +36,12 @@ import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiFile; import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager; import com.intellij.psi.PsiManager;
import com.intellij.util.Alarm; import com.intellij.util.Alarm;
import org.jetbrains.jet.analyzer.AnalyzeExhaust;
import org.jetbrains.jet.codegen.ClassBuilderFactories; import org.jetbrains.jet.codegen.ClassBuilderFactories;
import org.jetbrains.jet.codegen.ClassFileFactory; import org.jetbrains.jet.codegen.ClassFileFactory;
import org.jetbrains.jet.codegen.CompilationErrorHandler; import org.jetbrains.jet.codegen.CompilationErrorHandler;
import org.jetbrains.jet.codegen.GenerationState; import org.jetbrains.jet.codegen.GenerationState;
import org.jetbrains.jet.lang.psi.JetFile; import org.jetbrains.jet.lang.psi.JetFile;
import org.jetbrains.jet.lang.resolve.java.AnalyzeExhaust;
import org.jetbrains.jet.plugin.project.WholeProjectAnalyzerFacade; import org.jetbrains.jet.plugin.project.WholeProjectAnalyzerFacade;
import javax.swing.*; import javax.swing.*;
@@ -69,7 +69,8 @@ public class BytecodeToolwindow extends JPanel implements Disposable {
public BytecodeToolwindow(Project project) { public BytecodeToolwindow(Project project) {
super(new BorderLayout()); super(new BorderLayout());
myProject = project; 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()); add(myEditor.getComponent());
myUpdateAlarm = new Alarm(Alarm.ThreadToUse.SWING_THREAD, this); myUpdateAlarm = new Alarm(Alarm.ThreadToUse.SWING_THREAD, this);
myUpdateAlarm.addRequest(new Runnable() { myUpdateAlarm.addRequest(new Runnable() {
@@ -92,7 +93,7 @@ public class BytecodeToolwindow extends JPanel implements Disposable {
setText(DEFAULT_TEXT); setText(DEFAULT_TEXT);
} }
else { else {
VirtualFile vFile = ((EditorEx) editor).getVirtualFile(); VirtualFile vFile = ((EditorEx)editor).getVirtualFile();
if (vFile == null) { if (vFile == null) {
setText(DEFAULT_TEXT); setText(DEFAULT_TEXT);
return; return;
@@ -104,14 +105,18 @@ public class BytecodeToolwindow extends JPanel implements Disposable {
return; return;
} }
if (oldLocation == null || !Comparing.equal(oldLocation.editor, location.editor) || oldLocation.modificationStamp != location.modificationStamp) { if (oldLocation == null ||
setText(generateToText((JetFile) psiFile)); !Comparing.equal(oldLocation.editor, location.editor) ||
oldLocation.modificationStamp != location.modificationStamp) {
setText(generateToText((JetFile)psiFile));
} }
Document document = editor.getDocument(); Document document = editor.getDocument();
int startLine = document.getLineNumber(location.startOffset); int startLine = document.getLineNumber(location.startOffset);
int endLine = document.getLineNumber(location.endOffset); 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(); Document byteCodeDocument = myEditor.getDocument();
@@ -163,7 +168,7 @@ public class BytecodeToolwindow extends JPanel implements Disposable {
byteCodeStartLine = byteCodeLine; byteCodeStartLine = byteCodeLine;
} }
if (byteCodeStartLine > 0&& ktLineNum > endLine) { if (byteCodeStartLine > 0 && ktLineNum > endLine) {
byteCodeEndLine = byteCodeLine - 1; byteCodeEndLine = byteCodeLine - 1;
break; break;
} }
@@ -179,14 +184,12 @@ public class BytecodeToolwindow extends JPanel implements Disposable {
} }
if (byteCodeStartLine == -1 || byteCodeEndLine == -1) { if (byteCodeStartLine == -1 || byteCodeEndLine == -1) {
return new Pair<Integer, Integer>(0, 0); return new Pair<Integer, Integer>(0, 0);
} }
else { else {
return new Pair<Integer, Integer>(byteCodeStartLine, byteCodeEndLine); return new Pair<Integer, Integer>(byteCodeStartLine, byteCodeEndLine);
} }
} }
private void setText(final String text) { private void setText(final String text) {
@@ -269,7 +272,7 @@ public class BytecodeToolwindow extends JPanel implements Disposable {
if (this == o) return true; if (this == o) return true;
if (!(o instanceof Location)) return false; if (!(o instanceof Location)) return false;
Location location = (Location) o; Location location = (Location)o;
if (endOffset != location.endOffset) return false; if (endOffset != location.endOffset) return false;
if (modificationStamp != location.modificationStamp) return false; if (modificationStamp != location.modificationStamp) return false;
@@ -282,7 +285,7 @@ public class BytecodeToolwindow extends JPanel implements Disposable {
@Override @Override
public int hashCode() { public int hashCode() {
int result = editor != null ? editor.hashCode() : 0; 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 + startOffset;
result = 31 * result + endOffset; result = 31 * result + endOffset;
return result; return result;
@@ -30,6 +30,7 @@ import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager; import com.intellij.psi.PsiManager;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.jet.lang.psi.JetFile; import org.jetbrains.jet.lang.psi.JetFile;
import org.jetbrains.jet.plugin.project.IDEAConfig;
import org.jetbrains.k2js.facade.K2JSTranslator; import org.jetbrains.k2js.facade.K2JSTranslator;
import java.util.Collection; import java.util.Collection;
@@ -64,6 +65,7 @@ public final class K2JSRunnerUtils {
String outputFilePath = constructPathToGeneratedFile(project, outputDirPath); String outputFilePath = constructPathToGeneratedFile(project, outputDirPath);
K2JSTranslator.translateWithCallToMainAndSaveToFile(kotlinFiles, K2JSTranslator.translateWithCallToMainAndSaveToFile(kotlinFiles,
outputFilePath, outputFilePath,
new IDEAConfig(project),
project); project);
notifySuccess(outputDirPath); notifySuccess(outputDirPath);
} }
@@ -16,7 +16,6 @@
package org.jetbrains.jet.plugin.libraries; package org.jetbrains.jet.plugin.libraries;
import com.google.common.base.Predicates;
import com.intellij.openapi.project.DumbService; import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.project.Project; import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.OrderEntry; import com.intellij.openapi.roots.OrderEntry;
@@ -33,19 +32,17 @@ import com.intellij.psi.util.PsiTreeUtil;
import jet.Tuple2; import jet.Tuple2;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.jetbrains.jet.lang.cfg.pseudocode.JetControlFlowDataTraceFactory;
import org.jetbrains.jet.lang.descriptors.*; import org.jetbrains.jet.lang.descriptors.*;
import org.jetbrains.jet.lang.psi.*; import org.jetbrains.jet.lang.psi.*;
import org.jetbrains.jet.lang.resolve.BindingContext; import org.jetbrains.jet.lang.resolve.BindingContext;
import org.jetbrains.jet.lang.resolve.FqName; import org.jetbrains.jet.lang.resolve.FqName;
import org.jetbrains.jet.lang.resolve.java.AnalyzerFacadeForJVM; 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.JetScope;
import org.jetbrains.jet.lang.resolve.scopes.receivers.ReceiverDescriptor; import org.jetbrains.jet.lang.resolve.scopes.receivers.ReceiverDescriptor;
import org.jetbrains.jet.lang.types.JetType; import org.jetbrains.jet.lang.types.JetType;
import org.jetbrains.jet.plugin.project.AnalyzeSingleFileUtil;
import org.jetbrains.jet.resolve.DescriptorRenderer; 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.ArrayList;
import java.util.Collections; import java.util.Collections;
@@ -62,23 +59,19 @@ public class JetSourceNavigationHelper {
@Nullable @Nullable
private static<D extends ClassOrNamespaceDescriptor> Tuple2<BindingContext, D> private static<D extends ClassOrNamespaceDescriptor> Tuple2<BindingContext, D>
getBindingContextAndClassOrNamespaceDescriptor(@NotNull ReadOnlySlice<FqName, D> slice, getBindingContextAndClassOrNamespaceDescriptor(@NotNull WritableSlice<FqName, D> slice,
@NotNull JetDeclaration declaration, @NotNull JetDeclaration declaration,
@Nullable FqName fqName) { @Nullable FqName fqName) {
if (fqName == null || DumbService.isDumb(declaration.getProject())) { if (fqName == null || DumbService.isDumb(declaration.getProject())) {
return null; return null;
} }
final Project project = declaration.getProject();
final List<JetFile> libraryFiles = findAllSourceFilesWhichContainIdentifier(declaration); final List<JetFile> libraryFiles = findAllSourceFilesWhichContainIdentifier(declaration);
BindingContext bindingContext = AnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration( for (JetFile libraryFile : libraryFiles) {
project, BindingContext bindingContext = AnalyzeSingleFileUtil.getContextForSingleFile(libraryFile);
libraryFiles, D descriptor = bindingContext.get(slice, fqName);
Predicates.<PsiFile>alwaysTrue(), if (descriptor != null) {
JetControlFlowDataTraceFactory.EMPTY, return new Tuple2<BindingContext, D>(bindingContext, descriptor);
CompilerDependencies.compilerDependenciesForProduction(CompilerSpecialMode.REGULAR)).getBindingContext(); }
D descriptor = bindingContext.get(slice, fqName);
if (descriptor != null) {
return new Tuple2<BindingContext, D>(bindingContext, descriptor);
} }
return null; return null;
} }
@@ -31,13 +31,11 @@ import org.jetbrains.jet.lang.descriptors.*;
import org.jetbrains.jet.lang.psi.*; import org.jetbrains.jet.lang.psi.*;
import org.jetbrains.jet.lang.resolve.BindingContext; import org.jetbrains.jet.lang.resolve.BindingContext;
import org.jetbrains.jet.lang.resolve.JetVisibilityChecker; 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.resolve.scopes.JetScope;
import org.jetbrains.jet.lang.types.JetType; import org.jetbrains.jet.lang.types.JetType;
import org.jetbrains.jet.lang.types.checker.JetTypeChecker; import org.jetbrains.jet.lang.types.checker.JetTypeChecker;
import org.jetbrains.jet.lexer.JetTokens; import org.jetbrains.jet.lexer.JetTokens;
import org.jetbrains.jet.plugin.project.AnalyzeSingleFileUtil;
import org.jetbrains.jet.resolve.DescriptorRenderer; import org.jetbrains.jet.resolve.DescriptorRenderer;
import java.awt.*; import java.awt.*;
@@ -190,12 +188,9 @@ public class JetFunctionParameterInfoHandler implements
if (parameterOwner instanceof JetValueArgumentList) { if (parameterOwner instanceof JetValueArgumentList) {
JetValueArgumentList argumentList = (JetValueArgumentList) parameterOwner; JetValueArgumentList argumentList = (JetValueArgumentList) parameterOwner;
if (descriptor instanceof FunctionDescriptor) { if (descriptor instanceof FunctionDescriptor) {
JetFile file = (JetFile) argumentList.getContainingFile(); JetFile file = (JetFile)argumentList.getContainingFile();
BindingContext bindingContext = BindingContext bindingContext = AnalyzeSingleFileUtil.getContextForSingleFile(file);
AnalyzerFacadeForJVM.analyzeFileWithCache(file, AnalyzerFacadeForJVM.SINGLE_DECLARATION_PROVIDER, FunctionDescriptor functionDescriptor = (FunctionDescriptor)descriptor;
CompilerSpecialMode.REGULAR, CompilerDependencies.compilerDependenciesForProduction(CompilerSpecialMode.REGULAR))
.getBindingContext();
FunctionDescriptor functionDescriptor = (FunctionDescriptor) descriptor;
StringBuilder builder = new StringBuilder(); StringBuilder builder = new StringBuilder();
List<ValueParameterDescriptor> valueParameters = functionDescriptor.getValueParameters(); List<ValueParameterDescriptor> valueParameters = functionDescriptor.getValueParameters();
List<JetValueArgument> valueArguments = argumentList.getArguments(); List<JetValueArgument> valueArguments = argumentList.getArguments();
@@ -330,12 +325,12 @@ public class JetFunctionParameterInfoHandler implements
JetValueArgumentList argumentList = (JetValueArgumentList) element; JetValueArgumentList argumentList = (JetValueArgumentList) element;
JetCallElement callExpression; JetCallElement callExpression;
if (element.getParent() instanceof JetCallElement) { if (element.getParent() instanceof JetCallElement) {
callExpression = (JetCallElement) element.getParent(); callExpression = (JetCallElement)element.getParent();
} else return null; }
BindingContext bindingContext = AnalyzerFacadeForJVM.analyzeFileWithCache( else {
(JetFile) file, return null;
AnalyzerFacadeForJVM.SINGLE_DECLARATION_PROVIDER, CompilerSpecialMode.REGULAR, CompilerDependencies.compilerDependenciesForProduction(CompilerSpecialMode.REGULAR)) }
.getBindingContext(); BindingContext bindingContext = AnalyzeSingleFileUtil.getContextForSingleFile((JetFile)file);
JetExpression calleeExpression = callExpression.getCalleeExpression(); JetExpression calleeExpression = callExpression.getCalleeExpression();
if (calleeExpression == null) return null; if (calleeExpression == null) return null;
JetSimpleNameExpression refExpression = null; JetSimpleNameExpression refExpression = null;
@@ -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();
}
}
@@ -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;
}
}
@@ -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<CachedValue<AnalyzeExhaust>> ANALYZE_EXHAUST = Key.create("ANALYZE_EXHAUST");
private static final Object lock = new Object();
public static final Function<JetFile, Collection<JetFile>> SINGLE_DECLARATION_PROVIDER = new Function<JetFile, Collection<JetFile>>() {
@Override
public Collection<JetFile> 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<JetFile, Collection<JetFile>> declarationProvider) {
// Need lock for getValue(), because parallel threads can start evaluation of compute() simultaneously
synchronized (lock) {
CachedValue<AnalyzeExhaust> bindingContextCachedValue = file.getUserData(ANALYZE_EXHAUST);
if (bindingContextCachedValue == null) {
bindingContextCachedValue =
CachedValuesManager.getManager(file.getProject()).createCachedValue(new CachedValueProvider<AnalyzeExhaust>() {
@Override
public Result<AnalyzeExhaust> compute() {
try {
AnalyzeExhaust exhaust = AnalyzerFacadeProvider.getAnalyzerFacadeForFile(file)
.analyzeFiles(file.getProject(),
declarationProvider.fun(file),
Predicates.<PsiFile>equalTo(file),
JetControlFlowDataTraceFactory.EMPTY);
return new Result<AnalyzeExhaust>(exhaust, PsiModificationTracker.MODIFICATION_COUNT);
}
catch (ProcessCanceledException e) {
throw e;
}
catch (Throwable e) {
handleError(e);
return emptyExhaustWithDiagnosticOnFile(e);
}
}
@NotNull
private Result<AnalyzeExhaust> 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>(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<JetFile> files) {
// Need lock for getValue(), because parallel threads can start evaluation of compute() simultaneously
synchronized (lock) {
CachedValue<AnalyzeExhaust> bindingContextCachedValue = project.getUserData(ANALYZE_EXHAUST);
if (bindingContextCachedValue == null) {
bindingContextCachedValue =
CachedValuesManager.getManager(project).createCachedValue(new CachedValueProvider<AnalyzeExhaust>() {
@Override
public Result<AnalyzeExhaust> compute() {
try {
AnalyzeExhaust analyzeExhaust = AnalyzerFacadeProvider.getAnalyzerFacadeForProject(project)
.analyzeFiles(project,
files,
Predicates.<PsiFile>alwaysFalse(),
JetControlFlowDataTraceFactory.EMPTY);
return new Result<AnalyzeExhaust>(analyzeExhaust, PsiModificationTracker.MODIFICATION_COUNT);
}
catch (ProcessCanceledException e) {
throw e;
}
catch (Throwable e) {
handleError(e);
return emptyExhaust();
}
}
@NotNull
private Result<AnalyzeExhaust> emptyExhaust() {
BindingTraceContext bindingTraceContext = new BindingTraceContext();
AnalyzeExhaust analyzeExhaust = new AnalyzeExhaust(bindingTraceContext.getBindingContext(), null);
return new Result<AnalyzeExhaust>(analyzeExhaust, PsiModificationTracker.MODIFICATION_COUNT);
}
}, false);
project.putUserData(ANALYZE_EXHAUST, bindingContextCachedValue);
}
return bindingContextCachedValue.getValue();
}
}
}
@@ -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<JetFile> 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<JetFile> traverseArchive(@NotNull ZipFile file) throws IOException {
List<JetFile> result = Lists.newArrayList();
Enumeration<? extends ZipEntry> 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;
}
}
@@ -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<JetFile> files,
@NotNull Predicate<PsiFile> filesToAnalyzeCompletely,
@NotNull JetControlFlowDataTraceFactory flowDataTraceFactory) {
BindingContext context = AnalyzerFacadeForJS.analyzeFiles(files, new IDEAConfig(project));
return new AnalyzeExhaust(context, JetStandardLibrary.getInstance());
}
}
@@ -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;
}
}
@@ -19,31 +19,30 @@ package org.jetbrains.jet.plugin.project;
import com.intellij.openapi.project.Project; import com.intellij.openapi.project.Project;
import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.GlobalSearchScope;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.jet.analyzer.AnalyzeExhaust;
import org.jetbrains.jet.lang.psi.JetFile; 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 org.jetbrains.jet.lang.resolve.java.JetFilesProvider;
import static org.jetbrains.jet.plugin.project.AnalyzerFacadeWithCache.analyzeFileWithCache;
/** /**
* @author abreslav * @author abreslav
*/ */
public final class WholeProjectAnalyzerFacade { public final class WholeProjectAnalyzerFacade {
/** Forbid creating */ /**
private WholeProjectAnalyzerFacade() {} * Forbid creating
*/
private WholeProjectAnalyzerFacade() {
}
@NotNull @NotNull
public static AnalyzeExhaust analyzeProjectWithCacheOnAFile(@NotNull JetFile file) { public static AnalyzeExhaust analyzeProjectWithCacheOnAFile(@NotNull JetFile file) {
return AnalyzerFacadeForJVM.analyzeFileWithCache(file, JetFilesProvider.getInstance(file.getProject()).sampleToAllFilesInModule(), return analyzeFileWithCache(file, JetFilesProvider.getInstance(file.getProject()).sampleToAllFilesInModule());
CompilerSpecialMode.REGULAR, CompilerDependencies.compilerDependenciesForProduction(CompilerSpecialMode.REGULAR));
} }
@NotNull @NotNull
public static AnalyzeExhaust analyzeProjectWithCache(@NotNull Project project, @NotNull GlobalSearchScope scope) { public static AnalyzeExhaust analyzeProjectWithCache(@NotNull Project project, @NotNull GlobalSearchScope scope) {
return AnalyzerFacadeForJVM.analyzeProjectWithCache(project, JetFilesProvider.getInstance(project).allInScope(scope), return AnalyzerFacadeWithCache.analyzeProjectWithCache(project, JetFilesProvider.getInstance(project).allInScope(scope));
CompilerSpecialMode.REGULAR, CompilerDependencies.compilerDependenciesForProduction(CompilerSpecialMode.REGULAR));
} }
} }
@@ -31,11 +31,10 @@ import org.jetbrains.jet.lang.psi.JetPsiFactory;
import org.jetbrains.jet.lang.psi.JetSimpleNameExpression; import org.jetbrains.jet.lang.psi.JetSimpleNameExpression;
import org.jetbrains.jet.lang.resolve.BindingContext; import org.jetbrains.jet.lang.resolve.BindingContext;
import org.jetbrains.jet.lang.resolve.BindingContextUtils; 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 org.jetbrains.jet.plugin.JetBundle;
import static org.jetbrains.jet.plugin.project.AnalyzeSingleFileUtil.getContextForSingleFile;
/** /**
* @author svtk * @author svtk
*/ */
@@ -75,10 +74,7 @@ public class ChangeVariableMutabilityFix implements IntentionAction {
if (property != null) return property; if (property != null) return property;
JetSimpleNameExpression simpleNameExpression = PsiTreeUtil.getParentOfType(elementAtCaret, JetSimpleNameExpression.class); JetSimpleNameExpression simpleNameExpression = PsiTreeUtil.getParentOfType(elementAtCaret, JetSimpleNameExpression.class);
if (simpleNameExpression != null) { if (simpleNameExpression != null) {
BindingContext bindingContext = AnalyzerFacadeForJVM.analyzeFileWithCache( BindingContext bindingContext = getContextForSingleFile(file);
file, AnalyzerFacadeForJVM.SINGLE_DECLARATION_PROVIDER,
CompilerSpecialMode.REGULAR, CompilerDependencies.compilerDependenciesForProduction(CompilerSpecialMode.REGULAR))
.getBindingContext();
VariableDescriptor descriptor = BindingContextUtils.extractVariableDescriptorIfAny(bindingContext, simpleNameExpression, true); VariableDescriptor descriptor = BindingContextUtils.extractVariableDescriptorIfAny(bindingContext, simpleNameExpression, true);
if (descriptor != null) { if (descriptor != null) {
PsiElement declaration = bindingContext.get(BindingContext.DESCRIPTOR_TO_DECLARATION, descriptor); PsiElement declaration = bindingContext.get(BindingContext.DESCRIPTOR_TO_DECLARATION, descriptor);
@@ -50,12 +50,15 @@ import com.intellij.ui.EditorNotificationPanel;
import com.intellij.ui.EditorNotifications; import com.intellij.ui.EditorNotifications;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.jet.plugin.JetFileType; import org.jetbrains.jet.plugin.JetFileType;
import org.jetbrains.jet.plugin.project.JsModuleDetector;
import org.jetbrains.jet.utils.PathUtil; import org.jetbrains.jet.utils.PathUtil;
import javax.swing.*; import javax.swing.*;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import static org.jetbrains.jet.plugin.project.JsModuleDetector.*;
public class ConfigureKotlinLibraryNotificationProvider implements EditorNotifications.Provider<EditorNotificationPanel> { public class ConfigureKotlinLibraryNotificationProvider implements EditorNotifications.Provider<EditorNotificationPanel> {
private static final Key<EditorNotificationPanel> KEY = Key.create("configure.kotlin.library"); private static final Key<EditorNotificationPanel> KEY = Key.create("configure.kotlin.library");
private final Project myProject; private final Project myProject;
@@ -82,6 +85,8 @@ public class ConfigureKotlinLibraryNotificationProvider implements EditorNotific
if (isMavenModule(module)) return null; if (isMavenModule(module)) return null;
if (isJsProject(myProject)) return null;
GlobalSearchScope scope = module.getModuleWithDependenciesAndLibrariesScope(false); GlobalSearchScope scope = module.getModuleWithDependenciesAndLibrariesScope(false);
if (JavaPsiFacade.getInstance(myProject).findClass("jet.JetObject", scope) == null) { if (JavaPsiFacade.getInstance(myProject).findClass("jet.JetObject", scope) == null) {
return createNotificationPanel(module); return createNotificationPanel(module);
@@ -27,9 +27,6 @@ import org.jetbrains.jet.lang.psi.JetPsiUtil;
import org.jetbrains.jet.lang.resolve.BindingContext; import org.jetbrains.jet.lang.resolve.BindingContext;
import org.jetbrains.jet.lang.resolve.FqName; import org.jetbrains.jet.lang.resolve.FqName;
import org.jetbrains.jet.lang.resolve.ImportPath; 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.JavaBridgeConfiguration;
import org.jetbrains.jet.lang.resolve.java.JavaDescriptorResolver; import org.jetbrains.jet.lang.resolve.java.JavaDescriptorResolver;
import org.jetbrains.jet.lang.types.ErrorUtils; import org.jetbrains.jet.lang.types.ErrorUtils;
@@ -39,6 +36,8 @@ import org.jetbrains.jet.util.QualifiedNamesUtil;
import java.util.List; import java.util.List;
import static org.jetbrains.jet.plugin.project.AnalyzeSingleFileUtil.getContextForSingleFile;
/** /**
* @author svtk * @author svtk
*/ */
@@ -56,10 +55,7 @@ public class ImportInsertHelper {
if (JetPluginUtil.checkTypeIsStandard(type, file.getProject()) || ErrorUtils.isErrorType(type)) { if (JetPluginUtil.checkTypeIsStandard(type, file.getProject()) || ErrorUtils.isErrorType(type)) {
return; return;
} }
BindingContext bindingContext = AnalyzerFacadeForJVM.analyzeFileWithCache( BindingContext bindingContext = getContextForSingleFile(file);
file, AnalyzerFacadeForJVM.SINGLE_DECLARATION_PROVIDER,
CompilerSpecialMode.REGULAR, CompilerDependencies.compilerDependenciesForProduction(CompilerSpecialMode.REGULAR))
.getBindingContext();
PsiElement element = bindingContext.get(BindingContext.DESCRIPTOR_TO_DECLARATION, type.getMemberScope().getContainingDeclaration()); 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 if (element != null && element.getContainingFile() == file) { //declaration is in the same file, so no import is needed
return; return;
@@ -16,7 +16,6 @@
package org.jetbrains.jet.plugin.quickfix; package org.jetbrains.jet.plugin.quickfix;
import com.intellij.codeInsight.intention.IntentionAction;
import com.intellij.extapi.psi.ASTDelegatePsiElement; import com.intellij.extapi.psi.ASTDelegatePsiElement;
import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile; 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.JetFile;
import org.jetbrains.jet.lang.psi.JetNamedDeclaration; import org.jetbrains.jet.lang.psi.JetNamedDeclaration;
import org.jetbrains.jet.lang.resolve.BindingContext; 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.DeferredType;
import org.jetbrains.jet.lang.types.JetType; import org.jetbrains.jet.lang.types.JetType;
import static org.jetbrains.jet.plugin.project.AnalyzeSingleFileUtil.getContextForSingleFile;
/** /**
* @author svtk * @author svtk
*/ */
@@ -59,10 +57,7 @@ public class QuickFixUtil {
public static JetType getDeclarationReturnType(JetNamedDeclaration declaration) { public static JetType getDeclarationReturnType(JetNamedDeclaration declaration) {
PsiFile file = declaration.getContainingFile(); PsiFile file = declaration.getContainingFile();
if (!(file instanceof JetFile)) return null; if (!(file instanceof JetFile)) return null;
BindingContext bindingContext = AnalyzerFacadeForJVM.analyzeFileWithCache( BindingContext bindingContext = getContextForSingleFile((JetFile)file);
(JetFile) file, AnalyzerFacadeForJVM.SINGLE_DECLARATION_PROVIDER,
CompilerSpecialMode.REGULAR, CompilerDependencies.compilerDependenciesForProduction(CompilerSpecialMode.REGULAR))
.getBindingContext();
DeclarationDescriptor descriptor = bindingContext.get(BindingContext.DECLARATION_TO_DESCRIPTOR, declaration); DeclarationDescriptor descriptor = bindingContext.get(BindingContext.DECLARATION_TO_DESCRIPTOR, declaration);
if (!(descriptor instanceof CallableDescriptor)) return null; if (!(descriptor instanceof CallableDescriptor)) return null;
JetType type = ((CallableDescriptor) descriptor).getReturnType(); JetType type = ((CallableDescriptor) descriptor).getReturnType();
@@ -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.CompilerDependencies;
import org.jetbrains.jet.lang.resolve.java.CompilerSpecialMode; import org.jetbrains.jet.lang.resolve.java.CompilerSpecialMode;
import org.jetbrains.jet.lang.types.ErrorUtils; 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.JetType;
import org.jetbrains.jet.lang.types.TypeUtils; import org.jetbrains.jet.lang.types.TypeUtils;
import org.jetbrains.jet.lang.types.checker.JetTypeChecker; 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.JetLexer;
import org.jetbrains.jet.lexer.JetTokens; import org.jetbrains.jet.lexer.JetTokens;
import org.jetbrains.jet.plugin.project.AnalyzeSingleFileUtil;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.regex.Matcher; import java.util.regex.Matcher;
@@ -68,10 +69,7 @@ public class JetNameSuggester {
public static String[] suggestNames(JetExpression expression, JetNameValidator validator) { public static String[] suggestNames(JetExpression expression, JetNameValidator validator) {
ArrayList<String> result = new ArrayList<String>(); ArrayList<String> result = new ArrayList<String>();
BindingContext bindingContext = AnalyzerFacadeForJVM.analyzeFileWithCache((JetFile) expression.getContainingFile(), BindingContext bindingContext = AnalyzeSingleFileUtil.getContextForSingleFile((JetFile)expression.getContainingFile());
AnalyzerFacadeForJVM.SINGLE_DECLARATION_PROVIDER,
CompilerSpecialMode.REGULAR, CompilerDependencies.compilerDependenciesForProduction(CompilerSpecialMode.REGULAR))
.getBindingContext();
JetType jetType = bindingContext.get(BindingContext.EXPRESSION_TYPE, expression); JetType jetType = bindingContext.get(BindingContext.EXPRESSION_TYPE, expression);
if (jetType != null) { if (jetType != null) {
addNamesForType(result, jetType, validator); addNamesForType(result, jetType, validator);
@@ -155,8 +153,8 @@ public class JetNameSuggester {
private static void addCamelNames(ArrayList<String> result, String name, JetNameValidator validator) { private static void addCamelNames(ArrayList<String> result, String name, JetNameValidator validator) {
if (name == "") return; if (name == "") return;
String s = deleteNonLetterFromString(name); String s = deleteNonLetterFromString(name);
if (s.startsWith("get") || s.startsWith("set")) s = s.substring(3); if (s.startsWith("get") || s.startsWith("set")) s = s.substring(0, 3);
else if (s.startsWith("is")) s = s.substring(2); else if (s.startsWith("is")) s = s.substring(0, 2);
for (int i = 0; i < s.length(); ++i) { for (int i = 0; i < s.length(); ++i) {
if (i == 0) { if (i == 0) {
addName(result, StringUtil.decapitalize(s), validator); addName(result, StringUtil.decapitalize(s), validator);
@@ -30,13 +30,10 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.jetbrains.jet.lang.psi.*; import org.jetbrains.jet.lang.psi.*;
import org.jetbrains.jet.lang.resolve.BindingContext; 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.JetType;
import org.jetbrains.jet.lang.types.NamespaceType; import org.jetbrains.jet.lang.types.NamespaceType;
import org.jetbrains.jet.lang.types.checker.JetTypeChecker; import org.jetbrains.jet.lang.types.checker.JetTypeChecker;
import org.jetbrains.jet.lang.types.lang.JetStandardLibrary;
import javax.swing.*; import javax.swing.*;
import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionEvent;
@@ -45,6 +42,8 @@ import java.awt.*;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import static org.jetbrains.jet.plugin.project.AnalyzeSingleFileUtil.getContextForSingleFile;
/** /**
* User: Alefas * User: Alefas
* Date: 25.01.12 * Date: 25.01.12
@@ -103,11 +102,8 @@ public class JetRefactoringUtil {
} }
} }
if (addExpression) { if (addExpression) {
JetExpression expression = (JetExpression) element; JetExpression expression = (JetExpression)element;
BindingContext bindingContext = AnalyzerFacadeForJVM.analyzeFileWithCache((JetFile) expression.getContainingFile(), BindingContext bindingContext = getContextForSingleFile((JetFile)expression.getContainingFile());
AnalyzerFacadeForJVM.SINGLE_DECLARATION_PROVIDER, CompilerSpecialMode.REGULAR,
CompilerDependencies.compilerDependenciesForProduction(CompilerSpecialMode.REGULAR))
.getBindingContext();
JetType expressionType = bindingContext.get(BindingContext.EXPRESSION_TYPE, expression); JetType expressionType = bindingContext.get(BindingContext.EXPRESSION_TYPE, expression);
if (expressionType == null || !(expressionType instanceof NamespaceType) && if (expressionType == null || !(expressionType instanceof NamespaceType) &&
!JetTypeChecker.INSTANCE.equalTypes(JetStandardLibrary. !JetTypeChecker.INSTANCE.equalTypes(JetStandardLibrary.
@@ -38,13 +38,12 @@ import org.jetbrains.jet.lang.descriptors.DeclarationDescriptor;
import org.jetbrains.jet.lang.psi.*; import org.jetbrains.jet.lang.psi.*;
import org.jetbrains.jet.lang.resolve.BindingContext; import org.jetbrains.jet.lang.resolve.BindingContext;
import org.jetbrains.jet.lang.resolve.java.AnalyzerFacadeForJVM; 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.JetType;
import org.jetbrains.jet.lang.types.NamespaceType; import org.jetbrains.jet.lang.types.NamespaceType;
import org.jetbrains.jet.lang.types.checker.JetTypeChecker; 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.lexer.JetTokens;
import org.jetbrains.jet.plugin.project.AnalyzeSingleFileUtil;
import org.jetbrains.jet.plugin.refactoring.*; import org.jetbrains.jet.plugin.refactoring.*;
import java.util.*; import java.util.*;
@@ -67,7 +66,8 @@ public class JetIntroduceVariableHandler extends JetIntroduceHandlerBase {
}; };
try { try {
JetRefactoringUtil.selectExpression(editor, file, callback); JetRefactoringUtil.selectExpression(editor, file, callback);
} catch (JetRefactoringUtil.IntroduceRefactoringException e) { }
catch (JetRefactoringUtil.IntroduceRefactoringException e) {
showErrorHint(project, editor, e.getMessage()); showErrorHint(project, editor, e.getMessage());
} }
} }
@@ -78,34 +78,35 @@ public class JetIntroduceVariableHandler extends JetIntroduceHandlerBase {
return; return;
} }
if (_expression.getParent() instanceof JetParenthesizedExpression) { if (_expression.getParent() instanceof JetParenthesizedExpression) {
_expression = (JetExpression) _expression.getParent(); _expression = (JetExpression)_expression.getParent();
} }
final JetExpression expression = _expression; final JetExpression expression = _expression;
if (expression.getParent() instanceof JetQualifiedExpression) { if (expression.getParent() instanceof JetQualifiedExpression) {
JetQualifiedExpression qualifiedExpression = (JetQualifiedExpression) expression.getParent(); JetQualifiedExpression qualifiedExpression = (JetQualifiedExpression)expression.getParent();
if (qualifiedExpression.getReceiverExpression() != expression) { if (qualifiedExpression.getReceiverExpression() != expression) {
showErrorHint(project, editor, JetRefactoringBundle.message("cannot.refactor.no.expression")); showErrorHint(project, editor, JetRefactoringBundle.message("cannot.refactor.no.expression"));
return; 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")); showErrorHint(project, editor, JetRefactoringBundle.message("cannot.refactor.no.expression"));
return; 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) { if (operationExpression.getOperationReference() == expression) {
showErrorHint(project, editor, JetRefactoringBundle.message("cannot.refactor.no.expression")); showErrorHint(project, editor, JetRefactoringBundle.message("cannot.refactor.no.expression"));
return; return;
} }
} }
BindingContext bindingContext = AnalyzerFacadeForJVM.analyzeFileWithCache((JetFile) expression.getContainingFile(), BindingContext bindingContext = AnalyzeSingleFileUtil.getContextForSingleFile((JetFile)expression.getContainingFile());
AnalyzerFacadeForJVM.SINGLE_DECLARATION_PROVIDER, CompilerSpecialMode.REGULAR, CompilerDependencies.compilerDependenciesForProduction(CompilerSpecialMode.REGULAR))
.getBindingContext();
final JetType expressionType = bindingContext.get(BindingContext.EXPRESSION_TYPE, expression); //can be null or error type final JetType expressionType = bindingContext.get(BindingContext.EXPRESSION_TYPE, expression); //can be null or error type
if (expressionType instanceof NamespaceType) { if (expressionType instanceof NamespaceType) {
showErrorHint(project, editor, JetRefactoringBundle.message("cannot.refactor.namespace.expression")); showErrorHint(project, editor, JetRefactoringBundle.message("cannot.refactor.namespace.expression"));
return; 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")); showErrorHint(project, editor, JetRefactoringBundle.message("cannot.refactor.expression.has.unit.type"));
return; return;
} }
@@ -116,8 +117,8 @@ public class JetIntroduceVariableHandler extends JetIntroduceHandlerBase {
return; return;
} }
final boolean isInplaceAvailableOnDataContext = final boolean isInplaceAvailableOnDataContext =
editor.getSettings().isVariableInplaceRenameEnabled() && editor.getSettings().isVariableInplaceRenameEnabled() &&
!ApplicationManager.getApplication().isUnitTestMode(); !ApplicationManager.getApplication().isUnitTestMode();
final ArrayList<JetExpression> allOccurrences = findOccurrences(occurrenceContainer, expression); final ArrayList<JetExpression> allOccurrences = findOccurrences(occurrenceContainer, expression);
Pass<OccurrencesChooser.ReplaceChoice> callback = new Pass<OccurrencesChooser.ReplaceChoice>() { Pass<OccurrencesChooser.ReplaceChoice> callback = new Pass<OccurrencesChooser.ReplaceChoice>() {
@Override @Override
@@ -127,7 +128,8 @@ public class JetIntroduceVariableHandler extends JetIntroduceHandlerBase {
if (OccurrencesChooser.ReplaceChoice.ALL == replaceChoice) { if (OccurrencesChooser.ReplaceChoice.ALL == replaceChoice) {
if (allOccurrences.size() > 1) replaceOccurrence = true; if (allOccurrences.size() > 1) replaceOccurrence = true;
allReplaces = allOccurrences; allReplaces = allOccurrences;
} else { }
else {
allReplaces = Collections.singletonList(expression); allReplaces = Collections.singletonList(expression);
} }
@@ -144,8 +146,8 @@ public class JetIntroduceVariableHandler extends JetIntroduceHandlerBase {
final ArrayList<JetExpression> references = new ArrayList<JetExpression>(); final ArrayList<JetExpression> references = new ArrayList<JetExpression>();
final Ref<JetExpression> reference = new Ref<JetExpression>(); final Ref<JetExpression> reference = new Ref<JetExpression>();
final Runnable introduceRunnable = introduceVariable(project, expression, suggestedNames, allReplaces, commonContainer, final Runnable introduceRunnable = introduceVariable(project, expression, suggestedNames, allReplaces, commonContainer,
commonParent, replaceOccurrence, propertyRef, references, commonParent, replaceOccurrence, propertyRef, references,
reference); reference);
final boolean finalReplaceOccurrence = replaceOccurrence; final boolean finalReplaceOccurrence = replaceOccurrence;
CommandProcessor.getInstance().executeCommand(project, new Runnable() { CommandProcessor.getInstance().executeCommand(project, new Runnable() {
@Override @Override
@@ -158,13 +160,13 @@ public class JetIntroduceVariableHandler extends JetIntroduceHandlerBase {
if (isInplaceAvailableOnDataContext) { if (isInplaceAvailableOnDataContext) {
PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument()); PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument());
PsiDocumentManager.getInstance(project). PsiDocumentManager.getInstance(project).
doPostponedOperationsAndUnblockDocument(editor.getDocument()); doPostponedOperationsAndUnblockDocument(editor.getDocument());
JetInplaceVariableIntroducer variableIntroducer = JetInplaceVariableIntroducer variableIntroducer =
new JetInplaceVariableIntroducer(property, editor, project, INTRODUCE_VARIABLE, new JetInplaceVariableIntroducer(property, editor, project, INTRODUCE_VARIABLE,
references.toArray(new JetExpression[references.size()]), references.toArray(new JetExpression[references.size()]),
reference.get(), finalReplaceOccurrence, reference.get(), finalReplaceOccurrence,
property, /*todo*/false, /*todo*/false, property, /*todo*/false, /*todo*/false,
expressionType); expressionType);
variableIntroducer.performInplaceRefactoring(suggestedNamesSet); variableIntroducer.performInplaceRefactoring(suggestedNamesSet);
} }
} }
@@ -174,8 +176,9 @@ public class JetIntroduceVariableHandler extends JetIntroduceHandlerBase {
}; };
if (isInplaceAvailableOnDataContext) { if (isInplaceAvailableOnDataContext) {
OccurrencesChooser.<JetExpression>simpleChooser(editor). OccurrencesChooser.<JetExpression>simpleChooser(editor).
showChooser(expression, allOccurrences, callback); showChooser(expression, allOccurrences, callback);
} else { }
else {
callback.pass(OccurrencesChooser.ReplaceChoice.ALL); callback.pass(OccurrencesChooser.ReplaceChoice.ALL);
} }
} }
@@ -187,134 +190,149 @@ public class JetIntroduceVariableHandler extends JetIntroduceHandlerBase {
final Ref<JetProperty> propertyRef, final Ref<JetProperty> propertyRef,
final ArrayList<JetExpression> references, final ArrayList<JetExpression> references,
final Ref<JetExpression> reference) { final Ref<JetExpression> reference) {
return new Runnable() { return new Runnable() {
@Override @Override
public void run() { public void run() {
String variableText = "val " + suggestedNames[0] + " = "; String variableText = "val " + suggestedNames[0] + " = ";
if (expression instanceof JetParenthesizedExpression) { if (expression instanceof JetParenthesizedExpression) {
JetParenthesizedExpression parenthesizedExpression = (JetParenthesizedExpression) expression; JetParenthesizedExpression parenthesizedExpression = (JetParenthesizedExpression)expression;
JetExpression innerExpression = parenthesizedExpression.getExpression(); JetExpression innerExpression = parenthesizedExpression.getExpression();
if (innerExpression != null) variableText += innerExpression.getText(); if (innerExpression != null) {
else variableText += expression.getText(); variableText += innerExpression.getText();
} else variableText += expression.getText(); }
JetProperty property = JetPsiFactory.createProperty(project, variableText); else {
if (property == null) return; variableText += expression.getText();
PsiElement anchor = calculateAnchor(commonParent, commonContainer, allReplaces); }
if (anchor == null) return; }
boolean needBraces = !(commonContainer instanceof JetBlockExpression || else {
commonContainer instanceof JetClassBody || variableText += expression.getText();
commonContainer instanceof JetClassInitializer); }
if (!needBraces) { JetProperty property = JetPsiFactory.createProperty(project, variableText);
property = (JetProperty) commonContainer.addBefore(property, anchor); if (property == null) return;
commonContainer.addBefore(JetPsiFactory.createWhiteSpace(project, "\n"), anchor); PsiElement anchor = calculateAnchor(commonParent, commonContainer, allReplaces);
} else { if (anchor == null) return;
JetExpression emptyBody = JetPsiFactory.createEmptyBody(project); boolean needBraces = !(commonContainer instanceof JetBlockExpression ||
PsiElement firstChild = emptyBody.getFirstChild(); commonContainer instanceof JetClassBody ||
emptyBody.addAfter(JetPsiFactory.createWhiteSpace(project, "\n"), firstChild); commonContainer instanceof JetClassInitializer);
if (replaceOccurrence && commonContainer != null) { if (!needBraces) {
for (JetExpression replace : allReplaces) { property = (JetProperty)commonContainer.addBefore(property, anchor);
boolean isActualExpression = expression == replace; commonContainer.addBefore(JetPsiFactory.createWhiteSpace(project, "\n"), anchor);
JetExpression element = (JetExpression) replace.replace(JetPsiFactory.createExpression(project, suggestedNames[0])); }
if (isActualExpression) reference.set(element); else {
} JetExpression emptyBody = JetPsiFactory.createEmptyBody(project);
PsiElement oldElement = commonContainer; PsiElement firstChild = emptyBody.getFirstChild();
if (commonContainer instanceof JetWhenEntry) { emptyBody.addAfter(JetPsiFactory.createWhiteSpace(project, "\n"), firstChild);
JetExpression body = ((JetWhenEntry) commonContainer).getExpression(); if (replaceOccurrence && commonContainer != null) {
if (body != null) { for (JetExpression replace : allReplaces) {
oldElement = body; boolean isActualExpression = expression == replace;
} JetExpression element =
} else if (commonContainer instanceof JetNamedFunction) { (JetExpression)replace.replace(JetPsiFactory.createExpression(project, suggestedNames[0]));
JetExpression body = ((JetNamedFunction) commonContainer).getBodyExpression(); if (isActualExpression) reference.set(element);
if (body != null) { }
oldElement = body; PsiElement oldElement = commonContainer;
} if (commonContainer instanceof JetWhenEntry) {
} else if (commonContainer instanceof JetSecondaryConstructor) { JetExpression body = ((JetWhenEntry)commonContainer).getExpression();
JetExpression body = ((JetSecondaryConstructor) commonContainer).getBodyExpression(); if (body != null) {
if (body != null) { oldElement = body;
oldElement = body; }
} }
} else if (commonContainer instanceof JetContainerNode) { else if (commonContainer instanceof JetNamedFunction) {
JetContainerNode container = (JetContainerNode) commonContainer; JetExpression body = ((JetNamedFunction)commonContainer).getBodyExpression();
PsiElement[] children = container.getChildren(); if (body != null) {
for (PsiElement child : children) { oldElement = body;
if (child instanceof JetExpression) { }
oldElement = child; }
} else if (commonContainer instanceof JetSecondaryConstructor) {
} JetExpression body = ((JetSecondaryConstructor)commonContainer).getBodyExpression();
} if (body != null) {
//ugly logic to make sure we are working with right actual expression oldElement = body;
JetExpression actualExpression = reference.get(); }
int diff = actualExpression.getTextRange().getStartOffset() - oldElement.getTextRange().getStartOffset(); }
String actualExpressionText = actualExpression.getText(); else if (commonContainer instanceof JetContainerNode) {
PsiElement newElement = emptyBody.addAfter(oldElement, firstChild); JetContainerNode container = (JetContainerNode)commonContainer;
PsiElement elem = newElement.findElementAt(diff); PsiElement[] children = container.getChildren();
while (elem != null && !(elem instanceof JetExpression && for (PsiElement child : children) {
actualExpressionText.equals(elem.getText()))) { if (child instanceof JetExpression) {
elem = elem.getParent(); oldElement = child;
} }
if (elem != null) { }
reference.set((JetExpression) elem); }
} //ugly logic to make sure we are working with right actual expression
emptyBody.addAfter(JetPsiFactory.createWhiteSpace(project, "\n"), firstChild); JetExpression actualExpression = reference.get();
property = (JetProperty) emptyBody.addAfter(property, firstChild); int diff = actualExpression.getTextRange().getStartOffset() - oldElement.getTextRange().getStartOffset();
emptyBody.addAfter(JetPsiFactory.createWhiteSpace(project, "\n"), firstChild); String actualExpressionText = actualExpression.getText();
actualExpression = reference.get(); PsiElement newElement = emptyBody.addAfter(oldElement, firstChild);
diff = actualExpression.getTextRange().getStartOffset() - emptyBody.getTextRange().getStartOffset(); PsiElement elem = newElement.findElementAt(diff);
actualExpressionText = actualExpression.getText(); while (elem != null && !(elem instanceof JetExpression &&
emptyBody = (JetExpression) anchor.replace(emptyBody); actualExpressionText.equals(elem.getText()))) {
elem = emptyBody.findElementAt(diff); elem = elem.getParent();
while (elem != null && !(elem instanceof JetExpression && }
actualExpressionText.equals(elem.getText()))) { if (elem != null) {
elem = elem.getParent(); reference.set((JetExpression)elem);
} }
if (elem != null) { emptyBody.addAfter(JetPsiFactory.createWhiteSpace(project, "\n"), firstChild);
reference.set((JetExpression) elem); property = (JetProperty)emptyBody.addAfter(property, firstChild);
} emptyBody.addAfter(JetPsiFactory.createWhiteSpace(project, "\n"), firstChild);
} else { actualExpression = reference.get();
property = (JetProperty) emptyBody.addAfter(property, firstChild); diff = actualExpression.getTextRange().getStartOffset() - emptyBody.getTextRange().getStartOffset();
emptyBody.addAfter(JetPsiFactory.createWhiteSpace(project, "\n"), firstChild); actualExpressionText = actualExpression.getText();
emptyBody = (JetExpression) anchor.replace(emptyBody); emptyBody = (JetExpression)anchor.replace(emptyBody);
} elem = emptyBody.findElementAt(diff);
for (PsiElement child : emptyBody.getChildren()) { while (elem != null && !(elem instanceof JetExpression &&
if (child instanceof JetProperty) { actualExpressionText.equals(elem.getText()))) {
property = (JetProperty) child; elem = elem.getParent();
} }
} if (elem != null) {
if (commonContainer instanceof JetNamedFunction) { reference.set((JetExpression)elem);
//we should remove equals sign }
JetNamedFunction function = (JetNamedFunction) commonContainer; }
if (!function.hasDeclaredReturnType()) { else {
//todo: add return type property = (JetProperty)emptyBody.addAfter(property, firstChild);
} emptyBody.addAfter(JetPsiFactory.createWhiteSpace(project, "\n"), firstChild);
function.getEqualsToken().delete(); emptyBody = (JetExpression)anchor.replace(emptyBody);
} else if (commonContainer instanceof JetContainerNode) { }
JetContainerNode node = (JetContainerNode) commonContainer; for (PsiElement child : emptyBody.getChildren()) {
if (node.getParent() instanceof JetIfExpression) { if (child instanceof JetProperty) {
PsiElement next = node.getNextSibling(); property = (JetProperty)child;
if (next != null) { }
PsiElement nextnext = next.getNextSibling(); }
if (nextnext != null && nextnext.getNode().getElementType() == JetTokens.ELSE_KEYWORD) { if (commonContainer instanceof JetNamedFunction) {
if (next instanceof PsiWhiteSpace) { //we should remove equals sign
next.replace(JetPsiFactory.createWhiteSpace(project, " ")) ; JetNamedFunction function = (JetNamedFunction)commonContainer;
} if (!function.hasDeclaredReturnType()) {
} //todo: add return type
} }
} function.getEqualsToken().delete();
} }
} else if (commonContainer instanceof JetContainerNode) {
for (JetExpression replace : allReplaces) { JetContainerNode node = (JetContainerNode)commonContainer;
if (replaceOccurrence && !needBraces) { if (node.getParent() instanceof JetIfExpression) {
boolean isActualExpression = expression == replace; PsiElement next = node.getNextSibling();
JetExpression element = (JetExpression) replace.replace(JetPsiFactory.createExpression(project, suggestedNames[0])); if (next != null) {
references.add(element); PsiElement nextnext = next.getNextSibling();
if (isActualExpression) reference.set(element); if (nextnext != null && nextnext.getNode().getElementType() == JetTokens.ELSE_KEYWORD) {
} else if (!needBraces) { if (next instanceof PsiWhiteSpace) {
replace.delete(); next.replace(JetPsiFactory.createWhiteSpace(project, " "));
} }
} }
propertyRef.set(property); }
} }
}; }
}
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, private static PsiElement calculateAnchor(PsiElement commonParent, PsiElement commonContainer,
@@ -324,7 +342,8 @@ public class JetIntroduceVariableHandler extends JetIntroduceHandlerBase {
while (anchor.getParent() != commonContainer) { while (anchor.getParent() != commonContainer) {
anchor = anchor.getParent(); anchor = anchor.getParent();
} }
} else { }
else {
anchor = commonContainer.getFirstChild(); anchor = commonContainer.getFirstChild();
int startOffset = commonContainer.getTextRange().getEndOffset(); int startOffset = commonContainer.getTextRange().getEndOffset();
for (JetExpression expr : allReplaces) { for (JetExpression expr : allReplaces) {
@@ -341,7 +360,7 @@ public class JetIntroduceVariableHandler extends JetIntroduceHandlerBase {
private static ArrayList<JetExpression> findOccurrences(PsiElement occurrenceContainer, @NotNull JetExpression expression) { private static ArrayList<JetExpression> findOccurrences(PsiElement occurrenceContainer, @NotNull JetExpression expression) {
if (expression instanceof JetParenthesizedExpression) { if (expression instanceof JetParenthesizedExpression) {
JetParenthesizedExpression parenthesizedExpression = (JetParenthesizedExpression) expression; JetParenthesizedExpression parenthesizedExpression = (JetParenthesizedExpression)expression;
JetExpression innerExpression = parenthesizedExpression.getExpression(); JetExpression innerExpression = parenthesizedExpression.getExpression();
if (innerExpression != null) { if (innerExpression != null) {
expression = innerExpression; expression = innerExpression;
@@ -351,9 +370,7 @@ public class JetIntroduceVariableHandler extends JetIntroduceHandlerBase {
final ArrayList<JetExpression> result = new ArrayList<JetExpression>(); final ArrayList<JetExpression> result = new ArrayList<JetExpression>();
final BindingContext bindingContext = AnalyzerFacadeForJVM.analyzeFileWithCache((JetFile) expression.getContainingFile(), final BindingContext bindingContext = AnalyzeSingleFileUtil.getContextForSingleFile((JetFile)expression.getContainingFile());
AnalyzerFacadeForJVM.SINGLE_DECLARATION_PROVIDER, CompilerSpecialMode.REGULAR, CompilerDependencies.compilerDependenciesForProduction(CompilerSpecialMode.REGULAR))
.getBindingContext();
JetVisitorVoid visitor = new JetVisitorVoid() { JetVisitorVoid visitor = new JetVisitorVoid() {
@Override @Override
@@ -370,26 +387,36 @@ public class JetIntroduceVariableHandler extends JetIntroduceHandlerBase {
if (element1.getNode().getElementType() == JetTokens.IDENTIFIER && if (element1.getNode().getElementType() == JetTokens.IDENTIFIER &&
element2.getNode().getElementType() == JetTokens.IDENTIFIER) { element2.getNode().getElementType() == JetTokens.IDENTIFIER) {
if (element1.getParent() instanceof JetSimpleNameExpression && if (element1.getParent() instanceof JetSimpleNameExpression &&
element2.getParent() instanceof JetSimpleNameExpression) { element2.getParent() instanceof JetSimpleNameExpression) {
JetSimpleNameExpression expr1 = (JetSimpleNameExpression) element1.getParent(); JetSimpleNameExpression expr1 = (JetSimpleNameExpression)element1.getParent();
JetSimpleNameExpression expr2 = (JetSimpleNameExpression) element2.getParent(); JetSimpleNameExpression expr2 = (JetSimpleNameExpression)element2.getParent();
DeclarationDescriptor descr1 = bindingContext.get(BindingContext.REFERENCE_TARGET, expr1); DeclarationDescriptor descr1 = bindingContext.get(BindingContext.REFERENCE_TARGET, expr1);
DeclarationDescriptor descr2 = bindingContext.get(BindingContext.REFERENCE_TARGET, expr2); DeclarationDescriptor descr2 = bindingContext.get(BindingContext.REFERENCE_TARGET, expr2);
if (descr1 != descr2) return 1; if (descr1 != descr2) {
else return 0; return 1;
}
else {
return 0;
}
} }
} }
if (!element1.textMatches(element2)) return 1; if (!element1.textMatches(element2)) {
else return 0; return 1;
}
else {
return 0;
}
} }
}, null, false)) { }, null, false)) {
PsiElement parent = expression.getParent(); PsiElement parent = expression.getParent();
if (parent instanceof JetParenthesizedExpression) { if (parent instanceof JetParenthesizedExpression) {
result.add((JetParenthesizedExpression) parent); result.add((JetParenthesizedExpression)parent);
} else { }
else {
result.add(expression); result.add(expression);
} }
} else { }
else {
super.visitExpression(expression); super.visitExpression(expression);
} }
} }
@@ -401,25 +428,28 @@ public class JetIntroduceVariableHandler extends JetIntroduceHandlerBase {
@Nullable @Nullable
private static PsiElement getContainer(PsiElement place) { private static PsiElement getContainer(PsiElement place) {
if (place instanceof JetBlockExpression || place instanceof JetClassBody || if (place instanceof JetBlockExpression || place instanceof JetClassBody ||
place instanceof JetClassInitializer) { place instanceof JetClassInitializer) {
return place; return place;
} }
while (place != null) { while (place != null) {
PsiElement parent = place.getParent(); PsiElement parent = place.getParent();
if (parent instanceof JetContainerNode) { if (parent instanceof JetContainerNode) {
if (!isBadContainerNode((JetContainerNode) parent, place)) { if (!isBadContainerNode((JetContainerNode)parent, place)) {
return parent; return parent;
} }
} if (parent instanceof JetBlockExpression || parent instanceof JetWhenEntry || }
if (parent instanceof JetBlockExpression || parent instanceof JetWhenEntry ||
parent instanceof JetClassBody || parent instanceof JetClassInitializer) { parent instanceof JetClassBody || parent instanceof JetClassInitializer) {
return parent; return parent;
} else if (parent instanceof JetNamedFunction) { }
JetNamedFunction function = (JetNamedFunction) parent; else if (parent instanceof JetNamedFunction) {
JetNamedFunction function = (JetNamedFunction)parent;
if (function.getBodyExpression() == place) { if (function.getBodyExpression() == place) {
return parent; return parent;
} }
} else if (parent instanceof JetSecondaryConstructor) { }
JetSecondaryConstructor secondaryConstructor = (JetSecondaryConstructor) parent; else if (parent instanceof JetSecondaryConstructor) {
JetSecondaryConstructor secondaryConstructor = (JetSecondaryConstructor)parent;
if (secondaryConstructor.getBodyExpression() == place) { if (secondaryConstructor.getBodyExpression() == place) {
return parent; return parent;
} }
@@ -431,10 +461,11 @@ public class JetIntroduceVariableHandler extends JetIntroduceHandlerBase {
private static boolean isBadContainerNode(JetContainerNode parent, PsiElement place) { private static boolean isBadContainerNode(JetContainerNode parent, PsiElement place) {
if (parent.getParent() instanceof JetIfExpression && if (parent.getParent() instanceof JetIfExpression &&
((JetIfExpression) parent.getParent()).getCondition() == place) { ((JetIfExpression)parent.getParent()).getCondition() == place) {
return true; 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 true;
} }
return false; return false;
@@ -446,27 +477,36 @@ public class JetIntroduceVariableHandler extends JetIntroduceHandlerBase {
while (place != null) { while (place != null) {
PsiElement parent = place.getParent(); PsiElement parent = place.getParent();
if (parent instanceof JetContainerNode) { if (parent instanceof JetContainerNode) {
if (!(place instanceof JetBlockExpression) && !isBadContainerNode((JetContainerNode) parent, place)) { if (!(place instanceof JetBlockExpression) && !isBadContainerNode((JetContainerNode)parent, place)) {
result = parent; result = parent;
} }
} else if (parent instanceof JetClassBody || parent instanceof JetFile || parent instanceof JetClassInitializer) { }
if (result == null) return parent; else if (parent instanceof JetClassBody || parent instanceof JetFile || parent instanceof JetClassInitializer) {
else return result; if (result == null) {
} else if (parent instanceof JetBlockExpression) { return parent;
}
else {
return result;
}
}
else if (parent instanceof JetBlockExpression) {
result = parent; result = parent;
} else if (parent instanceof JetWhenEntry ) { }
else if (parent instanceof JetWhenEntry) {
if (!(place instanceof JetBlockExpression)) { if (!(place instanceof JetBlockExpression)) {
result = parent; 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 (function.getBodyExpression() == place) {
if (!(place instanceof JetBlockExpression)) { if (!(place instanceof JetBlockExpression)) {
result = parent; 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 (secondaryConstructor.getBodyExpression() == place) {
if (!(place instanceof JetBlockExpression)) { if (!(place instanceof JetBlockExpression)) {
result = parent; result = parent;
@@ -25,7 +25,6 @@ import org.jetbrains.k2js.config.Config;
import org.jetbrains.k2js.utils.JetFileUtils; import org.jetbrains.k2js.utils.JetFileUtils;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.util.ArrayList; import java.util.ArrayList;
@@ -57,21 +56,22 @@ public final class TestConfig extends Config {
try { try {
String text = FileUtil.loadTextAndClose(stream); String text = FileUtil.loadTextAndClose(stream);
file = JetFileUtils.createPsiFile(libFileName, text, project); file = JetFileUtils.createPsiFile(libFileName, text, project);
} catch (IOException e) { }
catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
libFiles.add(file); libFiles.add(file);
} catch (FileNotFoundException e) { }
//TODO: throw generic expception catch (Exception e) {
//TODO: throw generic exception
throw new IllegalStateException(e); throw new IllegalStateException(e);
} }
} }
return libFiles; return libFiles;
} }
@NotNull @NotNull
public List<JetFile> getLibFiles() { public List<JetFile> generateLibFiles() {
if (jsLibFiles == null) { if (jsLibFiles == null) {
jsLibFiles = initLibFiles(getProject()); jsLibFiles = initLibFiles(getProject());
} }
@@ -18,6 +18,8 @@ package org.jetbrains.k2js.analyze;
import com.google.common.base.Predicate; import com.google.common.base.Predicate;
import com.google.common.base.Predicates; 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.openapi.project.Project;
import com.intellij.psi.PsiFile; import com.intellij.psi.PsiFile;
import org.jetbrains.annotations.NotNull; 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.jet.lang.types.lang.JetStandardClasses;
import org.jetbrains.k2js.config.Config; import org.jetbrains.k2js.config.Config;
import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Set;
/** /**
* @author Pavel Talanov * @author Pavel Talanov
@@ -58,7 +60,7 @@ public final class AnalyzerFacadeForJS {
} }
@NotNull @NotNull
public static BindingContext analyzeFiles(@NotNull List<JetFile> files, public static BindingContext analyzeFiles(@NotNull Collection<JetFile> files,
@NotNull Config config) { @NotNull Config config) {
Project project = config.getProject(); Project project = config.getProject();
BindingTraceContext bindingTraceContext = new BindingTraceContext(); BindingTraceContext bindingTraceContext = new BindingTraceContext();
@@ -76,7 +78,7 @@ public final class AnalyzerFacadeForJS {
return bindingTraceContext.getBindingContext(); return bindingTraceContext.getBindingContext();
} }
private static void checkForErrors(@NotNull List<JetFile> allFiles, @NotNull BindingContext bindingContext) { private static void checkForErrors(@NotNull Collection<JetFile> allFiles, @NotNull BindingContext bindingContext) {
AnalyzingUtils.throwExceptionOnErrors(bindingContext); AnalyzingUtils.throwExceptionOnErrors(bindingContext);
for (JetFile file : allFiles) { for (JetFile file : allFiles) {
AnalyzingUtils.checkForSyntacticErrors(file); AnalyzingUtils.checkForSyntacticErrors(file);
@@ -84,10 +86,10 @@ public final class AnalyzerFacadeForJS {
} }
@NotNull @NotNull
public static List<JetFile> withJsLibAdded(@NotNull List<JetFile> files, @NotNull Config config) { public static Collection<JetFile> withJsLibAdded(@NotNull Collection<JetFile> files, @NotNull Config config) {
List<JetFile> allFiles = new ArrayList<JetFile>(); Set<JetFile> allFiles = Sets.newHashSet();
allFiles.addAll(files); allFiles.addAll(toOriginal(files));
allFiles.addAll(config.getLibFiles()); allFiles.addAll(toOriginal(config.getLibFiles()));
return allFiles; return allFiles;
} }
@@ -103,6 +105,17 @@ public final class AnalyzerFacadeForJS {
}; };
} }
@NotNull
private static Collection<JetFile> toOriginal(@NotNull Collection<JetFile> files) {
Collection<JetFile> result = Lists.newArrayList();
for (JetFile file : files) {
result.add(file);
}
return result;
}
//TODO: exclude?
@NotNull
public static BindingContext analyzeNamespace(@NotNull JetFile file) { public static BindingContext analyzeNamespace(@NotNull JetFile file) {
BindingTraceContext bindingTraceContext = new BindingTraceContext(); BindingTraceContext bindingTraceContext = new BindingTraceContext();
Project project = file.getProject(); Project project = file.getProject();
@@ -18,6 +18,7 @@ package org.jetbrains.k2js.config;
import com.intellij.openapi.project.Project; import com.intellij.openapi.project.Project;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.jet.lang.psi.JetFile; import org.jetbrains.jet.lang.psi.JetFile;
import java.util.Arrays; import java.util.Arrays;
@@ -52,6 +53,8 @@ public abstract class Config {
@NotNull @NotNull
private final Project project; private final Project project;
@Nullable
private List<JetFile> libFiles = null;
public Config(@NotNull Project project) { public Config(@NotNull Project project) {
this.project = project; this.project = project;
@@ -63,5 +66,13 @@ public abstract class Config {
} }
@NotNull @NotNull
public abstract List<JetFile> getLibFiles(); protected abstract List<JetFile> generateLibFiles();
@NotNull
public final List<JetFile> getLibFiles() {
if (libFiles == null) {
libFiles = generateLibFiles();
}
return libFiles;
}
} }
@@ -16,6 +16,7 @@
package org.jetbrains.k2js.facade; package org.jetbrains.k2js.facade;
import com.google.common.collect.Lists;
import com.google.dart.compiler.backend.js.ast.JsProgram; import com.google.dart.compiler.backend.js.ast.JsProgram;
import com.intellij.openapi.project.Project; import com.intellij.openapi.project.Project;
import org.jetbrains.annotations.NotNull; 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.jet.plugin.JetMainDetector;
import org.jetbrains.k2js.analyze.AnalyzerFacadeForJS; import org.jetbrains.k2js.analyze.AnalyzerFacadeForJS;
import org.jetbrains.k2js.config.Config; import org.jetbrains.k2js.config.Config;
import org.jetbrains.k2js.config.IDEAConfig;
import org.jetbrains.k2js.generate.CodeGenerator; import org.jetbrains.k2js.generate.CodeGenerator;
import org.jetbrains.k2js.translate.general.Translation; import org.jetbrains.k2js.translate.general.Translation;
import org.jetbrains.k2js.utils.GenerationUtils; import org.jetbrains.k2js.utils.GenerationUtils;
@@ -33,10 +33,7 @@ import org.jetbrains.k2js.utils.JetFileUtils;
import java.io.File; import java.io.File;
import java.io.FileWriter; import java.io.FileWriter;
import java.util.ArrayList; import java.util.*;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;
import static org.jetbrains.k2js.translate.utils.PsiUtils.getNamespaceName; import static org.jetbrains.k2js.translate.utils.PsiUtils.getNamespaceName;
@@ -51,8 +48,9 @@ public final class K2JSTranslator {
public static void translateWithCallToMainAndSaveToFile(@NotNull List<JetFile> files, public static void translateWithCallToMainAndSaveToFile(@NotNull List<JetFile> files,
@NotNull String outputPath, @NotNull String outputPath,
@NotNull Config config,
@NotNull Project project) throws Exception { @NotNull Project project) throws Exception {
K2JSTranslator translator = new K2JSTranslator(new IDEAConfig(project)); K2JSTranslator translator = new K2JSTranslator(config);
String programCode = translator.generateProgramCode(files) + "\n"; String programCode = translator.generateProgramCode(files) + "\n";
JetFile fileWithMain = JetMainDetector.getFileWithMain(files); JetFile fileWithMain = JetMainDetector.getFileWithMain(files);
if (fileWithMain == null) { if (fileWithMain == null) {
@@ -62,7 +60,8 @@ public final class K2JSTranslator {
FileWriter writer = new FileWriter(new File(outputPath)); FileWriter writer = new FileWriter(new File(outputPath));
try { try {
writer.write(programCode + callToMain); writer.write(programCode + callToMain);
} finally { }
finally {
writer.close(); writer.close();
} }
} }
@@ -106,10 +105,10 @@ public final class K2JSTranslator {
public JsProgram generateProgram(@NotNull List<JetFile> filesToTranslate) { public JsProgram generateProgram(@NotNull List<JetFile> filesToTranslate) {
JetStandardLibrary.initialize(config.getProject()); JetStandardLibrary.initialize(config.getProject());
BindingContext bindingContext = AnalyzerFacadeForJS.analyzeFilesAndCheckErrors(filesToTranslate, config); BindingContext bindingContext = AnalyzerFacadeForJS.analyzeFilesAndCheckErrors(filesToTranslate, config);
return Translation.generateAst(bindingContext, AnalyzerFacadeForJS.withJsLibAdded(filesToTranslate, config)); Collection<JetFile> files = AnalyzerFacadeForJS.withJsLibAdded(filesToTranslate, config);
return Translation.generateAst(bindingContext, Lists.newArrayList(files));
} }
@NotNull @NotNull
public static String generateCallToMain(@NotNull JetFile file, @NotNull String argumentString) { public static String generateCallToMain(@NotNull JetFile file, @NotNull String argumentString) {
String namespaceName = getNamespaceName(file); String namespaceName = getNamespaceName(file);
@@ -132,5 +131,4 @@ public final class K2JSTranslator {
private Project getProject() { private Project getProject() {
return config.getProject(); return config.getProject();
} }
} }