11package com.sourcegraph.semanticdb_kotlinc
22
3+ import java.io.PrintWriter
4+ import java.io.Writer
35import java.nio.file.Files
46import java.nio.file.Path
57import java.nio.file.Paths
68import kotlin.contracts.ExperimentalContracts
79import org.jetbrains.kotlin.KtSourceFile
810import org.jetbrains.kotlin.backend.common.extensions.IrGenerationExtension
911import org.jetbrains.kotlin.backend.common.extensions.IrPluginContext
12+ import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity
13+ import org.jetbrains.kotlin.cli.common.messages.MessageRenderer
14+ import org.jetbrains.kotlin.cli.common.messages.PrintingMessageCollector
15+ import org.jetbrains.kotlin.config.CommonConfigurationKeys
16+ import org.jetbrains.kotlin.config.CompilerConfiguration
1017import org.jetbrains.kotlin.ir.declarations.IrModuleFragment
1118
1219class PostAnalysisExtension (
@@ -16,12 +23,20 @@ class PostAnalysisExtension(
1623) : IrGenerationExtension {
1724 @OptIn(ExperimentalContracts ::class )
1825 override fun generate (moduleFragment : IrModuleFragment , pluginContext : IrPluginContext ) {
19- for ((ktSourceFile, visitor) in AnalyzerCheckers .visitors) {
20- val document = visitor.build()
21- semanticdbOutPathForFile(ktSourceFile)?.apply {
22- Files .write(this , TextDocuments { addDocuments(document) }.toByteArray())
26+ try {
27+ for ((ktSourceFile, visitor) in AnalyzerCheckers .visitors) {
28+ try {
29+ val document = visitor.build()
30+ semanticdbOutPathForFile(ktSourceFile)?.apply {
31+ Files .write(this , TextDocuments { addDocuments(document) }.toByteArray())
32+ }
33+ callback(document)
34+ } catch (e: Exception ) {
35+ handleException(e)
36+ }
2337 }
24- callback(document)
38+ } catch (e: Exception ) {
39+ handleException(e)
2540 }
2641 }
2742
@@ -44,4 +59,31 @@ class PostAnalysisExtension(
4459 " given file is not under the sourceroot.\n\t Sourceroot: $sourceRoot \n\t File path: ${file.path} \n\t Normalized file path: $normalizedPath " )
4560 return null
4661 }
62+
63+ private val messageCollector =
64+ CompilerConfiguration ()
65+ .get(
66+ CommonConfigurationKeys .MESSAGE_COLLECTOR_KEY ,
67+ PrintingMessageCollector (System .err, MessageRenderer .PLAIN_FULL_PATHS , false ))
68+
69+ private fun handleException (e : Exception ) {
70+ val writer =
71+ PrintWriter (
72+ object : Writer () {
73+ val buf = StringBuffer ()
74+ override fun close () =
75+ messageCollector.report(CompilerMessageSeverity .EXCEPTION , buf.toString())
76+
77+ override fun flush () = Unit
78+ override fun write (data : CharArray , offset : Int , len : Int ) {
79+ buf.append(data, offset, len)
80+ }
81+ },
82+ false )
83+ writer.println (" Exception in semanticdb-kotlin compiler plugin:" )
84+ e.printStackTrace(writer)
85+ writer.println (
86+ " Please report a bug to https://github.com/sourcegraph/lsif-kotlin with the stack trace above." )
87+ writer.close()
88+ }
4789}
0 commit comments