Minor: cleanup code in cli-js and js.sourcemap

This commit is contained in:
Nikolay Krasko
2022-09-29 11:04:51 +02:00
committed by Space Team
parent eb2326eabb
commit 20692c9837
4 changed files with 41 additions and 33 deletions
@@ -100,7 +100,7 @@ public class K2JSCompiler extends CLICompiler<K2JSCompilerArguments> {
doMain(new K2JSCompiler(), args);
}
final K2JSCompilerPerformanceManager performanceManager = new K2JSCompilerPerformanceManager();
private final K2JSCompilerPerformanceManager performanceManager = new K2JSCompilerPerformanceManager();
@NotNull
@Override
@@ -338,7 +338,6 @@ public class K2JSCompiler extends CLICompiler<K2JSCompilerArguments> {
TranslationResult translationResult;
try {
//noinspection unchecked
translationResult = translate(reporter, sourcesFiles, jsAnalysisResult, mainCallParameters, config);
}
catch (Exception e) {
@@ -57,12 +57,6 @@ import org.jetbrains.kotlin.utils.join
import java.io.File
import java.io.IOException
enum class ProduceKind {
DEFAULT, // Determine what to produce based on js-v1 options
JS,
KLIB
}
class K2JsIrCompiler : CLICompiler<K2JSCompilerArguments>() {
override val defaultPerformanceManager: CommonCompilerPerformanceManager =
@@ -157,16 +151,17 @@ class K2JsIrCompiler : CLICompiler<K2JSCompilerArguments>() {
val messageCollector = configuration.getNotNull(CLIConfigurationKeys.MESSAGE_COLLECTOR_KEY)
if (configuration.getBoolean(CommonConfigurationKeys.USE_FIR)) {
messageCollector.report(ERROR, "K2 does not support JS target right now")
return ExitCode.COMPILATION_ERROR
return COMPILATION_ERROR
}
val pluginLoadResult = loadPlugins(paths, arguments, configuration)
if (pluginLoadResult != ExitCode.OK) return pluginLoadResult
if (pluginLoadResult != OK) return pluginLoadResult
//TODO: add to configuration everything that may come in handy at script compiler and use it there
if (arguments.script) {
if (!arguments.enableJsScripting) {
@Suppress("SpellCheckingInspection")
messageCollector.report(ERROR, "Script for K/JS should be enabled explicitly, see -Xenable-js-scripting")
return COMPILATION_ERROR
}
@@ -233,22 +228,22 @@ class K2JsIrCompiler : CLICompiler<K2JSCompilerArguments>() {
configurationJs.put(JSConfigurationKeys.PROPERTY_LAZY_INITIALIZATION, arguments.irPropertyLazyInitialization)
configurationJs.put(JSConfigurationKeys.GENERATE_INLINE_ANONYMOUS_FUNCTIONS, arguments.irGenerateInlineAnonymousFunctions)
if (!checkKotlinPackageUsage(environmentForJS.configuration, sourcesFiles)) return ExitCode.COMPILATION_ERROR
if (!checkKotlinPackageUsage(environmentForJS.configuration, sourcesFiles)) return COMPILATION_ERROR
val outputDirPath = arguments.outputDir
val outputName = arguments.moduleName
if (outputDirPath == null) {
messageCollector.report(ERROR, "IR: Specify output dir via -Xir-output-dir", null)
return ExitCode.COMPILATION_ERROR
return COMPILATION_ERROR
}
if (outputName == null) {
messageCollector.report(ERROR, "IR: Specify output name via -Xir-module-name", null)
return ExitCode.COMPILATION_ERROR
return COMPILATION_ERROR
}
if (messageCollector.hasErrors()) {
return ExitCode.COMPILATION_ERROR
return COMPILATION_ERROR
}
if (sourcesFiles.isEmpty() && (!incrementalCompilationIsEnabledForJs(arguments)) && arguments.includes.isNullOrEmpty()) {
@@ -269,7 +264,7 @@ class K2JsIrCompiler : CLICompiler<K2JSCompilerArguments>() {
configurationJs.put(JSConfigurationKeys.OUTPUT_DIR, outputDir.canonicalFile)
} catch (e: IOException) {
messageCollector.report(ERROR, "Could not resolve output directory", null)
return ExitCode.COMPILATION_ERROR
return COMPILATION_ERROR
}
// TODO: Handle non-empty main call arguments
@@ -281,7 +276,7 @@ class K2JsIrCompiler : CLICompiler<K2JSCompilerArguments>() {
val icCaches = if (!arguments.wasm && cacheDirectories.isNotEmpty()) {
messageCollector.report(INFO, "")
messageCollector.report(INFO, "Building cache:")
messageCollector.report(INFO, "to: ${outputDir}")
messageCollector.report(INFO, "to: $outputDir")
messageCollector.report(INFO, arguments.cacheDirectories ?: "")
messageCollector.report(INFO, libraries.toString())
@@ -622,7 +617,7 @@ class K2JsIrCompiler : CLICompiler<K2JSCompilerArguments>() {
@JvmStatic
fun main(args: Array<String>) {
CLITool.doMain(K2JsIrCompiler(), args)
doMain(K2JsIrCompiler(), args)
}
private fun reportCompiledSourcesList(messageCollector: MessageCollector, sourceFiles: List<KtFile>) {
@@ -663,12 +658,12 @@ fun RuntimeDiagnostic.Companion.resolve(
}
fun loadPluginsForTests(configuration: CompilerConfiguration): ExitCode {
var pluginClasspaths: Iterable<String> = emptyList()
var pluginClasspath: Iterable<String> = emptyList()
val kotlinPaths = PathUtil.kotlinPathsForCompiler
val libPath = kotlinPaths.libPath.takeIf { it.exists() && it.isDirectory } ?: File(".")
val (jars, _) =
PathUtil.KOTLIN_SCRIPTING_PLUGIN_CLASSPATH_JARS.mapNotNull { File(libPath, it) }.partition { it.exists() }
pluginClasspaths = jars.map { it.canonicalPath } + pluginClasspaths
PathUtil.KOTLIN_SCRIPTING_PLUGIN_CLASSPATH_JARS.map { File(libPath, it) }.partition { it.exists() }
pluginClasspath = jars.map { it.canonicalPath } + pluginClasspath
return PluginCliParser.loadPluginsSafe(pluginClasspaths, listOf(), listOf(), configuration)
return PluginCliParser.loadPluginsSafe(pluginClasspath, listOf(), listOf(), configuration)
}
@@ -4,6 +4,7 @@
*/
@file:JvmName("JSStdlibLinker")
package org.jetbrains.kotlin.cli.js.internal
import com.google.gwt.dev.js.ThrowExceptionOnErrorReporter
@@ -36,27 +37,29 @@ fun main(args: Array<String>) {
private fun mergeStdlibParts(outputFile: File, wrapperFile: File, baseDir: File, inputPaths: List<File>) {
val program = JsProgram()
fun File.relativizeIfNecessary(): String = canonicalFile.toRelativeString(baseDir)
fun File.makeRelativeIfNecessary(): String = canonicalFile.toRelativeString(baseDir)
val wrapper = parse(wrapperFile.readText(), ThrowExceptionOnErrorReporter, program.scope, wrapperFile.relativizeIfNecessary())!!
val wrapper = parse(wrapperFile.readText(), ThrowExceptionOnErrorReporter, program.scope, wrapperFile.makeRelativeIfNecessary())
?: error("Should not be null because of error reporter")
val insertionPlace = wrapper.createInsertionPlace()
val allFiles = mutableListOf<File>()
inputPaths.forEach { collectFiles(it, allFiles) }
for (file in allFiles) {
val statements = parse(file.readText(), ThrowExceptionOnErrorReporter, program.scope, file.relativizeIfNecessary())!!
val statements = parse(file.readText(), ThrowExceptionOnErrorReporter, program.scope, file.makeRelativeIfNecessary())
?: error("Should not be null because of error reporter")
val block = JsBlock(statements)
block.fixForwardNameReferences()
val sourceMapFile = File(file.parent, file.name + ".map")
if (sourceMapFile.exists()) {
val sourceMapParse = SourceMapParser.parse(sourceMapFile)
when (sourceMapParse) {
when (val sourceMapParse = SourceMapParser.parse(sourceMapFile)) {
is SourceMapError -> {
System.err.println("Error parsing source map file $sourceMapFile: ${sourceMapParse.message}")
exitProcess(1)
}
is SourceMapSuccess -> {
val sourceMap = sourceMapParse.value
val remapper = SourceMapLocationRemapper(sourceMap)
@@ -73,7 +76,13 @@ private fun mergeStdlibParts(outputFile: File, wrapperFile: File, baseDir: File,
val sourceMapFile = File(outputFile.parentFile, outputFile.name + ".map")
val textOutput = TextOutputImpl()
val sourceMapBuilder = SourceMap3Builder(outputFile, textOutput, "")
val consumer = SourceMapBuilderConsumer(File("."), sourceMapBuilder, SourceFilePathResolver(mutableListOf()), true, true)
val consumer = SourceMapBuilderConsumer(
File("."),
sourceMapBuilder,
SourceFilePathResolver(mutableListOf()),
provideCurrentModuleContent = true,
provideExternalModuleContent = true
)
program.globalBlock.accept(JsToStringGenerationVisitor(textOutput, consumer))
val sourceMapContent = sourceMapBuilder.build()
@@ -101,16 +110,16 @@ private fun List<JsStatement>.createInsertionPlace(): JsBlock {
val visitor = object : JsVisitorWithContextImpl() {
override fun visit(x: JsExpressionStatement, ctx: JsContext<in JsStatement>): Boolean {
if (isInsertionPlace(x.expression)) {
return if (isInsertionPlace(x.expression)) {
ctx.replaceMe(block)
return false
false
} else {
return super.visit(x, ctx)
super.visit(x, ctx)
}
}
private fun isInsertionPlace(expression: JsExpression): Boolean {
if (expression !is JsInvocation || !expression.arguments.isEmpty()) return false
if (expression !is JsInvocation || expression.arguments.isNotEmpty()) return false
val qualifier = expression.qualifier
if (qualifier !is JsNameRef || qualifier.qualifier != null) return false
@@ -126,7 +135,7 @@ private fun List<JsStatement>.createInsertionPlace(): JsBlock {
private fun collectFiles(rootFile: File, target: MutableList<File>) {
if (rootFile.isDirectory) {
for (child in rootFile.listFiles().sorted()) {
for (child in (rootFile.listFiles() ?: error("Problem with listing files in $rootFile")).sorted()) {
collectFiles(child, target)
}
} else if (rootFile.extension == "js") {
@@ -64,6 +64,7 @@ class SourceMapBuilderConsumer(
throw RuntimeException("IO error occurred generating source maps", e)
}
}
is JsLocationWithSource -> {
val contentSupplier = if (provideExternalModuleContent) sourceInfo.sourceProvider else {
{ null }
@@ -87,7 +88,11 @@ class SourceMapBuilderConsumer(
sourceInfo.startChar
)
}
is JsNode, is KtPureElement -> { /* Can occur on legacy BE */ }
is JsNode, is KtPureElement -> {
/* Can occur on legacy BE */
}
else -> {}
}
}