Search in sources :

Example 6 with GenerationState

use of org.jetbrains.kotlin.codegen.state.GenerationState in project kotlin by JetBrains.

the class KotlinBytecodeToolWindow method getBytecodeForFile.

// public for tests
@NotNull
public static String getBytecodeForFile(@NotNull KtFile ktFile, @NotNull CompilerConfiguration configuration) {
    GenerationState state;
    try {
        state = compileSingleFile(ktFile, configuration);
    } catch (ProcessCanceledException e) {
        throw e;
    } catch (Exception e) {
        return printStackTraceToString(e);
    }
    StringBuilder answer = new StringBuilder();
    Collection<Diagnostic> diagnostics = state.getCollectedExtraJvmDiagnostics().all();
    if (!diagnostics.isEmpty()) {
        answer.append("// Backend Errors: \n");
        answer.append("// ================\n");
        for (Diagnostic diagnostic : diagnostics) {
            answer.append("// Error at ").append(diagnostic.getPsiFile().getName()).append(StringsKt.join(diagnostic.getTextRanges(), ",")).append(": ").append(DefaultErrorMessages.render(diagnostic)).append("\n");
        }
        answer.append("// ================\n\n");
    }
    OutputFileCollection outputFiles = state.getFactory();
    for (OutputFile outputFile : outputFiles.asList()) {
        answer.append("// ================");
        answer.append(outputFile.getRelativePath());
        answer.append(" =================\n");
        answer.append(outputFile.asText()).append("\n\n");
    }
    return answer.toString();
}
Also used : OutputFile(org.jetbrains.kotlin.backend.common.output.OutputFile) OutputFileCollection(org.jetbrains.kotlin.backend.common.output.OutputFileCollection) Diagnostic(org.jetbrains.kotlin.diagnostics.Diagnostic) GenerationState(org.jetbrains.kotlin.codegen.state.GenerationState) ProcessCanceledException(com.intellij.openapi.progress.ProcessCanceledException) ProcessCanceledException(com.intellij.openapi.progress.ProcessCanceledException) NotNull(org.jetbrains.annotations.NotNull)

Example 7 with GenerationState

use of org.jetbrains.kotlin.codegen.state.GenerationState 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 GenerationState

use of org.jetbrains.kotlin.codegen.state.GenerationState in project kotlin by JetBrains.

the class StdlibTest method testStdlib.

public void testStdlib() throws ClassNotFoundException {
    GenerationState state = KotlinToJVMBytecodeCompiler.INSTANCE.analyzeAndGenerate(getEnvironment());
    if (state == null) {
        fail("There were compilation errors");
    }
    classLoader = new GeneratedClassLoader(state.getFactory(), ForTestCompileRuntime.runtimeAndReflectJarClassLoader()) {

        @Override
        public Class<?> loadClass(@NotNull String name) throws ClassNotFoundException {
            if (name.startsWith("junit.") || name.startsWith("org.junit.")) {
                return StdlibTest.class.getClassLoader().loadClass(name);
            }
            return super.loadClass(name);
        }
    };
    TestSuite tests = new TestSuite("Standard Library Tests");
    for (KtFile file : getEnvironment().getSourceFiles()) {
        // Skip JS tests
        if (file.getVirtualFile().getPath().contains("/js/"))
            continue;
        for (KtDeclaration declaration : file.getDeclarations()) {
            if (!(declaration instanceof KtClass))
                continue;
            ClassDescriptor descriptor = (ClassDescriptor) BindingContextUtils.getNotNull(state.getBindingContext(), BindingContext.DECLARATION_TO_DESCRIPTOR, declaration);
            Test test = createTest(classLoader, state.getTypeMapper().mapClass(descriptor).getClassName());
            if (test != null) {
                tests.addTest(test);
            }
        }
    }
    TestResult result = new TestRunner(System.err).doRun(tests);
    if (!result.wasSuccessful()) {
        fail("Some stdlib tests failed, see stderr for details");
    }
}
Also used : ClassDescriptor(org.jetbrains.kotlin.descriptors.ClassDescriptor) TestRunner(junit.textui.TestRunner) KtClass(org.jetbrains.kotlin.psi.KtClass) GenerationState(org.jetbrains.kotlin.codegen.state.GenerationState) KtDeclaration(org.jetbrains.kotlin.psi.KtDeclaration) KtClass(org.jetbrains.kotlin.psi.KtClass) KtFile(org.jetbrains.kotlin.psi.KtFile)

Example 9 with GenerationState

use of org.jetbrains.kotlin.codegen.state.GenerationState in project kotlin by JetBrains.

the class CodegenTestUtil method generateFiles.

