Minor: reformat code

This commit is contained in:
Dmitry Petrov
2018-02-09 16:22:31 +03:00
parent a790195808
commit af79bbd247
3 changed files with 169 additions and 127 deletions
@@ -23,7 +23,8 @@ import org.jetbrains.kotlin.config.JvmTarget
class K2JVMCompilerArguments : CommonCompilerArguments() { class K2JVMCompilerArguments : CommonCompilerArguments() {
companion object { companion object {
@JvmStatic private val serialVersionUID = 0L @JvmStatic
private val serialVersionUID = 0L
} }
@Argument(value = "-d", valueDescription = "<directory|jar>", description = "Destination for generated class files") @Argument(value = "-d", valueDescription = "<directory|jar>", description = "Destination for generated class files")
@@ -38,9 +39,9 @@ class K2JVMCompilerArguments : CommonCompilerArguments() {
@GradleOption(DefaultValues.StringNullDefault::class) @GradleOption(DefaultValues.StringNullDefault::class)
@Argument( @Argument(
value = "-jdk-home", value = "-jdk-home",
valueDescription = "<path>", valueDescription = "<path>",
description = "Path to JDK home directory to include into classpath, if differs from default JAVA_HOME" description = "Path to JDK home directory to include into classpath, if differs from default JAVA_HOME"
) )
var jdkHome: String? by FreezableVar(null) var jdkHome: String? by FreezableVar(null)
@@ -60,9 +61,9 @@ class K2JVMCompilerArguments : CommonCompilerArguments() {
var script: Boolean by FreezableVar(false) var script: Boolean by FreezableVar(false)
@Argument( @Argument(
value = "-script-templates", value = "-script-templates",
valueDescription = "<fully qualified class name[,]>", valueDescription = "<fully qualified class name[,]>",
description = "Script definition template classes" description = "Script definition template classes"
) )
var scriptTemplates: Array<String>? by FreezableVar(null) var scriptTemplates: Array<String>? by FreezableVar(null)
@@ -71,9 +72,9 @@ class K2JVMCompilerArguments : CommonCompilerArguments() {
@GradleOption(DefaultValues.JvmTargetVersions::class) @GradleOption(DefaultValues.JvmTargetVersions::class)
@Argument( @Argument(
value = "-jvm-target", value = "-jvm-target",
valueDescription = "<version>", valueDescription = "<version>",
description = "Target version of the generated JVM bytecode (1.6 or 1.8), default is 1.6" description = "Target version of the generated JVM bytecode (1.6 or 1.8), default is 1.6"
) )
var jvmTarget: String? by FreezableVar(JvmTarget.DEFAULT.description) var jvmTarget: String? by FreezableVar(JvmTarget.DEFAULT.description)
@@ -87,20 +88,26 @@ class K2JVMCompilerArguments : CommonCompilerArguments() {
var javaModulePath: String? by FreezableVar(null) var javaModulePath: String? by FreezableVar(null)
@Argument( @Argument(
value = "-Xadd-modules", value = "-Xadd-modules",
valueDescription = "<module[,]>", valueDescription = "<module[,]>",
description = "Root modules to resolve in addition to the initial modules,\n" + description = "Root modules to resolve in addition to the initial modules,\n" +
"or all modules on the module path if <module> is ALL-MODULE-PATH" "or all modules on the module path if <module> is ALL-MODULE-PATH"
) )
var additionalJavaModules: Array<String>? by FreezableVar(null) var additionalJavaModules: Array<String>? by FreezableVar(null)
@Argument(value = "-Xno-call-assertions", description = "Don't generate not-null assertions for arguments of platform types") @Argument(value = "-Xno-call-assertions", description = "Don't generate not-null assertions for arguments of platform types")
var noCallAssertions: Boolean by FreezableVar(false) var noCallAssertions: Boolean by FreezableVar(false)
@Argument(value = "-Xno-receiver-assertions", description = "Don't generate not-null assertion for extension receiver arguments of platform types") @Argument(
value = "-Xno-receiver-assertions",
description = "Don't generate not-null assertion for extension receiver arguments of platform types"
)
var noReceiverAssertions: Boolean by FreezableVar(false) var noReceiverAssertions: Boolean by FreezableVar(false)
@Argument(value = "-Xno-param-assertions", description = "Don't generate not-null assertions on parameters of methods accessible from Java") @Argument(
value = "-Xno-param-assertions",
description = "Don't generate not-null assertions on parameters of methods accessible from Java"
)
var noParamAssertions: Boolean by FreezableVar(false) var noParamAssertions: Boolean by FreezableVar(false)
@Argument(value = "-Xstrict-java-nullability-assertions", description = "Generate nullability assertions for non-null Java expressions") @Argument(value = "-Xstrict-java-nullability-assertions", description = "Generate nullability assertions for non-null Java expressions")
@@ -110,51 +117,65 @@ class K2JVMCompilerArguments : CommonCompilerArguments() {
var noOptimize: Boolean by FreezableVar(false) var noOptimize: Boolean by FreezableVar(false)
@Argument( @Argument(
value = "-Xnormalize-constructor-calls", value = "-Xnormalize-constructor-calls",
valueDescription = "{disable|enable}", valueDescription = "{disable|enable}",
description = "Normalize constructor calls (disable: don't normalize; enable: normalize), default is disable" description = "Normalize constructor calls (disable: don't normalize; enable: normalize), default is disable"
) )
var constructorCallNormalizationMode: String? by FreezableVar(JVMConstructorCallNormalizationMode.DEFAULT.description) var constructorCallNormalizationMode: String? by FreezableVar(JVMConstructorCallNormalizationMode.DEFAULT.description)
@Argument(value = "-Xreport-perf", description = "Report detailed performance statistics") @Argument(value = "-Xreport-perf", description = "Report detailed performance statistics")
var reportPerf: Boolean by FreezableVar(false) var reportPerf: Boolean by FreezableVar(false)
@Argument(value = "-Xbuild-file", deprecatedName = "-module", valueDescription = "<path>", description = "Path to the .xml build file to compile") @Argument(
value = "-Xbuild-file",
deprecatedName = "-module",
valueDescription = "<path>",
description = "Path to the .xml build file to compile"
)
var buildFile: String? by FreezableVar(null) var buildFile: String? by FreezableVar(null)
@Argument(value = "-Xmultifile-parts-inherit", description = "Compile multifile classes as a hierarchy of parts and facade") @Argument(value = "-Xmultifile-parts-inherit", description = "Compile multifile classes as a hierarchy of parts and facade")
var inheritMultifileParts: Boolean by FreezableVar(false) var inheritMultifileParts: Boolean by FreezableVar(false)
@Argument(value = "-Xskip-runtime-version-check", description = "Allow Kotlin runtime libraries of incompatible versions in the classpath") @Argument(
value = "-Xskip-runtime-version-check",
description = "Allow Kotlin runtime libraries of incompatible versions in the classpath"
)
var skipRuntimeVersionCheck: Boolean by FreezableVar(false) var skipRuntimeVersionCheck: Boolean by FreezableVar(false)
@Argument( @Argument(
value = "-Xuse-old-class-files-reading", value = "-Xuse-old-class-files-reading",
description = "Use old class files reading implementation " + description = "Use old class files reading implementation " +
"(may slow down the build and should be used in case of problems with the new implementation)" "(may slow down the build and should be used in case of problems with the new implementation)"
) )
var useOldClassFilesReading: Boolean by FreezableVar(false) var useOldClassFilesReading: Boolean by FreezableVar(false)
@Argument( @Argument(
value = "-Xdump-declarations-to", value = "-Xdump-declarations-to",
valueDescription = "<path>", valueDescription = "<path>",
description = "Path to JSON file to dump Java to Kotlin declaration mappings" description = "Path to JSON file to dump Java to Kotlin declaration mappings"
) )
var declarationsOutputPath: String? by FreezableVar(null) var declarationsOutputPath: String? by FreezableVar(null)
@Argument(value = "-Xsingle-module", description = "Combine modules for source files and binary dependencies into a single module") @Argument(value = "-Xsingle-module", description = "Combine modules for source files and binary dependencies into a single module")
var singleModule: Boolean by FreezableVar(false) var singleModule: Boolean by FreezableVar(false)
@Argument(value = "-Xadd-compiler-builtins", description = "Add definitions of built-in declarations to the compilation classpath (useful with -no-stdlib)") @Argument(
value = "-Xadd-compiler-builtins",
description = "Add definitions of built-in declarations to the compilation classpath (useful with -no-stdlib)"
)
var addCompilerBuiltIns: Boolean by FreezableVar(false) var addCompilerBuiltIns: Boolean by FreezableVar(false)
@Argument(value = "-Xload-builtins-from-dependencies", description = "Load definitions of built-in declarations from module dependencies, instead of from the compiler") @Argument(
value = "-Xload-builtins-from-dependencies",
description = "Load definitions of built-in declarations from module dependencies, instead of from the compiler"
)
var loadBuiltInsFromDependencies: Boolean by FreezableVar(false) var loadBuiltInsFromDependencies: Boolean by FreezableVar(false)
@Argument( @Argument(
value = "-Xscript-resolver-environment", value = "-Xscript-resolver-environment",
valueDescription = "<key=value[,]>", valueDescription = "<key=value[,]>",
description = "Script resolver environment in key-value pairs (the value could be quoted and escaped)" description = "Script resolver environment in key-value pairs (the value could be quoted and escaped)"
) )
var scriptResolverEnvironment: Array<String>? by FreezableVar(null) var scriptResolverEnvironment: Array<String>? by FreezableVar(null)
@@ -166,25 +187,26 @@ class K2JVMCompilerArguments : CommonCompilerArguments() {
var compileJava by FreezableVar(false) var compileJava by FreezableVar(false)
@Argument( @Argument(
value = "-Xjavac-arguments", value = "-Xjavac-arguments",
valueDescription = "<option[,]>", valueDescription = "<option[,]>",
description = "Java compiler arguments") description = "Java compiler arguments"
)
var javacArguments: Array<String>? by FreezableVar(null) var javacArguments: Array<String>? by FreezableVar(null)
@Argument( @Argument(
value = "-Xjsr305", value = "-Xjsr305",
deprecatedName = "-Xjsr305-annotations", deprecatedName = "-Xjsr305-annotations",
valueDescription = "{ignore/strict/warn}" + valueDescription = "{ignore/strict/warn}" +
"|under-migration:{ignore/strict/warn}" + "|under-migration:{ignore/strict/warn}" +
"|@<fq.name>:{ignore/strict/warn}", "|@<fq.name>:{ignore/strict/warn}",
description = "Specify behavior for JSR-305 nullability annotations:\n" + description = "Specify behavior for JSR-305 nullability annotations:\n" +
"-Xjsr305={ignore/strict/warn} globally (all non-@UnderMigration annotations)\n" + "-Xjsr305={ignore/strict/warn} globally (all non-@UnderMigration annotations)\n" +
"-Xjsr305=under-migration:{ignore/strict/warn} all @UnderMigration annotations\n" + "-Xjsr305=under-migration:{ignore/strict/warn} all @UnderMigration annotations\n" +
"-Xjsr305=@<fq.name>:{ignore/strict/warn} annotation with the given fully qualified class name\n" + "-Xjsr305=@<fq.name>:{ignore/strict/warn} annotation with the given fully qualified class name\n" +
"Modes:\n" + "Modes:\n" +
" * ignore\n" + " * ignore\n" +
" * strict (experimental; treat as other supported nullability annotations)\n" + " * strict (experimental; treat as other supported nullability annotations)\n" +
" * warn (report a warning)" " * warn (report a warning)"
) )
var jsr305: Array<String>? by FreezableVar(null) var jsr305: Array<String>? by FreezableVar(null)
@@ -197,8 +219,8 @@ class K2JVMCompilerArguments : CommonCompilerArguments() {
var supportCompatqualCheckerFrameworkAnnotations: String? by FreezableVar(null) var supportCompatqualCheckerFrameworkAnnotations: String? by FreezableVar(null)
@Argument( @Argument(
value = "-Xno-exception-on-explicit-equals-for-boxed-null", value = "-Xno-exception-on-explicit-equals-for-boxed-null",
description = "Do not throw NPE on explicit 'equals' call for null receiver of platform boxed primitive type" description = "Do not throw NPE on explicit 'equals' call for null receiver of platform boxed primitive type"
) )
var noExceptionOnExplicitEqualsForBoxedNull by FreezableVar(false) var noExceptionOnExplicitEqualsForBoxedNull by FreezableVar(false)
@@ -62,10 +62,10 @@ import java.util.concurrent.TimeUnit
class K2JVMCompiler : CLICompiler<K2JVMCompilerArguments>() { class K2JVMCompiler : CLICompiler<K2JVMCompilerArguments>() {
override fun doExecute( override fun doExecute(
arguments: K2JVMCompilerArguments, arguments: K2JVMCompilerArguments,
configuration: CompilerConfiguration, configuration: CompilerConfiguration,
rootDisposable: Disposable, rootDisposable: Disposable,
paths: KotlinPaths? paths: KotlinPaths?
): ExitCode { ): ExitCode {
PerformanceCounter.setTimeCounterEnabled(arguments.reportPerf) PerformanceCounter.setTimeCounterEnabled(arguments.reportPerf)
@@ -83,8 +83,7 @@ class K2JVMCompiler : CLICompiler<K2JVMCompilerArguments>() {
val file = File(arg) val file = File(arg)
if (file.extension == JavaFileType.DEFAULT_EXTENSION) { if (file.extension == JavaFileType.DEFAULT_EXTENSION) {
configuration.addJavaSourceRoot(file) configuration.addJavaSourceRoot(file)
} } else {
else {
configuration.addKotlinSourceRoot(arg) configuration.addKotlinSourceRoot(arg)
if (file.isDirectory) { if (file.isDirectory) {
configuration.addJavaSourceRoot(file) configuration.addJavaSourceRoot(file)
@@ -120,10 +119,11 @@ class K2JVMCompiler : CLICompiler<K2JVMCompilerArguments>() {
val jvmTarget = JvmTarget.fromString(arguments.jvmTarget!!) val jvmTarget = JvmTarget.fromString(arguments.jvmTarget!!)
if (jvmTarget != null) { if (jvmTarget != null) {
configuration.put(JVMConfigurationKeys.JVM_TARGET, jvmTarget) configuration.put(JVMConfigurationKeys.JVM_TARGET, jvmTarget)
} } else {
else { messageCollector.report(
messageCollector.report(ERROR, "Unknown JVM target version: ${arguments.jvmTarget}\n" + ERROR, "Unknown JVM target version: ${arguments.jvmTarget}\n" +
"Supported versions: ${JvmTarget.values().joinToString { it.description }}") "Supported versions: ${JvmTarget.values().joinToString { it.description }}"
)
} }
} }
@@ -138,8 +138,8 @@ class K2JVMCompiler : CLICompiler<K2JVMCompilerArguments>() {
if (arguments.buildFile != null) { if (arguments.buildFile != null) {
if (destination != null) { if (destination != null) {
messageCollector.report( messageCollector.report(
STRONG_WARNING, STRONG_WARNING,
"The '-d' option with a directory destination is ignored because '-Xbuild-file' is specified" "The '-d' option with a directory destination is ignored because '-Xbuild-file' is specified"
) )
} }
@@ -152,48 +152,45 @@ class K2JVMCompiler : CLICompiler<K2JVMCompilerArguments>() {
KotlinToJVMBytecodeCompiler.configureSourceRoots(configuration, moduleChunk.modules, buildFile) KotlinToJVMBytecodeCompiler.configureSourceRoots(configuration, moduleChunk.modules, buildFile)
val environment = createCoreEnvironment(rootDisposable, configuration, arguments, messageCollector) val environment = createCoreEnvironment(rootDisposable, configuration, arguments, messageCollector)
?: return COMPILATION_ERROR ?: return COMPILATION_ERROR
registerJavacIfNeeded(environment, arguments).let { registerJavacIfNeeded(environment, arguments).let {
if (!it) return COMPILATION_ERROR if (!it) return COMPILATION_ERROR
} }
KotlinToJVMBytecodeCompiler.compileModules(environment, buildFile, moduleChunk.modules) KotlinToJVMBytecodeCompiler.compileModules(environment, buildFile, moduleChunk.modules)
} } else if (arguments.script) {
else if (arguments.script) {
val sourcePath = arguments.freeArgs.first() val sourcePath = arguments.freeArgs.first()
configuration.addKotlinSourceRoot(sourcePath) configuration.addKotlinSourceRoot(sourcePath)
configuration.put(JVMConfigurationKeys.RETAIN_OUTPUT_IN_MEMORY, true) configuration.put(JVMConfigurationKeys.RETAIN_OUTPUT_IN_MEMORY, true)
val environment = createCoreEnvironment(rootDisposable, configuration, arguments, messageCollector) val environment = createCoreEnvironment(rootDisposable, configuration, arguments, messageCollector)
?: return COMPILATION_ERROR ?: return COMPILATION_ERROR
val scriptDefinitionProvider = ScriptDefinitionProvider.getInstance(environment.project) val scriptDefinitionProvider = ScriptDefinitionProvider.getInstance(environment.project)
val scriptFile = File(sourcePath) val scriptFile = File(sourcePath)
if (scriptFile.isDirectory || !scriptDefinitionProvider.isScript(scriptFile.name)) { if (scriptFile.isDirectory || !scriptDefinitionProvider.isScript(scriptFile.name)) {
val extensionHint = val extensionHint =
if (configuration.get(JVMConfigurationKeys.SCRIPT_DEFINITIONS) == listOf(StandardScriptDefinition)) " (.kts)" if (configuration.get(JVMConfigurationKeys.SCRIPT_DEFINITIONS) == listOf(StandardScriptDefinition)) " (.kts)"
else "" else ""
messageCollector.report(ERROR, "Specify path to the script file$extensionHint as the first argument") messageCollector.report(ERROR, "Specify path to the script file$extensionHint as the first argument")
return COMPILATION_ERROR return COMPILATION_ERROR
} }
val scriptArgs = arguments.freeArgs.subList(1, arguments.freeArgs.size) val scriptArgs = arguments.freeArgs.subList(1, arguments.freeArgs.size)
return KotlinToJVMBytecodeCompiler.compileAndExecuteScript(environment, scriptArgs) return KotlinToJVMBytecodeCompiler.compileAndExecuteScript(environment, scriptArgs)
} } else {
else {
if (destination != null) { if (destination != null) {
if (destination.endsWith(".jar")) { if (destination.endsWith(".jar")) {
configuration.put(JVMConfigurationKeys.OUTPUT_JAR, File(destination)) configuration.put(JVMConfigurationKeys.OUTPUT_JAR, File(destination))
} } else {
else {
configuration.put(JVMConfigurationKeys.OUTPUT_DIRECTORY, File(destination)) configuration.put(JVMConfigurationKeys.OUTPUT_DIRECTORY, File(destination))
} }
} }
val environment = createCoreEnvironment(rootDisposable, configuration, arguments, messageCollector) val environment = createCoreEnvironment(rootDisposable, configuration, arguments, messageCollector)
?: return COMPILATION_ERROR ?: return COMPILATION_ERROR
registerJavacIfNeeded(environment, arguments).let { registerJavacIfNeeded(environment, arguments).let {
if (!it) return COMPILATION_ERROR if (!it) return COMPILATION_ERROR
@@ -220,20 +217,19 @@ class K2JVMCompiler : CLICompiler<K2JVMCompilerArguments>() {
PerformanceCounter.report { s -> reportPerf(configuration, s) } PerformanceCounter.report { s -> reportPerf(configuration, s) }
} }
return OK return OK
} } catch (e: CompilationException) {
catch (e: CompilationException) {
messageCollector.report( messageCollector.report(
EXCEPTION, EXCEPTION,
OutputMessageUtil.renderException(e), OutputMessageUtil.renderException(e),
MessageUtil.psiElementToMessageLocation(e.element) MessageUtil.psiElementToMessageLocation(e.element)
) )
return INTERNAL_ERROR return INTERNAL_ERROR
} }
} }
override fun setupPlatformSpecificLanguageFeatureSettings( override fun setupPlatformSpecificLanguageFeatureSettings(
extraLanguageFeatures: MutableMap<LanguageFeature, LanguageFeature.State>, extraLanguageFeatures: MutableMap<LanguageFeature, LanguageFeature.State>,
commandLineArguments: K2JVMCompilerArguments commandLineArguments: K2JVMCompilerArguments
) { ) {
if (commandLineArguments.strictJavaNullabilityAssertions) { if (commandLineArguments.strictJavaNullabilityAssertions) {
extraLanguageFeatures[LanguageFeature.StrictJavaNullabilityAssertions] = LanguageFeature.State.ENABLED extraLanguageFeatures[LanguageFeature.StrictJavaNullabilityAssertions] = LanguageFeature.State.ENABLED
@@ -242,8 +238,10 @@ class K2JVMCompiler : CLICompiler<K2JVMCompilerArguments>() {
super.setupPlatformSpecificLanguageFeatureSettings(extraLanguageFeatures, commandLineArguments) super.setupPlatformSpecificLanguageFeatureSettings(extraLanguageFeatures, commandLineArguments)
} }
private fun registerJavacIfNeeded(environment: KotlinCoreEnvironment, private fun registerJavacIfNeeded(
arguments: K2JVMCompilerArguments): Boolean { environment: KotlinCoreEnvironment,
arguments: K2JVMCompilerArguments
): Boolean {
if (arguments.useJavac) { if (arguments.useJavac) {
environment.configuration.put(JVMConfigurationKeys.USE_JAVAC, true) environment.configuration.put(JVMConfigurationKeys.USE_JAVAC, true)
if (arguments.compileJava) { if (arguments.compileJava) {
@@ -255,8 +253,10 @@ class K2JVMCompiler : CLICompiler<K2JVMCompilerArguments>() {
return true return true
} }
private fun compileJavaFilesIfNeeded(environment: KotlinCoreEnvironment, private fun compileJavaFilesIfNeeded(
arguments: K2JVMCompilerArguments): Boolean { environment: KotlinCoreEnvironment,
arguments: K2JVMCompilerArguments
): Boolean {
if (arguments.compileJava) { if (arguments.compileJava) {
return JavacWrapper.getInstance(environment.project).use { it.compile() } return JavacWrapper.getInstance(environment.project).use { it.compile() }
} }
@@ -264,10 +264,10 @@ class K2JVMCompiler : CLICompiler<K2JVMCompilerArguments>() {
} }
private fun createCoreEnvironment( private fun createCoreEnvironment(
rootDisposable: Disposable, rootDisposable: Disposable,
configuration: CompilerConfiguration, configuration: CompilerConfiguration,
arguments: K2JVMCompilerArguments, arguments: K2JVMCompilerArguments,
messageCollector: MessageCollector messageCollector: MessageCollector
): KotlinCoreEnvironment? { ): KotlinCoreEnvironment? {
val scriptResolverEnv = createScriptResolverEnvironment(arguments, messageCollector) ?: return null val scriptResolverEnv = createScriptResolverEnvironment(arguments, messageCollector) ?: return null
configureScriptDefinitions(arguments.scriptTemplates, configuration, messageCollector, scriptResolverEnv) configureScriptDefinitions(arguments.scriptTemplates, configuration, messageCollector, scriptResolverEnv)
@@ -290,7 +290,7 @@ class K2JVMCompiler : CLICompiler<K2JVMCompilerArguments>() {
} }
override fun setupPlatformSpecificArgumentsAndServices( override fun setupPlatformSpecificArgumentsAndServices(
configuration: CompilerConfiguration, arguments: K2JVMCompilerArguments, services: Services configuration: CompilerConfiguration, arguments: K2JVMCompilerArguments, services: Services
) { ) {
if (IncrementalCompilation.isEnabled()) { if (IncrementalCompilation.isEnabled()) {
services.get(LookupTracker::class.java)?.let { services.get(LookupTracker::class.java)?.let {
@@ -335,7 +335,8 @@ class K2JVMCompiler : CLICompiler<K2JVMCompilerArguments>() {
} }
} }
@JvmStatic fun main(args: Array<String>) { @JvmStatic
fun main(args: Array<String>) {
CLITool.doMain(K2JVMCompiler(), args) CLITool.doMain(K2JVMCompiler(), args)
} }
@@ -366,17 +367,25 @@ class K2JVMCompiler : CLICompiler<K2JVMCompilerArguments>() {
configuration.put(JVMConfigurationKeys.DISABLE_CALL_ASSERTIONS, arguments.noCallAssertions) configuration.put(JVMConfigurationKeys.DISABLE_CALL_ASSERTIONS, arguments.noCallAssertions)
configuration.put(JVMConfigurationKeys.DISABLE_RECEIVER_ASSERTIONS, arguments.noReceiverAssertions) configuration.put(JVMConfigurationKeys.DISABLE_RECEIVER_ASSERTIONS, arguments.noReceiverAssertions)
configuration.put(JVMConfigurationKeys.DISABLE_PARAM_ASSERTIONS, arguments.noParamAssertions) configuration.put(JVMConfigurationKeys.DISABLE_PARAM_ASSERTIONS, arguments.noParamAssertions)
configuration.put(JVMConfigurationKeys.NO_EXCEPTION_ON_EXPLICIT_EQUALS_FOR_BOXED_NULL, arguments.noExceptionOnExplicitEqualsForBoxedNull) configuration.put(
JVMConfigurationKeys.NO_EXCEPTION_ON_EXPLICIT_EQUALS_FOR_BOXED_NULL,
arguments.noExceptionOnExplicitEqualsForBoxedNull
)
configuration.put(JVMConfigurationKeys.DISABLE_OPTIMIZATION, arguments.noOptimize) configuration.put(JVMConfigurationKeys.DISABLE_OPTIMIZATION, arguments.noOptimize)
val constructorCallNormalizationMode = JVMConstructorCallNormalizationMode.fromStringOrNull(arguments.constructorCallNormalizationMode) val constructorCallNormalizationMode =
JVMConstructorCallNormalizationMode.fromStringOrNull(arguments.constructorCallNormalizationMode)
if (constructorCallNormalizationMode == null) { if (constructorCallNormalizationMode == null) {
configuration.getNotNull(CLIConfigurationKeys.MESSAGE_COLLECTOR_KEY) configuration.getNotNull(CLIConfigurationKeys.MESSAGE_COLLECTOR_KEY).report(
.report(ERROR, "Unknown constructor call normalization mode: ${arguments.constructorCallNormalizationMode}, " + ERROR,
"supported modes: ${JVMConstructorCallNormalizationMode.values().map { it.description }}") "Unknown constructor call normalization mode: ${arguments.constructorCallNormalizationMode}, " +
"supported modes: ${JVMConstructorCallNormalizationMode.values().map { it.description }}"
)
} }
configuration.put(JVMConfigurationKeys.CONSTRUCTOR_CALL_NORMALIZATION_MODE, configuration.put(
constructorCallNormalizationMode ?: JVMConstructorCallNormalizationMode.DEFAULT) JVMConfigurationKeys.CONSTRUCTOR_CALL_NORMALIZATION_MODE,
constructorCallNormalizationMode ?: JVMConstructorCallNormalizationMode.DEFAULT
)
configuration.put(JVMConfigurationKeys.INHERIT_MULTIFILE_PARTS, arguments.inheritMultifileParts) configuration.put(JVMConfigurationKeys.INHERIT_MULTIFILE_PARTS, arguments.inheritMultifileParts)
configuration.put(JVMConfigurationKeys.SKIP_RUNTIME_VERSION_CHECK, arguments.skipRuntimeVersionCheck) configuration.put(JVMConfigurationKeys.SKIP_RUNTIME_VERSION_CHECK, arguments.skipRuntimeVersionCheck)
@@ -384,7 +393,7 @@ class K2JVMCompiler : CLICompiler<K2JVMCompilerArguments>() {
if (arguments.useOldClassFilesReading) { if (arguments.useOldClassFilesReading) {
configuration.getNotNull(CLIConfigurationKeys.MESSAGE_COLLECTOR_KEY) configuration.getNotNull(CLIConfigurationKeys.MESSAGE_COLLECTOR_KEY)
.report(INFO, "Using the old java class files reading implementation") .report(INFO, "Using the old java class files reading implementation")
} }
configuration.put(CLIConfigurationKeys.ALLOW_KOTLIN_PACKAGE, arguments.allowKotlinPackage) configuration.put(CLIConfigurationKeys.ALLOW_KOTLIN_PACKAGE, arguments.allowKotlinPackage)
@@ -412,8 +421,7 @@ class K2JVMCompiler : CLICompiler<K2JVMCompilerArguments>() {
if (isModularJava) { if (isModularJava) {
configuration.add(JVMConfigurationKeys.CONTENT_ROOTS, JvmModulePathRoot(file)) configuration.add(JVMConfigurationKeys.CONTENT_ROOTS, JvmModulePathRoot(file))
configuration.add(JVMConfigurationKeys.ADDITIONAL_JAVA_MODULES, moduleName) configuration.add(JVMConfigurationKeys.ADDITIONAL_JAVA_MODULES, moduleName)
} } else {
else {
configuration.add(JVMConfigurationKeys.CONTENT_ROOTS, JvmClasspathRoot(file)) configuration.add(JVMConfigurationKeys.CONTENT_ROOTS, JvmClasspathRoot(file))
} }
} }
@@ -429,7 +437,11 @@ class K2JVMCompiler : CLICompiler<K2JVMCompilerArguments>() {
} }
} }
private fun configureJdkHome(arguments: K2JVMCompilerArguments, configuration: CompilerConfiguration, messageCollector: MessageCollector): ExitCode { private fun configureJdkHome(
arguments: K2JVMCompilerArguments,
configuration: CompilerConfiguration,
messageCollector: MessageCollector
): ExitCode {
if (arguments.noJdk) { if (arguments.noJdk) {
configuration.put(JVMConfigurationKeys.NO_JDK, true) configuration.put(JVMConfigurationKeys.NO_JDK, true)
@@ -454,14 +466,17 @@ class K2JVMCompiler : CLICompiler<K2JVMCompilerArguments>() {
return OK return OK
} }
fun configureScriptDefinitions(scriptTemplates: Array<String>?, fun configureScriptDefinitions(
configuration: CompilerConfiguration, scriptTemplates: Array<String>?,
messageCollector: MessageCollector, configuration: CompilerConfiguration,
scriptResolverEnv: HashMap<String, Any?>) { messageCollector: MessageCollector,
scriptResolverEnv: HashMap<String, Any?>
) {
val classpath = configuration.jvmClasspathRoots val classpath = configuration.jvmClasspathRoots
// TODO: consider using escaping to allow kotlin escaped names in class names // TODO: consider using escaping to allow kotlin escaped names in class names
if (scriptTemplates != null && scriptTemplates.isNotEmpty()) { if (scriptTemplates != null && scriptTemplates.isNotEmpty()) {
val classloader = URLClassLoader(classpath.map { it.toURI().toURL() }.toTypedArray(), Thread.currentThread().contextClassLoader) val classloader =
URLClassLoader(classpath.map { it.toURI().toURL() }.toTypedArray(), Thread.currentThread().contextClassLoader)
var hasErrors = false var hasErrors = false
for (template in scriptTemplates) { for (template in scriptTemplates) {
try { try {
@@ -469,16 +484,14 @@ class K2JVMCompiler : CLICompiler<K2JVMCompilerArguments>() {
val def = KotlinScriptDefinitionFromAnnotatedTemplate(cls.kotlin, scriptResolverEnv) val def = KotlinScriptDefinitionFromAnnotatedTemplate(cls.kotlin, scriptResolverEnv)
configuration.add(JVMConfigurationKeys.SCRIPT_DEFINITIONS, def) configuration.add(JVMConfigurationKeys.SCRIPT_DEFINITIONS, def)
messageCollector.report( messageCollector.report(
INFO, INFO,
"Added script definition $template to configuration: files pattern = \"${def.scriptFilePattern}\", " + "Added script definition $template to configuration: files pattern = \"${def.scriptFilePattern}\", " +
"resolver = ${def.dependencyResolver.javaClass.name}" "resolver = ${def.dependencyResolver.javaClass.name}"
) )
} } catch (ex: ClassNotFoundException) {
catch (ex: ClassNotFoundException) {
messageCollector.report(ERROR, "Cannot find script definition template class $template") messageCollector.report(ERROR, "Cannot find script definition template class $template")
hasErrors = true hasErrors = true
} } catch (ex: Exception) {
catch (ex: Exception) {
messageCollector.report(ERROR, "Error processing script definition template $template: ${ex.message}") messageCollector.report(ERROR, "Error processing script definition template $template: ${ex.message}")
hasErrors = true hasErrors = true
break break
@@ -507,7 +520,9 @@ class K2JVMCompiler : CLICompiler<K2JVMCompilerArguments>() {
messageCollector.report(ERROR, "Unable to parse script-resolver-environment argument $envParam") messageCollector.report(ERROR, "Unable to parse script-resolver-environment argument $envParam")
return null return null
} }
scriptResolverEnv.put(match.groupValues[1], match.groupValues.drop(2).firstOrNull { it.isNotEmpty() }?.let { unescapeRe.replace(it, "\$1") }) scriptResolverEnv.put(
match.groupValues[1],
match.groupValues.drop(2).firstOrNull { it.isNotEmpty() }?.let { unescapeRe.replace(it, "\$1") })
} }
} }
return scriptResolverEnv return scriptResolverEnv
@@ -10,10 +10,10 @@ import org.jetbrains.kotlin.utils.DescriptionAware
import java.util.* import java.util.*
enum class LanguageFeature( enum class LanguageFeature(
val sinceVersion: LanguageVersion?, val sinceVersion: LanguageVersion?,
val sinceApiVersion: ApiVersion = ApiVersion.KOTLIN_1_0, val sinceApiVersion: ApiVersion = ApiVersion.KOTLIN_1_0,
val hintUrl: String? = null, val hintUrl: String? = null,
val defaultState: State = State.ENABLED val defaultState: State = State.ENABLED
) { ) {
// Note: names of these entries are also used in diagnostic tests and in user-visible messages (see presentableText below) // Note: names of these entries are also used in diagnostic tests and in user-visible messages (see presentableText below)
TypeAliases(KOTLIN_1_1), TypeAliases(KOTLIN_1_1),
@@ -77,7 +77,11 @@ enum class LanguageFeature(
// Experimental features // Experimental features
Coroutines(KOTLIN_1_1, ApiVersion.KOTLIN_1_1, "https://kotlinlang.org/docs/diagnostics/experimental-coroutines", State.ENABLED_WITH_WARNING), Coroutines(
KOTLIN_1_1, ApiVersion.KOTLIN_1_1,
"https://kotlinlang.org/docs/diagnostics/experimental-coroutines",
State.ENABLED_WITH_WARNING
),
MultiPlatformProjects(sinceVersion = null, defaultState = State.DISABLED), MultiPlatformProjects(sinceVersion = null, defaultState = State.DISABLED),
@@ -86,7 +90,7 @@ enum class LanguageFeature(
; ;
val presentableName: String val presentableName: String
// E.g. "DestructuringLambdaParameters" -> ["Destructuring", "Lambda", "Parameters"] -> "destructuring lambda parameters" // E.g. "DestructuringLambdaParameters" -> ["Destructuring", "Lambda", "Parameters"] -> "destructuring lambda parameters"
get() = name.split("(?<!^)(?=[A-Z])".toRegex()).joinToString(separator = " ", transform = String::toLowerCase) get() = name.split("(?<!^)(?=[A-Z])".toRegex()).joinToString(separator = " ", transform = String::toLowerCase)
val presentableText get() = if (hintUrl == null) presentableName else "$presentableName (See: $hintUrl)" val presentableText get() = if (hintUrl == null) presentableName else "$presentableName (See: $hintUrl)"
@@ -126,7 +130,8 @@ enum class LanguageVersion(val major: Int, val minor: Int) : DescriptionAware {
fun fromVersionString(str: String?) = values().find { it.versionString == str } fun fromVersionString(str: String?) = values().find { it.versionString == str }
@JvmStatic @JvmStatic
fun fromFullVersionString(str: String) = str.split(".", "-").let { if (it.size >= 2) fromVersionString("${it[0]}.${it[1]}") else null } fun fromFullVersionString(str: String) =
str.split(".", "-").let { if (it.size >= 2) fromVersionString("${it[0]}.${it[1]}") else null }
@JvmField @JvmField
val LATEST_STABLE = KOTLIN_1_2 val LATEST_STABLE = KOTLIN_1_2
@@ -137,7 +142,7 @@ interface LanguageVersionSettings {
fun getFeatureSupport(feature: LanguageFeature): LanguageFeature.State fun getFeatureSupport(feature: LanguageFeature): LanguageFeature.State
fun supportsFeature(feature: LanguageFeature): Boolean = fun supportsFeature(feature: LanguageFeature): Boolean =
getFeatureSupport(feature).let { it == LanguageFeature.State.ENABLED || it == LanguageFeature.State.ENABLED_WITH_WARNING } getFeatureSupport(feature).let { it == LanguageFeature.State.ENABLED || it == LanguageFeature.State.ENABLED_WITH_WARNING }
fun <T> getFlag(flag: AnalysisFlag<T>): T fun <T> getFlag(flag: AnalysisFlag<T>): T
@@ -148,10 +153,10 @@ interface LanguageVersionSettings {
} }
class LanguageVersionSettingsImpl @JvmOverloads constructor( class LanguageVersionSettingsImpl @JvmOverloads constructor(
override val languageVersion: LanguageVersion, override val languageVersion: LanguageVersion,
override val apiVersion: ApiVersion, override val apiVersion: ApiVersion,
analysisFlags: Map<AnalysisFlag<*>, Any?> = emptyMap(), analysisFlags: Map<AnalysisFlag<*>, Any?> = emptyMap(),
specificFeatures: Map<LanguageFeature, LanguageFeature.State> = emptyMap() specificFeatures: Map<LanguageFeature, LanguageFeature.State> = emptyMap()
) : LanguageVersionSettings { ) : LanguageVersionSettings {
private val analysisFlags: Map<AnalysisFlag<*>, *> = Collections.unmodifiableMap(analysisFlags) private val analysisFlags: Map<AnalysisFlag<*>, *> = Collections.unmodifiableMap(analysisFlags)
private val specificFeatures: Map<LanguageFeature, LanguageFeature.State> = Collections.unmodifiableMap(specificFeatures) private val specificFeatures: Map<LanguageFeature, LanguageFeature.State> = Collections.unmodifiableMap(specificFeatures)
@@ -189,7 +194,7 @@ class LanguageVersionSettingsImpl @JvmOverloads constructor(
} }
fun LanguageVersionSettings.isPreRelease(): Boolean = fun LanguageVersionSettings.isPreRelease(): Boolean =
languageVersion.isPreRelease() languageVersion.isPreRelease()
fun LanguageVersion.isPreRelease(): Boolean { fun LanguageVersion.isPreRelease(): Boolean {
if (!isStable) return true if (!isStable) return true