Search in sources :

Example 6 with KotlinCoreEnvironment

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

the class AbstractLoadJavaTest method doTestCompiledJavaAndKotlin.

// Java-Kotlin dependencies are not supported in this method for simplicity
protected void doTestCompiledJavaAndKotlin(@NotNull String expectedFileName) throws Exception {
    File expectedFile = new File(expectedFileName);
    File sourcesDir = new File(expectedFileName.replaceFirst("\\.txt$", ""));
    List<File> kotlinSources = FileUtil.findFilesByMask(Pattern.compile(".+\\.kt"), sourcesDir);
    KotlinCoreEnvironment environment = KotlinTestUtils.createEnvironmentWithMockJdkAndIdeaAnnotations(myTestRootDisposable, ConfigurationKind.JDK_ONLY);
    compileKotlinToDirAndGetModule(kotlinSources, tmpdir, environment);
    List<File> javaSources = FileUtil.findFilesByMask(Pattern.compile(".+\\.java"), sourcesDir);
    Pair<PackageViewDescriptor, BindingContext> binaryPackageAndContext = compileJavaAndLoadTestPackageAndBindingContextFromBinary(javaSources, tmpdir, ConfigurationKind.JDK_ONLY);
    checkJavaPackage(expectedFile, binaryPackageAndContext.first, binaryPackageAndContext.second, COMPARATOR_CONFIGURATION);
}
Also used : KotlinCoreEnvironment(org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment) BindingContext(org.jetbrains.kotlin.resolve.BindingContext) KtFile(org.jetbrains.kotlin.psi.KtFile) File(java.io.File)

Example 7 with KotlinCoreEnvironment

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

the class ExecuteKotlinScriptMojo method executeScriptFile.

private void executeScriptFile(File scriptFile) throws MojoExecutionException {
    initCompiler();
    Disposable rootDisposable = Disposer.newDisposable();
    try {
        MavenPluginLogMessageCollector messageCollector = new MavenPluginLogMessageCollector(getLog());
        CompilerConfiguration configuration = new CompilerConfiguration();
        configuration.put(CLIConfigurationKeys.MESSAGE_COLLECTOR_KEY, messageCollector);
        List<File> deps = new ArrayList<File>();
        deps.addAll(PathUtil.getJdkClassesRoots());
        deps.addAll(getDependenciesForScript());
        for (File item : deps) {
            if (item.exists()) {
                configuration.add(JVMConfigurationKeys.CONTENT_ROOTS, new JvmClasspathRoot(item));
                getLog().debug("Adding to classpath: " + item.getAbsolutePath());
            } else {
                getLog().debug("Skipping non-existing dependency: " + item.getAbsolutePath());
            }
        }
        configuration.add(JVMConfigurationKeys.CONTENT_ROOTS, new KotlinSourceRoot(scriptFile.getAbsolutePath()));
        configuration.put(CommonConfigurationKeys.MODULE_NAME, JvmAbi.DEFAULT_MODULE_NAME);
        K2JVMCompiler.Companion.configureScriptDefinitions(scriptTemplates.toArray(new String[scriptTemplates.size()]), configuration, messageCollector, new HashMap<String, Object>());
        KotlinCoreEnvironment environment = KotlinCoreEnvironment.createForProduction(rootDisposable, configuration, EnvironmentConfigFiles.JVM_CONFIG_FILES);
        GenerationState state = KotlinToJVMBytecodeCompiler.INSTANCE.analyzeAndGenerate(environment);
        if (state == null) {
            throw new ScriptExecutionException(scriptFile, "compile error");
        }
        GeneratedClassLoader classLoader = new GeneratedClassLoader(state.getFactory(), getClass().getClassLoader());
        KtScript script = environment.getSourceFiles().get(0).getScript();
        FqName nameForScript = script.getFqName();
        try {
            Class<?> klass = classLoader.loadClass(nameForScript.asString());
            ExecuteKotlinScriptMojo.INSTANCE = this;
            if (ReflectionUtilKt.tryConstructClassFromStringArgs(klass, scriptArguments) == null)
                throw new ScriptExecutionException(scriptFile, "unable to construct script");
        } catch (ClassNotFoundException e) {
            throw new ScriptExecutionException(scriptFile, "internal error", e);
        }
    } finally {
        rootDisposable.dispose();
        ExecuteKotlinScriptMojo.INSTANCE = null;
    }
}
Also used : Disposable(com.intellij.openapi.Disposable) KtScript(org.jetbrains.kotlin.psi.KtScript) KotlinSourceRoot(org.jetbrains.kotlin.config.KotlinSourceRoot) FqName(org.jetbrains.kotlin.name.FqName) ArrayList(java.util.ArrayList) GenerationState(org.jetbrains.kotlin.codegen.state.GenerationState) JvmClasspathRoot(org.jetbrains.kotlin.cli.jvm.config.JvmClasspathRoot) GeneratedClassLoader(org.jetbrains.kotlin.codegen.GeneratedClassLoader) KotlinCoreEnvironment(org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment) CompilerConfiguration(org.jetbrains.kotlin.config.CompilerConfiguration) File(java.io.File)

Example 8 with KotlinCoreEnvironment

use of org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment 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);
}
Also used : KotlinCoreEnvironment(org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment) RecursiveDescriptorComparator.validateAndCompareDescriptorWithFile(org.jetbrains.kotlin.test.util.RecursiveDescriptorComparator.validateAndCompareDescriptorWithFile) File(java.io.File) AnalysisResult(org.jetbrains.kotlin.analyzer.AnalysisResult) PackageViewDescriptor(org.jetbrains.kotlin.descriptors.PackageViewDescriptor)