@NotNull
public static ClassFileFactory generateFiles(@NotNull KotlinCoreEnvironment environment, @NotNull CodegenTestFiles files, @NotNull ClassBuilderFactory classBuilderFactory) {
    AnalysisResult analysisResult = JvmResolveUtil.analyzeAndCheckForErrors(files.getPsiFiles(), environment);
    analysisResult.throwIfError();
    AnalyzingUtils.throwExceptionOnErrors(analysisResult.getBindingContext());
    CompilerConfiguration configuration = environment.getConfiguration();
    GenerationState state = new GenerationState(environment.getProject(), classBuilderFactory, analysisResult.getModuleDescriptor(), analysisResult.getBindingContext(), files.getPsiFiles(), configuration);
    if (analysisResult.getShouldGenerateCode()) {
        KotlinCodegenFacade.compileCorrectFiles(state, CompilationErrorHandler.THROW_EXCEPTION);
    }
    // For JVM-specific errors
    AnalyzingUtils.throwExceptionOnErrors(state.getCollectedExtraJvmDiagnostics());
    return state.getFactory();
}
Also used : CompilerConfiguration(org.jetbrains.kotlin.config.CompilerConfiguration) AnalysisResult(org.jetbrains.kotlin.analyzer.AnalysisResult) GenerationState(org.jetbrains.kotlin.codegen.state.GenerationState) NotNull(org.jetbrains.annotations.NotNull)

Example 10 with GenerationState

use of org.jetbrains.kotlin.codegen.state.GenerationState in project kotlin by JetBrains.

the class AbstractPositionManagerTest method performTest.

private void performTest() {
    Project project = getProject();
    List<KtFile> files = new ArrayList<KtFile>(PluginJetFilesProvider.allFilesInProject(project));
    if (files.isEmpty())
        return;
    final List<Breakpoint> breakpoints = Lists.newArrayList();
    for (KtFile file : files) {
        breakpoints.addAll(extractBreakpointsInfo(file, file.getText()));
    }
    CompilerConfiguration configuration = KotlinTestUtils.newConfiguration(ConfigurationKind.JDK_ONLY, TestJdkKind.MOCK_JDK);
    // TODO: delete this once IDEVirtualFileFinder supports loading .kotlin_builtins files
    configuration.put(JVMConfigurationKeys.ADD_BUILT_INS_FROM_COMPILER_TO_DEPENDENCIES, true);
    GenerationState state = GenerationUtils.compileFiles(files, configuration, new Function1<GlobalSearchScope, PackagePartProvider>() {

        @Override
        public PackagePartProvider invoke(GlobalSearchScope scope) {
            return PackagePartProvider.Empty.INSTANCE;
        }
    });
    Map<String, ReferenceType> referencesByName = getReferenceMap(state.getFactory());
    debugProcess = createDebugProcess(referencesByName);
    final PositionManager positionManager = createPositionManager(debugProcess, files, state);
    ApplicationManager.getApplication().runReadAction(new Runnable() {

        @Override
        public void run() {
            try {
                for (Breakpoint breakpoint : breakpoints) {
                    assertBreakpointIsHandledCorrectly(breakpoint, positionManager);
                }
            } catch (NoDataException e) {
                throw ExceptionUtilsKt.rethrow(e);
            }
        }
    });
}
Also used : PositionManager(com.intellij.debugger.PositionManager) ArrayList(java.util.ArrayList) GenerationState(org.jetbrains.kotlin.codegen.state.GenerationState) ReferenceType(com.sun.jdi.ReferenceType) Project(com.intellij.openapi.project.Project) GlobalSearchScope(com.intellij.psi.search.GlobalSearchScope) PackagePartProvider(org.jetbrains.kotlin.descriptors.PackagePartProvider) CompilerConfiguration(org.jetbrains.kotlin.config.CompilerConfiguration) KtFile(org.jetbrains.kotlin.psi.KtFile) NoDataException(com.intellij.debugger.NoDataException)

Aggregations

GenerationState (org.jetbrains.kotlin.codegen.state.GenerationState)11 NotNull (org.jetbrains.annotations.NotNull)7 CompilerConfiguration (org.jetbrains.kotlin.config.CompilerConfiguration)3 KtFile (org.jetbrains.kotlin.psi.KtFile)3 KotlinType (org.jetbrains.kotlin.types.KotlinType)3 ArrayList (java.util.ArrayList)2 KtScript (org.jetbrains.kotlin.psi.KtScript)2 NoDataException (com.intellij.debugger.NoDataException)1 PositionManager (com.intellij.debugger.PositionManager)1 Disposable (com.intellij.openapi.Disposable)1 ProcessCanceledException (com.intellij.openapi.progress.ProcessCanceledException)1 Project (com.intellij.openapi.project.Project)1 GlobalSearchScope (com.intellij.psi.search.GlobalSearchScope)1 ReferenceType (com.sun.jdi.ReferenceType)1 File (java.io.File)1 List (java.util.List)1 TestRunner (junit.textui.TestRunner)1 AnalysisResult (org.jetbrains.kotlin.analyzer.AnalysisResult)1 OutputFile (org.jetbrains.kotlin.backend.common.output.OutputFile)1 OutputFileCollection (org.jetbrains.kotlin.backend.common.output.OutputFileCollection)1