Search in sources :

Example 11 with KotlinCoreEnvironment

use of org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment 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;
}
Also used : MainCallParameters(org.jetbrains.kotlin.js.facade.MainCallParameters) JsConfig(org.jetbrains.kotlin.js.config.JsConfig) AnalyzerWithCompilerReport(org.jetbrains.kotlin.cli.common.messages.AnalyzerWithCompilerReport) K2JSTranslator(org.jetbrains.kotlin.js.facade.K2JSTranslator) LibrarySourcesConfig(org.jetbrains.kotlin.js.config.LibrarySourcesConfig) JsAnalysisResult(org.jetbrains.kotlin.js.analyzer.JsAnalysisResult) AnalysisResult(org.jetbrains.kotlin.analyzer.AnalysisResult) Project(com.intellij.openapi.project.Project) JsAnalysisResult(org.jetbrains.kotlin.js.analyzer.JsAnalysisResult) OutputFileCollection(org.jetbrains.kotlin.backend.common.output.OutputFileCollection) KotlinCoreEnvironment(org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment) MessageCollector(org.jetbrains.kotlin.cli.common.messages.MessageCollector) KtFile(org.jetbrains.kotlin.psi.KtFile) TranslationResult(org.jetbrains.kotlin.js.facade.TranslationResult) VirtualFile(com.intellij.openapi.vfs.VirtualFile) KtFile(org.jetbrains.kotlin.psi.KtFile) File(java.io.File) NotNull(org.jetbrains.annotations.NotNull)

Example 12 with KotlinCoreEnvironment

use of org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment in project kotlin by JetBrains.

the class AbstractLoadJavaTest method doTestCompiledKotlin.

private void doTestCompiledKotlin(@NotNull String ktFileName, @NotNull ConfigurationKind configurationKind, boolean useTypeTableInSerializer) throws Exception {
    File ktFile = new File(ktFileName);
    File txtFile = new File(ktFileName.replaceFirst("\\.kt$", ".txt"));
    CompilerConfiguration configuration = newConfiguration(configurationKind, TestJdkKind.MOCK_JDK, getAnnotationsJar());
    if (useTypeTableInSerializer) {
        configuration.put(JVMConfigurationKeys.USE_TYPE_TABLE, true);
    }
    KotlinCoreEnvironment environment = KotlinCoreEnvironment.createForTests(getTestRootDisposable(), configuration, EnvironmentConfigFiles.JVM_CONFIG_FILES);
    ModuleDescriptor module = compileKotlinToDirAndGetModule(Collections.singletonList(ktFile), tmpdir, environment);
    PackageViewDescriptor packageFromSource = module.getPackage(TEST_PACKAGE_FQNAME);
    Assert.assertEquals("test", packageFromSource.getName().asString());
    PackageViewDescriptor packageFromBinary = LoadDescriptorUtil.loadTestPackageAndBindingContextFromJavaRoot(tmpdir, getTestRootDisposable(), getJdkKind(), configurationKind, true).first;
    for (DeclarationDescriptor descriptor : DescriptorUtils.getAllDescriptors(packageFromBinary.getMemberScope())) {
        if (descriptor instanceof ClassDescriptor) {
            assert descriptor instanceof DeserializedClassDescriptor : DescriptorUtils.getFqName(descriptor) + " is loaded as " + descriptor.getClass();
        }
    }
    DescriptorValidator.validate(errorTypesForbidden(), packageFromSource);
    DescriptorValidator.validate(new DeserializedScopeValidationVisitor(), packageFromBinary);
    Configuration comparatorConfiguration = COMPARATOR_CONFIGURATION.checkPrimaryConstructors(true).checkPropertyAccessors(true);
    compareDescriptors(packageFromSource, packageFromBinary, comparatorConfiguration, txtFile);
}
Also used : DeserializedClassDescriptor(org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedClassDescriptor) CompilerConfiguration(org.jetbrains.kotlin.config.CompilerConfiguration) KotlinCoreEnvironment(org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment) CompilerConfiguration(org.jetbrains.kotlin.config.CompilerConfiguration) KtFile(org.jetbrains.kotlin.psi.KtFile) File(java.io.File) DeserializedClassDescriptor(org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedClassDescriptor)

Example 13 with KotlinCoreEnvironment

use of org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment in project kotlin by JetBrains.

the class LoadDescriptorUtil method loadTestPackageAndBindingContextFromJavaRoot.