Example 9 with KotlinCoreEnvironment

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

the class ResolveDescriptorsFromExternalLibraries method parseLibraryFileChunk.

private static boolean parseLibraryFileChunk(File jar, String libDescription, ZipInputStream zip, int classesPerChunk) throws IOException {
    Disposable junk = new Disposable() {

        @Override
        public void dispose() {
        }
    };
    KotlinCoreEnvironment environment;
    if (jar != null) {
        environment = KotlinCoreEnvironment.createForTests(junk, KotlinTestUtils.newConfiguration(ConfigurationKind.JDK_ONLY, TestJdkKind.MOCK_JDK, KotlinTestUtils.getAnnotationsJar(), jar), EnvironmentConfigFiles.JVM_CONFIG_FILES);
    } else {
        CompilerConfiguration configuration = KotlinTestUtils.newConfiguration(ConfigurationKind.JDK_ONLY, TestJdkKind.FULL_JDK);
        environment = KotlinCoreEnvironment.createForTests(junk, configuration, EnvironmentConfigFiles.JVM_CONFIG_FILES);
        if (!findRtJar().equals(jar)) {
            throw new RuntimeException("rt.jar mismatch: " + jar + ", " + findRtJar());
        }
    }
    ModuleDescriptor module = JvmResolveUtil.analyze(environment).getModuleDescriptor();
    boolean hasErrors;
    try {
        hasErrors = false;
        for (int count = 0; count < classesPerChunk; ) {
            ZipEntry entry = zip.getNextEntry();
            if (entry == null) {
                break;
            }
            if (count == 0) {
                System.err.println("chunk from " + entry.getName());
            }
            System.err.println(entry.getName());
            String entryName = entry.getName();
            if (!entryName.endsWith(".class")) {
                continue;
            }
            if (entryName.matches("(.*/|)package-info\\.class")) {
                continue;
            }
            if (entryName.contains("$")) {
                continue;
            }
            String className = entryName.substring(0, entryName.length() - ".class".length()).replace("/", ".");
            try {
                ClassDescriptor clazz = DescriptorUtilsKt.resolveTopLevelClass(module, new FqName(className), NoLookupLocation.FROM_TEST);
                if (clazz == null) {
                    throw new IllegalStateException("class not found by name " + className + " in " + libDescription);
                }
                DescriptorUtils.getAllDescriptors(clazz.getDefaultType().getMemberScope());
            } catch (Exception e) {
                System.err.println("failed to resolve " + className);
                e.printStackTrace();
                //throw new RuntimeException("failed to resolve " + className + ": " + e, e);
                hasErrors = true;
            }
            ++count;
        }
    } finally {
        Disposer.dispose(junk);
    }
    return hasErrors;
}
Also used : Disposable(com.intellij.openapi.Disposable) ClassDescriptor(org.jetbrains.kotlin.descriptors.ClassDescriptor) FqName(org.jetbrains.kotlin.name.FqName) ZipEntry(java.util.zip.ZipEntry) ModuleDescriptor(org.jetbrains.kotlin.descriptors.ModuleDescriptor) KotlinCoreEnvironment(org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment) CompilerConfiguration(org.jetbrains.kotlin.config.CompilerConfiguration)

Example 10 with KotlinCoreEnvironment

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

the class StdlibTest method createEnvironment.

@Override
protected KotlinCoreEnvironment createEnvironment() {
    @SuppressWarnings("deprecation") File[] runtimeClasspath = ForTestCompileRuntime.runtimeClassesForTests();
    CompilerConfiguration configuration = KotlinTestUtils.newConfiguration(ConfigurationKind.JDK_NO_RUNTIME, TestJdkKind.FULL_JDK, runtimeClasspath);
    JvmContentRootsKt.addJvmClasspathRoot(configuration, ForTestCompileRuntime.kotlinTestJarForTests());
    File junitJar = new File("libraries/lib/junit-4.11.jar");
    assertTrue(junitJar.exists());
    JvmContentRootsKt.addJvmClasspathRoot(configuration, junitJar);
    ContentRootsKt.addKotlinSourceRoot(configuration, KotlinTestUtils.getHomeDirectory() + "/libraries/stdlib/test");
    configuration.put(CLIConfigurationKeys.MESSAGE_COLLECTOR_KEY, new PrintingMessageCollector(System.err, MessageRenderer.PLAIN_FULL_PATHS, false));
    KotlinCoreEnvironment environment = KotlinCoreEnvironment.createForTests(getTestRootDisposable(), configuration, EnvironmentConfigFiles.JVM_CONFIG_FILES);
    ModuleVisibilityManager moduleVisibilityManager = ModuleVisibilityManager.SERVICE.getInstance(environment.getProject());
    for (File path : runtimeClasspath) {
        moduleVisibilityManager.addFriendPath(path.getPath());
    }
    return environment;
}
Also used : ModuleVisibilityManager(org.jetbrains.kotlin.load.kotlin.ModuleVisibilityManager) KotlinCoreEnvironment(org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment) CompilerConfiguration(org.jetbrains.kotlin.config.CompilerConfiguration) KtFile(org.jetbrains.kotlin.psi.KtFile) File(java.io.File) PrintingMessageCollector(org.jetbrains.kotlin.cli.common.messages.PrintingMessageCollector)

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