Skip to content

Commit b5631da

Browse files
authored
Improve javac error output parsing - Fix #336 (#337)
Instead of two separate 'while' loops, one inline and one in an extra method, parsing stack traces after finding error messages specific to the English locale of the JDK, now there is generic stack trace parsing, which works in these two cases independent of locale and also in others previously not covered. For backward compatibility, the Javac localized message 'javac.msg.bug' ("An exception has occurred in the compiler ... Please file a bug") is salvaged in a locale-independent way, matching on error reporting URLs always occurring in all JDK locales (English, Japanese, Chinese, German as of JDK 21). Fixes #336
1 parent b37ca33 commit b5631da

File tree

4 files changed

+188
-69
lines changed

4 files changed

+188
-69
lines changed

plexus-compilers/plexus-compiler-javac/pom.xml

+5
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,11 @@
2727
<artifactId>junit-jupiter-api</artifactId>
2828
<scope>test</scope>
2929
</dependency>
30+
<dependency>
31+
<groupId>org.junit.jupiter</groupId>
32+
<artifactId>junit-jupiter-params</artifactId>
33+
<scope>test</scope>
34+
</dependency>
3035
<dependency>
3136
<groupId>org.hamcrest</groupId>
3237
<artifactId>hamcrest</artifactId>

plexus-compilers/plexus-compiler-javac/src/main/java/org/codehaus/plexus/compiler/javac/JavacCompiler.java

+46-31
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,7 @@
6565
import java.util.Properties;
6666
import java.util.StringTokenizer;
6767
import java.util.concurrent.ConcurrentLinkedDeque;
68+
import java.util.regex.Pattern;
6869

6970
import org.codehaus.plexus.compiler.AbstractCompiler;
7071
import org.codehaus.plexus.compiler.CompilerConfiguration;
@@ -627,6 +628,16 @@ private static CompilerResult compileInProcess0(Class<?> javacClass, String[] ar
627628
return new CompilerResult(success, messages);
628629
}
629630

