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();
}
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;
}
}
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");
}
}
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();
}
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);
}
}
});
}
Aggregations