Use null instead of CompilerMessageLocation.NO_LOCATION in MessageCollector

This commit is contained in:
Alexander Udalov
2017-03-31 17:39:03 +03:00
parent 411a8dc206
commit 861d9a1620
46 changed files with 279 additions and 390 deletions
@@ -21,7 +21,6 @@ import org.jetbrains.kotlin.analyzer.common.DefaultAnalyzerFacade
import org.jetbrains.kotlin.builtins.BuiltInsBinaryVersion import org.jetbrains.kotlin.builtins.BuiltInsBinaryVersion
import org.jetbrains.kotlin.cli.common.CLIConfigurationKeys import org.jetbrains.kotlin.cli.common.CLIConfigurationKeys
import org.jetbrains.kotlin.cli.common.messages.AnalyzerWithCompilerReport import org.jetbrains.kotlin.cli.common.messages.AnalyzerWithCompilerReport
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageLocation
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity
import org.jetbrains.kotlin.cli.jvm.compiler.JvmPackagePartProvider import org.jetbrains.kotlin.cli.jvm.compiler.JvmPackagePartProvider
import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment
@@ -58,7 +57,7 @@ open class MetadataSerializer(private val dependOnOldBuiltIns: Boolean) {
val moduleName = Name.special("<${configuration.getNotNull(CommonConfigurationKeys.MODULE_NAME)}>") val moduleName = Name.special("<${configuration.getNotNull(CommonConfigurationKeys.MODULE_NAME)}>")
val destDir = configuration.get(CLIConfigurationKeys.METADATA_DESTINATION_DIRECTORY) ?: run { val destDir = configuration.get(CLIConfigurationKeys.METADATA_DESTINATION_DIRECTORY) ?: run {
messageCollector.report(CompilerMessageSeverity.ERROR, "Specify destination via -d", CompilerMessageLocation.NO_LOCATION) messageCollector.report(CompilerMessageSeverity.ERROR, "Specify destination via -d")
return return
} }
@@ -75,10 +75,10 @@ class BuiltInsSerializer(dependOnOldBuiltIns: Boolean) : MetadataSerializer(depe
private fun createMessageCollector() = object : GroupingMessageCollector( private fun createMessageCollector() = object : GroupingMessageCollector(
PrintingMessageCollector(System.err, MessageRenderer.PLAIN_RELATIVE_PATHS, /* verbose = */ false) PrintingMessageCollector(System.err, MessageRenderer.PLAIN_RELATIVE_PATHS, /* verbose = */ false)
) { ) {
override fun report(severity: CompilerMessageSeverity, message: String, location: CompilerMessageLocation) { override fun report(severity: CompilerMessageSeverity, message: String, location: CompilerMessageLocation?) {
// Only report diagnostics without a particular location because there's plenty of errors in built-in sources // Only report diagnostics without a particular location because there's plenty of errors in built-in sources
// (functions without bodies, incorrect combination of modifiers, etc.) // (functions without bodies, incorrect combination of modifiers, etc.)
if (location.path == null) { if (location == null) {
super.report(severity, message, location) super.report(severity, message, location)
} }
} }
@@ -17,6 +17,7 @@
package org.jetbrains.kotlin.cli.common.messages; package org.jetbrains.kotlin.cli.common.messages;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.function.Predicate; import java.util.function.Predicate;
@@ -35,9 +36,7 @@ public class FilteringMessageCollector implements MessageCollector {
} }
@Override @Override
public void report( public void report(@NotNull CompilerMessageSeverity severity, @NotNull String message, @Nullable CompilerMessageLocation location) {
@NotNull CompilerMessageSeverity severity, @NotNull String message, @NotNull CompilerMessageLocation location
) {
if (!decline.test(severity)) { if (!decline.test(severity)) {
messageCollector.report(severity, message, location); messageCollector.report(severity, message, location);
} }
@@ -19,14 +19,11 @@ package org.jetbrains.kotlin.cli.common.messages;
import com.google.common.collect.LinkedHashMultimap; import com.google.common.collect.LinkedHashMultimap;
import com.google.common.collect.Multimap; import com.google.common.collect.Multimap;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList; import java.util.*;
import java.util.Collection;
import java.util.List;
import java.util.Map;
public class GroupingMessageCollector implements MessageCollector { public class GroupingMessageCollector implements MessageCollector {
private final MessageCollector delegate; private final MessageCollector delegate;
// File path (nullable) -> message // File path (nullable) -> message
@@ -45,25 +42,19 @@ public class GroupingMessageCollector implements MessageCollector {
public void report( public void report(
@NotNull CompilerMessageSeverity severity, @NotNull CompilerMessageSeverity severity,
@NotNull String message, @NotNull String message,
@NotNull CompilerMessageLocation location @Nullable CompilerMessageLocation location
) { ) {
if (CompilerMessageSeverity.VERBOSE.contains(severity)) { if (CompilerMessageSeverity.VERBOSE.contains(severity)) {
delegate.report(severity, message, location); delegate.report(severity, message, location);
} }
else { else {
groupedMessages.put(location.getPath(), new Message(severity, message, location)); groupedMessages.put(location != null ? location.getPath() : null, new Message(severity, message, location));
} }
} }
@Override @Override
public boolean hasErrors() { public boolean hasErrors() {
for (Map.Entry<String, Message> entry : groupedMessages.entries()) { return groupedMessages.entries().stream().anyMatch(entry -> entry.getValue().severity.isError());
if (entry.getValue().severity.isError()) {
return true;
}
}
return false;
} }
public void flush() { public void flush() {
@@ -82,14 +73,9 @@ public class GroupingMessageCollector implements MessageCollector {
@NotNull @NotNull
private Collection<String> sortedKeys() { private Collection<String> sortedKeys() {
List<String> sortedKeys = new ArrayList<>(groupedMessages.keySet());
// ensure that messages with no location i.e. perf, incomplete hierarchy are always reported first // ensure that messages with no location i.e. perf, incomplete hierarchy are always reported first
sortedKeys.sort((o1, o2) -> { List<String> sortedKeys = new ArrayList<>(groupedMessages.keySet());
if (o1 == o2) return 0; sortedKeys.sort(Comparator.nullsFirst(Comparator.naturalOrder()));
if (o1 == null) return -1;
if (o2 == null) return 1;
return o1.compareTo(o2);
});
return sortedKeys; return sortedKeys;
} }
@@ -98,7 +84,7 @@ public class GroupingMessageCollector implements MessageCollector {
private final String message; private final String message;
private final CompilerMessageLocation location; private final CompilerMessageLocation location;
private Message(@NotNull CompilerMessageSeverity severity, @NotNull String message, @NotNull CompilerMessageLocation location) { private Message(@NotNull CompilerMessageSeverity severity, @NotNull String message, @Nullable CompilerMessageLocation location) {
this.severity = severity; this.severity = severity;
this.message = message; this.message = message;
this.location = location; this.location = location;
@@ -109,11 +95,11 @@ public class GroupingMessageCollector implements MessageCollector {
if (this == o) return true; if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false; if (o == null || getClass() != o.getClass()) return false;
Message message1 = (Message) o; Message other = (Message) o;
if (!location.equals(message1.location)) return false; if (!Objects.equals(location, other.location)) return false;
if (!message.equals(message1.message)) return false; if (!message.equals(other.message)) return false;
if (severity != message1.severity) return false; if (severity != other.severity) return false;
return true; return true;
} }
@@ -122,8 +108,13 @@ public class GroupingMessageCollector implements MessageCollector {
public int hashCode() { public int hashCode() {
int result = severity.hashCode(); int result = severity.hashCode();
result = 31 * result + message.hashCode(); result = 31 * result + message.hashCode();
result = 31 * result + location.hashCode(); result = 31 * result + (location != null ? location.hashCode() : 0);
return result; return result;
} }
@Override
public String toString() {
return "[" + severity + "] " + message + (location != null ? " (at " + location + ")" : " (no location)");
}
} }
} }
@@ -1,44 +0,0 @@
/*
* Copyright 2010-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.cli.common.messages;
import org.jetbrains.annotations.NotNull;
public interface MessageCollector {
MessageCollector NONE = new MessageCollector() {
@Override
public void report(@NotNull CompilerMessageSeverity severity, @NotNull String message, @NotNull CompilerMessageLocation location) {
// Do nothing
}
@Override
public void clear() {
// Do nothing
}
@Override
public boolean hasErrors() {
return false;
}
};
void clear();
void report(@NotNull CompilerMessageSeverity severity, @NotNull String message, @NotNull CompilerMessageLocation location);
boolean hasErrors();
}
@@ -0,0 +1,39 @@
/*
* Copyright 2010-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.cli.common.messages
interface MessageCollector {
fun clear()
fun report(severity: CompilerMessageSeverity, message: String, location: CompilerMessageLocation? = null)
fun hasErrors(): Boolean
companion object {
val NONE: MessageCollector = object : MessageCollector {
override fun report(severity: CompilerMessageSeverity, message: String, location: CompilerMessageLocation?) {
// Do nothing
}
override fun clear() {
// Do nothing
}
override fun hasErrors(): Boolean = false
}
}
}
@@ -20,7 +20,6 @@ import org.jetbrains.annotations.NotNull;
public class MessageCollectorUtil { public class MessageCollectorUtil {
public static void reportException(@NotNull MessageCollector messageCollector, @NotNull Throwable exception) { public static void reportException(@NotNull MessageCollector messageCollector, @NotNull Throwable exception) {
messageCollector.report(CompilerMessageSeverity.EXCEPTION, OutputMessageUtil.renderException(exception), messageCollector.report(CompilerMessageSeverity.EXCEPTION, OutputMessageUtil.renderException(exception), null);
CompilerMessageLocation.NO_LOCATION);
} }
} }
@@ -35,7 +35,6 @@ import javax.xml.parsers.SAXParserFactory;
import java.io.*; import java.io.*;
import java.util.List; import java.util.List;
import static org.jetbrains.kotlin.cli.common.messages.CompilerMessageLocation.NO_LOCATION;
import static org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity.ERROR; import static org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity.ERROR;
public class ModuleXmlParser { public class ModuleXmlParser {
@@ -103,7 +102,7 @@ public class ModuleXmlParser {
MessageCollectorUtil.reportException(messageCollector, e); MessageCollectorUtil.reportException(messageCollector, e);
} }
catch (SAXException e) { catch (SAXException e) {
messageCollector.report(ERROR, OutputMessageUtil.renderException(e), NO_LOCATION); messageCollector.report(ERROR, OutputMessageUtil.renderException(e), null);
} }
return ModuleScriptData.EMPTY; return ModuleScriptData.EMPTY;
} }
@@ -42,6 +42,7 @@ import java.util.function.Predicate;
import static org.jetbrains.kotlin.cli.common.ExitCode.*; import static org.jetbrains.kotlin.cli.common.ExitCode.*;
import static org.jetbrains.kotlin.cli.common.environment.UtilKt.setIdeaIoUseFallback; import static org.jetbrains.kotlin.cli.common.environment.UtilKt.setIdeaIoUseFallback;
import static org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity.*;
public abstract class CLICompiler<A extends CommonCompilerArguments> { public abstract class CLICompiler<A extends CommonCompilerArguments> {
@@ -76,11 +77,7 @@ public abstract class CLICompiler<A extends CommonCompilerArguments> {
Usage.print(errStream, createArguments(), false); Usage.print(errStream, createArguments(), false);
} }
catch (Throwable t) { catch (Throwable t) {
errStream.println(messageRenderer.render( errStream.println(messageRenderer.render(EXCEPTION, OutputMessageUtil.renderException(t), CompilerMessageLocation.NO_LOCATION));
CompilerMessageSeverity.EXCEPTION,
OutputMessageUtil.renderException(t),
CompilerMessageLocation.NO_LOCATION)
);
} }
return null; return null;
} }
@@ -137,7 +134,7 @@ public abstract class CLICompiler<A extends CommonCompilerArguments> {
printVersionIfNeeded(messageCollector, arguments); printVersionIfNeeded(messageCollector, arguments);
if (arguments.suppressWarnings) { if (arguments.suppressWarnings) {
messageCollector = new FilteringMessageCollector(messageCollector, Predicate.isEqual(CompilerMessageSeverity.WARNING)); messageCollector = new FilteringMessageCollector(messageCollector, Predicate.isEqual(WARNING));
} }
reportUnknownExtraFlags(messageCollector, arguments); reportUnknownExtraFlags(messageCollector, arguments);
@@ -176,14 +173,13 @@ public abstract class CLICompiler<A extends CommonCompilerArguments> {
exitCode = groupingCollector.hasErrors() ? COMPILATION_ERROR : code; exitCode = groupingCollector.hasErrors() ? COMPILATION_ERROR : code;
} }
catch (CompilationCanceledException e) { catch (CompilationCanceledException e) {
messageCollector.report(CompilerMessageSeverity.INFO, "Compilation was canceled", CompilerMessageLocation.NO_LOCATION); messageCollector.report(INFO, "Compilation was canceled", null);
return ExitCode.OK; return ExitCode.OK;
} }
catch (RuntimeException e) { catch (RuntimeException e) {
Throwable cause = e.getCause(); Throwable cause = e.getCause();
if (cause instanceof CompilationCanceledException) { if (cause instanceof CompilationCanceledException) {
messageCollector messageCollector.report(INFO, "Compilation was canceled", null);
.report(CompilerMessageSeverity.INFO, "Compilation was canceled", CompilerMessageLocation.NO_LOCATION);
return ExitCode.OK; return ExitCode.OK;
} }
else { else {
@@ -197,8 +193,7 @@ public abstract class CLICompiler<A extends CommonCompilerArguments> {
return exitCode; return exitCode;
} }
catch (Throwable t) { catch (Throwable t) {
groupingCollector.report(CompilerMessageSeverity.EXCEPTION, OutputMessageUtil.renderException(t), MessageCollectorUtil.reportException(groupingCollector, t);
CompilerMessageLocation.NO_LOCATION);
return INTERNAL_ERROR; return INTERNAL_ERROR;
} }
finally { finally {
@@ -243,19 +238,19 @@ public abstract class CLICompiler<A extends CommonCompilerArguments> {
if (apiVersion.compareTo(languageVersion) > 0) { if (apiVersion.compareTo(languageVersion) > 0) {
configuration.getNotNull(CLIConfigurationKeys.MESSAGE_COLLECTOR_KEY).report( configuration.getNotNull(CLIConfigurationKeys.MESSAGE_COLLECTOR_KEY).report(
CompilerMessageSeverity.ERROR, ERROR,
"-api-version (" + apiVersion.getVersionString() + ") cannot be greater than " + "-api-version (" + apiVersion.getVersionString() + ") cannot be greater than " +
"-language-version (" + languageVersion.getVersionString() + ")", "-language-version (" + languageVersion.getVersionString() + ")",
CompilerMessageLocation.NO_LOCATION null
); );
} }
if (!languageVersion.isStable()) { if (!languageVersion.isStable()) {
configuration.getNotNull(CLIConfigurationKeys.MESSAGE_COLLECTOR_KEY).report( configuration.getNotNull(CLIConfigurationKeys.MESSAGE_COLLECTOR_KEY).report(
CompilerMessageSeverity.STRONG_WARNING, STRONG_WARNING,
"Language version " + languageVersion.getVersionString() + " is experimental, there are " + "Language version " + languageVersion.getVersionString() + " is experimental, there are " +
"no backwards compatibility guarantees for new language and library features", "no backwards compatibility guarantees for new language and library features",
CompilerMessageLocation.NO_LOCATION null
); );
} }
@@ -292,10 +287,7 @@ public abstract class CLICompiler<A extends CommonCompilerArguments> {
} }
else { else {
String message = "The -Xcoroutines can only have one value"; String message = "The -Xcoroutines can only have one value";
configuration.getNotNull(CLIConfigurationKeys.MESSAGE_COLLECTOR_KEY).report( configuration.getNotNull(CLIConfigurationKeys.MESSAGE_COLLECTOR_KEY).report(ERROR, message, null);
CompilerMessageSeverity.ERROR, message, CompilerMessageLocation.NO_LOCATION
);
return null; return null;
} }
} }
@@ -314,10 +306,7 @@ public abstract class CLICompiler<A extends CommonCompilerArguments> {
List<String> versionStrings = ArraysKt.map(LanguageVersion.values(), LanguageVersion::getDescription); List<String> versionStrings = ArraysKt.map(LanguageVersion.values(), LanguageVersion::getDescription);
String message = "Unknown " + versionOf + " version: " + value + "\n" + String message = "Unknown " + versionOf + " version: " + value + "\n" +
"Supported " + versionOf + " versions: " + StringsKt.join(versionStrings, ", "); "Supported " + versionOf + " versions: " + StringsKt.join(versionStrings, ", ");
configuration.getNotNull(CLIConfigurationKeys.MESSAGE_COLLECTOR_KEY).report( configuration.getNotNull(CLIConfigurationKeys.MESSAGE_COLLECTOR_KEY).report(ERROR, message, null);
CompilerMessageSeverity.ERROR, message, CompilerMessageLocation.NO_LOCATION
);
return null; return null;
} }
@@ -327,11 +316,7 @@ public abstract class CLICompiler<A extends CommonCompilerArguments> {
private void reportUnknownExtraFlags(@NotNull MessageCollector collector, @NotNull A arguments) { private void reportUnknownExtraFlags(@NotNull MessageCollector collector, @NotNull A arguments) {
for (String flag : arguments.unknownExtraFlags) { for (String flag : arguments.unknownExtraFlags) {
collector.report( collector.report(STRONG_WARNING, "Flag is not supported by this version of the compiler: " + flag, null);
CompilerMessageSeverity.STRONG_WARNING,
"Flag is not supported by this version of the compiler: " + flag,
CompilerMessageLocation.NO_LOCATION
);
} }
} }
@@ -345,9 +330,7 @@ public abstract class CLICompiler<A extends CommonCompilerArguments> {
private void printVersionIfNeeded(@NotNull MessageCollector messageCollector, @NotNull A arguments) { private void printVersionIfNeeded(@NotNull MessageCollector messageCollector, @NotNull A arguments) {
if (!arguments.version) return; if (!arguments.version) return;
messageCollector.report(CompilerMessageSeverity.INFO, messageCollector.report(INFO, "Kotlin Compiler version " + KotlinCompilerVersion.VERSION, null);
"Kotlin Compiler version " + KotlinCompilerVersion.VERSION,
CompilerMessageLocation.NO_LOCATION);
} }
/** /**
@@ -23,6 +23,7 @@ import com.intellij.psi.PsiErrorElement
import com.intellij.psi.PsiModifierListOwner import com.intellij.psi.PsiModifierListOwner
import com.intellij.psi.util.PsiFormatUtil import com.intellij.psi.util.PsiFormatUtil
import org.jetbrains.kotlin.analyzer.AnalysisResult import org.jetbrains.kotlin.analyzer.AnalysisResult
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity.*
import org.jetbrains.kotlin.codegen.state.IncompatibleClassTrackerImpl import org.jetbrains.kotlin.codegen.state.IncompatibleClassTrackerImpl
import org.jetbrains.kotlin.diagnostics.* import org.jetbrains.kotlin.diagnostics.*
import org.jetbrains.kotlin.diagnostics.DiagnosticUtils.sortedDiagnostics import org.jetbrains.kotlin.diagnostics.DiagnosticUtils.sortedDiagnostics
@@ -54,7 +55,7 @@ class AnalyzerWithCompilerReport(private val messageCollector: MessageCollector)
assert(unresolved != null && !unresolved.isEmpty()) { "Incomplete hierarchy should be reported with names of unresolved superclasses: " + fqName } assert(unresolved != null && !unresolved.isEmpty()) { "Incomplete hierarchy should be reported with names of unresolved superclasses: " + fqName }
message.append(" class ").append(fqName).append(", unresolved supertypes: ").append(unresolved!!.joinToString()).append("\n") message.append(" class ").append(fqName).append(", unresolved supertypes: ").append(unresolved!!.joinToString()).append("\n")
} }
messageCollector.report(CompilerMessageSeverity.ERROR, message.toString(), CompilerMessageLocation.NO_LOCATION) messageCollector.report(ERROR, message.toString())
} }
} }
@@ -77,7 +78,7 @@ class AnalyzerWithCompilerReport(private val messageCollector: MessageCollector)
message.append(" ").append(error).append("\n") message.append(" ").append(error).append("\n")
} }
} }
messageCollector.report(CompilerMessageSeverity.ERROR, message.toString(), CompilerMessageLocation.NO_LOCATION) messageCollector.report(ERROR, message.toString())
} }
} }
@@ -120,9 +121,9 @@ class AnalyzerWithCompilerReport(private val messageCollector: MessageCollector)
companion object { companion object {
fun convertSeverity(severity: Severity): CompilerMessageSeverity = when (severity) { fun convertSeverity(severity: Severity): CompilerMessageSeverity = when (severity) {
Severity.INFO -> CompilerMessageSeverity.INFO Severity.INFO -> INFO
Severity.ERROR -> CompilerMessageSeverity.ERROR Severity.ERROR -> ERROR
Severity.WARNING -> CompilerMessageSeverity.WARNING Severity.WARNING -> WARNING
else -> throw IllegalStateException("Unknown severity: " + severity) else -> throw IllegalStateException("Unknown severity: " + severity)
} }
@@ -160,10 +161,9 @@ class AnalyzerWithCompilerReport(private val messageCollector: MessageCollector)
if (hasIncompatibleClassErrors) { if (hasIncompatibleClassErrors) {
messageCollector.report( messageCollector.report(
CompilerMessageSeverity.ERROR, ERROR,
"Incompatible classes were found in dependencies. " + "Incompatible classes were found in dependencies. " +
"Remove them from the classpath or use '-Xskip-metadata-version-check' to suppress errors", "Remove them from the classpath or use '-Xskip-metadata-version-check' to suppress errors"
CompilerMessageLocation.NO_LOCATION
) )
} }
@@ -205,10 +205,9 @@ class AnalyzerWithCompilerReport(private val messageCollector: MessageCollector)
} }
fun reportBytecodeVersionErrors(bindingContext: BindingContext, messageCollector: MessageCollector) { fun reportBytecodeVersionErrors(bindingContext: BindingContext, messageCollector: MessageCollector) {
val severity = if (System.getProperty("kotlin.jvm.disable.bytecode.version.error") == "true") val severity =
CompilerMessageSeverity.STRONG_WARNING if (System.getProperty("kotlin.jvm.disable.bytecode.version.error") == "true") STRONG_WARNING
else else ERROR
CompilerMessageSeverity.ERROR
val locations = bindingContext.getKeys(IncompatibleClassTrackerImpl.BYTECODE_VERSION_ERRORS) val locations = bindingContext.getKeys(IncompatibleClassTrackerImpl.BYTECODE_VERSION_ERRORS)
if (locations.isEmpty()) return if (locations.isEmpty()) return
@@ -30,9 +30,9 @@ import static com.intellij.openapi.util.io.FileUtil.toSystemDependentName;
public class MessageUtil { public class MessageUtil {
private MessageUtil() {} private MessageUtil() {}
@NotNull @Nullable
public static CompilerMessageLocation psiElementToMessageLocation(@Nullable PsiElement element) { public static CompilerMessageLocation psiElementToMessageLocation(@Nullable PsiElement element) {
if (element == null) return CompilerMessageLocation.NO_LOCATION; if (element == null) return null;
PsiFile file = element.getContainingFile(); PsiFile file = element.getContainingFile();
return psiFileToMessageLocation(file, "<no path>", DiagnosticUtils.getLineAndColumnInPsiFile(file, element.getTextRange())); return psiFileToMessageLocation(file, "<no path>", DiagnosticUtils.getLineAndColumnInPsiFile(file, element.getTextRange()));
} }
@@ -17,6 +17,7 @@
package org.jetbrains.kotlin.cli.common.messages; package org.jetbrains.kotlin.cli.common.messages;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.PrintStream; import java.io.PrintStream;
@@ -41,13 +42,13 @@ public class PrintingMessageCollector implements MessageCollector {
public void report( public void report(
@NotNull CompilerMessageSeverity severity, @NotNull CompilerMessageSeverity severity,
@NotNull String message, @NotNull String message,
@NotNull CompilerMessageLocation location @Nullable CompilerMessageLocation location
) { ) {
if (!verbose && CompilerMessageSeverity.VERBOSE.contains(severity)) return; if (!verbose && CompilerMessageSeverity.VERBOSE.contains(severity)) return;
hasErrors |= severity.isError(); hasErrors |= severity.isError();
errStream.println(messageRenderer.render(severity, message, location)); errStream.println(messageRenderer.render(severity, message, location != null ? location : CompilerMessageLocation.NO_LOCATION));
} }
@Override @Override
@@ -16,14 +16,13 @@
package org.jetbrains.kotlin.cli.common.output.outputUtils package org.jetbrains.kotlin.cli.common.output.outputUtils
import org.jetbrains.kotlin.backend.common.output.OutputFileCollection
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageLocation
import org.jetbrains.kotlin.cli.common.messages.OutputMessageUtil
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity
import org.jetbrains.kotlin.cli.common.messages.MessageCollector
import java.io.File
import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.io.FileUtil
import org.jetbrains.kotlin.backend.common.output.OutputFile import org.jetbrains.kotlin.backend.common.output.OutputFile
import org.jetbrains.kotlin.backend.common.output.OutputFileCollection
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity
import org.jetbrains.kotlin.cli.common.messages.MessageCollector
import org.jetbrains.kotlin.cli.common.messages.OutputMessageUtil
import java.io.File
fun OutputFileCollection.writeAll(outputDir: File, report: (file: OutputFile, sources: List<File>, output: File) -> Unit) { fun OutputFileCollection.writeAll(outputDir: File, report: (file: OutputFile, sources: List<File>, output: File) -> Unit) {
for (file in asList()) { for (file in asList()) {
@@ -42,6 +41,6 @@ fun OutputFileCollection.writeAllTo(outputDir: File) {
fun OutputFileCollection.writeAll(outputDir: File, messageCollector: MessageCollector) { fun OutputFileCollection.writeAll(outputDir: File, messageCollector: MessageCollector) {
writeAll(outputDir) { _, sources, output -> writeAll(outputDir) { _, sources, output ->
messageCollector.report(CompilerMessageSeverity.OUTPUT, OutputMessageUtil.formatOutputMessage(sources, output), CompilerMessageLocation.NO_LOCATION) messageCollector.report(CompilerMessageSeverity.OUTPUT, OutputMessageUtil.formatOutputMessage(sources, output))
} }
} }
@@ -16,7 +16,6 @@
package org.jetbrains.kotlin.cli.js; package org.jetbrains.kotlin.cli.js;
import com.google.common.base.Joiner;
import com.intellij.openapi.Disposable; import com.intellij.openapi.Disposable;
import com.intellij.openapi.project.Project; import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.io.FileUtil;
@@ -35,8 +34,6 @@ import org.jetbrains.kotlin.cli.common.ExitCode;
import org.jetbrains.kotlin.cli.common.arguments.K2JSCompilerArguments; import org.jetbrains.kotlin.cli.common.arguments.K2JSCompilerArguments;
import org.jetbrains.kotlin.cli.common.arguments.K2JsArgumentConstants; import org.jetbrains.kotlin.cli.common.arguments.K2JsArgumentConstants;
import org.jetbrains.kotlin.cli.common.messages.AnalyzerWithCompilerReport; import org.jetbrains.kotlin.cli.common.messages.AnalyzerWithCompilerReport;
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageLocation;
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity;
import org.jetbrains.kotlin.cli.common.messages.MessageCollector; import org.jetbrains.kotlin.cli.common.messages.MessageCollector;
import org.jetbrains.kotlin.cli.common.output.outputUtils.OutputUtilsKt; import org.jetbrains.kotlin.cli.common.output.outputUtils.OutputUtilsKt;
import org.jetbrains.kotlin.cli.jvm.compiler.EnvironmentConfigFiles; import org.jetbrains.kotlin.cli.jvm.compiler.EnvironmentConfigFiles;
@@ -58,6 +55,7 @@ import org.jetbrains.kotlin.psi.KtFile;
import org.jetbrains.kotlin.serialization.js.ModuleKind; import org.jetbrains.kotlin.serialization.js.ModuleKind;
import org.jetbrains.kotlin.utils.ExceptionUtilsKt; import org.jetbrains.kotlin.utils.ExceptionUtilsKt;
import org.jetbrains.kotlin.utils.PathUtil; import org.jetbrains.kotlin.utils.PathUtil;
import org.jetbrains.kotlin.utils.StringsKt;
import java.io.File; import java.io.File;
import java.util.List; import java.util.List;
@@ -66,7 +64,7 @@ import java.util.Map;
import static org.jetbrains.kotlin.cli.common.ExitCode.COMPILATION_ERROR; import static org.jetbrains.kotlin.cli.common.ExitCode.COMPILATION_ERROR;
import static org.jetbrains.kotlin.cli.common.ExitCode.OK; import static org.jetbrains.kotlin.cli.common.ExitCode.OK;
import static org.jetbrains.kotlin.cli.common.UtilsKt.checkKotlinPackageUsage; import static org.jetbrains.kotlin.cli.common.UtilsKt.checkKotlinPackageUsage;
import static org.jetbrains.kotlin.cli.common.messages.CompilerMessageLocation.NO_LOCATION; import static org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity.*;
public class K2JSCompiler extends CLICompiler<K2JSCompilerArguments> { public class K2JSCompiler extends CLICompiler<K2JSCompilerArguments> {
private static final Map<String, ModuleKind> moduleKindMap = new HashMap<>(); private static final Map<String, ModuleKind> moduleKindMap = new HashMap<>();
@@ -99,7 +97,7 @@ public class K2JSCompiler extends CLICompiler<K2JSCompilerArguments> {
if (arguments.version) { if (arguments.version) {
return OK; return OK;
} }
messageCollector.report(CompilerMessageSeverity.ERROR, "Specify at least one source file or directory", NO_LOCATION); messageCollector.report(ERROR, "Specify at least one source file or directory", null);
return COMPILATION_ERROR; return COMPILATION_ERROR;
} }
@@ -115,7 +113,7 @@ public class K2JSCompiler extends CLICompiler<K2JSCompilerArguments> {
if (!checkKotlinPackageUsage(environmentForJS, sourcesFiles)) return ExitCode.COMPILATION_ERROR; if (!checkKotlinPackageUsage(environmentForJS, sourcesFiles)) return ExitCode.COMPILATION_ERROR;
if (arguments.outputFile == null) { if (arguments.outputFile == null) {
messageCollector.report(CompilerMessageSeverity.ERROR, "Specify output file via -output", CompilerMessageLocation.NO_LOCATION); messageCollector.report(ERROR, "Specify output file via -output", null);
return ExitCode.COMPILATION_ERROR; return ExitCode.COMPILATION_ERROR;
} }
@@ -124,7 +122,7 @@ public class K2JSCompiler extends CLICompiler<K2JSCompilerArguments> {
} }
if (sourcesFiles.isEmpty()) { if (sourcesFiles.isEmpty()) {
messageCollector.report(CompilerMessageSeverity.ERROR, "No source files", CompilerMessageLocation.NO_LOCATION); messageCollector.report(ERROR, "No source files", null);
return COMPILATION_ERROR; return COMPILATION_ERROR;
} }
@@ -140,12 +138,12 @@ public class K2JSCompiler extends CLICompiler<K2JSCompilerArguments> {
if (config.checkLibFilesAndReportErrors(new JsConfig.Reporter() { if (config.checkLibFilesAndReportErrors(new JsConfig.Reporter() {
@Override @Override
public void error(@NotNull String message) { public void error(@NotNull String message) {
messageCollector.report(CompilerMessageSeverity.ERROR, message, CompilerMessageLocation.NO_LOCATION); messageCollector.report(ERROR, message, null);
} }
@Override @Override
public void warning(@NotNull String message) { public void warning(@NotNull String message) {
messageCollector.report(CompilerMessageSeverity.STRONG_WARNING, message, CompilerMessageLocation.NO_LOCATION); messageCollector.report(STRONG_WARNING, message, null);
} }
})) { })) {
return COMPILATION_ERROR; return COMPILATION_ERROR;
@@ -166,9 +164,7 @@ public class K2JSCompiler extends CLICompiler<K2JSCompilerArguments> {
if (arguments.outputPrefix != null) { if (arguments.outputPrefix != null) {
outputPrefixFile = new File(arguments.outputPrefix); outputPrefixFile = new File(arguments.outputPrefix);
if (!outputPrefixFile.exists()) { if (!outputPrefixFile.exists()) {
messageCollector.report(CompilerMessageSeverity.ERROR, messageCollector.report(ERROR, "Output prefix file '" + arguments.outputPrefix + "' not found", null);
"Output prefix file '" + arguments.outputPrefix + "' not found",
CompilerMessageLocation.NO_LOCATION);
return ExitCode.COMPILATION_ERROR; return ExitCode.COMPILATION_ERROR;
} }
} }
@@ -177,9 +173,7 @@ public class K2JSCompiler extends CLICompiler<K2JSCompilerArguments> {
if (arguments.outputPostfix != null) { if (arguments.outputPostfix != null) {
outputPostfixFile = new File(arguments.outputPostfix); outputPostfixFile = new File(arguments.outputPostfix);
if (!outputPostfixFile.exists()) { if (!outputPostfixFile.exists()) {
messageCollector.report(CompilerMessageSeverity.ERROR, messageCollector.report(ERROR, "Output postfix file '" + arguments.outputPostfix + "' not found", null);
"Output postfix file '" + arguments.outputPostfix + "' not found",
CompilerMessageLocation.NO_LOCATION);
return ExitCode.COMPILATION_ERROR; return ExitCode.COMPILATION_ERROR;
} }
} }
@@ -206,9 +200,7 @@ public class K2JSCompiler extends CLICompiler<K2JSCompilerArguments> {
OutputFileCollection outputFiles = successResult.getOutputFiles(outputFile, outputPrefixFile, outputPostfixFile); OutputFileCollection outputFiles = successResult.getOutputFiles(outputFile, outputPrefixFile, outputPostfixFile);
if (outputFile.isDirectory()) { if (outputFile.isDirectory()) {
messageCollector.report(CompilerMessageSeverity.ERROR, messageCollector.report(ERROR, "Cannot open output file '" + outputFile.getPath() + "': is a directory", null);
"Cannot open output file '" + outputFile.getPath() + "': is a directory",
CompilerMessageLocation.NO_LOCATION);
return ExitCode.COMPILATION_ERROR; return ExitCode.COMPILATION_ERROR;
} }
@@ -232,8 +224,7 @@ public class K2JSCompiler extends CLICompiler<K2JSCompilerArguments> {
} }
return file.getName() + "(no virtual file)"; return file.getName() + "(no virtual file)";
}); });
messageCollector.report(CompilerMessageSeverity.LOGGING, "Compiling source files: " + Joiner.on(", ").join(fileNames), messageCollector.report(LOGGING, "Compiling source files: " + StringsKt.join(fileNames, ", "), null);
CompilerMessageLocation.NO_LOCATION);
} }
private static AnalyzerWithCompilerReport analyzeAndReportErrors( private static AnalyzerWithCompilerReport analyzeAndReportErrors(
@@ -291,9 +282,9 @@ public class K2JSCompiler extends CLICompiler<K2JSCompilerArguments> {
String moduleKindName = arguments.moduleKind; String moduleKindName = arguments.moduleKind;
ModuleKind moduleKind = moduleKindName != null ? moduleKindMap.get(moduleKindName) : ModuleKind.PLAIN; ModuleKind moduleKind = moduleKindName != null ? moduleKindMap.get(moduleKindName) : ModuleKind.PLAIN;
if (moduleKind == null) { if (moduleKind == null) {
messageCollector.report(CompilerMessageSeverity.ERROR, "Unknown module kind: " + moduleKindName + ". " + messageCollector.report(
"Valid values are: plain, amd, commonjs, umd", ERROR, "Unknown module kind: " + moduleKindName + ". Valid values are: plain, amd, commonjs, umd", null
CompilerMessageLocation.NO_LOCATION); );
} }
configuration.put(JSConfigurationKeys.MODULE_KIND, moduleKind); configuration.put(JSConfigurationKeys.MODULE_KIND, moduleKind);
} }
@@ -23,6 +23,7 @@ import org.jetbrains.kotlin.cli.common.ExitCode
import org.jetbrains.kotlin.cli.common.ExitCode.* import org.jetbrains.kotlin.cli.common.ExitCode.*
import org.jetbrains.kotlin.cli.common.arguments.K2JVMCompilerArguments import org.jetbrains.kotlin.cli.common.arguments.K2JVMCompilerArguments
import org.jetbrains.kotlin.cli.common.messages.* import org.jetbrains.kotlin.cli.common.messages.*
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity.*
import org.jetbrains.kotlin.cli.jvm.compiler.CompileEnvironmentUtil import org.jetbrains.kotlin.cli.jvm.compiler.CompileEnvironmentUtil
import org.jetbrains.kotlin.cli.jvm.compiler.EnvironmentConfigFiles import org.jetbrains.kotlin.cli.jvm.compiler.EnvironmentConfigFiles
import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment
@@ -59,7 +60,7 @@ class K2JVMCompiler : CLICompiler<K2JVMCompilerArguments>() {
else else
PathUtil.getKotlinPathsForCompiler() PathUtil.getKotlinPathsForCompiler()
messageCollector.report(CompilerMessageSeverity.LOGGING, "Using Kotlin home directory " + paths.homePath, CompilerMessageLocation.NO_LOCATION) messageCollector.report(LOGGING, "Using Kotlin home directory ${paths.homePath}")
PerformanceCounter.setTimeCounterEnabled(arguments.reportPerf) PerformanceCounter.setTimeCounterEnabled(arguments.reportPerf)
setupJdkClasspathRoots(arguments, configuration, messageCollector).let { setupJdkClasspathRoots(arguments, configuration, messageCollector).let {
@@ -71,11 +72,11 @@ class K2JVMCompiler : CLICompiler<K2JVMCompilerArguments>() {
} }
catch (e: PluginCliOptionProcessingException) { catch (e: PluginCliOptionProcessingException) {
val message = e.message + "\n\n" + cliPluginUsageString(e.pluginId, e.options) val message = e.message + "\n\n" + cliPluginUsageString(e.pluginId, e.options)
messageCollector.report(CompilerMessageSeverity.ERROR, message, CompilerMessageLocation.NO_LOCATION) messageCollector.report(ERROR, message)
return INTERNAL_ERROR return INTERNAL_ERROR
} }
catch (e: CliOptionProcessingException) { catch (e: CliOptionProcessingException) {
messageCollector.report(CompilerMessageSeverity.ERROR, e.message!!, CompilerMessageLocation.NO_LOCATION) messageCollector.report(ERROR, e.message!!)
return INTERNAL_ERROR return INTERNAL_ERROR
} }
catch (t: Throwable) { catch (t: Throwable) {
@@ -85,9 +86,7 @@ class K2JVMCompiler : CLICompiler<K2JVMCompilerArguments>() {
if (arguments.script) { if (arguments.script) {
if (arguments.freeArgs.isEmpty()) { if (arguments.freeArgs.isEmpty()) {
messageCollector.report( messageCollector.report(ERROR, "Specify script source path to evaluate")
CompilerMessageSeverity.ERROR, "Specify script source path to evaluate", CompilerMessageLocation.NO_LOCATION
)
return COMPILATION_ERROR return COMPILATION_ERROR
} }
configuration.addKotlinSourceRoot(arguments.freeArgs[0]) configuration.addKotlinSourceRoot(arguments.freeArgs[0])
@@ -126,9 +125,8 @@ class K2JVMCompiler : CLICompiler<K2JVMCompilerArguments>() {
configuration.put(JVMConfigurationKeys.JVM_TARGET, jvmTarget) configuration.put(JVMConfigurationKeys.JVM_TARGET, jvmTarget)
} }
else { else {
val errorMessage = "Unknown JVM target version: ${arguments.jvmTarget}\n" + messageCollector.report(ERROR, "Unknown JVM target version: ${arguments.jvmTarget}\n" +
"Supported versions: ${JvmTarget.values().joinToString { it.description }}" "Supported versions: ${JvmTarget.values().joinToString { it.description }}")
messageCollector.report(CompilerMessageSeverity.ERROR, errorMessage, CompilerMessageLocation.NO_LOCATION)
} }
} }
@@ -136,19 +134,18 @@ class K2JVMCompiler : CLICompiler<K2JVMCompilerArguments>() {
putAdvancedOptions(configuration, arguments) putAdvancedOptions(configuration, arguments)
messageCollector.report(CompilerMessageSeverity.LOGGING, "Configuring the compilation environment", CompilerMessageLocation.NO_LOCATION) messageCollector.report(LOGGING, "Configuring the compilation environment")
try { try {
val destination = arguments.destination val destination = arguments.destination
if (arguments.module != null) { if (arguments.module != null) {
val sanitizedCollector = FilteringMessageCollector(messageCollector, CompilerMessageSeverity.VERBOSE::contains) val sanitizedCollector = FilteringMessageCollector(messageCollector, VERBOSE::contains)
val moduleScript = CompileEnvironmentUtil.loadModuleDescriptions(arguments.module, sanitizedCollector) val moduleScript = CompileEnvironmentUtil.loadModuleDescriptions(arguments.module, sanitizedCollector)
if (destination != null) { if (destination != null) {
messageCollector.report( messageCollector.report(
CompilerMessageSeverity.STRONG_WARNING, STRONG_WARNING,
"The '-d' option with a directory destination is ignored because '-module' is specified", "The '-d' option with a directory destination is ignored because '-module' is specified"
CompilerMessageLocation.NO_LOCATION
) )
} }
@@ -190,7 +187,7 @@ class K2JVMCompiler : CLICompiler<K2JVMCompilerArguments>() {
if (arguments.version) { if (arguments.version) {
return OK return OK
} }
messageCollector.report(CompilerMessageSeverity.ERROR, "No source files", CompilerMessageLocation.NO_LOCATION) messageCollector.report(ERROR, "No source files")
return COMPILATION_ERROR return COMPILATION_ERROR
} }
@@ -206,7 +203,7 @@ class K2JVMCompiler : CLICompiler<K2JVMCompilerArguments>() {
} }
catch (e: CompilationException) { catch (e: CompilationException) {
messageCollector.report( messageCollector.report(
CompilerMessageSeverity.EXCEPTION, EXCEPTION,
OutputMessageUtil.renderException(e), OutputMessageUtil.renderException(e),
MessageUtil.psiElementToMessageLocation(e.element) MessageUtil.psiElementToMessageLocation(e.element)
) )
@@ -285,8 +282,7 @@ class K2JVMCompiler : CLICompiler<K2JVMCompilerArguments>() {
fun reportPerf(configuration: CompilerConfiguration, message: String) { fun reportPerf(configuration: CompilerConfiguration, message: String) {
if (!configuration.getBoolean(CLIConfigurationKeys.REPORT_PERF)) return if (!configuration.getBoolean(CLIConfigurationKeys.REPORT_PERF)) return
val collector = configuration.getNotNull(CLIConfigurationKeys.MESSAGE_COLLECTOR_KEY) configuration.getNotNull(CLIConfigurationKeys.MESSAGE_COLLECTOR_KEY).report(INFO, "PERF: $message")
collector.report(CompilerMessageSeverity.INFO, "PERF: " + message, CompilerMessageLocation.NO_LOCATION)
} }
fun reportGCTime(configuration: CompilerConfiguration) { fun reportGCTime(configuration: CompilerConfiguration) {
@@ -342,14 +338,10 @@ class K2JVMCompiler : CLICompiler<K2JVMCompilerArguments>() {
try { try {
if (!arguments.noJdk) { if (!arguments.noJdk) {
if (arguments.jdkHome != null) { if (arguments.jdkHome != null) {
messageCollector.report(CompilerMessageSeverity.LOGGING, messageCollector.report(LOGGING, "Using JDK home directory ${arguments.jdkHome}")
"Using JDK home directory ${arguments.jdkHome}",
CompilerMessageLocation.NO_LOCATION)
val classesRoots = PathUtil.getJdkClassesRoots(File(arguments.jdkHome)) val classesRoots = PathUtil.getJdkClassesRoots(File(arguments.jdkHome))
if (classesRoots.isEmpty()) { if (classesRoots.isEmpty()) {
messageCollector.report(CompilerMessageSeverity.ERROR, messageCollector.report(ERROR, "No class roots are found in the JDK path: ${arguments.jdkHome}")
"No class roots are found in the JDK path: ${arguments.jdkHome}",
CompilerMessageLocation.NO_LOCATION)
return COMPILATION_ERROR return COMPILATION_ERROR
} }
configuration.addJvmClasspathRoots(classesRoots) configuration.addJvmClasspathRoots(classesRoots)
@@ -360,9 +352,7 @@ class K2JVMCompiler : CLICompiler<K2JVMCompilerArguments>() {
} }
else { else {
if (arguments.jdkHome != null) { if (arguments.jdkHome != null) {
messageCollector.report(CompilerMessageSeverity.STRONG_WARNING, messageCollector.report(STRONG_WARNING, "The '-jdk-home' option is ignored because '-no-jdk' is specified")
"The '-jdk-home' option is ignored because '-no-jdk' is specified",
CompilerMessageLocation.NO_LOCATION)
} }
} }
} }
@@ -388,29 +378,23 @@ class K2JVMCompiler : CLICompiler<K2JVMCompilerArguments>() {
val def = KotlinScriptDefinitionFromAnnotatedTemplate(cls.kotlin, null, null, scriptResolverEnv) val def = KotlinScriptDefinitionFromAnnotatedTemplate(cls.kotlin, null, null, scriptResolverEnv)
configuration.add(JVMConfigurationKeys.SCRIPT_DEFINITIONS, def) configuration.add(JVMConfigurationKeys.SCRIPT_DEFINITIONS, def)
messageCollector.report( messageCollector.report(
CompilerMessageSeverity.INFO, INFO,
"Added script definition $template to configuration: files pattern = \"${def.scriptFilePattern}\", resolver = ${def.resolver?.javaClass?.name}", "Added script definition $template to configuration: files pattern = \"${def.scriptFilePattern}\", " +
CompilerMessageLocation.NO_LOCATION "resolver = ${def.resolver?.javaClass?.name}"
) )
} }
catch (ex: ClassNotFoundException) { catch (ex: ClassNotFoundException) {
messageCollector.report( messageCollector.report(ERROR, "Cannot find script definition template class $template")
CompilerMessageSeverity.ERROR, "Cannot find script definition template class $template", CompilerMessageLocation.NO_LOCATION
)
hasErrors = true hasErrors = true
} }
catch (ex: Exception) { catch (ex: Exception) {
messageCollector.report( messageCollector.report(ERROR, "Error processing script definition template $template: ${ex.message}")
CompilerMessageSeverity.ERROR, "Error processing script definition template $template: ${ex.message}", CompilerMessageLocation.NO_LOCATION
)
hasErrors = true hasErrors = true
break break
} }
} }
if (hasErrors) { if (hasErrors) {
messageCollector.report( messageCollector.report(LOGGING, "(Classpath used for templates loading: $classpath)")
CompilerMessageSeverity.LOGGING, "(Classpath used for templates loading: $classpath)", CompilerMessageLocation.NO_LOCATION
)
return return
} }
} }
@@ -429,7 +413,7 @@ class K2JVMCompiler : CLICompiler<K2JVMCompilerArguments>() {
for (envParam in arguments.scriptResolverEnvironment) { for (envParam in arguments.scriptResolverEnvironment) {
val match = envParseRe.matchEntire(envParam) val match = envParseRe.matchEntire(envParam)
if (match == null || match.groupValues.size < 4 || match.groupValues[1].isBlank()) { if (match == null || match.groupValues.size < 4 || match.groupValues[1].isBlank()) {
messageCollector.report(CompilerMessageSeverity.ERROR, "Unable to parse script-resolver-environment argument $envParam", CompilerMessageLocation.NO_LOCATION) 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") })
@@ -54,7 +54,6 @@ import java.util.List;
import java.util.Set; import java.util.Set;
import java.util.jar.*; import java.util.jar.*;
import static org.jetbrains.kotlin.cli.common.messages.CompilerMessageLocation.NO_LOCATION;
import static org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity.ERROR; import static org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity.ERROR;
public class CompileEnvironmentUtil { public class CompileEnvironmentUtil {
@@ -64,14 +63,14 @@ public class CompileEnvironmentUtil {
public static ModuleScriptData loadModuleDescriptions(String moduleDefinitionFile, MessageCollector messageCollector) { public static ModuleScriptData loadModuleDescriptions(String moduleDefinitionFile, MessageCollector messageCollector) {
File file = new File(moduleDefinitionFile); File file = new File(moduleDefinitionFile);
if (!file.exists()) { if (!file.exists()) {
messageCollector.report(ERROR, "Module definition file does not exist: " + moduleDefinitionFile, NO_LOCATION); messageCollector.report(ERROR, "Module definition file does not exist: " + moduleDefinitionFile, null);
return ModuleScriptData.EMPTY; return ModuleScriptData.EMPTY;
} }
String extension = FileUtilRt.getExtension(moduleDefinitionFile); String extension = FileUtilRt.getExtension(moduleDefinitionFile);
if ("xml".equalsIgnoreCase(extension)) { if ("xml".equalsIgnoreCase(extension)) {
return ModuleXmlParser.parseModuleScript(moduleDefinitionFile, messageCollector); return ModuleXmlParser.parseModuleScript(moduleDefinitionFile, messageCollector);
} }
messageCollector.report(ERROR, "Unknown module definition type: " + moduleDefinitionFile, NO_LOCATION); messageCollector.report(ERROR, "Unknown module definition type: " + moduleDefinitionFile, null);
return ModuleScriptData.EMPTY; return ModuleScriptData.EMPTY;
} }
@@ -66,7 +66,6 @@ import org.jetbrains.kotlin.asJava.finder.JavaElementFinder
import org.jetbrains.kotlin.cli.common.CLIConfigurationKeys import org.jetbrains.kotlin.cli.common.CLIConfigurationKeys
import org.jetbrains.kotlin.cli.common.CliModuleVisibilityManagerImpl import org.jetbrains.kotlin.cli.common.CliModuleVisibilityManagerImpl
import org.jetbrains.kotlin.cli.common.KOTLIN_COMPILER_ENVIRONMENT_KEEPALIVE_PROPERTY import org.jetbrains.kotlin.cli.common.KOTLIN_COMPILER_ENVIRONMENT_KEEPALIVE_PROPERTY
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageLocation
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity.ERROR import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity.ERROR
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity.STRONG_WARNING import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity.STRONG_WARNING
@@ -325,8 +324,7 @@ class KotlinCoreEnvironment private constructor(
fun getSourceFiles(): List<KtFile> = sourceFiles fun getSourceFiles(): List<KtFile> = sourceFiles
private fun report(severity: CompilerMessageSeverity, message: String) { private fun report(severity: CompilerMessageSeverity, message: String) {
val messageCollector = configuration.getNotNull(CLIConfigurationKeys.MESSAGE_COLLECTOR_KEY) configuration.getNotNull(CLIConfigurationKeys.MESSAGE_COLLECTOR_KEY).report(severity, message)
messageCollector.report(severity, message, CompilerMessageLocation.NO_LOCATION)
} }
companion object { companion object {
@@ -32,7 +32,11 @@ import org.jetbrains.kotlin.backend.common.output.SimpleOutputFileCollection
import org.jetbrains.kotlin.cli.common.CLIConfigurationKeys import org.jetbrains.kotlin.cli.common.CLIConfigurationKeys
import org.jetbrains.kotlin.cli.common.ExitCode import org.jetbrains.kotlin.cli.common.ExitCode
import org.jetbrains.kotlin.cli.common.checkKotlinPackageUsage import org.jetbrains.kotlin.cli.common.checkKotlinPackageUsage
import org.jetbrains.kotlin.cli.common.messages.* import org.jetbrains.kotlin.cli.common.messages.AnalyzerWithCompilerReport
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity.ERROR
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity.OUTPUT
import org.jetbrains.kotlin.cli.common.messages.MessageCollector
import org.jetbrains.kotlin.cli.common.messages.OutputMessageUtil
import org.jetbrains.kotlin.cli.common.output.outputUtils.writeAll import org.jetbrains.kotlin.cli.common.output.outputUtils.writeAll
import org.jetbrains.kotlin.cli.jvm.K2JVMCompiler import org.jetbrains.kotlin.cli.jvm.K2JVMCompiler
import org.jetbrains.kotlin.cli.jvm.config.* import org.jetbrains.kotlin.cli.jvm.config.*
@@ -88,8 +92,9 @@ object KotlinToJVMBytecodeCompiler {
if (jarPath != null) { if (jarPath != null) {
val includeRuntime = configuration.get(JVMConfigurationKeys.INCLUDE_RUNTIME, false) val includeRuntime = configuration.get(JVMConfigurationKeys.INCLUDE_RUNTIME, false)
CompileEnvironmentUtil.writeToJar(jarPath, includeRuntime, mainClass, outputFiles) CompileEnvironmentUtil.writeToJar(jarPath, includeRuntime, mainClass, outputFiles)
messageCollector.report(CompilerMessageSeverity.OUTPUT, messageCollector.report(
OutputMessageUtil.formatOutputMessage(outputFiles.asList().flatMap { it.sourceFiles }.distinct(), jarPath), CompilerMessageLocation.NO_LOCATION) OUTPUT, OutputMessageUtil.formatOutputMessage(outputFiles.asList().flatMap { it.sourceFiles }.distinct(), jarPath)
)
return return
} }
@@ -466,9 +471,7 @@ object KotlinToJVMBytecodeCompiler {
} }
if (runtimeVersions.toSet().size > 1) { if (runtimeVersions.toSet().size > 1) {
messageCollector.report(CompilerMessageSeverity.ERROR, messageCollector.report(ERROR, "Conflicting versions of Kotlin runtime on classpath: " + runtimes.joinToString { it.path })
"Conflicting versions of Kotlin runtime on classpath: " + runtimes.joinToString { it.path },
CompilerMessageLocation.NO_LOCATION)
} }
} }
} }
@@ -21,8 +21,7 @@ import org.jetbrains.kotlin.cli.common.CLICompiler
import org.jetbrains.kotlin.cli.common.CLIConfigurationKeys import org.jetbrains.kotlin.cli.common.CLIConfigurationKeys
import org.jetbrains.kotlin.cli.common.ExitCode import org.jetbrains.kotlin.cli.common.ExitCode
import org.jetbrains.kotlin.cli.common.arguments.K2MetadataCompilerArguments import org.jetbrains.kotlin.cli.common.arguments.K2MetadataCompilerArguments
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageLocation import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity.*
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity
import org.jetbrains.kotlin.cli.common.messages.MessageUtil import org.jetbrains.kotlin.cli.common.messages.MessageUtil
import org.jetbrains.kotlin.cli.common.messages.OutputMessageUtil import org.jetbrains.kotlin.cli.common.messages.OutputMessageUtil
import org.jetbrains.kotlin.cli.jvm.compiler.EnvironmentConfigFiles import org.jetbrains.kotlin.cli.jvm.compiler.EnvironmentConfigFiles
@@ -64,11 +63,7 @@ class K2MetadataCompiler : CLICompiler<K2MetadataCompilerArguments>() {
if (destination != null) { if (destination != null) {
if (destination.endsWith(".jar")) { if (destination.endsWith(".jar")) {
// TODO: support .jar destination // TODO: support .jar destination
collector.report( collector.report(STRONG_WARNING, ".jar destination is not yet supported, results will be written to the directory with the given name")
CompilerMessageSeverity.STRONG_WARNING,
".jar destination is not yet supported, results will be written to the directory with the given name",
CompilerMessageLocation.NO_LOCATION
)
} }
configuration.put(CLIConfigurationKeys.METADATA_DESTINATION_DIRECTORY, File(destination)) configuration.put(CLIConfigurationKeys.METADATA_DESTINATION_DIRECTORY, File(destination))
} }
@@ -79,7 +74,7 @@ class K2MetadataCompiler : CLICompiler<K2MetadataCompilerArguments>() {
if (arguments.version) { if (arguments.version) {
return ExitCode.OK return ExitCode.OK
} }
collector.report(CompilerMessageSeverity.ERROR, "No source files", CompilerMessageLocation.NO_LOCATION) collector.report(ERROR, "No source files")
return ExitCode.COMPILATION_ERROR return ExitCode.COMPILATION_ERROR
} }
@@ -87,11 +82,7 @@ class K2MetadataCompiler : CLICompiler<K2MetadataCompilerArguments>() {
MetadataSerializer(true).serialize(environment) MetadataSerializer(true).serialize(environment)
} }
catch (e: CompilationException) { catch (e: CompilationException) {
collector.report( collector.report(EXCEPTION, OutputMessageUtil.renderException(e), MessageUtil.psiElementToMessageLocation(e.element))
CompilerMessageSeverity.EXCEPTION,
OutputMessageUtil.renderException(e),
MessageUtil.psiElementToMessageLocation(e.element)
)
return ExitCode.INTERNAL_ERROR return ExitCode.INTERNAL_ERROR
} }
@@ -20,21 +20,17 @@ import com.intellij.openapi.util.io.FileUtil
import com.intellij.util.containers.Stack import com.intellij.util.containers.Stack
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageLocation import org.jetbrains.kotlin.cli.common.messages.CompilerMessageLocation
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity.*
import org.jetbrains.kotlin.cli.common.messages.MessageCollector import org.jetbrains.kotlin.cli.common.messages.MessageCollector
import org.jetbrains.kotlin.cli.common.messages.MessageCollectorUtil.reportException
import org.jetbrains.kotlin.cli.common.messages.OutputMessageUtil import org.jetbrains.kotlin.cli.common.messages.OutputMessageUtil
import org.xml.sax.Attributes import org.xml.sax.Attributes
import org.xml.sax.InputSource import org.xml.sax.InputSource
import org.xml.sax.SAXException import org.xml.sax.SAXException
import org.xml.sax.helpers.DefaultHandler import org.xml.sax.helpers.DefaultHandler
import javax.xml.parsers.SAXParser
import javax.xml.parsers.SAXParserFactory
import java.io.IOException import java.io.IOException
import java.io.Reader import java.io.Reader
import javax.xml.parsers.SAXParserFactory
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageLocation.Companion.NO_LOCATION
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity.*
import org.jetbrains.kotlin.cli.common.messages.MessageCollectorUtil.reportException
object CompilerOutputParser { object CompilerOutputParser {
fun parseCompilerMessagesFromReader(messageCollector: MessageCollector, reader: Reader, collector: OutputItemsCollector) { fun parseCompilerMessagesFromReader(messageCollector: MessageCollector, reader: Reader, collector: OutputItemsCollector) {
@@ -77,7 +73,7 @@ object CompilerOutputParser {
val message = stringBuilder.toString() val message = stringBuilder.toString()
reportException(messageCollector, IllegalStateException(message, e)) reportException(messageCollector, IllegalStateException(message, e))
messageCollector.report(ERROR, message, NO_LOCATION) messageCollector.report(ERROR, message)
} }
finally { finally {
try { try {
@@ -86,7 +82,6 @@ object CompilerOutputParser {
catch (e: IOException) { catch (e: IOException) {
reportException(messageCollector, e) reportException(messageCollector, e)
} }
} }
} }
@@ -115,7 +110,7 @@ object CompilerOutputParser {
// We're directly inside the root tag: <MESSAGES> // We're directly inside the root tag: <MESSAGES>
val message = String(ch!!, start, length) val message = String(ch!!, start, length)
if (!message.trim { it <= ' ' }.isEmpty()) { if (!message.trim { it <= ' ' }.isEmpty()) {
messageCollector.report(ERROR, "Unhandled compiler output: " + message, NO_LOCATION) messageCollector.report(ERROR, "Unhandled compiler output: $message")
} }
} }
else { else {
@@ -132,7 +127,7 @@ object CompilerOutputParser {
val qNameLowerCase = qName.toLowerCase() val qNameLowerCase = qName.toLowerCase()
var category: CompilerMessageSeverity? = CATEGORIES[qNameLowerCase] var category: CompilerMessageSeverity? = CATEGORIES[qNameLowerCase]
if (category == null) { if (category == null) {
messageCollector.report(ERROR, "Unknown compiler message tag: " + qName, NO_LOCATION) messageCollector.report(ERROR, "Unknown compiler message tag: $qName")
category = INFO category = INFO
} }
val text = message.toString() val text = message.toString()
@@ -18,19 +18,14 @@ package org.jetbrains.kotlin.compilerRunner
import org.jetbrains.kotlin.cli.common.ExitCode import org.jetbrains.kotlin.cli.common.ExitCode
import org.jetbrains.kotlin.cli.common.arguments.CommonCompilerArguments import org.jetbrains.kotlin.cli.common.arguments.CommonCompilerArguments
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageLocation
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity.ERROR
import org.jetbrains.kotlin.cli.common.messages.MessageCollector import org.jetbrains.kotlin.cli.common.messages.MessageCollector
import org.jetbrains.kotlin.cli.common.messages.MessageCollectorUtil import org.jetbrains.kotlin.cli.common.messages.MessageCollectorUtil
import org.jetbrains.kotlin.daemon.client.CompileServiceSession import org.jetbrains.kotlin.daemon.client.CompileServiceSession
import org.jetbrains.kotlin.daemon.client.CompilationServices
import org.jetbrains.kotlin.daemon.client.DaemonReportMessage import org.jetbrains.kotlin.daemon.client.DaemonReportMessage
import org.jetbrains.kotlin.daemon.client.DaemonReportingTargets import org.jetbrains.kotlin.daemon.client.DaemonReportingTargets
import org.jetbrains.kotlin.daemon.client.KotlinCompilerClient import org.jetbrains.kotlin.daemon.client.KotlinCompilerClient
import org.jetbrains.kotlin.daemon.common.* import org.jetbrains.kotlin.daemon.common.*
import org.jetbrains.kotlin.load.kotlin.incremental.components.IncrementalCompilationComponents
import org.jetbrains.kotlin.progress.CompilationCanceledStatus
import java.io.BufferedReader import java.io.BufferedReader
import java.io.ByteArrayOutputStream import java.io.ByteArrayOutputStream
import java.io.File import java.io.File
@@ -90,7 +85,7 @@ abstract class KotlinCompilerRunner<in Env : CompilerEnvironment> {
DaemonReportCategory.INFO -> CompilerMessageSeverity.INFO DaemonReportCategory.INFO -> CompilerMessageSeverity.INFO
DaemonReportCategory.EXCEPTION -> CompilerMessageSeverity.EXCEPTION DaemonReportCategory.EXCEPTION -> CompilerMessageSeverity.EXCEPTION
} }
environment.messageCollector.report(severity, message.message, CompilerMessageLocation.NO_LOCATION) environment.messageCollector.report(severity, message.message)
} }
} }
@@ -98,9 +93,7 @@ abstract class KotlinCompilerRunner<in Env : CompilerEnvironment> {
if (daemonOptions.reportPerf) { if (daemonOptions.reportPerf) {
fun Long.ms() = TimeUnit.NANOSECONDS.toMillis(this) fun Long.ms() = TimeUnit.NANOSECONDS.toMillis(this)
val counters = profiler.getTotalCounters() val counters = profiler.getTotalCounters()
messageCollector.report(CompilerMessageSeverity.INFO, messageCollector.report(CompilerMessageSeverity.INFO, "PERF: $message ${counters.time.ms()} ms, thread ${counters.threadTime.ms()}")
"PERF: $message ${counters.time.ms()} ms, thread ${counters.threadTime.ms()}",
CompilerMessageLocation.NO_LOCATION)
} }
} }
@@ -122,7 +115,7 @@ abstract class KotlinCompilerRunner<in Env : CompilerEnvironment> {
} }
protected fun reportInternalCompilerError(messageCollector: MessageCollector): ExitCode { protected fun reportInternalCompilerError(messageCollector: MessageCollector): ExitCode {
messageCollector.report(ERROR, "Compiler terminated with internal error", CompilerMessageLocation.NO_LOCATION) messageCollector.report(CompilerMessageSeverity.ERROR, "Compiler terminated with internal error")
return ExitCode.INTERNAL_ERROR return ExitCode.INTERNAL_ERROR
} }
@@ -21,8 +21,8 @@ import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity
import org.jetbrains.kotlin.cli.common.messages.MessageCollector import org.jetbrains.kotlin.cli.common.messages.MessageCollector
import org.jetbrains.kotlin.cli.common.messages.OutputMessageUtil import org.jetbrains.kotlin.cli.common.messages.OutputMessageUtil
import org.jetbrains.kotlin.daemon.common.* import org.jetbrains.kotlin.daemon.common.*
import java.io.Serializable
import java.io.File import java.io.File
import java.io.Serializable
import java.rmi.server.UnicastRemoteObject import java.rmi.server.UnicastRemoteObject
@@ -51,11 +51,11 @@ fun MessageCollector.reportFromDaemon(outputsCollector: ((File, List<File>) -> U
} }
} }
else { else {
report(CompilerMessageSeverity.OUTPUT, message!!, CompilerMessageLocation.NO_LOCATION) report(CompilerMessageSeverity.OUTPUT, message!!)
} }
} }
ReportCategory.EXCEPTION -> { ReportCategory.EXCEPTION -> {
report(CompilerMessageSeverity.EXCEPTION, message.orEmpty(), CompilerMessageLocation.NO_LOCATION) report(CompilerMessageSeverity.EXCEPTION, message.orEmpty())
} }
ReportCategory.COMPILER_MESSAGE -> { ReportCategory.COMPILER_MESSAGE -> {
val compilerSeverity = when (ReportSeverity.fromCode(severity)) { val compilerSeverity = when (ReportSeverity.fromCode(severity)) {
@@ -65,7 +65,7 @@ fun MessageCollector.reportFromDaemon(outputsCollector: ((File, List<File>) -> U
ReportSeverity.DEBUG -> CompilerMessageSeverity.LOGGING ReportSeverity.DEBUG -> CompilerMessageSeverity.LOGGING
else -> throw IllegalStateException("Unexpected compiler message report severity $severity") else -> throw IllegalStateException("Unexpected compiler message report severity $severity")
} }
if (message != null && attachment is CompilerMessageLocation) { if (message != null && attachment is CompilerMessageLocation?) {
report(compilerSeverity, message, attachment) report(compilerSeverity, message, attachment)
} }
else { else {
@@ -75,7 +75,7 @@ fun MessageCollector.reportFromDaemon(outputsCollector: ((File, List<File>) -> U
ReportCategory.DAEMON_MESSAGE, ReportCategory.DAEMON_MESSAGE,
ReportCategory.IC_MESSAGE -> { ReportCategory.IC_MESSAGE -> {
if (message != null) { if (message != null) {
report(CompilerMessageSeverity.LOGGING, message, CompilerMessageLocation.NO_LOCATION) report(CompilerMessageSeverity.LOGGING, message)
} }
else { else {
reportUnexpected(category, severity, message, attachment) reportUnexpected(category, severity, message, attachment)
@@ -95,8 +95,5 @@ private fun MessageCollector.reportUnexpected(category: Int, severity: Int, mess
else -> CompilerMessageSeverity.LOGGING else -> CompilerMessageSeverity.LOGGING
} }
report(compilerMessageSeverity, report(compilerMessageSeverity, "Unexpected message: category=$category; severity=$severity; message='$message'; attachment=$attachment")
"Unexpected message: category=$category; severity=$severity; message='$message'; attachment=$attachment",
CompilerMessageLocation.NO_LOCATION)
} }
@@ -16,7 +16,6 @@
package org.jetbrains.kotlin.daemon.client package org.jetbrains.kotlin.daemon.client
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageLocation
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity
import org.jetbrains.kotlin.cli.common.messages.MessageCollector import org.jetbrains.kotlin.cli.common.messages.MessageCollector
import org.jetbrains.kotlin.daemon.common.* import org.jetbrains.kotlin.daemon.common.*
@@ -33,7 +32,6 @@ import java.rmi.UnmarshalException
import java.rmi.server.UnicastRemoteObject import java.rmi.server.UnicastRemoteObject
import java.util.concurrent.Semaphore import java.util.concurrent.Semaphore
import java.util.concurrent.TimeUnit import java.util.concurrent.TimeUnit
import kotlin.comparisons.compareByDescending
import kotlin.concurrent.thread import kotlin.concurrent.thread
class CompilationServices( class CompilationServices(
@@ -343,17 +341,17 @@ object KotlinCompilerClient {
messages?.add(DaemonReportMessage(category, "[$source] $message")) messages?.add(DaemonReportMessage(category, "[$source] $message"))
messageCollector?.let { messageCollector?.let {
when (category) { when (category) {
DaemonReportCategory.DEBUG -> it.report(CompilerMessageSeverity.LOGGING, message, CompilerMessageLocation.NO_LOCATION) DaemonReportCategory.DEBUG -> it.report(CompilerMessageSeverity.LOGGING, message)
DaemonReportCategory.INFO -> it.report(CompilerMessageSeverity.INFO, message, CompilerMessageLocation.NO_LOCATION) DaemonReportCategory.INFO -> it.report(CompilerMessageSeverity.INFO, message)
DaemonReportCategory.EXCEPTION -> it.report(CompilerMessageSeverity.EXCEPTION, message, CompilerMessageLocation.NO_LOCATION) DaemonReportCategory.EXCEPTION -> it.report(CompilerMessageSeverity.EXCEPTION, message)
} }
} }
compilerServices?.let { compilerServices?.let {
when (category) { when (category) {
DaemonReportCategory.DEBUG -> it.report(ReportCategory.DAEMON_MESSAGE, ReportSeverity.DEBUG, message, source) DaemonReportCategory.DEBUG -> it.report(ReportCategory.DAEMON_MESSAGE, ReportSeverity.DEBUG, message, source)
DaemonReportCategory.INFO -> it.report(ReportCategory.DAEMON_MESSAGE, ReportSeverity.INFO, message, source) DaemonReportCategory.INFO -> it.report(ReportCategory.DAEMON_MESSAGE, ReportSeverity.INFO, message, source)
DaemonReportCategory.EXCEPTION -> it.report(ReportCategory.EXCEPTION, ReportSeverity.ERROR, message, source) DaemonReportCategory.EXCEPTION -> it.report(ReportCategory.EXCEPTION, ReportSeverity.ERROR, message, source)
} }
} }
} }
@@ -27,9 +27,15 @@ import org.jetbrains.kotlin.cli.common.arguments.CommonCompilerArguments
import org.jetbrains.kotlin.cli.common.arguments.K2JSCompilerArguments import org.jetbrains.kotlin.cli.common.arguments.K2JSCompilerArguments
import org.jetbrains.kotlin.cli.common.arguments.K2JVMCompilerArguments import org.jetbrains.kotlin.cli.common.arguments.K2JVMCompilerArguments
import org.jetbrains.kotlin.cli.common.arguments.K2MetadataCompilerArguments import org.jetbrains.kotlin.cli.common.arguments.K2MetadataCompilerArguments
import org.jetbrains.kotlin.cli.common.messages.* import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity
import org.jetbrains.kotlin.cli.common.messages.MessageCollector
import org.jetbrains.kotlin.cli.common.messages.MessageRenderer
import org.jetbrains.kotlin.cli.common.messages.PrintingMessageCollector
import org.jetbrains.kotlin.cli.common.modules.ModuleXmlParser import org.jetbrains.kotlin.cli.common.modules.ModuleXmlParser
import org.jetbrains.kotlin.cli.common.repl.* import org.jetbrains.kotlin.cli.common.repl.ReplCheckResult
import org.jetbrains.kotlin.cli.common.repl.ReplCodeLine
import org.jetbrains.kotlin.cli.common.repl.ReplCompileResult
import org.jetbrains.kotlin.cli.common.repl.ReplEvalResult
import org.jetbrains.kotlin.cli.js.K2JSCompiler import org.jetbrains.kotlin.cli.js.K2JSCompiler
import org.jetbrains.kotlin.cli.jvm.K2JVMCompiler import org.jetbrains.kotlin.cli.jvm.K2JVMCompiler
import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment
@@ -337,7 +343,7 @@ class CompileServiceImpl(
} }
} }
catch (e: IllegalArgumentException) { catch (e: IllegalArgumentException) {
messageCollector.report(CompilerMessageSeverity.EXCEPTION, e.stackTraceStr, CompilerMessageLocation.NO_LOCATION) messageCollector.report(CompilerMessageSeverity.EXCEPTION, e.stackTraceStr)
return@ifAlive CompileService.CallResult.Error("Could not deserialize compiler arguments") return@ifAlive CompileService.CallResult.Error("Could not deserialize compiler arguments")
} }
@@ -18,6 +18,8 @@ package org.jetbrains.kotlin.daemon
import com.intellij.openapi.Disposable import com.intellij.openapi.Disposable
import org.jetbrains.kotlin.cli.common.messages.* import org.jetbrains.kotlin.cli.common.messages.*
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity.ERROR
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity.INFO
import org.jetbrains.kotlin.cli.common.repl.* import org.jetbrains.kotlin.cli.common.repl.*
import org.jetbrains.kotlin.cli.jvm.config.addJvmClasspathRoots import org.jetbrains.kotlin.cli.jvm.config.addJvmClasspathRoots
import org.jetbrains.kotlin.cli.jvm.repl.GenericReplCompiler import org.jetbrains.kotlin.cli.jvm.repl.GenericReplCompiler
@@ -63,22 +65,15 @@ open class KotlinJvmReplService(
try { try {
val cls = classloader.loadClass(templateClassName) val cls = classloader.loadClass(templateClassName)
val def = KotlinScriptDefinitionFromAnnotatedTemplate(cls.kotlin, null, null, emptyMap()) val def = KotlinScriptDefinitionFromAnnotatedTemplate(cls.kotlin, null, null, emptyMap())
messageCollector.report( messageCollector.report(INFO, "New script definition $templateClassName: files pattern = \"${def.scriptFilePattern}\", " +
CompilerMessageSeverity.INFO, "resolver = ${def.resolver?.javaClass?.name}")
"New script definition $templateClassName: files pattern = \"${def.scriptFilePattern}\", resolver = ${def.resolver?.javaClass?.name}",
CompilerMessageLocation.NO_LOCATION
)
return def return def
} }
catch (ex: ClassNotFoundException) { catch (ex: ClassNotFoundException) {
messageCollector.report( messageCollector.report(ERROR, "Cannot find script definition template class $templateClassName")
CompilerMessageSeverity.ERROR, "Cannot find script definition template class $templateClassName", CompilerMessageLocation.NO_LOCATION
)
} }
catch (ex: Exception) { catch (ex: Exception) {
messageCollector.report( messageCollector.report(ERROR, "Error processing script definition template $templateClassName: ${ex.message}")
CompilerMessageSeverity.ERROR, "Error processing script definition template $templateClassName: ${ex.message}", CompilerMessageLocation.NO_LOCATION
)
} }
return null return null
} }
@@ -150,7 +145,7 @@ internal class KeepFirstErrorMessageCollector(compilerMessagesStream: PrintStrea
internal var firstErrorMessage: String? = null internal var firstErrorMessage: String? = null
internal var firstErrorLocation: CompilerMessageLocation? = null internal var firstErrorLocation: CompilerMessageLocation? = null
override fun report(severity: CompilerMessageSeverity, message: String, location: CompilerMessageLocation) { override fun report(severity: CompilerMessageSeverity, message: String, location: CompilerMessageLocation?) {
if (firstErrorMessage == null && severity.isError) { if (firstErrorMessage == null && severity.isError) {
firstErrorMessage = message firstErrorMessage = message
firstErrorLocation = location firstErrorLocation = location
@@ -34,8 +34,8 @@ internal class CompileServicesFacadeMessageCollector(
hasErrors = false hasErrors = false
} }
override fun report(severity: CompilerMessageSeverity, message: String, location: CompilerMessageLocation) { override fun report(severity: CompilerMessageSeverity, message: String, location: CompilerMessageLocation?) {
log.info("Message: " + MessageRenderer.WITHOUT_PATHS.render(severity, message, location)) log.info("Message: " + MessageRenderer.WITHOUT_PATHS.render(severity, message, location ?: CompilerMessageLocation.NO_LOCATION))
when (severity) { when (severity) {
CompilerMessageSeverity.OUTPUT -> { CompilerMessageSeverity.OUTPUT -> {
servicesFacade.report(ReportCategory.OUTPUT_MESSAGE, ReportSeverity.ERROR, message) servicesFacade.report(ReportCategory.OUTPUT_MESSAGE, ReportSeverity.ERROR, message)
@@ -16,6 +16,7 @@
package org.jetbrains.kotlin.incremental package org.jetbrains.kotlin.incremental
import com.intellij.util.io.PersistentEnumeratorBase
import org.jetbrains.kotlin.annotation.AnnotationFileUpdater import org.jetbrains.kotlin.annotation.AnnotationFileUpdater
import org.jetbrains.kotlin.build.GeneratedFile import org.jetbrains.kotlin.build.GeneratedFile
import org.jetbrains.kotlin.build.GeneratedJvmClass import org.jetbrains.kotlin.build.GeneratedJvmClass
@@ -26,7 +27,6 @@ import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity
import org.jetbrains.kotlin.cli.common.messages.MessageCollector import org.jetbrains.kotlin.cli.common.messages.MessageCollector
import org.jetbrains.kotlin.cli.common.messages.OutputMessageUtil import org.jetbrains.kotlin.cli.common.messages.OutputMessageUtil
import org.jetbrains.kotlin.cli.jvm.K2JVMCompiler import org.jetbrains.kotlin.cli.jvm.K2JVMCompiler
import com.intellij.util.io.PersistentEnumeratorBase
import org.jetbrains.kotlin.compilerRunner.ArgumentUtils import org.jetbrains.kotlin.compilerRunner.ArgumentUtils
import org.jetbrains.kotlin.compilerRunner.OutputItemsCollector import org.jetbrains.kotlin.compilerRunner.OutputItemsCollector
import org.jetbrains.kotlin.compilerRunner.OutputItemsCollectorImpl import org.jetbrains.kotlin.compilerRunner.OutputItemsCollectorImpl
@@ -453,7 +453,7 @@ class IncrementalJvmCompilerRunner(
private val delegate: MessageCollector, private val delegate: MessageCollector,
private val outputCollector: OutputItemsCollector private val outputCollector: OutputItemsCollector
) : MessageCollector by delegate { ) : MessageCollector by delegate {
override fun report(severity: CompilerMessageSeverity, message: String, location: CompilerMessageLocation) { override fun report(severity: CompilerMessageSeverity, message: String, location: CompilerMessageLocation?) {
// TODO: consider adding some other way of passing input -> output mapping from compiler, e.g. dedicated service // TODO: consider adding some other way of passing input -> output mapping from compiler, e.g. dedicated service
OutputMessageUtil.parseOutputMessage(message)?.let { OutputMessageUtil.parseOutputMessage(message)?.let {
outputCollector.add(it.sourceFiles, it.outputFile) outputCollector.add(it.sourceFiles, it.outputFile)
@@ -475,4 +475,4 @@ var K2JVMCompilerArguments.destinationAsFile: File
var K2JVMCompilerArguments.classpathAsList: List<File> var K2JVMCompilerArguments.classpathAsList: List<File>
get() = classpath.split(File.pathSeparator).map(::File) get() = classpath.split(File.pathSeparator).map(::File)
set(value) { classpath = value.joinToString(separator = File.pathSeparator, transform = { it.path }) } set(value) { classpath = value.joinToString(separator = File.pathSeparator, transform = { it.path }) }
@@ -16,15 +16,15 @@
package org.jetbrains.kotlin.incremental package org.jetbrains.kotlin.incremental
import com.intellij.util.containers.HashMap
import org.jetbrains.kotlin.TestWithWorkingDir import org.jetbrains.kotlin.TestWithWorkingDir
import org.jetbrains.kotlin.cli.common.ExitCode import org.jetbrains.kotlin.cli.common.ExitCode
import org.jetbrains.kotlin.cli.common.arguments.K2JVMCompilerArguments import org.jetbrains.kotlin.cli.common.arguments.K2JVMCompilerArguments
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageLocation import org.jetbrains.kotlin.cli.common.messages.CompilerMessageLocation
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity
import org.jetbrains.kotlin.cli.common.messages.MessageCollector import org.jetbrains.kotlin.cli.common.messages.MessageCollector
import com.intellij.util.containers.HashMap
import org.junit.Assert.assertEquals
import org.jetbrains.kotlin.incremental.testingUtils.* import org.jetbrains.kotlin.incremental.testingUtils.*
import org.junit.Assert.assertEquals
import org.junit.Test import org.junit.Test
import org.junit.runner.RunWith import org.junit.runner.RunWith
import org.junit.runners.Parameterized import org.junit.runners.Parameterized
@@ -169,7 +169,7 @@ class KotlinStandaloneIncrementalCompilationTest : TestWithWorkingDir() {
private class ErrorMessageCollector : MessageCollector { private class ErrorMessageCollector : MessageCollector {
val errors = ArrayList<String>() val errors = ArrayList<String>()
override fun report(severity: CompilerMessageSeverity, message: String, location: CompilerMessageLocation) { override fun report(severity: CompilerMessageSeverity, message: String, location: CompilerMessageLocation?) {
if (severity.isError) { if (severity.isError) {
errors.add(message) errors.add(message)
} }
@@ -219,4 +219,3 @@ class KotlinStandaloneIncrementalCompilationTest : TestWithWorkingDir() {
} }
} }
} }
@@ -188,8 +188,7 @@ class CompilerApiTest : KotlinIntegrationTestBase() {
} }
class TestMessageCollector : MessageCollector { class TestMessageCollector : MessageCollector {
data class Message(val severity: CompilerMessageSeverity, val message: String, val location: CompilerMessageLocation?)
data class Message(val severity: CompilerMessageSeverity, val message: String, val location: CompilerMessageLocation)
val messages = arrayListOf<Message>() val messages = arrayListOf<Message>()
@@ -197,9 +196,9 @@ class TestMessageCollector : MessageCollector {
messages.clear() messages.clear()
} }
override fun report(severity: CompilerMessageSeverity, message: String, location: CompilerMessageLocation) { override fun report(severity: CompilerMessageSeverity, message: String, location: CompilerMessageLocation?) {
messages.add(Message(severity, message, location)) messages.add(Message(severity, message, location))
} }
override fun hasErrors(): Boolean = messages.any { it.severity == CompilerMessageSeverity.EXCEPTION || it.severity == CompilerMessageSeverity.ERROR } override fun hasErrors(): Boolean = messages.any { it.severity == CompilerMessageSeverity.EXCEPTION || it.severity == CompilerMessageSeverity.ERROR }
} }
@@ -19,6 +19,7 @@ package org.jetbrains.kotlin.modules.xml;
import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.io.FileUtil;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageLocation; import org.jetbrains.kotlin.cli.common.messages.CompilerMessageLocation;
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity; import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity;
import org.jetbrains.kotlin.cli.common.messages.MessageCollector; import org.jetbrains.kotlin.cli.common.messages.MessageCollector;
@@ -39,9 +40,11 @@ public abstract class AbstractModuleXmlParserTest extends TestCase {
ModuleScriptData result = ModuleXmlParser.parseModuleScript(xmlPath, new MessageCollector() { ModuleScriptData result = ModuleXmlParser.parseModuleScript(xmlPath, new MessageCollector() {
@Override @Override
public void report( public void report(
@NotNull CompilerMessageSeverity severity, @NotNull String message, @NotNull CompilerMessageLocation location @NotNull CompilerMessageSeverity severity, @NotNull String message, @Nullable CompilerMessageLocation location
) { ) {
throw new AssertionError(MessageRenderer.PLAIN_FULL_PATHS.render(severity, message, location)); throw new AssertionError(MessageRenderer.PLAIN_FULL_PATHS.render(
severity, message, location != null ? location : CompilerMessageLocation.NO_LOCATION
));
} }
@Override @Override
@@ -80,18 +80,17 @@ class KotlinJsr223JvmScriptEngine4Idea(
override fun createState(lock: ReentrantReadWriteLock): IReplStageState<*> = replEvaluator.createState(lock) override fun createState(lock: ReentrantReadWriteLock): IReplStageState<*> = replEvaluator.createState(lock)
private class MyMessageCollector : MessageCollector { private class MyMessageCollector : MessageCollector {
private var hasErrors: Boolean = false
var _hasErrors: Boolean = false override fun report(severity: CompilerMessageSeverity, message: String, location: CompilerMessageLocation?) {
override fun report(severity: CompilerMessageSeverity, message: String, location: CompilerMessageLocation) {
System.err.println(message) // TODO: proper location printing System.err.println(message) // TODO: proper location printing
if (!_hasErrors) { if (!hasErrors) {
_hasErrors = severity == CompilerMessageSeverity.EXCEPTION || severity == CompilerMessageSeverity.ERROR hasErrors = severity == CompilerMessageSeverity.EXCEPTION || severity == CompilerMessageSeverity.ERROR
} }
} }
override fun clear() {} override fun clear() {}
override fun hasErrors(): Boolean = _hasErrors override fun hasErrors(): Boolean = hasErrors
} }
} }
@@ -30,7 +30,6 @@ import java.lang.ref.SoftReference;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.util.Collections; import java.util.Collections;
import static org.jetbrains.kotlin.cli.common.messages.CompilerMessageLocation.NO_LOCATION;
import static org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity.ERROR; import static org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity.ERROR;
public class CompilerRunnerUtil { public class CompilerRunnerUtil {
@@ -63,7 +62,7 @@ public class CompilerRunnerUtil {
messageCollector.report( messageCollector.report(
ERROR, ERROR,
"Broken compiler at '" + libs.getAbsolutePath() + "'. Make sure plugin is properly installed", "Broken compiler at '" + libs.getAbsolutePath() + "'. Make sure plugin is properly installed",
NO_LOCATION null
); );
return null; return null;
@@ -16,8 +16,7 @@
package org.jetbrains.kotlin.compilerRunner package org.jetbrains.kotlin.compilerRunner
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageLocation import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity.ERROR
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity
import org.jetbrains.kotlin.cli.common.messages.MessageCollector import org.jetbrains.kotlin.cli.common.messages.MessageCollector
import org.jetbrains.kotlin.config.Services import org.jetbrains.kotlin.config.Services
import org.jetbrains.kotlin.preloading.ClassCondition import org.jetbrains.kotlin.preloading.ClassCondition
@@ -37,8 +36,8 @@ class JpsCompilerEnvironment(
fun reportErrorsTo(messageCollector: MessageCollector) { fun reportErrorsTo(messageCollector: MessageCollector) {
if (!kotlinPaths.homePath.exists()) { if (!kotlinPaths.homePath.exists()) {
messageCollector.report(CompilerMessageSeverity.ERROR, "Cannot find kotlinc home: " + kotlinPaths.homePath + ". Make sure plugin is properly installed, " + messageCollector.report(ERROR, "Cannot find kotlinc home: " + kotlinPaths.homePath + ". Make sure plugin is properly installed, " +
"or specify " + PathUtil.JPS_KOTLIN_HOME_PROPERTY + " system property", CompilerMessageLocation.NO_LOCATION) "or specify " + PathUtil.JPS_KOTLIN_HOME_PROPERTY + " system property")
} }
} }
} }
@@ -21,7 +21,6 @@ import org.jetbrains.jps.api.GlobalOptions
import org.jetbrains.kotlin.cli.common.ExitCode import org.jetbrains.kotlin.cli.common.ExitCode
import org.jetbrains.kotlin.cli.common.KOTLIN_COMPILER_ENVIRONMENT_KEEPALIVE_PROPERTY import org.jetbrains.kotlin.cli.common.KOTLIN_COMPILER_ENVIRONMENT_KEEPALIVE_PROPERTY
import org.jetbrains.kotlin.cli.common.arguments.* import org.jetbrains.kotlin.cli.common.arguments.*
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageLocation
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity
import org.jetbrains.kotlin.config.CompilerSettings import org.jetbrains.kotlin.config.CompilerSettings
import org.jetbrains.kotlin.config.additionalArgumentsAsList import org.jetbrains.kotlin.config.additionalArgumentsAsList
@@ -105,7 +104,7 @@ class JpsKotlinCompilerRunner : KotlinCompilerRunner<JpsCompilerEnvironment>() {
compilerArgs: CommonCompilerArguments, compilerArgs: CommonCompilerArguments,
environment: JpsCompilerEnvironment environment: JpsCompilerEnvironment
): ExitCode { ): ExitCode {
environment.messageCollector.report(CompilerMessageSeverity.INFO, "Using kotlin-home = " + environment.kotlinPaths.homePath, CompilerMessageLocation.NO_LOCATION) environment.messageCollector.report(CompilerMessageSeverity.INFO, "Using kotlin-home = " + environment.kotlinPaths.homePath)
return if (isDaemonEnabled()) { return if (isDaemonEnabled()) {
val daemonExitCode = compileWithDaemon(compilerClassName, compilerArgs, environment) val daemonExitCode = compileWithDaemon(compilerClassName, compilerArgs, environment)
@@ -241,4 +240,4 @@ class JpsKotlinCompilerRunner : KotlinCompilerRunner<JpsCompilerEnvironment>() {
val sessionFlagFile = makeAutodeletingFlagFile("compiler-jps-session-", File(daemonOptions.runFilesPathOrDefault)) val sessionFlagFile = makeAutodeletingFlagFile("compiler-jps-session-", File(daemonOptions.runFilesPathOrDefault))
newDaemonConnection(compilerId, clientFlagFile, sessionFlagFile, environment, daemonOptions) newDaemonConnection(compilerId, clientFlagFile, sessionFlagFile, environment, daemonOptions)
} }
} }
@@ -46,7 +46,7 @@ import org.jetbrains.kotlin.cli.common.messages.CompilerMessageLocation
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity.* import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity.*
import org.jetbrains.kotlin.cli.common.messages.MessageCollector import org.jetbrains.kotlin.cli.common.messages.MessageCollector
import org.jetbrains.kotlin.cli.common.messages.OutputMessageUtil import org.jetbrains.kotlin.cli.common.messages.MessageCollectorUtil
import org.jetbrains.kotlin.compilerRunner.JpsCompilerEnvironment import org.jetbrains.kotlin.compilerRunner.JpsCompilerEnvironment
import org.jetbrains.kotlin.compilerRunner.JpsKotlinCompilerRunner import org.jetbrains.kotlin.compilerRunner.JpsKotlinCompilerRunner
import org.jetbrains.kotlin.compilerRunner.OutputItemsCollector import org.jetbrains.kotlin.compilerRunner.OutputItemsCollector
@@ -194,12 +194,7 @@ class KotlinBuilder : ModuleLevelBuilder(BuilderCategory.SOURCE_PROCESSOR) {
} }
catch (e: Throwable) { catch (e: Throwable) {
LOG.info("Caught exception: " + e) LOG.info("Caught exception: " + e)
MessageCollectorUtil.reportException(messageCollector, e)
messageCollector.report(
CompilerMessageSeverity.EXCEPTION,
OutputMessageUtil.renderException(e),
CompilerMessageLocation.NO_LOCATION
)
return ABORT return ABORT
} }
} }
@@ -214,7 +209,7 @@ class KotlinBuilder : ModuleLevelBuilder(BuilderCategory.SOURCE_PROCESSOR) {
): ModuleLevelBuilder.ExitCode { ): ModuleLevelBuilder.ExitCode {
// Workaround for Android Studio // Workaround for Android Studio
if (!JavaBuilder.IS_ENABLED[context, true] && !JpsUtils.isJsKotlinModule(chunk.representativeTarget())) { if (!JavaBuilder.IS_ENABLED[context, true] && !JpsUtils.isJsKotlinModule(chunk.representativeTarget())) {
messageCollector.report(INFO, "Kotlin JPS plugin is disabled", CompilerMessageLocation.NO_LOCATION) messageCollector.report(INFO, "Kotlin JPS plugin is disabled")
return NOTHING_DONE return NOTHING_DONE
} }
@@ -235,11 +230,11 @@ class KotlinBuilder : ModuleLevelBuilder(BuilderCategory.SOURCE_PROCESSOR) {
return NOTHING_DONE return NOTHING_DONE
} }
messageCollector.report(INFO, "Kotlin JPS plugin version " + KotlinCompilerVersion.VERSION, CompilerMessageLocation.NO_LOCATION) messageCollector.report(INFO, "Kotlin JPS plugin version " + KotlinCompilerVersion.VERSION)
val targetsWithoutOutputDir = targets.filter { it.outputDir == null } val targetsWithoutOutputDir = targets.filter { it.outputDir == null }
if (targetsWithoutOutputDir.isNotEmpty()) { if (targetsWithoutOutputDir.isNotEmpty()) {
messageCollector.report(ERROR, "Output directory not specified for " + targetsWithoutOutputDir.joinToString(), CompilerMessageLocation.NO_LOCATION) messageCollector.report(ERROR, "Output directory not specified for " + targetsWithoutOutputDir.joinToString())
return ABORT return ABORT
} }
@@ -448,11 +443,7 @@ class KotlinBuilder : ModuleLevelBuilder(BuilderCategory.SOURCE_PROCESSOR) {
commonArguments.pluginClasspaths = concatenate(commonArguments.pluginClasspaths, commonArguments.pluginClasspaths = concatenate(commonArguments.pluginClasspaths,
argumentProvider.getClasspath(representativeTarget, context)) argumentProvider.getClasspath(representativeTarget, context))
messageCollector.report( messageCollector.report(INFO, "Plugin loaded: ${argumentProvider::class.java.simpleName}")
INFO,
"Plugin loaded: ${argumentProvider::class.java.simpleName}",
CompilerMessageLocation.NO_LOCATION
)
} }
return compileToJvm(allCompiledFiles, chunk, commonArguments, context, dirtyFilesHolder, environment, filesToCompile) return compileToJvm(allCompiledFiles, chunk, commonArguments, context, dirtyFilesHolder, environment, filesToCompile)
@@ -651,8 +642,7 @@ class KotlinBuilder : ModuleLevelBuilder(BuilderCategory.SOURCE_PROCESSOR) {
STRONG_WARNING, STRONG_WARNING,
"Circular dependencies are not supported. The following JS modules depend on each other: " "Circular dependencies are not supported. The following JS modules depend on each other: "
+ chunk.modules.map { it.name }.joinToString(", ") + ". " + chunk.modules.map { it.name }.joinToString(", ") + ". "
+ "Kotlin is not compiled for these modules", + "Kotlin is not compiled for these modules"
CompilerMessageLocation.NO_LOCATION
) )
return null return null
} }
@@ -702,8 +692,7 @@ class KotlinBuilder : ModuleLevelBuilder(BuilderCategory.SOURCE_PROCESSOR) {
STRONG_WARNING, STRONG_WARNING,
"Circular dependencies are only partially supported. The following modules depend on each other: " "Circular dependencies are only partially supported. The following modules depend on each other: "
+ chunk.modules.map { it.name }.joinToString(", ") + ". " + chunk.modules.map { it.name }.joinToString(", ") + ". "
+ "Kotlin will compile them, but some strange effect may happen", + "Kotlin will compile them, but some strange effect may happen"
CompilerMessageLocation.NO_LOCATION
) )
} }
@@ -746,7 +735,7 @@ class KotlinBuilder : ModuleLevelBuilder(BuilderCategory.SOURCE_PROCESSOR) {
class MessageCollectorAdapter(private val context: CompileContext) : MessageCollector { class MessageCollectorAdapter(private val context: CompileContext) : MessageCollector {
private var hasErrors = false private var hasErrors = false
override fun report(severity: CompilerMessageSeverity, message: String, location: CompilerMessageLocation) { override fun report(severity: CompilerMessageSeverity, message: String, location: CompilerMessageLocation?) {
hasErrors = hasErrors or severity.isError hasErrors = hasErrors or severity.isError
var prefix = "" var prefix = ""
if (severity == EXCEPTION) { if (severity == EXCEPTION) {
@@ -755,10 +744,11 @@ class KotlinBuilder : ModuleLevelBuilder(BuilderCategory.SOURCE_PROCESSOR) {
context.processMessage(CompilerMessage( context.processMessage(CompilerMessage(
CompilerRunnerConstants.KOTLIN_COMPILER_NAME, CompilerRunnerConstants.KOTLIN_COMPILER_NAME,
kind(severity), kind(severity),
prefix + message + renderLocationIfNeeded(location), prefix + message,
location.path, location?.path,
-1, -1, -1, -1, -1, -1,
location.line.toLong(), location.column.toLong() location?.line?.toLong() ?: -1,
location?.column?.toLong() ?: -1
)) ))
} }
@@ -768,16 +758,6 @@ class KotlinBuilder : ModuleLevelBuilder(BuilderCategory.SOURCE_PROCESSOR) {
override fun hasErrors(): Boolean = hasErrors override fun hasErrors(): Boolean = hasErrors
private fun renderLocationIfNeeded(location: CompilerMessageLocation): String {
if (location == CompilerMessageLocation.NO_LOCATION) return ""
// Sometimes we report errors in JavaScript library stubs, i.e. files like core/javautil.kt
// IDEA can't find these files, and does not display paths in Messages View, so we add the position information
// to the error message itself:
val pathname = "" + location.path
return if (File(pathname).exists()) "" else " ($location)"
}
private fun kind(severity: CompilerMessageSeverity): BuildMessage.Kind { private fun kind(severity: CompilerMessageSeverity): BuildMessage.Kind {
return when (severity) { return when (severity) {
INFO -> BuildMessage.Kind.INFO INFO -> BuildMessage.Kind.INFO
@@ -17,7 +17,6 @@
package example package example
import org.jetbrains.kotlin.cli.common.CLIConfigurationKeys import org.jetbrains.kotlin.cli.common.CLIConfigurationKeys
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageLocation
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity
import org.jetbrains.kotlin.cli.common.messages.MessageCollector import org.jetbrains.kotlin.cli.common.messages.MessageCollector
import org.jetbrains.kotlin.config.CompilerConfigurationKey import org.jetbrains.kotlin.config.CompilerConfigurationKey
@@ -50,10 +49,9 @@ public class ExampleCommandLineProcessor : CommandLineProcessor {
} }
public class ExampleComponentRegistrar : ComponentRegistrar { public class ExampleComponentRegistrar : ComponentRegistrar {
public override fun registerProjectComponents(project: MockProject, configuration: CompilerConfiguration) { public override fun registerProjectComponents(project: MockProject, configuration: CompilerConfiguration) {
val exampleValue = configuration.get(ExampleConfigurationKeys.EXAMPLE_KEY) val exampleValue = configuration.get(ExampleConfigurationKeys.EXAMPLE_KEY)
val messageCollector = configuration.get(CLIConfigurationKeys.MESSAGE_COLLECTOR_KEY, MessageCollector.NONE) val messageCollector = configuration.get(CLIConfigurationKeys.MESSAGE_COLLECTOR_KEY, MessageCollector.NONE)
messageCollector.report(CompilerMessageSeverity.INFO, "Project component registration: $exampleValue", CompilerMessageLocation.NO_LOCATION) messageCollector.report(CompilerMessageSeverity.INFO, "Project component registration: $exampleValue")
} }
} }
@@ -33,10 +33,10 @@ internal open class GradleCompilerServicesFacadeImpl(
when (reportCategory) { when (reportCategory) {
ReportCategory.OUTPUT_MESSAGE -> { ReportCategory.OUTPUT_MESSAGE -> {
compilerMessageCollector.report(CompilerMessageSeverity.OUTPUT, message!!, CompilerMessageLocation.NO_LOCATION) compilerMessageCollector.report(CompilerMessageSeverity.OUTPUT, message!!)
} }
ReportCategory.EXCEPTION -> { ReportCategory.EXCEPTION -> {
compilerMessageCollector.report(CompilerMessageSeverity.EXCEPTION, message!!, CompilerMessageLocation.NO_LOCATION) compilerMessageCollector.report(CompilerMessageSeverity.EXCEPTION, message!!)
} }
ReportCategory.COMPILER_MESSAGE -> { ReportCategory.COMPILER_MESSAGE -> {
val compilerSeverity = when (ReportSeverity.fromCode(severity)) { val compilerSeverity = when (ReportSeverity.fromCode(severity)) {
@@ -46,7 +46,7 @@ internal open class GradleCompilerServicesFacadeImpl(
ReportSeverity.DEBUG -> CompilerMessageSeverity.LOGGING ReportSeverity.DEBUG -> CompilerMessageSeverity.LOGGING
else -> throw IllegalStateException("Unexpected compiler message report severity $severity") else -> throw IllegalStateException("Unexpected compiler message report severity $severity")
} }
if (message != null && attachment is CompilerMessageLocation) { if (message != null && attachment is CompilerMessageLocation?) {
compilerMessageCollector.report(compilerSeverity, message, attachment) compilerMessageCollector.report(compilerSeverity, message, attachment)
} }
else { else {
@@ -117,4 +117,4 @@ internal class GradleIncrementalCompilerServicesFacadeImpl(
registry.add(artifactFile, ArtifactDifference(timestamp, DirtyData())) registry.add(artifactFile, ArtifactDifference(timestamp, DirtyData()))
} }
} }
} }
@@ -402,8 +402,8 @@ internal class GradleMessageCollector(val logger: Logger) : MessageCollector {
// Do nothing // Do nothing
} }
override fun report(severity: CompilerMessageSeverity, message: String, location: CompilerMessageLocation) { override fun report(severity: CompilerMessageSeverity, message: String, location: CompilerMessageLocation?) {
val text = with(StringBuilder()) { val text = buildString {
append(when (severity) { append(when (severity) {
in CompilerMessageSeverity.VERBOSE -> "v" in CompilerMessageSeverity.VERBOSE -> "v"
in CompilerMessageSeverity.ERRORS -> { in CompilerMessageSeverity.ERRORS -> {
@@ -416,18 +416,18 @@ internal class GradleMessageCollector(val logger: Logger) : MessageCollector {
}) })
append(": ") append(": ")
val (path, line, column) = location if (location != null) {
if (path != null) { val (path, line, column) = location
append(path) if (path != null) {
append(": ") append(path)
if (line > 0 && column > 0) { append(": ")
append("($line, $column): ") if (line > 0 && column > 0) {
append("($line, $column): ")
}
} }
} }
append(message) append(message)
toString()
} }
when (severity) { when (severity) {
in CompilerMessageSeverity.VERBOSE -> logger.debug(text) in CompilerMessageSeverity.VERBOSE -> logger.debug(text)
@@ -35,7 +35,7 @@ class TestKotlinPluginRegistrar : ComponentRegistrar {
val collector = configuration.get(CLIConfigurationKeys.MESSAGE_COLLECTOR_KEY)!! val collector = configuration.get(CLIConfigurationKeys.MESSAGE_COLLECTOR_KEY)!!
val option = configuration.get(TestPluginKeys.TestOption)!! val option = configuration.get(TestPluginKeys.TestOption)!!
collector.report(CompilerMessageSeverity.INFO, "Plugin applied", CompilerMessageLocation.NO_LOCATION) collector.report(CompilerMessageSeverity.INFO, "Plugin applied")
collector.report(CompilerMessageSeverity.INFO, "Option value: $option", CompilerMessageLocation.NO_LOCATION) collector.report(CompilerMessageSeverity.INFO, "Option value: $option")
} }
} }
@@ -22,6 +22,7 @@ import kotlin.jvm.functions.Function1;
import org.apache.maven.plugin.logging.Log; import org.apache.maven.plugin.logging.Log;
import org.codehaus.plexus.compiler.CompilerMessage; import org.codehaus.plexus.compiler.CompilerMessage;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageLocation; import org.jetbrains.kotlin.cli.common.messages.CompilerMessageLocation;
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity; import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity;
import org.jetbrains.kotlin.cli.common.messages.MessageCollector; import org.jetbrains.kotlin.cli.common.messages.MessageCollector;
@@ -56,9 +57,8 @@ public class MavenPluginLogMessageCollector implements MessageCollector {
} }
@Override @Override
public void report(@NotNull CompilerMessageSeverity severity, @NotNull String message, @NotNull CompilerMessageLocation location) { public void report(@NotNull CompilerMessageSeverity severity, @NotNull String message, @Nullable CompilerMessageLocation location) {
String path = location.getPath(); String position = location == null ? "" : location.getPath() + ": (" + (location.getLine() + ", " + location.getColumn()) + ") ";
String position = path == null ? "" : path + ": (" + (location.getLine() + ", " + location.getColumn()) + ") ";
String text = position + message; String text = position + message;
@@ -81,6 +81,10 @@ public class MavenPluginLogMessageCollector implements MessageCollector {
public CompilerMessage invoke(Pair<CompilerMessageLocation, String> pair) { public CompilerMessage invoke(Pair<CompilerMessageLocation, String> pair) {
CompilerMessageLocation location = pair.getFirst(); CompilerMessageLocation location = pair.getFirst();
String message = pair.getSecond(); String message = pair.getSecond();
if (location == null) {
return new CompilerMessage(null, CompilerMessage.Kind.ERROR, 0, 0, 0, 0, message);
}
String lineContent = location.getLineContent(); String lineContent = location.getLineContent();
int lineContentLength = lineContent == null ? 0 : lineContent.length(); int lineContentLength = lineContent == null ? 0 : lineContent.length();
@@ -13,7 +13,7 @@ public class KotlinCompilationFailureExceptionTest {
@Test @Test
public void testNoLocation() throws Exception { public void testNoLocation() throws Exception {
MavenPluginLogMessageCollector collector = new MavenPluginLogMessageCollector(new SilentLog()); MavenPluginLogMessageCollector collector = new MavenPluginLogMessageCollector(new SilentLog());
collector.report(CompilerMessageSeverity.ERROR, "Something went wrong", CompilerMessageLocation.NO_LOCATION); collector.report(CompilerMessageSeverity.ERROR, "Something went wrong", null);
try { try {
collector.throwKotlinCompilerException(); collector.throwKotlinCompilerException();
@@ -16,7 +16,6 @@
package org.jetbrains.kotlin.annotation.processing.impl package org.jetbrains.kotlin.annotation.processing.impl
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageLocation
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity
import org.jetbrains.kotlin.cli.common.messages.MessageCollector import org.jetbrains.kotlin.cli.common.messages.MessageCollector
import javax.annotation.processing.Messager import javax.annotation.processing.Messager
@@ -57,6 +56,6 @@ class KotlinMessager(private val messageCollector: MessageCollector) : Messager
} }
else -> CompilerMessageSeverity.LOGGING else -> CompilerMessageSeverity.LOGGING
} }
messageCollector.report(severity, msg.toString(), CompilerMessageLocation.NO_LOCATION) messageCollector.report(severity, msg.toString())
} }
} }
@@ -19,12 +19,12 @@ package org.jetbrains.kotlin.kapt3
import com.intellij.openapi.project.Project import com.intellij.openapi.project.Project
import com.sun.tools.javac.tree.JCTree import com.sun.tools.javac.tree.JCTree
import org.jetbrains.kotlin.analyzer.AnalysisResult import org.jetbrains.kotlin.analyzer.AnalysisResult
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageLocation
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity
import org.jetbrains.kotlin.cli.common.messages.MessageCollector import org.jetbrains.kotlin.cli.common.messages.MessageCollector
import org.jetbrains.kotlin.cli.common.messages.OutputMessageUtil import org.jetbrains.kotlin.cli.common.messages.OutputMessageUtil
import org.jetbrains.kotlin.cli.common.output.outputUtils.writeAll import org.jetbrains.kotlin.cli.common.output.outputUtils.writeAll
import org.jetbrains.kotlin.codegen.* import org.jetbrains.kotlin.codegen.CompilationErrorHandler
import org.jetbrains.kotlin.codegen.KotlinCodegenFacade
import org.jetbrains.kotlin.codegen.state.GenerationState import org.jetbrains.kotlin.codegen.state.GenerationState
import org.jetbrains.kotlin.config.CompilerConfiguration import org.jetbrains.kotlin.config.CompilerConfiguration
import org.jetbrains.kotlin.descriptors.ModuleDescriptor import org.jetbrains.kotlin.descriptors.ModuleDescriptor
@@ -255,15 +255,12 @@ abstract class AbstractKapt3Extension(
if (stubFileObject != null) { if (stubFileObject != null) {
val stubFile = File(stubsOutputDir, stubFileObject.name) val stubFile = File(stubsOutputDir, stubFileObject.name)
if (stubFile.exists()) { if (stubFile.exists()) {
messageCollector.report(CompilerMessageSeverity.OUTPUT, messageCollector.report(CompilerMessageSeverity.OUTPUT, OutputMessageUtil.formatOutputMessage(sources, stubFile))
OutputMessageUtil.formatOutputMessage(sources, stubFile), CompilerMessageLocation.NO_LOCATION)
} }
} }
messageCollector.report(CompilerMessageSeverity.OUTPUT, messageCollector.report(CompilerMessageSeverity.OUTPUT, OutputMessageUtil.formatOutputMessage(sources, output))
OutputMessageUtil.formatOutputMessage(sources, output), CompilerMessageLocation.NO_LOCATION)
} }
} }
protected abstract fun loadProcessors(): List<Processor> protected abstract fun loadProcessors(): List<Processor>
@@ -273,4 +270,4 @@ private inline fun <T> measureTimeMillis(block: () -> T) : Pair<Long, T> {
val start = System.currentTimeMillis() val start = System.currentTimeMillis()
val result = block() val result = block()
return Pair(System.currentTimeMillis() - start, result) return Pair(System.currentTimeMillis() - start, result)
} }
@@ -16,8 +16,10 @@
package org.jetbrains.kotlin.kapt3.util package org.jetbrains.kotlin.kapt3.util
import org.jetbrains.kotlin.cli.common.messages.* import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity
import java.io.ByteArrayOutputStream import org.jetbrains.kotlin.cli.common.messages.MessageCollector
import org.jetbrains.kotlin.cli.common.messages.MessageRenderer
import org.jetbrains.kotlin.cli.common.messages.PrintingMessageCollector
import java.io.PrintWriter import java.io.PrintWriter
import java.io.StringWriter import java.io.StringWriter
@@ -31,7 +33,7 @@ class KaptLogger(
fun info(message: String) { fun info(message: String) {
if (isVerbose) { if (isVerbose) {
messageCollector.report(CompilerMessageSeverity.INFO, PREFIX + message, CompilerMessageLocation.NO_LOCATION) messageCollector.report(CompilerMessageSeverity.INFO, PREFIX + message)
} }
} }
@@ -42,11 +44,11 @@ class KaptLogger(
} }
fun warn(message: String) { fun warn(message: String) {
messageCollector.report(CompilerMessageSeverity.WARNING, PREFIX + message, CompilerMessageLocation.NO_LOCATION) messageCollector.report(CompilerMessageSeverity.WARNING, PREFIX + message)
} }
fun error(message: String) { fun error(message: String) {
messageCollector.report(CompilerMessageSeverity.ERROR, PREFIX + message, CompilerMessageLocation.NO_LOCATION) messageCollector.report(CompilerMessageSeverity.ERROR, PREFIX + message)
} }
fun exception(e: Throwable) { fun exception(e: Throwable) {
@@ -55,6 +57,6 @@ class KaptLogger(
e.printStackTrace(PrintWriter(writer)) e.printStackTrace(PrintWriter(writer))
writer.toString() writer.toString()
} }
messageCollector.report(CompilerMessageSeverity.EXCEPTION, PREFIX + "An exception occurred: " + stacktrace, CompilerMessageLocation.NO_LOCATION) messageCollector.report(CompilerMessageSeverity.EXCEPTION, PREFIX + "An exception occurred: " + stacktrace)
} }
} }
@@ -16,7 +16,6 @@
package org.jetbrains.kotlin.kapt3.util package org.jetbrains.kotlin.kapt3.util
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageLocation
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity
import org.jetbrains.kotlin.cli.common.messages.GroupingMessageCollector import org.jetbrains.kotlin.cli.common.messages.GroupingMessageCollector
import org.jetbrains.kotlin.cli.common.messages.MessageCollector import org.jetbrains.kotlin.cli.common.messages.MessageCollector
@@ -24,7 +23,7 @@ import java.io.Writer
class MessageCollectorBackedWriter(val messageCollector: MessageCollector, val severity: CompilerMessageSeverity) : Writer() { class MessageCollectorBackedWriter(val messageCollector: MessageCollector, val severity: CompilerMessageSeverity) : Writer() {
override fun write(buffer: CharArray, offset: Int, length: Int) { override fun write(buffer: CharArray, offset: Int, length: Int) {
messageCollector.report(severity, String(buffer, offset, length), CompilerMessageLocation.NO_LOCATION) messageCollector.report(severity, String(buffer, offset, length))
} }
override fun flush() { override fun flush() {
@@ -36,4 +35,4 @@ class MessageCollectorBackedWriter(val messageCollector: MessageCollector, val s
override fun close() { override fun close() {
flush() flush()
} }
} }
@@ -279,8 +279,7 @@ internal fun<T> captureOut(body: () -> T): Pair<String, T> {
} }
class TestMessageCollector : MessageCollector { class TestMessageCollector : MessageCollector {
data class Message(val severity: CompilerMessageSeverity, val message: String, val location: CompilerMessageLocation?)
data class Message(val severity: CompilerMessageSeverity, val message: String, val location: CompilerMessageLocation)
val messages = arrayListOf<Message>() val messages = arrayListOf<Message>()
@@ -288,7 +287,7 @@ class TestMessageCollector : MessageCollector {
messages.clear() messages.clear()
} }
override fun report(severity: CompilerMessageSeverity, message: String, location: CompilerMessageLocation) { override fun report(severity: CompilerMessageSeverity, message: String, location: CompilerMessageLocation?) {
messages.add(Message(severity, message, location)) messages.add(Message(severity, message, location))
} }