631+
// Match ~95% of existing JDK exception name patterns (last checked for JDK 21)
632+
private static final Pattern STACK_TRACE_FIRST_LINE = Pattern.compile("^(?:[\\w+.-]+\\.)[\\w$]*?(?:"
633+
+ "Exception|Error|Throwable|Failure|Result|Abort|Fault|ThreadDeath|Overflow|Warning|"
634+
+ "NotSupported|NotFound|BadArgs|BadClassFile|Illegal|Invalid|Unexpected|Unchecked|Unmatched\\w+"
635+
+ ").*$");
636+
637+
// Match exception causes, existing and omitted stack trace elements
638+
private static final Pattern STACK_TRACE_OTHER_LINE =
639+
Pattern.compile("^(?:Caused by:\\s.*|\\s*at .*|\\s*\\.\\.\\.\\s\\d+\\smore)$");
640+
630641
/**
631642
* Parse the output from the compiler into a list of CompilerMessage objects
632643
*
@@ -643,13 +654,14 @@ static List<CompilerMessage> parseModernStream(int exitCode, BufferedReader inpu
643654
StringBuilder buffer = new StringBuilder();
644655

645656
boolean hasPointer = false;
657+
int stackTraceLineCount = 0;
646658

647659
while (true) {
648660
line = input.readLine();
649661

650662
if (line == null) {
651663
// javac output not detected by other parsing
652-
// maybe better to ignore only the summary an mark the rest as error
664+
// maybe better to ignore only the summary and mark the rest as error
653665
String bufferAsString = buffer.toString();
654666
if (buffer.length() > 0) {
655667
if (bufferAsString.startsWith("javac:")) {
@@ -659,26 +671,44 @@ static List<CompilerMessage> parseModernStream(int exitCode, BufferedReader inpu
659671
} else if (hasPointer) {
660672
// A compiler message remains in buffer at end of parse stream
661673
errors.add(parseModernError(exitCode, bufferAsString));
674+
} else if (stackTraceLineCount > 0) {
675+
// Extract stack trace from end of buffer
676+
String[] lines = bufferAsString.split("\\R");
677+
int linesTotal = lines.length;
678+
buffer = new StringBuilder();
679+
int firstLine = linesTotal - stackTraceLineCount;
680+
681+
// Salvage Javac localized message 'javac.msg.bug' ("An exception has occurred in the
682+
// compiler ... Please file a bug")
683+
if (firstLine > 0) {
684+
final String lineBeforeStackTrace = lines[firstLine - 1];
685+
// One of those two URL substrings should always appear, without regard to JVM locale.
686+
// TODO: Update, if the URL changes, last checked for JDK 21.
687+
if (lineBeforeStackTrace.contains("java.sun.com/webapps/bugreport")
688+
|| lineBeforeStackTrace.contains("bugreport.java.com")) {
689+
firstLine--;
690+
}
691+
}
692+
693+
// Note: For message 'javac.msg.proc.annotation.uncaught.exception' ("An annotation processor
694+
// threw an uncaught exception"), there is no locale-independent substring, and the header is
695+
// also multi-line. It was discarded in the removed method 'parseAnnotationProcessorStream',
696+
// and we continue to do so.
697+
698+
for (int i = firstLine; i < linesTotal; i++) {
699+
buffer.append(lines[i]).append(EOL);
700+
}
701+
errors.add(new CompilerMessage(buffer.toString(), CompilerMessage.Kind.ERROR));
662702
}
663703
}
664704
return errors;
665705
}
666706

667-
// A compiler error occurred, treat everything that follows as part of the error.
668-
if (line.startsWith("An exception has occurred in the compiler")) {
669-
buffer = new StringBuilder();
670-
671-
while (line != null) {
672-
buffer.append(line);
673-
buffer.append(EOL);
674-
line = input.readLine();
675-
}
676-
677-
errors.add(new CompilerMessage(buffer.toString(), CompilerMessage.Kind.ERROR));
678-
return errors;
679-
} else if (line.startsWith("An annotation processor threw an uncaught exception.")) {
680-
CompilerMessage annotationProcessingError = parseAnnotationProcessorStream(input);
681-
errors.add(annotationProcessingError);
707+
if (stackTraceLineCount == 0 && STACK_TRACE_FIRST_LINE.matcher(line).matches()
708+
|| STACK_TRACE_OTHER_LINE.matcher(line).matches()) {
709+
stackTraceLineCount++;
710+
} else {
711+
stackTraceLineCount = 0;
682712
}
683713

684714
// new error block?
@@ -714,21 +744,6 @@ static List<CompilerMessage> parseModernStream(int exitCode, BufferedReader inpu
714744
}
715745
}
716746

717-
private static CompilerMessage parseAnnotationProcessorStream(final BufferedReader input) throws IOException {
718-
String line = input.readLine();
719-
final StringBuilder buffer = new StringBuilder();
720-
721-
while (line != null) {
722-
if (!line.startsWith("Consult the following stack trace for details.")) {
723-
buffer.append(line);
724-
buffer.append(EOL);
725-
}
726-
line = input.readLine();
727-
}
728-
729-
return new CompilerMessage(buffer.toString(), CompilerMessage.Kind.ERROR);
730-
}
731-
732747
private static boolean isMisc(String line) {
733748
return startsWithPrefix(line, MISC_PREFIXES);
734749
}

plexus-compilers/plexus-compiler-javac/src/test/java/org/codehaus/plexus/compiler/javac/ErrorMessageParserTest.java

+77-12
Original file line numberDiff line numberDiff line change
@@ -28,20 +28,25 @@
2828
import java.io.StringReader;
2929
import java.util.ArrayList;
3030
import java.util.List;
31+
import java.util.stream.Stream;
3132

3233
import org.codehaus.plexus.compiler.CompilerMessage;
3334
import org.codehaus.plexus.util.Os;
3435
import org.junit.jupiter.api.Test;
36+
import org.junit.jupiter.params.ParameterizedTest;
37+
import org.junit.jupiter.params.provider.Arguments;
38+
import org.junit.jupiter.params.provider.MethodSource;
3539

40+
import static org.hamcrest.CoreMatchers.endsWith;
41+
import static org.hamcrest.CoreMatchers.startsWith;
3642
import static org.hamcrest.MatcherAssert.assertThat;
3743
import static org.hamcrest.Matchers.hasSize;
3844
import static org.hamcrest.Matchers.is;
3945
import static org.hamcrest.Matchers.notNullValue;
40-
import static org.hamcrest.core.StringEndsWith.endsWith;
41-
import static org.hamcrest.core.StringStartsWith.startsWith;
4246

4347
/**
4448
* @author <a href="mailto:trygvis@inamo.no">Trygve Laugst&oslash;l</a>
49+
* @author Alexander Kriegisch
4550
*/
4651
public class ErrorMessageParserTest {
4752
private static final String EOL = System.getProperty("line.separator");
@@ -775,19 +780,79 @@ public void testJava7Error() throws Exception {
775780
assertThat(message2.getEndLine(), is(3));
776781
}
777782

778-
@Test
779-
public void testBugParade() throws Exception {
780-
String out = "An exception has occurred in the compiler (1.7.0_80). "
781-
+ "Please file a bug at the Java Developer Connection (http://java.sun.com/webapps/bugreport) after checking the Bug Parade for duplicates. "
782-
+ "Include your program and the following diagnostic in your report. Thank you." + EOL
783-
+ "com.sun.tools.javac.code.Symbol$CompletionFailure: class file for java.util.Optional not found";
783+
@ParameterizedTest(name = "{0}")
784+
@MethodSource("testBugParade_args")
785+
public void testBugParade(String jdkAndLocale, String stackTraceHeader) throws Exception {
786+
String stackTraceWithHeader = stackTraceHeader + stackTraceInternalCompilerError;
784787

785-
List<CompilerMessage> compilerErrors =
786-
JavacCompiler.parseModernStream(4, new BufferedReader(new StringReader(out)));
788+
List<CompilerMessage> compilerMessages =
789+
JavacCompiler.parseModernStream(4, new BufferedReader(new StringReader(stackTraceWithHeader)));
787790

788-
assertThat(compilerErrors, notNullValue());
791+
assertThat(compilerMessages, notNullValue());
792+
assertThat(compilerMessages, hasSize(1));
789793

790-
assertThat(compilerErrors.size(), is(1));
794+
String message = compilerMessages.get(0).getMessage().replaceAll(EOL, "\n");
795+
// Parser retains stack trace header
796+
assertThat(message, startsWith(stackTraceHeader));
797+
assertThat(message, endsWith(stackTraceInternalCompilerError));
798+
}
799+
800+
private static final String stackTraceInternalCompilerError =
801+
"\tat com.sun.tools.javac.comp.MemberEnter.baseEnv(MemberEnter.java:1388)\n"
802+
+ "\tat com.sun.tools.javac.comp.MemberEnter.complete(MemberEnter.java:1046)\n"
803+
+ "\tat com.sun.tools.javac.code.Symbol.complete(Symbol.java:574)\n"
804+
+ "\tat com.sun.tools.javac.code.Symbol$ClassSymbol.complete(Symbol.java:1037)\n"
805+
+ "\tat com.sun.tools.javac.code.Symbol$ClassSymbol.flags(Symbol.java:973)\n"
806+
+ "\tat com.sun.tools.javac.code.Symbol$ClassSymbol.getKind(Symbol.java:1101)\n"
807+
+ "\tat com.sun.tools.javac.code.Kinds.kindName(Kinds.java:162)\n"
808+
+ "\tat com.sun.tools.javac.comp.Check.duplicateError(Check.java:329)\n"
809+
+ "\tat com.sun.tools.javac.comp.Check.checkUnique(Check.java:3435)\n"
810+
+ "\tat com.sun.tools.javac.comp.Enter.visitTypeParameter(Enter.java:454)\n"
811+
+ "\tat com.sun.tools.javac.tree.JCTree$JCTypeParameter.accept(JCTree.java:2224)\n"
812+
+ "\tat com.sun.tools.javac.comp.Enter.classEnter(Enter.java:258)\n"
813+
+ "\tat com.sun.tools.javac.comp.Enter.classEnter(Enter.java:272)\n"
814+
+ "\tat com.sun.tools.javac.comp.Enter.visitClassDef(Enter.java:418)\n"
815+
+ "\tat com.sun.tools.javac.tree.JCTree$JCClassDecl.accept(JCTree.java:693)\n"
816+
+ "\tat com.sun.tools.javac.comp.Enter.classEnter(Enter.java:258)\n"
817+
+ "\tat com.sun.tools.javac.comp.Enter.classEnter(Enter.java:272)\n"
818+
+ "\tat com.sun.tools.javac.comp.Enter.visitTopLevel(Enter.java:334)\n"
819+
+ "\tat com.sun.tools.javac.tree.JCTree$JCCompilationUnit.accept(JCTree.java:518)\n"
820+
+ "\tat com.sun.tools.javac.comp.Enter.classEnter(Enter.java:258)\n"
821+
+ "\tat com.sun.tools.javac.comp.Enter.classEnter(Enter.java:272)\n"
822+
+ "\tat com.sun.tools.javac.comp.Enter.complete(Enter.java:486)\n"
823+
+ "\tat com.sun.tools.javac.comp.Enter.main(Enter.java:471)\n"
824+
+ "\tat com.sun.tools.javac.main.JavaCompiler.enterTrees(JavaCompiler.java:982)\n"
825+
+ "\tat com.sun.tools.javac.main.JavaCompiler.compile(JavaCompiler.java:857)\n"
826+
+ "\tat com.sun.tools.javac.main.Main.compile(Main.java:523)\n"
827+
+ "\tat com.sun.tools.javac.main.Main.compile(Main.java:381)\n"
828+
+ "\tat com.sun.tools.javac.main.Main.compile(Main.java:370)\n"
829+
+ "\tat com.sun.tools.javac.main.Main.compile(Main.java:361)\n"
830+
+ "\tat com.sun.tools.javac.Main.compile(Main.java:56)\n"
831+
+ "\tat com.sun.tools.javac.Main.main(Main.java:42)\n";
832+
833+
private static Stream<Arguments> testBugParade_args() {
834+
return Stream.of(
835+
Arguments.of(
836+
"JDK 8 English",
837+
"An exception has occurred in the compiler ({0}). Please file a bug at the Java Developer Connection (http://java.sun.com/webapps/bugreport) after checking the Bug Parade for duplicates. Include your program and the following diagnostic in your report. Thank you.\n"),
838+
Arguments.of(
839+
"JDK 8 Japanese",
840+
"コンパイラで例外が発生しました({0})。Bug Paradeで重複がないかをご確認のうえ、Java Developer Connection (http://java.sun.com/webapps/bugreport)でbugの登録をお願いいたします。レポートには、そのプログラムと下記の診断内容を含めてください。ご協力ありがとうございます。\n"),
841+
Arguments.of(
842+
"JDK 8 Chinese",
843+
"编译器 ({0}) 中出现异常错误。 如果在 Bug Parade 中没有找到该错误, 请在 Java Developer Connection (http://java.sun.com/webapps/bugreport) 中建立 Bug。请在报告中附上您的程序和以下诊断信息。谢谢。\n"),
844+
Arguments.of(
845+
"JDK 21 English",
846+
"An exception has occurred in the compiler ({0}). Please file a bug against the Java compiler via the Java bug reporting page (https://bugreport.java.com) after checking the Bug Database (https://bugs.java.com) for duplicates. Include your program, the following diagnostic, and the parameters passed to the Java compiler in your report. Thank you.\n"),
847+
Arguments.of(
848+
"JDK 21 Japanese",
849+
"コンパイラで例外が発生しました({0})。バグ・データベース(https://bugs.java.com)で重複がないかをご確認のうえ、Javaのバグ・レポート・ページ(https://bugreport.java.com)から、Javaコンパイラに対するバグの登録をお願いいたします。レポートには、該当のプログラム、次の診断内容、およびJavaコンパイラに渡されたパラメータをご入力ください。ご協力ありがとうございます。\n"),
850+
Arguments.of(
851+
"JDK 21 Chinese",
852+
"编译器 ({0}) 中出现异常错误。如果在 Bug Database (https://bugs.java.com) 中没有找到有关该错误的 Java 编译器 Bug,请通过 Java Bug 报告页 (https://bugreport.java.com) 提交 Java 编译器 Bug。请在报告中附上您的程序、以下诊断信息以及传递到 Java 编译器的参数。谢谢。\n"),
853+
Arguments.of(
854+
"JDK 21 German",
855+
"Im Compiler ({0}) ist eine Ausnahme aufgetreten. Erstellen Sie auf der Java-Seite zum Melden von Bugs (https://bugreport.java.com) einen Bugbericht, nachdem Sie die Bugdatenbank (https://bugs.java.com) auf Duplikate geprüft haben. Geben Sie in Ihrem Bericht Ihr Programm, die folgende Diagnose und die Parameter an, die Sie dem Java-Compiler übergeben haben. Vielen Dank.\n"));
791856
}
792857

793858
@Test

0 commit comments

Comments
 (0)