use of org.jetbrains.kotlin.analyzer.AnalysisResult in project kotlin by JetBrains.
the class AbstractDiagnosticMessageTest method doTest.
public void doTest(String filePath) throws Exception {
File file = new File(filePath);
String fileName = file.getName();
String fileData = KotlinTestUtils.doLoadFile(file);
Map<String, String> directives = KotlinTestUtils.parseDirectives(fileData);
int diagnosticNumber = getDiagnosticNumber(directives);
final Set<DiagnosticFactory<?>> diagnosticFactories = getDiagnosticFactories(directives);
MessageType messageType = getMessageTypeDirective(directives);
String explicitLanguageVersion = InTextDirectivesUtils.findStringWithPrefixes(fileData, "// LANGUAGE_VERSION:");
LanguageVersion version = explicitLanguageVersion == null ? null : LanguageVersion.fromVersionString(explicitLanguageVersion);
KtFile psiFile = KotlinTestUtils.createFile(fileName, KotlinTestUtils.doLoadFile(getTestDataPath(), fileName), getProject());
AnalysisResult analysisResult = analyze(psiFile, version);
BindingContext bindingContext = analysisResult.getBindingContext();
List<Diagnostic> diagnostics = ContainerUtil.filter(bindingContext.getDiagnostics().all(), new Condition<Diagnostic>() {
@Override
public boolean value(Diagnostic diagnostic) {
return diagnosticFactories.contains(diagnostic.getFactory());
}
});
assertEquals("Expected diagnostics number mismatch:", diagnosticNumber, diagnostics.size());
int index = 1;
String name = FileUtil.getNameWithoutExtension(fileName);
for (Diagnostic diagnostic : diagnostics) {
String readableDiagnosticText;
String extension;
if (messageType != MessageType.TEXT && IdeErrorMessages.hasIdeSpecificMessage(diagnostic)) {
readableDiagnosticText = FormatHtmlUtilKt.formatHtml(IdeErrorMessages.render(diagnostic));
extension = MessageType.HTML.extension;
} else {
readableDiagnosticText = DefaultErrorMessages.render(diagnostic);
extension = MessageType.TEXT.extension;
}
String errorMessageFileName = name + index;
String path = getTestDataPath() + "/" + errorMessageFileName + "." + extension;
String actualText = "<!-- " + errorMessageFileName + " -->\n" + readableDiagnosticText;
assertSameLinesWithFile(path, actualText);
index++;
}
}
use of org.jetbrains.kotlin.analyzer.AnalysisResult in project kotlin by JetBrains.
the class KotlinTypeCheckerTest method getDeclarationsScope.
@NotNull
private LexicalScope getDeclarationsScope(String path) throws IOException {
KtFile ktFile = KotlinTestUtils.loadJetFile(getProject(), new File(path));
AnalysisResult result = JvmResolveUtil.analyze(ktFile, getEnvironment());
//noinspection ConstantConditions
return result.getBindingContext().get(BindingContext.LEXICAL_SCOPE, ktFile);
}
use of org.jetbrains.kotlin.analyzer.AnalysisResult in project kotlin by JetBrains.
the class TypeSubstitutorTest method getContextScope.
private LexicalScope getContextScope() throws IOException {
// todo comments
String text = FileUtil.loadFile(new File("compiler/testData/type-substitutor.kt"), true);
KtFile ktFile = KtPsiFactoryKt.KtPsiFactory(getProject()).createFile(text);
AnalysisResult analysisResult = JvmResolveUtil.analyze(ktFile, getEnvironment());
ModuleDescriptor module = analysisResult.getModuleDescriptor();
LexicalScope topLevelScope = analysisResult.getBindingContext().get(BindingContext.LEXICAL_SCOPE, ktFile);
final ClassifierDescriptor contextClass = ScopeUtilsKt.findClassifier(topLevelScope, Name.identifier("___Context"), NoLookupLocation.FROM_TEST);
assert contextClass instanceof ClassDescriptor;
LocalRedeclarationChecker redeclarationChecker = new ThrowingLocalRedeclarationChecker(new OverloadChecker(TypeSpecificityComparator.NONE.INSTANCE));
LexicalScope typeParameters = new LexicalScopeImpl(topLevelScope, module, false, null, LexicalScopeKind.SYNTHETIC, redeclarationChecker, new Function1<LexicalScopeImpl.InitializeHandler, Unit>() {
@Override
public Unit invoke(LexicalScopeImpl.InitializeHandler handler) {
for (TypeParameterDescriptor parameterDescriptor : contextClass.getTypeConstructor().getParameters()) {
handler.addClassifierDescriptor(parameterDescriptor);
}
return Unit.INSTANCE;
}
});
return new LexicalChainedScope(typeParameters, module, false, null, LexicalScopeKind.SYNTHETIC, Arrays.asList(contextClass.getDefaultType().getMemberScope(), module.getBuiltIns().getBuiltInsPackageScope()));
}
use of org.jetbrains.kotlin.analyzer.AnalysisResult in project kotlin by JetBrains.
the class AbstractCompileJavaAgainstKotlinTest method doTest.
protected void doTest(String ktFilePath) throws IOException {
Assert.assertTrue(ktFilePath.endsWith(".kt"));
File ktFile = new File(ktFilePath);
File javaFile = new File(ktFilePath.replaceFirst("\\.kt$", ".java"));
File expectedFile = new File(ktFilePath.replaceFirst("\\.kt$", ".txt"));
File javaErrorFile = new File(ktFilePath.replaceFirst("\\.kt$", ".javaerr.txt"));
File out = new File(tmpdir, "out");
compileKotlinWithJava(Collections.singletonList(javaFile), Collections.singletonList(ktFile), out, getTestRootDisposable(), javaErrorFile);
KotlinCoreEnvironment environment = KotlinCoreEnvironment.createForTests(getTestRootDisposable(), newConfiguration(ConfigurationKind.ALL, TestJdkKind.MOCK_JDK, getAnnotationsJar(), out), EnvironmentConfigFiles.JVM_CONFIG_FILES);
AnalysisResult analysisResult = JvmResolveUtil.analyze(environment);
PackageViewDescriptor packageView = analysisResult.getModuleDescriptor().getPackage(LoadDescriptorUtil.TEST_PACKAGE_FQNAME);
assertFalse("Nothing found in package " + LoadDescriptorUtil.TEST_PACKAGE_FQNAME, packageView.isEmpty());
validateAndCompareDescriptorWithFile(packageView, CONFIGURATION, expectedFile);
}
use of org.jetbrains.kotlin.analyzer.AnalysisResult in project kotlin by JetBrains.
the class K2JSCompiler method doExecute.
@NotNull
@Override
protected ExitCode doExecute(@NotNull K2JSCompilerArguments arguments, @NotNull CompilerConfiguration configuration, @NotNull Disposable rootDisposable) {
final MessageCollector messageCollector = configuration.getNotNull(CLIConfigurationKeys.MESSAGE_COLLECTOR_KEY);
if (arguments.freeArgs.isEmpty()) {
if (arguments.version) {
return OK;
}
messageCollector.report(CompilerMessageSeverity.ERROR, "Specify at least one source file or directory", NO_LOCATION);
return COMPILATION_ERROR;
}
ContentRootsKt.addKotlinSourceRoots(configuration, arguments.freeArgs);
KotlinCoreEnvironment environmentForJS = KotlinCoreEnvironment.createForProduction(rootDisposable, configuration, EnvironmentConfigFiles.JS_CONFIG_FILES);
Project project = environmentForJS.getProject();
List<KtFile> sourcesFiles = environmentForJS.getSourceFiles();
environmentForJS.getConfiguration().put(CLIConfigurationKeys.ALLOW_KOTLIN_PACKAGE, arguments.allowKotlinPackage);
if (!checkKotlinPackageUsage(environmentForJS, sourcesFiles))
return ExitCode.COMPILATION_ERROR;
if (arguments.outputFile == null) {
messageCollector.report(CompilerMessageSeverity.ERROR, "Specify output file via -output", CompilerMessageLocation.NO_LOCATION);
return ExitCode.COMPILATION_ERROR;
}
if (messageCollector.hasErrors()) {
return ExitCode.COMPILATION_ERROR;
}
if (sourcesFiles.isEmpty()) {
messageCollector.report(CompilerMessageSeverity.ERROR, "No source files", CompilerMessageLocation.NO_LOCATION);
return COMPILATION_ERROR;
}
if (arguments.verbose) {
reportCompiledSourcesList(messageCollector, sourcesFiles);
}
File outputFile = new File(arguments.outputFile);
configuration.put(CommonConfigurationKeys.MODULE_NAME, FileUtil.getNameWithoutExtension(outputFile));
JsConfig config = new LibrarySourcesConfig(project, configuration);
if (config.checkLibFilesAndReportErrors(new JsConfig.Reporter() {
@Override
public void error(@NotNull String message) {
messageCollector.report(CompilerMessageSeverity.ERROR, message, CompilerMessageLocation.NO_LOCATION);
}
@Override
public void warning(@NotNull String message) {
messageCollector.report(CompilerMessageSeverity.STRONG_WARNING, message, CompilerMessageLocation.NO_LOCATION);
}
})) {
return COMPILATION_ERROR;
}
AnalyzerWithCompilerReport analyzerWithCompilerReport = analyzeAndReportErrors(messageCollector, sourcesFiles, config);
if (analyzerWithCompilerReport.hasErrors()) {
return COMPILATION_ERROR;
}
ProgressIndicatorAndCompilationCanceledStatus.checkCanceled();
AnalysisResult analysisResult = analyzerWithCompilerReport.getAnalysisResult();
assert analysisResult instanceof JsAnalysisResult : "analysisResult should be instance of JsAnalysisResult, but " + analysisResult;
JsAnalysisResult jsAnalysisResult = (JsAnalysisResult) analysisResult;
File outputPrefixFile = null;
if (arguments.outputPrefix != null) {
outputPrefixFile = new File(arguments.outputPrefix);
if (!outputPrefixFile.exists()) {
messageCollector.report(CompilerMessageSeverity.ERROR, "Output prefix file '" + arguments.outputPrefix + "' not found", CompilerMessageLocation.NO_LOCATION);
return ExitCode.COMPILATION_ERROR;
}
}
File outputPostfixFile = null;
if (arguments.outputPostfix != null) {
outputPostfixFile = new File(arguments.outputPostfix);
if (!outputPostfixFile.exists()) {
messageCollector.report(CompilerMessageSeverity.ERROR, "Output postfix file '" + arguments.outputPostfix + "' not found", CompilerMessageLocation.NO_LOCATION);
return ExitCode.COMPILATION_ERROR;
}
}
MainCallParameters mainCallParameters = createMainCallParameters(arguments.main);
TranslationResult translationResult;
K2JSTranslator translator = new K2JSTranslator(config);
try {
//noinspection unchecked
translationResult = translator.translate(sourcesFiles, mainCallParameters, jsAnalysisResult);
} catch (Exception e) {
throw ExceptionUtilsKt.rethrow(e);
}
ProgressIndicatorAndCompilationCanceledStatus.checkCanceled();
AnalyzerWithCompilerReport.Companion.reportDiagnostics(translationResult.getDiagnostics(), messageCollector);
if (!(translationResult instanceof TranslationResult.Success))
return ExitCode.COMPILATION_ERROR;
TranslationResult.Success successResult = (TranslationResult.Success) translationResult;
OutputFileCollection outputFiles = successResult.getOutputFiles(outputFile, outputPrefixFile, outputPostfixFile);
if (outputFile.isDirectory()) {
messageCollector.report(CompilerMessageSeverity.ERROR, "Cannot open output file '" + outputFile.getPath() + "': is a directory", CompilerMessageLocation.NO_LOCATION);
return ExitCode.COMPILATION_ERROR;
}
File outputDir = outputFile.getParentFile();
if (outputDir == null) {
outputDir = outputFile.getAbsoluteFile().getParentFile();
}
ProgressIndicatorAndCompilationCanceledStatus.checkCanceled();
OutputUtilsKt.writeAll(outputFiles, outputDir, messageCollector);
return OK;
}
Aggregations