@NotNull
public static Pair<PackageViewDescriptor, BindingContext> loadTestPackageAndBindingContextFromJavaRoot(@NotNull File javaRoot, @NotNull Disposable disposable, @NotNull TestJdkKind testJdkKind, @NotNull ConfigurationKind configurationKind, boolean isBinaryRoot) {
    List<File> javaBinaryRoots = new ArrayList<File>();
    javaBinaryRoots.add(KotlinTestUtils.getAnnotationsJar());
    List<File> javaSourceRoots = new ArrayList<File>();
    javaSourceRoots.add(new File("compiler/testData/loadJava/include"));
    if (isBinaryRoot) {
        javaBinaryRoots.add(javaRoot);
    } else {
        javaSourceRoots.add(javaRoot);
    }
    CompilerConfiguration configuration = KotlinTestUtils.newConfiguration(configurationKind, testJdkKind, javaBinaryRoots, javaSourceRoots);
    KotlinCoreEnvironment environment = KotlinCoreEnvironment.createForTests(disposable, configuration, EnvironmentConfigFiles.JVM_CONFIG_FILES);
    AnalysisResult analysisResult = JvmResolveUtil.analyze(environment);
    PackageViewDescriptor packageView = analysisResult.getModuleDescriptor().getPackage(TEST_PACKAGE_FQNAME);
    return Pair.create(packageView, analysisResult.getBindingContext());
}
Also used : KotlinCoreEnvironment(org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment) ArrayList(java.util.ArrayList) CompilerConfiguration(org.jetbrains.kotlin.config.CompilerConfiguration) KtFile(org.jetbrains.kotlin.psi.KtFile) File(java.io.File) AnalysisResult(org.jetbrains.kotlin.analyzer.AnalysisResult) PackageViewDescriptor(org.jetbrains.kotlin.descriptors.PackageViewDescriptor) NotNull(org.jetbrains.annotations.NotNull)

Example 14 with KotlinCoreEnvironment

use of org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment in project kotlin by JetBrains.

the class AbstractLineNumberTest method doTest.

private void doTest(@NotNull String filename, boolean custom) {
    Pair<KtFile, KotlinCoreEnvironment> fileAndEnv = createPsiFile(filename);
    KtFile psiFile = fileAndEnv.getFirst();
    KotlinCoreEnvironment environment = fileAndEnv.getSecond();
    ClassFileFactory classFileFactory = GenerationUtils.compileFile(psiFile, environment);
    try {
        if (custom) {
            List<String> actualLineNumbers = extractActualLineNumbersFromBytecode(classFileFactory, false);
            String text = psiFile.getText();
            String newFileText = text.substring(0, text.indexOf("// ")) + getActualLineNumbersAsString(actualLineNumbers);
            KotlinTestUtils.assertEqualsToFile(new File(filename), newFileText);
        } else {
            List<String> expectedLineNumbers = extractSelectedLineNumbersFromSource(psiFile);
            List<String> actualLineNumbers = extractActualLineNumbersFromBytecode(classFileFactory, true);
            assertSameElements(actualLineNumbers, expectedLineNumbers);
        }
    } catch (Throwable e) {
        System.out.println(classFileFactory.createText());
        throw ExceptionUtilsKt.rethrow(e);
    }
}
Also used : KotlinCoreEnvironment(org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment) KtFile(org.jetbrains.kotlin.psi.KtFile) KtFile(org.jetbrains.kotlin.psi.KtFile) File(java.io.File) OutputFile(org.jetbrains.kotlin.backend.common.output.OutputFile)

Example 15 with KotlinCoreEnvironment

use of org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment in project kotlin by JetBrains.

the class AbstractLineNumberTest method setUp.

@Override
public void setUp() throws Exception {
    super.setUp();
    KotlinCoreEnvironment environment = createEnvironment();
    KtFile psiFile = KotlinTestUtils.createFile(LINE_NUMBER_FUN + ".kt", "package test;\n\npublic fun " + LINE_NUMBER_FUN + "(): Int = 0\n", environment.getProject());
    GenerationUtils.compileFileTo(psiFile, environment, tmpdir);
}
Also used : KotlinCoreEnvironment(org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment) KtFile(org.jetbrains.kotlin.psi.KtFile)

Aggregations

KotlinCoreEnvironment (org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment)19 File (java.io.File)12 KtFile (org.jetbrains.kotlin.psi.KtFile)11 CompilerConfiguration (org.jetbrains.kotlin.config.CompilerConfiguration)8 NotNull (org.jetbrains.annotations.NotNull)6 AnalysisResult (org.jetbrains.kotlin.analyzer.AnalysisResult)6 Disposable (com.intellij.openapi.Disposable)4 PackageViewDescriptor (org.jetbrains.kotlin.descriptors.PackageViewDescriptor)3 ArrayList (java.util.ArrayList)2 OutputFile (org.jetbrains.kotlin.backend.common.output.OutputFile)2 PrintingMessageCollector (org.jetbrains.kotlin.cli.common.messages.PrintingMessageCollector)2 FqName (org.jetbrains.kotlin.name.FqName)2 BindingContext (org.jetbrains.kotlin.resolve.BindingContext)2 Project (com.intellij.openapi.project.Project)1 VirtualFile (com.intellij.openapi.vfs.VirtualFile)1 GlobalSearchScope (com.intellij.psi.search.GlobalSearchScope)1 FileFilter (java.io.FileFilter)1 IOException (java.io.IOException)1 ZipEntry (java.util.zip.ZipEntry)1 Pair (kotlin.Pair)1