From a95b881bd126714aae5bd562ec4bd532768ebe30 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Tue, 6 Oct 2026 17:06:41 -0700 Subject: [PATCH 01/16] Reject bad command-line options with a non-zero exit status Add DaikonGetopt, a Getopt subclass that throws a UserError describing an unrecognized, ambiguous, or malformed option and handles -h and --help. Use it in Daikon and in the other tools that use Getopt. Remove Diff's -u and -z options, which had no effect. Co-Authored-By: Claude Opus 5.5 --- doc/CHANGELOG.md | 9 + doc/daikon.texinfo | 3 - java/Makefile | 2 +- java/daikon/Daikon.java | 18 +- java/daikon/DaikonGetopt.java | 279 ++++++++++++++++++ java/daikon/MergeInvariants.java | 21 +- java/daikon/PrintInvariants.java | 19 +- java/daikon/UnionInvariants.java | 18 +- java/daikon/diff/Diff.java | 40 +-- java/daikon/test/AllTestsSuite.java | 1 + java/daikon/test/BadOptionTest.java | 199 +++++++++++++ java/daikon/test/SampleTester.java | 47 +-- .../split/SplitterFactoryTestUpdater.java | 50 ++-- java/daikon/tools/DtraceDiff.java | 20 +- java/daikon/tools/ExtractConsequent.java | 18 +- java/daikon/tools/InvariantChecker.java | 19 +- java/daikon/tools/compare/LogicalCompare.java | 19 +- java/daikon/tools/jtb/Annotate.java | 24 +- java/daikon/tools/jtb/CreateSpinfo.java | 18 +- tests/diff-tests/Makefile.common | 4 +- tests/diff-tests/StackAr/StackAr-u.txt.goal | 105 ------- .../diff-tests/schedule2/schedule2-u.txt.goal | 77 ----- 22 files changed, 610 insertions(+), 400 deletions(-) create mode 100644 java/daikon/DaikonGetopt.java create mode 100644 java/daikon/test/BadOptionTest.java delete mode 100644 tests/diff-tests/StackAr/StackAr-u.txt.goal delete mode 100644 tests/diff-tests/schedule2/schedule2-u.txt.goal diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 6db6daed42..6aa334f3e8 100644 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -21,6 +21,15 @@ Further documentation can be found in: `make -C $DAIKONDIR/java javadoc` It is also available at . +## Version 5.9.1 (???, 2026) + +* Daikon and its tools now reject an unrecognized, ambiguous, or malformed + command-line option: they describe the problem and exit with a non-zero + status. Previously, Daikon printed its usage message and exited with + status 0, and most other tools ignored the bad option and continued. +* `daikon.diff.Diff` no longer accepts the `-u` and `-z` options, which had + no effect. + ## Version 5.9.0 (September 1, 2026) * All Daikon tools now work with Java 8-26. diff --git a/doc/daikon.texinfo b/doc/daikon.texinfo index 2c7d2f72e6..63824ae74e 100644 --- a/doc/daikon.texinfo +++ b/doc/daikon.texinfo @@ -6749,9 +6749,6 @@ invariants must be justified. Does not print ``uninteresting'' invariants Display the tree of all invariants. Includes invariants that are the same in @var{file1} and @var{file2}, and unjustified invariants. -@item -u -Include ``uninteresting'' invariants in the tree of differing invariants. - @item -y @itemx --ignore_unjustified Include (statistically) unjustified invariants. diff --git a/java/Makefile b/java/Makefile index a259f02945..675725091f 100644 --- a/java/Makefile +++ b/java/Makefile @@ -181,7 +181,7 @@ JAVADOC_COMMAND := ${JAVADOC} -cp ${DAIKON_CLASSPATH} JAVAC_COMMAND := ${JAVAC} -cp ${DAIKON_CLASSPATH} -Xlint -J-Xmx7g ${JAVAC_ARGS} JAVA_COMMAND := ${JAVA} -cp ${DAIKON_CLASSPATH} -DOCLETPATH := ${DAIKONDIR}/java:$(wildcard ${DAIKONDIR}/java/lib/bcel-util-*.jar):$(wildcard ${DAIKONDIR}/java/lib/plume-util-*.jar):$(wildcard ${DAIKONDIR}/java/lib/reflection-util-*.jar):$(wildcard ${DAIKONDIR}/java/lib/hashmap-util-*.jar):${DAIKONDIR}/java/lib/daikon-plumelib.jar +DOCLETPATH := ${DAIKONDIR}/java:$(wildcard ${DAIKONDIR}/java/lib/java-getopt-*.jar):$(wildcard ${DAIKONDIR}/java/lib/bcel-util-*.jar):$(wildcard ${DAIKONDIR}/java/lib/plume-util-*.jar):$(wildcard ${DAIKONDIR}/java/lib/reflection-util-*.jar):$(wildcard ${DAIKONDIR}/java/lib/hashmap-util-*.jar):${DAIKONDIR}/java/lib/daikon-plumelib.jar DOCLET_FLAGS := LINKOFFLINE := https://docs.oracle.com/javase/8/docs/api/ diff --git a/java/daikon/Daikon.java b/java/daikon/Daikon.java index 1e7c1e1b73..aaa2b3f3d6 100644 --- a/java/daikon/Daikon.java +++ b/java/daikon/Daikon.java @@ -1022,7 +1022,6 @@ static FileOptions read_options(String[] args, String usage) { LongOpt[] longopts = new LongOpt[] { // Control output - new LongOpt(help_SWITCH, LongOpt.NO_ARGUMENT, null, 0), new LongOpt(no_text_output_SWITCH, LongOpt.NO_ARGUMENT, null, 0), new LongOpt(format_SWITCH, LongOpt.REQUIRED_ARGUMENT, null, 0), new LongOpt(show_progress_SWITCH, LongOpt.NO_ARGUMENT, null, 0), @@ -1055,7 +1054,7 @@ static FileOptions read_options(String[] args, String usage) { new LongOpt(disc_reason_SWITCH, LongOpt.REQUIRED_ARGUMENT, null, 0), new LongOpt(mem_stat_SWITCH, LongOpt.NO_ARGUMENT, null, 0), }; - Getopt g = new Getopt("daikon.Daikon", args, "ho:", longopts); + DaikonGetopt g = new DaikonGetopt(args, "o:", longopts, usage); int c; while ((c = g.getopt()) != -1) { @@ -1065,10 +1064,7 @@ static FileOptions read_options(String[] args, String usage) { String option_name = longopts[g.getLongind()].getName(); // Control output - if (help_SWITCH.equals(option_name)) { - System.out.println(usage); - throw new Daikon.NormalTermination(); - } else if (no_text_output_SWITCH.equals(option_name)) { + if (no_text_output_SWITCH.equals(option_name)) { no_text_output = true; } else if (format_SWITCH.equals(option_name)) { String format_name = getOptarg(g); @@ -1367,12 +1363,9 @@ else if (ppt_regexp_SWITCH.equals(option_name)) { } else if (mem_stat_SWITCH.equals(option_name)) { use_mem_monitor = true; } else { - throw new Daikon.UserError("Unknown option " + option_name + " on command line"); + throw new Daikon.BugInDaikon("Unhandled long option " + option_name); } break; - case 'h': - System.out.println(usage); - throw new Daikon.NormalTermination(); case 'o': String inv_filename = getOptarg(g); @@ -1391,11 +1384,6 @@ else if (ppt_regexp_SWITCH.equals(option_name)) { } break; // - case '?': - // break; // getopt() already printed an error - System.out.println(usage); - throw new Daikon.NormalTermination(); - // default: throw new Daikon.BugInDaikon("getopt() returned " + c); } diff --git a/java/daikon/DaikonGetopt.java b/java/daikon/DaikonGetopt.java new file mode 100644 index 0000000000..0f71e31406 --- /dev/null +++ b/java/daikon/DaikonGetopt.java @@ -0,0 +1,279 @@ +package daikon; + +import gnu.getopt.Getopt; +import gnu.getopt.LongOpt; +import java.util.Arrays; +import java.util.function.Supplier; +import org.checkerframework.checker.nullness.qual.Nullable; +import org.plumelib.util.ArraysPlume; + +/** + * A command-line option processor that throws a {@link Daikon.UserError} that describes a bad + * command-line option, instead of printing a message and returning {@code '?'} or {@code ':'}. + * + *

If constructed with a usage message, it also handles {@code -h} and {@code --help}: it prints + * the usage message and throws {@link Daikon.NormalTermination}. + */ +public class DaikonGetopt extends Getopt { + + /** + * The name passed to {@link Getopt}, which uses it only in messages that DaikonGetopt suppresses. + */ + private static final String PROGNAME = "DaikonGetopt"; + + /** + * Computes the usage message printed for {@code -h} and {@code --help}, or null if the caller + * handles them. + */ + private final @Nullable Supplier usage; + + /** Text appended to the description of a bad command-line option, or null to append nothing. */ + private @Nullable String usageHint = "run with -h for usage"; + + /** + * Creates a command-line option processor that recognizes short and long options. + * + * @param argv the command-line arguments + * @param optstring the short options, in the format of {@link Getopt} + * @param longopts the long options + */ + public DaikonGetopt(String[] argv, String optstring, LongOpt[] longopts) { + super(PROGNAME, argv, optstring, longopts); + this.usage = null; + opterr = false; + } + + /** + * Creates a command-line option processor that recognizes short and long options, plus {@code -h} + * and {@code --help}, which print the usage message and throw {@link Daikon.NormalTermination}. + * + * @param argv the command-line arguments + * @param optstring the short options, in the format of {@link Getopt}; must not contain {@code h} + * @param longopts the long options; must not contain {@code help} + * @param usage the usage message to print for {@code -h} and {@code --help} + */ + public DaikonGetopt(String[] argv, String optstring, LongOpt[] longopts, String usage) { + this(argv, optstring, longopts, () -> usage); + } + + /** + * Creates a command-line option processor that recognizes short and long options, plus {@code -h} + * and {@code --help}, which print the usage message and throw {@link Daikon.NormalTermination}. + * The usage message is computed only if it is needed. + * + * @param argv the command-line arguments + * @param optstring the short options, in the format of {@link Getopt}; must not contain {@code h} + * @param longopts the long options; must not contain {@code help} + * @param usage computes the usage message to print for {@code -h} and {@code --help} + */ + public DaikonGetopt(String[] argv, String optstring, LongOpt[] longopts, Supplier usage) { + super(PROGNAME, argv, withH(optstring), withHelp(longopts)); + this.usage = usage; + opterr = false; + } + + /** + * Returns the given short options plus {@code -h}. + * + * @param optstring short options, in the format of {@link Getopt}; must not contain {@code h} + * @return {@code optstring} plus {@code -h} + */ + private static String withH(String optstring) { + if (optstring.indexOf('h') != -1) { + throw new IllegalArgumentException("optstring already contains h: " + optstring); + } + return optstring + "h"; + } + + /** + * Returns the given long options plus {@code --help}. + * + * @param longopts long options; must not contain {@code help} + * @return {@code longopts} plus {@code --help} + */ + private static LongOpt[] withHelp(LongOpt[] longopts) { + for (LongOpt longopt : longopts) { + if (longopt.getName().equals(Daikon.help_SWITCH)) { + throw new IllegalArgumentException("longopts already contains " + Daikon.help_SWITCH); + } + } + return ArraysPlume.append( + longopts, new LongOpt(Daikon.help_SWITCH, LongOpt.NO_ARGUMENT, null, 'h')); + } + + /** + * Processes the command-line arguments of a program that takes no options other than {@code -h} + * and {@code --help}. + * + * @param argv the command-line arguments + * @param usage the usage message to print for {@code -h} and {@code --help} + * @return the arguments that are not options + * @throws Daikon.NormalTermination after printing the usage message, if an argument requests it + * @throws Daikon.UserError if an argument is any other option + */ + public static String[] nonOptionArgs(String[] argv, String usage) { + return argsAfterOptions(argv, "", () -> usage); + } + + /** + * Processes the leading command-line arguments of a program that takes no options other than + * {@code -h} and {@code --help}. Processing stops at the first argument that is not an option, so + * later arguments may be options for some other program. + * + * @param argv the command-line arguments + * @param usage the usage message to print for {@code -h} and {@code --help} + * @return the arguments from the first one that is not an option onward + * @throws Daikon.NormalTermination after printing the usage message, if a leading argument + * requests it + * @throws Daikon.UserError if a leading argument is any other option + */ + public static String[] argsAfterLeadingOptions(String[] argv, String usage) { + return argsAfterLeadingOptions(argv, () -> usage); + } + + /** + * Like {@link #argsAfterLeadingOptions(String[], String)}, but computes the usage message only if + * it is needed. + * + * @param argv the command-line arguments + * @param usage computes the usage message to print for {@code -h} and {@code --help} + * @return the arguments from the first one that is not an option onward + * @throws Daikon.NormalTermination after printing the usage message, if a leading argument + * requests it + * @throws Daikon.UserError if a leading argument is any other option + */ + public static String[] argsAfterLeadingOptions(String[] argv, Supplier usage) { + // A leading "+" tells Getopt to stop at the first argument that is not an option. + return argsAfterOptions(argv, "+", usage); + } + + /** + * Processes command-line arguments, permitting no options other than {@code -h} and {@code + * --help}. + * + * @param argv the command-line arguments + * @param optstring "" to process all the arguments, or "+" to stop at the first non-option + * @param usage computes the usage message to print for {@code -h} and {@code --help} + * @return the arguments that Getopt did not process as options + * @throws Daikon.NormalTermination after printing the usage message, if an argument requests it + * @throws Daikon.UserError if an argument is any other option + */ + private static String[] argsAfterOptions( + String[] argv, String optstring, Supplier usage) { + // Getopt permutes its argument array, so give it a copy to avoid modifying the caller's array. + String[] argvCopy = argv.clone(); + DaikonGetopt g = new DaikonGetopt(argvCopy, optstring, new LongOpt[0], usage); + // Every option other than -h and --help is bad, so getopt() returns only -1 or throws. + int c = g.getopt(); + if (c != -1) { + throw new Daikon.BugInDaikon("getopt() returned " + c); + } + return Arrays.copyOfRange(argvCopy, g.getOptind(), argvCopy.length); + } + + /** + * Sets the text that is appended to the description of a bad command-line option. The default + * tells the user to run the program with -h. + * + * @param usageHint text appended to the description of a bad command-line option, or null to + * append nothing + */ + public void setUsageHint(@Nullable String usageHint) { + this.usageHint = usageHint; + } + + /** + * Like {@link Getopt#getopt()}, but never returns {@code '?'} or {@code ':'}. Getopt returns + * {@code ':'} for a missing argument if the optstring starts with {@code ':'}. If this was + * constructed with a usage message, also never returns {@code 'h'}. + * + * @return the next option, as described in {@link Getopt#getopt()} + * @throws Daikon.UserError if the next option is unrecognized, ambiguous, or malformed + * @throws Daikon.NormalTermination after printing the usage message, if the next option is {@code + * -h} or {@code --help} and this was constructed with a usage message + */ + @Override + public int getopt() { + int c = super.getopt(); + if (c == '?' || c == ':') { + throw badOptionError(); + } + if (c == 'h' && usage != null) { + System.out.println(usage.get()); + throw new Daikon.NormalTermination(); + } + return c; + } + + /** + * Returns an exception that describes the bad command-line option that {@link Getopt#getopt()} + * just rejected. + * + * @return an exception that describes the bad command-line option + */ + private Daikon.UserError badOptionError() { + String message = badOptionMessage(); + if (usageHint != null) { + message += "; " + usageHint; + } + return new Daikon.UserError(message); + } + + /** + * Returns a description of the bad command-line option that {@link Getopt#getopt()} just + * rejected. + * + * @return a description of the bad command-line option + */ + private String badOptionMessage() { + // For every bad long option, Getopt clears nextchar and advances optind past the option. A + // bad short option has no such guarantee, because it may be followed by other short options in + // the same argument, as in "-xh". + if ("".equals(nextchar) && argv[optind - 1].startsWith("--")) { + return longOptionMessage(argv[optind - 1]); + } + char c = (char) optopt; + if (c == ':' || optstring.indexOf(c) == -1) { + return "Unrecognized command-line option -" + c; + } else { + return "Command-line option -" + c + " requires an argument"; + } + } + + /** + * Returns a description of a bad long command-line option. Uses {@code longind}, which Getopt + * sets to the index of the long option that matched the argument, or to -1 if none matched. + * + * @param arg the bad command-line argument, which starts with "--" + * @return a description of the bad command-line option + */ + private String longOptionMessage(String arg) { + int equalsPos = arg.indexOf('='); + String name = (equalsPos == -1) ? arg.substring(2) : arg.substring(2, equalsPos); + LongOpt[] longopts = long_options; + // Getopt treats an empty name, as in "--=foo", as a prefix of every long option. + if (name.isEmpty()) { + return "Unrecognized command-line option " + arg; + } + if (longopts == null || longind == -1) { + return "Unrecognized command-line option --" + name; + } + LongOpt match = longopts[longind]; + // For an inexact match, Getopt sets longind to the first long option that has the given + // prefix. The match is ambiguous if a later long option also has the prefix. + if (!match.getName().equals(name)) { + for (int i = longind + 1; i < longopts.length; i++) { + if (longopts[i].getName().startsWith(name)) { + return "Ambiguous command-line option --" + name; + } + } + } + if (equalsPos != -1 && match.getHasArg() == LongOpt.NO_ARGUMENT) { + return "Command-line option --" + match.getName() + " does not take an argument"; + } else if (equalsPos == -1 && match.getHasArg() == LongOpt.REQUIRED_ARGUMENT) { + return "Command-line option --" + match.getName() + " requires an argument"; + } else { + return "Bad command-line option " + arg; + } + } +} diff --git a/java/daikon/MergeInvariants.java b/java/daikon/MergeInvariants.java index bc2009da5d..8a814a80fb 100644 --- a/java/daikon/MergeInvariants.java +++ b/java/daikon/MergeInvariants.java @@ -5,7 +5,6 @@ import daikon.split.PptSplitter; import daikon.suppress.NIS; -import gnu.getopt.Getopt; import gnu.getopt.LongOpt; import java.io.File; import java.io.FileNotFoundException; @@ -97,14 +96,13 @@ public static void mainHelper(String[] args) LongOpt[] longopts = new LongOpt[] { - new LongOpt(Daikon.help_SWITCH, LongOpt.NO_ARGUMENT, null, 0), new LongOpt(Daikon.config_option_SWITCH, LongOpt.REQUIRED_ARGUMENT, null, 0), new LongOpt(Daikon.debugAll_SWITCH, LongOpt.NO_ARGUMENT, null, 0), new LongOpt(Daikon.debug_SWITCH, LongOpt.REQUIRED_ARGUMENT, null, 0), new LongOpt(Daikon.track_SWITCH, LongOpt.REQUIRED_ARGUMENT, null, 0), }; - Getopt g = new Getopt("daikon.MergeInvariants", args, "ho:", longopts); + DaikonGetopt g = new DaikonGetopt(args, "o:", longopts, usage); int c; while ((c = g.getopt()) != -1) { switch (c) { @@ -112,10 +110,7 @@ public static void mainHelper(String[] args) // long option case 0: String option_name = longopts[g.getLongind()].getName(); - if (Daikon.help_SWITCH.equals(option_name)) { - System.out.println(usage); - throw new Daikon.NormalTermination(); - } else if (Daikon.config_option_SWITCH.equals(option_name)) { + if (Daikon.config_option_SWITCH.equals(option_name)) { String item = Daikon.getOptarg(g); daikon.config.Configuration.getInstance().apply(item); break; @@ -133,14 +128,10 @@ public static void mainHelper(String[] args) "Error parsing track argument '" + Daikon.getOptarg(g) + "' - " + error); } } else { - throw new Daikon.UserError("Unknown long option received: " + option_name); + throw new Daikon.BugInDaikon("Unhandled long option " + option_name); } break; - case 'h': - System.out.println(usage); - throw new Daikon.NormalTermination(); - case 'o': String output_inv_filename = Daikon.getOptarg(g); @@ -160,12 +151,8 @@ public static void mainHelper(String[] args) } break; - case '?': - break; // getopt() already printed an error - default: - System.out.println("getopt() returned " + c); - break; + throw new Daikon.BugInDaikon("getopt() returned " + c); } } diff --git a/java/daikon/PrintInvariants.java b/java/daikon/PrintInvariants.java index f7bc9121c3..57f483661d 100644 --- a/java/daikon/PrintInvariants.java +++ b/java/daikon/PrintInvariants.java @@ -24,7 +24,6 @@ import daikon.split.PptSplitter; import daikon.suppress.NIS; import daikon.suppress.NISuppressionSet; -import gnu.getopt.Getopt; import gnu.getopt.LongOpt; import java.io.BufferedWriter; import java.io.File; @@ -329,7 +328,6 @@ public static void mainHelper(String[] args) LongOpt[] longopts = new LongOpt[] { - new LongOpt(Daikon.help_SWITCH, LongOpt.NO_ARGUMENT, null, 0), new LongOpt(Daikon.format_SWITCH, LongOpt.REQUIRED_ARGUMENT, null, 0), new LongOpt(Daikon.suppress_redundant_SWITCH, LongOpt.NO_ARGUMENT, null, 0), new LongOpt(Daikon.output_num_samples_SWITCH, LongOpt.NO_ARGUMENT, null, 0), @@ -344,17 +342,14 @@ public static void mainHelper(String[] args) new LongOpt( PrintInvariants.print_csharp_metadata_SWITCH, LongOpt.OPTIONAL_ARGUMENT, null, 0), }; - Getopt g = new Getopt("daikon.PrintInvariants", args, "h", longopts); + DaikonGetopt g = new DaikonGetopt(args, "", longopts, usage); int c; while ((c = g.getopt()) != -1) { switch (c) { case 0: // got a long option String option_name = longopts[g.getLongind()].getName(); - if (Daikon.help_SWITCH.equals(option_name)) { - System.out.println(usage); - throw new Daikon.NormalTermination(); - } else if (Daikon.ppt_regexp_SWITCH.equals(option_name)) { + if (Daikon.ppt_regexp_SWITCH.equals(option_name)) { if (ppt_regexp != null) { throw new Error( "multiple --" @@ -430,17 +425,11 @@ public static void mainHelper(String[] args) } else if (Daikon.wrap_xml_SWITCH.equals(option_name)) { wrap_xml = true; } else { - throw new RuntimeException("Unknown long option received: " + option_name); + throw new Daikon.BugInDaikon("Unhandled long option " + option_name); } break; - case 'h': - System.out.println(usage); - throw new Daikon.NormalTermination(); - case '?': - break; // getopt() already printed an error default: - System.out.println("getopt() returned " + c); - break; + throw new Daikon.BugInDaikon("getopt() returned " + c); } } diff --git a/java/daikon/UnionInvariants.java b/java/daikon/UnionInvariants.java index ea34b0f075..c07e19d7ce 100644 --- a/java/daikon/UnionInvariants.java +++ b/java/daikon/UnionInvariants.java @@ -1,6 +1,5 @@ package daikon; -import gnu.getopt.Getopt; import gnu.getopt.LongOpt; import java.io.File; import org.plumelib.util.FilesPlume; @@ -52,25 +51,19 @@ public static void mainHelper(String[] args) throws Exception { new LongOpt[] { new LongOpt(Daikon.suppress_redundant_SWITCH, LongOpt.NO_ARGUMENT, null, 0), }; - Getopt g = new Getopt("daikon.UnionInvariants", args, "ho:", longopts); + DaikonGetopt g = new DaikonGetopt(args, "o:", longopts, usage); int c; while ((c = g.getopt()) != -1) { switch (c) { case 0: // got a long option String option_name = longopts[g.getLongind()].getName(); - if (Daikon.help_SWITCH.equals(option_name)) { - System.out.println(usage); - throw new Daikon.NormalTermination(); - } else if (Daikon.suppress_redundant_SWITCH.equals(option_name)) { + if (Daikon.suppress_redundant_SWITCH.equals(option_name)) { Daikon.suppress_redundant_invariants_with_simplify = true; } else { - throw new Daikon.UserError("Unknown option received: " + option_name); + throw new Daikon.BugInDaikon("Unhandled long option " + option_name); } break; - case 'h': - System.out.println(usage); - throw new Daikon.NormalTermination(); case 'o': String inv_filename = Daikon.getOptarg(g); @@ -90,11 +83,8 @@ public static void mainHelper(String[] args) throws Exception { } break; // - case '?': - break; // getopt() already printed an error default: - System.out.println("getopt() returned " + c); - break; + throw new Daikon.BugInDaikon("getopt() returned " + c); } } diff --git a/java/daikon/diff/Diff.java b/java/daikon/diff/Diff.java index 0019d1e935..6355ef0892 100644 --- a/java/daikon/diff/Diff.java +++ b/java/daikon/diff/Diff.java @@ -4,13 +4,13 @@ import static java.util.logging.Level.INFO; import daikon.Daikon; +import daikon.DaikonGetopt; import daikon.FileIO; import daikon.Ppt; import daikon.PptConditional; import daikon.PptMap; import daikon.PptTopLevel; import daikon.inv.Invariant; -import gnu.getopt.Getopt; import gnu.getopt.LongOpt; import java.io.File; import java.io.FileNotFoundException; @@ -68,13 +68,19 @@ public final class Diff { " For a list of flags, see the Daikon manual, which appears in the ", " Daikon distribution and also at http://plse.cs.washington.edu/daikon/."); - /** The long command line options. */ - private static final String HELP_SWITCH = "help"; - + /** The long command-line option that specifies the comparator to sort the first set of invs. */ private static final String INV_SORT_COMPARATOR1_SWITCH = "invSortComparator1"; + + /** The long command-line option that specifies the comparator to sort the second set of invs. */ private static final String INV_SORT_COMPARATOR2_SWITCH = "invSortComparator2"; + + /** The long command-line option that specifies the comparator to pair up invs. */ private static final String INV_PAIR_COMPARATOR_SWITCH = "invPairComparator"; + + /** The long command-line option that is a synonym for -y. */ private static final String IGNORE_UNJUSTIFIED_SWITCH = "ignore_unjustified"; + + /** The long command-line option that ignores numbered exit points. */ private static final String IGNORE_NUMBERED_EXITS_SWITCH = "ignore_exitNN"; /** Determine which ppts should be paired together in the tree. */ @@ -193,7 +199,6 @@ public static void mainHelper(final String[] args) LongOpt[] longOpts = new LongOpt[] { - new LongOpt(HELP_SWITCH, LongOpt.NO_ARGUMENT, null, 0), new LongOpt(INV_SORT_COMPARATOR1_SWITCH, LongOpt.REQUIRED_ARGUMENT, null, 0), new LongOpt(INV_SORT_COMPARATOR2_SWITCH, LongOpt.REQUIRED_ARGUMENT, null, 0), new LongOpt(INV_PAIR_COMPARATOR_SWITCH, LongOpt.REQUIRED_ARGUMENT, null, 0), @@ -201,20 +206,14 @@ public static void mainHelper(final String[] args) new LongOpt(IGNORE_NUMBERED_EXITS_SWITCH, LongOpt.NO_ARGUMENT, null, 0), }; - Getopt g = - new Getopt( - "daikon.diff.Diff", args, - "Hhyduastmxno:jzpevl", longOpts); + DaikonGetopt g = new DaikonGetopt(args, "Hydastmxno:jpevl", longOpts, usage); int c; while ((c = g.getopt()) != -1) { switch (c) { case 0: // got a long option String optionName = longOpts[g.getLongind()].getName(); - if (Daikon.help_SWITCH.equals(optionName)) { - System.out.println(usage); - throw new Daikon.NormalTermination(); - } else if (INV_SORT_COMPARATOR1_SWITCH.equals(optionName)) { + if (INV_SORT_COMPARATOR1_SWITCH.equals(optionName)) { if (invSortComparator1Classname != null) { throw new Error( "multiple --" @@ -252,12 +251,9 @@ public static void mainHelper(final String[] args) ignoreNumberedExits = true; break; } else { - throw new RuntimeException("Unknown long option received: " + optionName); + throw new Daikon.BugInDaikon("Unhandled long option " + optionName); } break; - case 'h': - System.out.println(usage); - throw new Daikon.NormalTermination(); case 'H': PrintAllVisitor.HUMAN_OUTPUT = true; break; @@ -318,13 +314,8 @@ public static void mainHelper(final String[] args) case 'l': logging = true; break; - case '?': - // getopt() already printed an error - System.out.println(usage); - throw new Daikon.UserError("Bad argument"); default: - System.out.println("getopt() returned " + c); - break; + throw new Daikon.BugInDaikon("getopt() returned " + c); } } @@ -422,8 +413,7 @@ public static void mainHelper(final String[] args) v1.printAll(); return; } else { - System.out.println(usage); - throw new Daikon.NormalTermination(); + throw new Daikon.UserError("No invariant files specified" + Daikon.lineSep + usage); } if (logging) { diff --git a/java/daikon/test/AllTestsSuite.java b/java/daikon/test/AllTestsSuite.java index 7d74e7e7ac..9a817b266f 100644 --- a/java/daikon/test/AllTestsSuite.java +++ b/java/daikon/test/AllTestsSuite.java @@ -7,6 +7,7 @@ @RunWith(Suite.class) @Suite.SuiteClasses({ daikon.chicory.RuntimeTest.class, + daikon.test.BadOptionTest.class, daikon.test.TestClassOrInterfaceTypeDecorateVisitor.class, daikon.test.TestAst.class, daikon.test.config.ConfigurationTest.class, diff --git a/java/daikon/test/BadOptionTest.java b/java/daikon/test/BadOptionTest.java new file mode 100644 index 0000000000..af9b745d24 --- /dev/null +++ b/java/daikon/test/BadOptionTest.java @@ -0,0 +1,199 @@ +package daikon.test; + +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertThrows; + +import daikon.Daikon; +import daikon.DaikonGetopt; +import daikon.PrintInvariants; +import daikon.UnionInvariants; +import daikon.tools.DtraceDiff; +import gnu.getopt.LongOpt; +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import org.junit.Test; +import org.junit.function.ThrowingRunnable; + +/** + * Tests that Daikon tools reject bad command-line options with a UserError. + * + *

These tests do not call {@code Daikon.mainHelper}, because it resets Daikon's global state, + * which other tests in the same JVM depend on. + */ +public class BadOptionTest { + + /** The long options used by {@link #parse}. */ + private static final LongOpt[] longopts = + new LongOpt[] { + new LongOpt("help", LongOpt.NO_ARGUMENT, null, 0), + new LongOpt("config", LongOpt.REQUIRED_ARGUMENT, null, 0), + new LongOpt("config_option", LongOpt.REQUIRED_ARGUMENT, null, 0), + new LongOpt("debug", LongOpt.REQUIRED_ARGUMENT, null, 'd'), + new LongOpt("verbose", LongOpt.NO_ARGUMENT, null, 'v'), + }; + + /** + * Parses the given command-line arguments, which must contain a bad option, and returns the + * resulting error message. + * + * @param args command-line arguments + * @return the message of the UserError for the bad option + */ + private static String parse(String... args) { + DaikonGetopt g = new DaikonGetopt(args, "ho:", longopts); + Daikon.UserError e = assertThrows(Daikon.UserError.class, () -> consumeAll(g)); + return String.valueOf(e.getMessage()); + } + + /** + * Calls {@code getopt()} until all command-line arguments have been processed. + * + * @param g the command-line parser + */ + private static void consumeAll(DaikonGetopt g) { + while (g.getopt() != -1) {} + } + + /** + * Returns the expected message for a bad option. + * + * @param description a description of the bad option + * @return the expected message for a bad option + */ + private static String expected(String description) { + return description + "; run with -h for usage"; + } + + /** Tests an unrecognized long option. */ + @Test + public void testUnrecognizedLongOption() { + assertEquals(expected("Unrecognized command-line option --bogus"), parse("--bogus")); + assertEquals(expected("Unrecognized command-line option --bogus"), parse("--bogus=3")); + assertEquals(expected("Unrecognized command-line option --=3"), parse("--=3")); + assertEquals( + expected("Unrecognized command-line option --bogus"), parse("-h", "--bogus", "file")); + } + + /** Tests an unrecognized short option, alone and combined with a valid one. */ + @Test + public void testUnrecognizedShortOption() { + assertEquals(expected("Unrecognized command-line option -x"), parse("-x")); + assertEquals(expected("Unrecognized command-line option -x"), parse("-xh")); + assertEquals(expected("Unrecognized command-line option -x"), parse("-hx")); + assertEquals(expected("Unrecognized command-line option -:"), parse("-:")); + } + + /** Tests an ambiguous abbreviation of a long option. */ + @Test + public void testAmbiguousLongOption() { + assertEquals(expected("Ambiguous command-line option --conf"), parse("--conf=x")); + assertEquals(expected("Ambiguous command-line option --conf"), parse("--conf")); + } + + /** Tests that a usage hint of null appends nothing to the description of a bad option. */ + @Test + public void testNoUsageHint() { + DaikonGetopt g = new DaikonGetopt(new String[] {"--bogus"}, "h", longopts); + g.setUsageHint(null); + Daikon.UserError e = assertThrows(Daikon.UserError.class, g::getopt); + assertEquals("Unrecognized command-line option --bogus", String.valueOf(e.getMessage())); + } + + /** Tests options that are missing their required argument. */ + @Test + public void testMissingArgument() { + assertEquals(expected("Command-line option --config requires an argument"), parse("--config")); + assertEquals(expected("Command-line option --debug requires an argument"), parse("--deb")); + assertEquals(expected("Command-line option -o requires an argument"), parse("-o")); + assertEquals(expected("Command-line option -o requires an argument"), parse("-ho")); + } + + /** Tests options that are missing their required argument, when the optstring starts with ':'. */ + @Test + public void testMissingArgumentLeadingColon() { + DaikonGetopt g = new DaikonGetopt(new String[] {"-o"}, ":ho:", longopts); + Daikon.UserError e = assertThrows(Daikon.UserError.class, g::getopt); + assertEquals( + expected("Command-line option -o requires an argument"), String.valueOf(e.getMessage())); + g = new DaikonGetopt(new String[] {"--config"}, ":ho:", longopts); + e = assertThrows(Daikon.UserError.class, g::getopt); + assertEquals( + expected("Command-line option --config requires an argument"), + String.valueOf(e.getMessage())); + } + + /** Tests long options that are given an argument they do not take. */ + @Test + public void testUnexpectedArgument() { + assertEquals( + expected("Command-line option --help does not take an argument"), parse("--help=x")); + assertEquals( + expected("Command-line option --verbose does not take an argument"), parse("--verb=x")); + } + + /** + * Asserts that running {@code mainCall} throws a UserError with the given message. + * + * @param description a description of the bad option + * @param mainCall a call to a tool's {@code mainHelper} method + */ + private static void assertBadOption(String description, ThrowingRunnable mainCall) { + Daikon.UserError e = assertThrows(Daikon.UserError.class, mainCall); + assertEquals(expected(description), String.valueOf(e.getMessage())); + } + + /** Tests an unrecognized long option in a tool. */ + @Test + public void testPrintInvariantsUnrecognizedOption() { + assertBadOption( + "Unrecognized command-line option --bogus", + () -> PrintInvariants.mainHelper(new String[] {"--bogus", "foo.inv.gz"})); + } + + /** Tests that tools accept the {@code --help} option that their usage messages document. */ + @Test + public void testHelpOption() { + assertPrintsUsage(() -> DtraceDiff.mainHelper(new String[] {"--help"})); + assertPrintsUsage(() -> UnionInvariants.mainHelper(new String[] {"--help"})); + } + + /** + * Asserts that the given code prints a usage message to standard output and throws {@link + * Daikon.NormalTermination}. Captures the usage message so that it does not clutter the test + * output. + * + * @param code the code to run + */ + private static void assertPrintsUsage(ThrowingRunnable code) { + PrintStream oldOut = System.out; + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + System.setOut(new PrintStream(bytes, true, UTF_8)); + try { + assertThrows(Daikon.NormalTermination.class, code); + } finally { + System.setOut(oldOut); + } + assertNotEquals("", bytes.toString(UTF_8).trim()); + } + + /** Tests {@link DaikonGetopt#nonOptionArgs}. */ + @Test + public void testNonOptionArgs() { + assertArrayEquals( + new String[] {"a.dtrace", "b.dtrace"}, + DaikonGetopt.nonOptionArgs(new String[] {"a.dtrace", "b.dtrace"}, "u")); + assertArrayEquals( + new String[] {"-a.dtrace"}, + DaikonGetopt.nonOptionArgs(new String[] {"--", "-a.dtrace"}, "u")); + assertBadOption( + "Unrecognized command-line option --bogus", + () -> DaikonGetopt.nonOptionArgs(new String[] {"x", "--bogus"}, "u")); + assertBadOption( + "Unrecognized command-line option -x", + () -> DaikonGetopt.nonOptionArgs(new String[] {"-x"}, "u")); + assertPrintsUsage(() -> DaikonGetopt.nonOptionArgs(new String[] {"x", "--help"}, "u")); + } +} diff --git a/java/daikon/test/SampleTester.java b/java/daikon/test/SampleTester.java index 40919edb6b..b984841454 100644 --- a/java/daikon/test/SampleTester.java +++ b/java/daikon/test/SampleTester.java @@ -8,6 +8,7 @@ import static org.junit.Assert.fail; import daikon.Daikon; +import daikon.DaikonGetopt; import daikon.Debug; import daikon.FileIO; import daikon.Global; @@ -18,7 +19,6 @@ import daikon.ValueTuple; import daikon.VarInfo; import daikon.inv.Invariant; -import gnu.getopt.Getopt; import gnu.getopt.LongOpt; import java.io.File; import java.io.IOException; @@ -67,7 +67,7 @@ public class SampleTester { /** The usage message for this program. */ private static String usage = StringsPlume.joinLines( - "Usage: java daikon.PrintInvariants [OPTION]... FILE", + "Usage: java daikon.test.SampleTester [OPTION]...", " -h, --" + Daikon.help_SWITCH, " Display this usage message", " --" + Daikon.config_option_SWITCH, @@ -78,8 +78,29 @@ public class SampleTester { " Specify a class, varinfos, and ppt to debug track.", " Format is class@ppt"); - @SuppressWarnings("JUnitMethodInvoked") // main() runs the tests without JUnit + /** + * Runs the tests without JUnit. + * + * @param args command-line arguments, like those of {@link #mainHelper} + * @throws IOException if there is a problem reading a test file + */ public static void main(String[] args) throws IOException { + try { + mainHelper(args); + } catch (Daikon.DaikonTerminationException e) { + Daikon.handleDaikonTerminationException(e); + } + } + + /** + * This does the work of {@link #main(String[])}, but it never calls System.exit, so it is + * appropriate to be called programmatically. + * + * @param args command-line arguments, like those of {@link #main} + * @throws IOException if there is a problem reading a test file + */ + @SuppressWarnings("JUnitMethodInvoked") // mainHelper() runs the tests without JUnit + public static void mainHelper(String[] args) throws IOException { LongOpt[] longopts = new LongOpt[] { @@ -89,7 +110,7 @@ public static void main(String[] args) throws IOException { new LongOpt(Daikon.track_SWITCH, LongOpt.REQUIRED_ARGUMENT, null, 0), }; - Getopt g = new Getopt("daikon.test.SampleTester", args, "h:", longopts); + DaikonGetopt g = new DaikonGetopt(args, "", longopts, usage); int c; while ((c = g.getopt()) != -1) { switch (c) { @@ -97,11 +118,7 @@ public static void main(String[] args) throws IOException { // long option case 0: String option_name = longopts[g.getLongind()].getName(); - if (Daikon.help_SWITCH.equals(option_name)) { - System.out.println(usage); - throw new Daikon.NormalTermination(); - - } else if (Daikon.config_option_SWITCH.equals(option_name)) { + if (Daikon.config_option_SWITCH.equals(option_name)) { String item = Daikon.getOptarg(g); daikon.config.Configuration.getInstance().apply(item); break; @@ -119,20 +136,12 @@ public static void main(String[] args) throws IOException { "Error parsing track argument '" + Daikon.getOptarg(g) + "' - " + error); } } else { - throw new RuntimeException("Unknown long option received: " + option_name); + throw new Daikon.BugInDaikon("Unhandled long option " + option_name); } break; - case 'h': - System.out.println(usage); - throw new Daikon.NormalTermination(); - - case '?': - break; // getopt() already printed an error - default: - System.out.println("getopt() returned " + c); - break; + throw new Daikon.BugInDaikon("getopt() returned " + c); } } diff --git a/java/daikon/test/split/SplitterFactoryTestUpdater.java b/java/daikon/test/split/SplitterFactoryTestUpdater.java index 0c806f6071..c5be608fc7 100644 --- a/java/daikon/test/split/SplitterFactoryTestUpdater.java +++ b/java/daikon/test/split/SplitterFactoryTestUpdater.java @@ -195,7 +195,11 @@ private static String getTestClassText() { ps.println("import java.io.*;"); ps.println("import java.util.*;"); ps.println("import junit.framework.*;"); + ps.println("import org.junit.BeforeClass;"); ps.println("import org.junit.Test;"); + ps.println("import org.junit.runner.JUnitCore;"); + ps.println("import org.junit.runner.Result;"); + ps.println("import org.junit.runner.notification.Failure;"); ps.println("import org.plumelib.util.FilesPlume;"); ps.println("import org.plumelib.util.StringsPlume;"); ps.println("import org.plumelib.util.UtilPlume;"); @@ -229,11 +233,6 @@ private static String getTestClassText() { ps.println(" // java files it produces, changing the order that the setUpTests"); ps.println(" // commands are run will cause the tests to fail."); ps.println(); - ps.println(" /** Do not instantiate. */"); - ps.println(" private SplitterFactoryTest() {"); - ps.println(" throw new Error(\"Do not instantiate\");"); - ps.println(" }"); - ps.println(); ps.println(" private static String targetDir = \"" + targetDir + "\";"); ps.println(); ps.println(" private static @Nullable String tempDir = null;"); @@ -242,31 +241,41 @@ private static String getTestClassText() { ps.println(); ps.println(" private static String usage ="); ps.println(" StringsPlume.joinLines("); - ps.println(" \"Usage: java daikon.tools.CreateSpinfo FILE.java ...\","); + ps.println(" \"Usage: java daikon.test.split.SplitterFactoryTest [OPTION]...\","); ps.println( - " \" -s Save (do not delete) the splitter java files in the temp directory\","); - ps.println(" \" -h Display this usage message\");"); + " \" -s Save (do not delete) the splitter java files in the temp" + + " directory\","); + ps.println(" \" -h, --help Display this usage message\");"); ps.println(); ps.println(" public static void main(String[] args) {"); - ps.println( - " Getopt g = new Getopt(\"daikon.test.split.SplitterFactoryTest\", args, \"hs\");"); + ps.println(" try {"); + ps.println(" mainHelper(args);"); + ps.println(" } catch (Daikon.DaikonTerminationException e) {"); + ps.println(" Daikon.handleDaikonTerminationException(e);"); + ps.println(" }"); + ps.println(" }"); + ps.println(); + ps.println(" public static void mainHelper(String[] args) {"); + ps.println(" DaikonGetopt g = new DaikonGetopt(args, \"s\", new LongOpt[0], usage);"); ps.println(" int c;"); ps.println(" while ((c = g.getopt()) != -1) {"); ps.println(" switch (c) {"); ps.println(" case 's':"); ps.println(" saveFiles = true;"); ps.println(" break;"); - ps.println(" case 'h':"); - ps.println(" System.out.println(usage);"); - ps.println(" System.exit(1);"); - ps.println(" break;"); - ps.println(" case '?':"); - ps.println(" break;"); ps.println(" default:"); - ps.println(" System.out.println(\"getopt() returned \" + c);"); - ps.println(" break;"); + ps.println(" throw new Daikon.BugInDaikon(\"getopt() returned \" + c);"); ps.println(" }"); ps.println(" }"); + ps.println(" Result result = JUnitCore.runClasses(SplitterFactoryTest.class);"); + ps.println(" for (Failure failure : result.getFailures()) {"); + ps.println(" System.out.println(failure.getTrace());"); + ps.println(" }"); + ps.println(" if (!result.wasSuccessful()) {"); + ps.println( + " throw new Daikon.UserError(StringsPlume.nPlural(result.getFailureCount(), \"test\")" + + " + \" failed\");"); + ps.println(" }"); ps.println(" }"); ps.println(); @@ -320,7 +329,8 @@ private static String getTestClassText() { * SplitterFactoryTest to set up the needed files to run the tests on. */ public static void appendSetUpTest(PrintStream ps) { - ps.println(" private static void setUpTests() {"); + ps.println(" @BeforeClass"); + ps.println(" public static void setUpTests() {"); ps.println(" List spinfoFiles;"); ps.println(" List declsFiles;"); for (int i = 0; i < spinfoFileLists.size(); i++) { @@ -350,7 +360,7 @@ private static void appendTests(PrintStream ps) { ps.println(); for (String className : classNames) { ps.println(" @Test"); - ps.println(" public static void test" + className + "() {"); + ps.println(" public void test" + className + "() {"); ps.println(" assertEqualFiles(\"" + className + ".java\");"); ps.println(" }"); ps.println(); diff --git a/java/daikon/tools/DtraceDiff.java b/java/daikon/tools/DtraceDiff.java index 7d158ccc29..e1c7bbce3f 100644 --- a/java/daikon/tools/DtraceDiff.java +++ b/java/daikon/tools/DtraceDiff.java @@ -6,6 +6,7 @@ import static daikon.tools.nullness.NullnessUtil.*; import daikon.Daikon; +import daikon.DaikonGetopt; import daikon.FileIO; import daikon.Global; import daikon.PptMap; @@ -124,7 +125,7 @@ public static void mainHelper(final String[] args) { new LongOpt(Daikon.config_option_SWITCH, LongOpt.REQUIRED_ARGUMENT, null, 0), }; - Getopt g = new Getopt("daikon.tools.DtraceDiff", args, "h:", longopts); + DaikonGetopt g = new DaikonGetopt(args, "", longopts, usage); int c; while ((c = g.getopt()) != -1) { switch (c) { @@ -132,10 +133,7 @@ public static void mainHelper(final String[] args) { // long option case 0: String option_name = longopts[g.getLongind()].getName(); - if (Daikon.help_SWITCH.equals(option_name)) { - System.out.println(usage); - throw new Daikon.NormalTermination(); - } else if (Daikon.ppt_regexp_SWITCH.equals(option_name)) { + if (Daikon.ppt_regexp_SWITCH.equals(option_name)) { if (Daikon.ppt_regexp != null) { throw new Error( "multiple --" @@ -224,20 +222,12 @@ public static void mainHelper(final String[] args) { Configuration.getInstance().apply(item); break; } else { - throw new RuntimeException("Unknown long option received: " + option_name); + throw new Daikon.BugInDaikon("Unhandled long option " + option_name); } // short options - case 'h': - System.out.println(usage); - throw new Daikon.NormalTermination(); - - case '?': - break; // getopt() already printed an error - default: - System.out.println("getopt() returned " + c); - break; + throw new Daikon.BugInDaikon("getopt() returned " + c); } } diff --git a/java/daikon/tools/ExtractConsequent.java b/java/daikon/tools/ExtractConsequent.java index f2ecf3caf3..d4f94d9f49 100644 --- a/java/daikon/tools/ExtractConsequent.java +++ b/java/daikon/tools/ExtractConsequent.java @@ -5,6 +5,7 @@ import static java.util.logging.Level.INFO; import daikon.Daikon; +import daikon.DaikonGetopt; import daikon.FileIO; import daikon.Global; import daikon.Ppt; @@ -118,17 +119,14 @@ public static void mainHelper(final String[] args) throws IOException { new LongOpt(Daikon.debugAll_SWITCH, LongOpt.NO_ARGUMENT, null, 0), new LongOpt(Daikon.debug_SWITCH, LongOpt.REQUIRED_ARGUMENT, null, 0), }; - Getopt g = new Getopt("daikon.ExtractConsequent", args, "h", longopts); + DaikonGetopt g = new DaikonGetopt(args, "", longopts, usage); int c; while ((c = g.getopt()) != -1) { switch (c) { case 0: // got a long option String option_name = longopts[g.getLongind()].getName(); - if (Daikon.help_SWITCH.equals(option_name)) { - System.out.println(usage); - throw new Daikon.NormalTermination(); - } else if (Daikon.suppress_redundant_SWITCH.equals(option_name)) { + if (Daikon.suppress_redundant_SWITCH.equals(option_name)) { Daikon.suppress_redundant_invariants_with_simplify = true; } else if (Daikon.config_option_SWITCH.equals(option_name)) { String item = Daikon.getOptarg(g); @@ -139,17 +137,11 @@ public static void mainHelper(final String[] args) throws IOException { } else if (Daikon.debug_SWITCH.equals(option_name)) { daikon.LogHelper.setLevel(Daikon.getOptarg(g), FINE); } else { - throw new RuntimeException("Unknown long option received: " + option_name); + throw new Daikon.BugInDaikon("Unhandled long option " + option_name); } break; - case 'h': - System.out.println(usage); - throw new Daikon.NormalTermination(); - case '?': - break; // getopt() already printed an error default: - System.out.println("getopt() returned " + c); - break; + throw new Daikon.BugInDaikon("getopt() returned " + c); } } // The index of the first non-option argument -- the name of the file diff --git a/java/daikon/tools/InvariantChecker.java b/java/daikon/tools/InvariantChecker.java index 70a3c804d1..3f8c7c56b7 100644 --- a/java/daikon/tools/InvariantChecker.java +++ b/java/daikon/tools/InvariantChecker.java @@ -4,6 +4,7 @@ import static java.util.logging.Level.INFO; import daikon.Daikon; +import daikon.DaikonGetopt; import daikon.Debug; import daikon.FileIO; import daikon.Global; @@ -135,20 +136,16 @@ public static void mainHelper(final String[] args) new LongOpt(verbose_SWITCH, LongOpt.NO_ARGUMENT, null, 0), new LongOpt(Daikon.debugAll_SWITCH, LongOpt.NO_ARGUMENT, null, 0), new LongOpt(Daikon.debug_SWITCH, LongOpt.REQUIRED_ARGUMENT, null, 0), - new LongOpt(Daikon.ppt_regexp_SWITCH, LongOpt.REQUIRED_ARGUMENT, null, 0), new LongOpt(Daikon.track_SWITCH, LongOpt.REQUIRED_ARGUMENT, null, 0), }; - Getopt g = new Getopt("daikon.tools.InvariantChecker", args, "h", longopts); + DaikonGetopt g = new DaikonGetopt(args, "", longopts, usage); int c; while ((c = g.getopt()) != -1) { switch (c) { case 0: // got a long option String option_name = longopts[g.getLongind()].getName(); - if (Daikon.help_SWITCH.equals(option_name)) { - System.out.println(usage); - throw new Daikon.NormalTermination(); - } else if (conf_SWITCH.equals(option_name)) { + if (conf_SWITCH.equals(option_name)) { doConf = true; } else if (filter_SWITCH.equals(option_name)) { doFilter = true; @@ -179,17 +176,11 @@ public static void mainHelper(final String[] args) "Error parsing track argument '" + Daikon.getOptarg(g) + "' - " + error); } } else { - throw new RuntimeException("Unknown long option received: " + option_name); + throw new Daikon.BugInDaikon("Unhandled long option " + option_name); } break; - case 'h': - System.out.println(usage); - throw new Daikon.NormalTermination(); - case '?': - break; // getopt() already printed an error default: - System.out.println("getopt() returned " + c); - break; + throw new Daikon.BugInDaikon("getopt() returned " + c); } } diff --git a/java/daikon/tools/compare/LogicalCompare.java b/java/daikon/tools/compare/LogicalCompare.java index bbbc6df993..371d26ea25 100644 --- a/java/daikon/tools/compare/LogicalCompare.java +++ b/java/daikon/tools/compare/LogicalCompare.java @@ -5,6 +5,7 @@ import static java.util.logging.Level.INFO; import daikon.Daikon; +import daikon.DaikonGetopt; import daikon.FileIO; import daikon.Global; import daikon.PptMap; @@ -658,7 +659,6 @@ public static void mainHelper(final String[] args) new LongOpt(Daikon.debugAll_SWITCH, LongOpt.NO_ARGUMENT, null, 0), new LongOpt(Daikon.debug_SWITCH, LongOpt.REQUIRED_ARGUMENT, null, 0), new LongOpt("filters", LongOpt.REQUIRED_ARGUMENT, null, 0), - new LongOpt("help", LongOpt.NO_ARGUMENT, null, 0), new LongOpt("minimize-classes", LongOpt.NO_ARGUMENT, null, 0), new LongOpt("no-post-after-pre-failure", LongOpt.NO_ARGUMENT, null, 0), new LongOpt("post-after-pre-failure", LongOpt.NO_ARGUMENT, null, 0), @@ -675,7 +675,7 @@ public static void mainHelper(final String[] args) extra_assumptions = new LinkedHashMap<>(); - Getopt g = new Getopt("daikon.tools.compare.LogicalCompare", args, "h", longopts); + DaikonGetopt g = new DaikonGetopt(args, "", longopts, usage); int c; boolean user_filters = false; while ((c = g.getopt()) != -1) { @@ -683,10 +683,7 @@ public static void mainHelper(final String[] args) case 0: // got a long option String option_name = longopts[g.getLongind()].getName(); - if (Daikon.help_SWITCH.equals(option_name)) { - System.out.println(usage); - throw new Daikon.NormalTermination(); - } else if (option_name.equals("config-file")) { + if (option_name.equals("config-file")) { String config_file = Daikon.getOptarg(g); try (InputStream stream = new FileInputStream(config_file)) { Configuration.getInstance().apply(stream); @@ -727,15 +724,11 @@ public static void mainHelper(final String[] args) } else if (option_name.equals("minimize-classes")) { opt_minimize_classes = true; } else { - throw new Error(); + throw new Daikon.BugInDaikon("Unhandled long option " + option_name); } break; - case 'h': - System.out.println(usage); - throw new Daikon.NormalTermination(); - case '?': - // getopt() already printed an error - throw new Daikon.UserError("Bad argument"); + default: + throw new Daikon.BugInDaikon("getopt() returned " + c); } } diff --git a/java/daikon/tools/jtb/Annotate.java b/java/daikon/tools/jtb/Annotate.java index 9635cc5912..cee7292928 100644 --- a/java/daikon/tools/jtb/Annotate.java +++ b/java/daikon/tools/jtb/Annotate.java @@ -24,8 +24,7 @@ * *

The first argument is a Daikon {@code .inv} file -- a serialized file of Invariant objects. * All subsequent arguments are {@code Foo.java} files that are rewritten into {@code - * Foo.java-jmlannotated} versions; alternately, use the {@code -r} flag to process every {@code - * .java} file under the current directory. + * Foo.java-jmlannotated} versions. */ public class Annotate { @@ -88,10 +87,9 @@ private Annotate() { private static String usage = StringsPlume.joinLines( "Usage: java daikon.tools.Annotate FILE.inv FILE.java ...", - " -h Display this usage message", + " -h, --help Display this usage message", " -i Insert invariants not supported by ESC with \"!\" instead of \"@\";", " by default these \"inexpressible\" invariants are simply omitted", - " -r Use all .java files under the current directory as arguments", " -s Use // comments rather than /* comments", " --format name Insert specifications in the given format: DBC, ESC, JML, Java", " --wrap_xml Wrap each annotation and auxiliary information in XML tags", @@ -132,7 +130,6 @@ public static void mainHelper(final String[] args) throws Exception { Daikon.output_format = OutputFormat.ESCJAVA; LongOpt[] longopts = new LongOpt[] { - new LongOpt(Daikon.help_SWITCH, LongOpt.NO_ARGUMENT, null, 0), new LongOpt(Daikon.debugAll_SWITCH, LongOpt.NO_ARGUMENT, null, 0), new LongOpt(Daikon.debug_SWITCH, LongOpt.REQUIRED_ARGUMENT, null, 0), new LongOpt(Daikon.format_SWITCH, LongOpt.REQUIRED_ARGUMENT, null, 0), @@ -140,7 +137,7 @@ public static void mainHelper(final String[] args) throws Exception { new LongOpt(max_invariants_pp_SWITCH, LongOpt.REQUIRED_ARGUMENT, null, 0), new LongOpt(no_reflection_SWITCH, LongOpt.NO_ARGUMENT, null, 0) }; - Getopt g = new Getopt("daikon.tools.jtb.Annotate", args, "hs", longopts); + DaikonGetopt g = new DaikonGetopt(args, "is", longopts, usage); int c; while ((c = g.getopt()) != -1) { switch (c) { @@ -148,10 +145,7 @@ public static void mainHelper(final String[] args) throws Exception { // got a long option String option_name = longopts[g.getLongind()].getName(); - if (Daikon.help_SWITCH.equals(option_name)) { - System.out.println(usage); - throw new Daikon.NormalTermination(); - } else if (no_reflection_SWITCH.equals(option_name)) { + if (no_reflection_SWITCH.equals(option_name)) { useReflection = false; } else if (max_invariants_pp_SWITCH.equals(option_name)) { try { @@ -181,12 +175,9 @@ public static void mainHelper(final String[] args) throws Exception { setLightweight = true; } } else { - throw new Daikon.UserError("Unknown long option received: " + option_name); + throw new Daikon.BugInDaikon("Unhandled long option " + option_name); } break; - case 'h': - System.out.println(usage); - throw new Daikon.NormalTermination(); case 'i': insert_inexpressible = true; break; @@ -200,11 +191,8 @@ public static void mainHelper(final String[] args) throws Exception { case 's': slashslash = true; break; - case '?': - break; // getopt() already printed an error default: - System.out.println("getopt() returned " + c); - break; + throw new Daikon.BugInDaikon("getopt() returned " + c); } } diff --git a/java/daikon/tools/jtb/CreateSpinfo.java b/java/daikon/tools/jtb/CreateSpinfo.java index 56f1b154e2..76d4b23b05 100644 --- a/java/daikon/tools/jtb/CreateSpinfo.java +++ b/java/daikon/tools/jtb/CreateSpinfo.java @@ -83,40 +83,30 @@ public static void mainHelper(final String[] args) throws IOException { daikon.LogHelper.setupLogs(INFO); LongOpt[] longopts = new LongOpt[] { - new LongOpt(Daikon.help_SWITCH, LongOpt.NO_ARGUMENT, null, 0), new LongOpt(Daikon.debugAll_SWITCH, LongOpt.NO_ARGUMENT, null, 0), new LongOpt(Daikon.debug_SWITCH, LongOpt.REQUIRED_ARGUMENT, null, 0), }; - Getopt g = new Getopt("daikon.tools.jtb.CreateSpinfo", args, "ho:", longopts); + DaikonGetopt g = new DaikonGetopt(args, "o:", longopts, usage); int c; while ((c = g.getopt()) != -1) { switch (c) { case 0: // got a long option String option_name = longopts[g.getLongind()].getName(); - if (Daikon.help_SWITCH.equals(option_name)) { - System.out.println(usage); - throw new Daikon.NormalTermination(); - } else if (Daikon.debugAll_SWITCH.equals(option_name)) { + if (Daikon.debugAll_SWITCH.equals(option_name)) { Global.debugAll = true; } else if (Daikon.debug_SWITCH.equals(option_name)) { daikon.LogHelper.setLevel(Daikon.getOptarg(g), FINE); } else { - throw new RuntimeException("Unknown long option received: " + option_name); + throw new Daikon.BugInDaikon("Unhandled long option " + option_name); } break; case 'o': outputfilename = Daikon.getOptarg(g); break; - case 'h': - System.out.println(usage); - throw new Daikon.NormalTermination(); - case '?': - break; // getopt() already printed an error default: - System.out.println("getopt() returned " + c); - break; + throw new Daikon.BugInDaikon("getopt() returned " + c); } } diff --git a/tests/diff-tests/Makefile.common b/tests/diff-tests/Makefile.common index 7a22461dfd..014605b8b4 100644 --- a/tests/diff-tests/Makefile.common +++ b/tests/diff-tests/Makefile.common @@ -20,10 +20,10 @@ INV_FILES := $(PROGRAM)-1.inv.gz $(PROGRAM)-2.inv.gz # An output file must satisfy the pattern program%.txt, where the % is # the options passed to Diff ## Must reinstate -a and -ap and -p in V3 as soon as possible. -MDE 6/10/2003 -# OUTPUT := $(PROGRAM).txt $(PROGRAM)-u.txt $(PROGRAM)-a.txt $(PROGRAM)-p.txt \ +# OUTPUT := $(PROGRAM).txt $(PROGRAM)-a.txt $(PROGRAM)-p.txt \ # $(PROGRAM)-e.txt $(PROGRAM)-ap.txt $(PROGRAM)-t.txt \ # $(PROGRAM)-jt.txt -OUTPUT := $(PROGRAM).txt $(PROGRAM)-u.txt \ +OUTPUT := $(PROGRAM).txt \ $(PROGRAM)-e.txt $(PROGRAM)-t.txt \ $(PROGRAM)-jt.txt # Must be handled differently than OUTPUT, because map files are diff --git a/tests/diff-tests/StackAr/StackAr-u.txt.goal b/tests/diff-tests/StackAr/StackAr-u.txt.goal deleted file mode 100644 index f3164de375..0000000000 --- a/tests/diff-tests/StackAr/StackAr-u.txt.goal +++ /dev/null @@ -1,105 +0,0 @@ -(I)V:::ENTER> - = 0 {0+}, capacity >= 2 {1-}> (UInt,DJU) - (U!Int,DUU) -(I)V:::EXIT> - (Bin,MJ) - (Bin,MJ) - = -1 {0.8136-}, this.topOfStack >= -1 {0.8333-}> (U!Int,SUU) - (UInt,SJU) - (U!Int,DUU) - (U!Int,SUU) - (UInt,SJU) - (UInt,MJ) - - = -1 {0+}, this.topOfStack >= -1 {0+}> (U!Int,SJJ) - (U!Int,DJU) - (U!Int,DUU) - (UInt,MJ) - - = -1 {0+}, this.topOfStack >= -1 {0+}> (U!Int,SJJ) - (U!Int,DJU) - (U!Int,DJU) - (U!Int,DUU) - (UInt,MJ) - - (Bin,MJ) - = -1 {0+}, this.topOfStack >= -1 {0+}> (U!Int,SJJ) - (U!Int,DJJ) - (U!Int,DUU) - - (Bin,MJ) - = -1 {0+}, this.topOfStack >= -1 {0+}> (U!Int,SJJ) - (UInt,MJ) - (U!Int,DJJ) - (U!Int,DJJ) - (U!Int,DUU) - - (Bin,JM) - = -1 {0+}, this.topOfStack >= 9223372036854775807 {1-}> (U!Int,DJU) - (U!Int,UM) - (U!Int,DUU) - (UInt,JM) - (UInt,JM) - (UInt,DJU) - - (Bin,JM) - (Bin,JM) - (Bin,JM) - (Bin,JM) - (Bin,JM) - = -1 {0+}, null> (U!Int,JM) - = -1 {0.8205-}, this.topOfStack >= 9223372036854775807 {1-}> (U!Int,DUU) - (UInt,DJU) - (U!Int,UM) - (U!Int,UM) - (U!Int,UM) - (U!Int,DUU) - (UInt,DJU) - (UInt,JM) - (UInt,JM) - (UInt,DJU) - (UInt,DJU) - - = 9223372036854775807 {1-}, this.topOfStack >= 9223372036854775807 {1-}> (U!Int,SUU) - (U!Int,SUU) - - = 9223372036854775807 {1-}, this.topOfStack >= 9223372036854775807 {1-}> (U!Int,SUU) - (U!Int,SUU) - - = -1 {0+}, this.topOfStack >= -1 {0+}> (U!Int,SJJ) - (U!Int,DJJ) - (U!Int,DUU) - - = -1 {0+}, orig(this.topOfStack) >= -1 {0+}> (U!Int,SJJ) - (U!Int,DUU) - (U!Int,DJJ) - (U!Int,DJJ) - (U!Int,DUU) - - = -1 {0+}, this.topOfStack >= 0 {0+}> (UInt,DJJ) - (U!Int,DJJ) - (U!Int,DUU) - - (Bin,MJ) - (Bin,MJ) - (Bin,MJ) - (Bin,MJ) - = -1 {0+}, this.topOfStack >= 0 {0+}> (UInt,DJJ) - (UInt,MJ) - (U!Int,DJJ) - (U!Int,DJJ) - (U!Int,DUU) - - = -1 {0+}, this.topOfStack >= -1 {0+}> (U!Int,SJJ) - (U!Int,DJU) - (U!Int,DUU) - - (Bin,MJ) - (Bin,MJ) - (Bin,MJ) - = -1 {0+}, orig(this.topOfStack) >= -1 {0+}> (U!Int,SJJ) - = -1 {0+}, this.topOfStack >= -1 {0+}> (U!Int,SJJ) - (U!Int,DUU) - (U!Int,DJU) - (U!Int,DJU) - (U!Int,DUU) diff --git a/tests/diff-tests/schedule2/schedule2-u.txt.goal b/tests/diff-tests/schedule2/schedule2-u.txt.goal deleted file mode 100644 index ef71a1c0d9..0000000000 --- a/tests/diff-tests/schedule2/schedule2-u.txt.goal +++ /dev/null @@ -1,77 +0,0 @@ -getopt() returned 117 - - <::next_pid >= 0 {0-}, ::next_pid >= 0 {1+}> (Una,SUJ) - - <::next_pid >= 0 {0-}, ::next_pid >= 0 {1+}> (Una,SUJ) - - = 0 {1+}, prio >= -1 {1+}> (Una,DJJ) - - (return is a pointer) {1+}> (Nul,MJ) - (prio >= -1) {1+}> (Nul,MJ) - (prio >= 0) {1+}> (Nul,MJ) - (prio != 0) {0.9999+}> (Nul,MJ) - = 0 {1+}, prio >= -1 {1+}> (Una,DJJ) - (Una,DJJ) - - <*prio >= -1 {1+}, *prio >= -2 {0-}> (Una,DJU) - <*command != 0 {1+}, null> (Una,JM) - - (*prio >= -1) {1+}> (Nul,MJ) - (orig(*prio) >= -1) {1+}> (Nul,MJ) - <(return == 1) ==> (*prio != 0) {1+}, null> (Nul,JM) - (*command == 0) {1+}> (Bin,MJ) - <(*prio == 0) ==> (orig(*prio) == 0) {1+}, null> (Bin,JM) - <*prio >= -1 {1+}, *prio >= -2 {0-}> (Una,DJU) - <*command != 0 {1+}, null> (Una,JM) - - <::next_pid >= 0 {0.4444-}, ::next_pid >= 0 {1+}> (Una,SUJ) - - <::next_pid >= 0 {0.4444-}, ::next_pid >= 0 {1+}> (Una,SUJ) - - = 0.0 {1+}, ratio >= -1.0 {0.0721-}> (Una,DJU) - - = 0.0 {1+}, ratio >= -1.0 {0.0721-}> (Una,DJU) - (Una,DJJ) - - (Una,JM) - - = orig(::next_pid) {1+}> (Bin,MJ) - <::next_pid - orig(::next_pid) - 1 == 0 {1+}, null> (Bin,JM) - (orig(::next_pid) == 0) {1+}> (Bin,MJ) - <::next_pid >= 1 {1+}, ::next_pid >= 0 {0.3333-}> (Una,DJU) - (Una,DUJ) - (Una,JM) - (Una,DJJ) - - = 0 {1+}, prio >= -1 {1+}> (Una,DJJ) - - (return is a pointer) {1+}> (Nul,MJ) - (prio >= -1) {1+}> (Nul,MJ) - (prio >= 0) {1+}> (Nul,MJ) - (prio != 0) {0.9999+}> (Nul,MJ) - = 0 {1+}, prio >= -1 {1+}> (Una,DJJ) - (Una,DJJ) - - = -1 {1+}, prio >= -2 {0-}> (Una,DJU) - (Una,JM) - (Una,JM) - - = -1 {1+}, prio >= -2 {0-}> (Una,DJU) - (Una,JM) - (Una,JM) - (Una,JM) - (Una,JM) - - (Una,SUJ) - - (Una,SUJ) - (Una,DJJ) - - <::next_pid >= 0 {1+}, ::next_pid >= 0 {0.7779-}> (Una,SJU) - (Una,SUJ) - (Una,JM) - - <::next_pid >= 0 {1+}, ::next_pid >= 0 {0.7779-}> (Una,SJU) - (Una,SUJ) - (Una,JM) - (Una,DJJ) From 23f6b2e125ddbaa7a3a7a559963271d42319e044 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Tue, 6 Oct 2026 17:06:52 -0700 Subject: [PATCH 02/16] All tools accept -h and --help Tools that take no options other than -h and --help now use DaikonGetopt, so they print a usage message for -h and --help and reject other options. Tools that use plume-lib Options exit with status 0 after printing help. Co-Authored-By: Claude Opus 5.5 --- doc/CHANGELOG.md | 2 ++ doc/daikon.texinfo | 3 +++ java/daikon/AnnotateNullable.java | 16 ++++++++++++-- java/daikon/Chicory.java | 2 +- java/daikon/DynComp.java | 2 +- java/daikon/SplitDtrace.java | 28 ++++++++++++++++++++----- java/daikon/dcomp/BuildJDK.java | 4 ++++ java/daikon/dcomp/BuildJDK24.java | 4 ++++ java/daikon/test/BadOptionTest.java | 2 ++ java/daikon/tools/DtraceNonceFixer.java | 10 +++++---- java/daikon/tools/ReadTrace.java | 26 ++++++++++++++++++++++- 11 files changed, 85 insertions(+), 14 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 6aa334f3e8..9493cc5a69 100644 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -27,6 +27,8 @@ Further documentation can be found in: command-line option: they describe the problem and exit with a non-zero status. Previously, Daikon printed its usage message and exited with status 0, and most other tools ignored the bad option and continued. +* All tools accept `-h` and `--help`, which print a usage message and exit + with status 0. * `daikon.diff.Diff` no longer accepts the `-u` and `-z` options, which had no effect. diff --git a/doc/daikon.texinfo b/doc/daikon.texinfo index 63824ae74e..ea54039cec 100644 --- a/doc/daikon.texinfo +++ b/doc/daikon.texinfo @@ -7034,6 +7034,9 @@ java -cp $@{DAIKONDIR@}/daikon.jar daikon.AnnotateNullable @i{[@var{flags}]} @va The flags are: @table @option +@item -h --help +Print usage message. + @item -n --nonnull-annotations Adds @samp{NonNull} annotations as well as @samp{Nullable} annotations. Unlike @samp{Nullable} annotations, @samp{NonNull} annotations are not guaranteed to be correct. diff --git a/java/daikon/AnnotateNullable.java b/java/daikon/AnnotateNullable.java index 5241c5e722..957fe44e40 100644 --- a/java/daikon/AnnotateNullable.java +++ b/java/daikon/AnnotateNullable.java @@ -64,12 +64,24 @@ private AnnotateNullable() { @Option("-n Insert NonNull as well as Nullable annotations") public static boolean nonnull_annotations = false; + /** If true, print a usage message and exit. */ + @Option("-h Display usage information") + public static boolean help = false; + public static void main(String[] args) throws IOException { Options options = - new Options("plume.AnnotateNullable [options] ", AnnotateNullable.class); + new Options("daikon.AnnotateNullable [options] ", AnnotateNullable.class); String[] inv_files = options.parse(true, args); - assert inv_files.length == 1; + if (help) { + options.printUsage(); + System.exit(0); + } + if (inv_files.length != 1) { + System.err.println("must specify exactly one invariant file"); + options.printUsage(); + System.exit(1); + } // Read the serialized invariant file File inv_file = new File(inv_files[0]); diff --git a/java/daikon/Chicory.java b/java/daikon/Chicory.java index c77e6426b5..eafad6653c 100644 --- a/java/daikon/Chicory.java +++ b/java/daikon/Chicory.java @@ -240,7 +240,7 @@ public static void main(String[] args) { public static void check_args(Options options, String[] target_args) { if (help) { options.printUsage(); - System.exit(1); + System.exit(0); } if (nesting_depth < 0) { System.out.printf("nesting depth (%d) must not be negative%n", nesting_depth); diff --git a/java/daikon/DynComp.java b/java/daikon/DynComp.java index d7a4118c0a..3c03de694f 100644 --- a/java/daikon/DynComp.java +++ b/java/daikon/DynComp.java @@ -179,7 +179,7 @@ public static void main(String[] args) { public static void check_args(Options options, String[] targetArgs) { if (help) { options.printUsage(); - System.exit(1); + System.exit(0); } if (nesting_depth < 0) { System.out.printf("nesting depth (%d) must not be negative%n", nesting_depth); diff --git a/java/daikon/SplitDtrace.java b/java/daikon/SplitDtrace.java index d13b4b81cb..aff7705ba9 100644 --- a/java/daikon/SplitDtrace.java +++ b/java/daikon/SplitDtrace.java @@ -29,6 +29,9 @@ */ public final class SplitDtrace { + /** The usage message for this program. */ + private static final String usage = "Usage: java daikon.SplitDtrace file.dtrace[.gz]"; + /** Do not instantiate. */ private SplitDtrace() { throw new UnsupportedOperationException("Do not instantiate"); @@ -40,14 +43,29 @@ private SplitDtrace() { * @param args one argument, the name of the .dtrace or .dtrace.gz file */ public static void main(String[] args) throws IOException { - if (args.length != 1) { - throw new RuntimeException( - "You must supply one argument which is the filename of the dtrace file"); + try { + mainHelper(args); + } catch (Daikon.DaikonTerminationException e) { + Daikon.handleDaikonTerminationException(e); + } + } + + /** + * This does the work of {@link #main(String[])}, but it never calls System.exit, so it is + * appropriate to be called programmatically. + * + * @param args command-line arguments, like those of {@link #main} + * @throws IOException if there is a problem reading or writing a file + */ + public static void mainHelper(String[] args) throws IOException { + String[] files = DaikonGetopt.nonOptionArgs(args, usage); + if (files.length != 1) { + throw new Daikon.UserError(usage); } - String filename = args[0].trim(); + String filename = files[0].trim(); boolean isGz = filename.endsWith(".dtrace.gz"); if (!filename.endsWith(".dtrace") && !isGz) { - throw new RuntimeException( + throw new Daikon.UserError( "Filename must end with .dtrace or .dtrace.gz: filename=" + filename); } int declNum = 1; diff --git a/java/daikon/dcomp/BuildJDK.java b/java/daikon/dcomp/BuildJDK.java index 7f1cae05f3..35cf4b0583 100644 --- a/java/daikon/dcomp/BuildJDK.java +++ b/java/daikon/dcomp/BuildJDK.java @@ -122,6 +122,10 @@ public static void main(String[] args) throws IOException { DynComp.class, DCInstrument.class); String[] cl_args = options.parse(true, args); + if (DynComp.help) { + options.printUsage(); + System.exit(0); + } if (cl_args.length < 1) { System.err.println("must specify destination dir"); options.printUsage(); diff --git a/java/daikon/dcomp/BuildJDK24.java b/java/daikon/dcomp/BuildJDK24.java index 74c83abacf..13fb445108 100644 --- a/java/daikon/dcomp/BuildJDK24.java +++ b/java/daikon/dcomp/BuildJDK24.java @@ -132,6 +132,10 @@ public static void main(String[] args) throws IOException { DynComp.class, DCInstrument24.class); String[] cl_args = options.parse(true, args); + if (DynComp.help) { + options.printUsage(); + System.exit(0); + } if (cl_args.length < 1) { System.err.println("must specify destination dir"); options.printUsage(); diff --git a/java/daikon/test/BadOptionTest.java b/java/daikon/test/BadOptionTest.java index af9b745d24..4442f98f53 100644 --- a/java/daikon/test/BadOptionTest.java +++ b/java/daikon/test/BadOptionTest.java @@ -9,6 +9,7 @@ import daikon.Daikon; import daikon.DaikonGetopt; import daikon.PrintInvariants; +import daikon.SplitDtrace; import daikon.UnionInvariants; import daikon.tools.DtraceDiff; import gnu.getopt.LongOpt; @@ -158,6 +159,7 @@ public void testPrintInvariantsUnrecognizedOption() { public void testHelpOption() { assertPrintsUsage(() -> DtraceDiff.mainHelper(new String[] {"--help"})); assertPrintsUsage(() -> UnionInvariants.mainHelper(new String[] {"--help"})); + assertPrintsUsage(() -> SplitDtrace.mainHelper(new String[] {"-h", "x"})); } /** diff --git a/java/daikon/tools/DtraceNonceFixer.java b/java/daikon/tools/DtraceNonceFixer.java index 942ed31dca..273e0de541 100644 --- a/java/daikon/tools/DtraceNonceFixer.java +++ b/java/daikon/tools/DtraceNonceFixer.java @@ -2,6 +2,7 @@ package daikon.tools; +import daikon.DaikonGetopt; import java.io.BufferedReader; import java.io.IOException; import java.io.PrintWriter; @@ -53,14 +54,15 @@ public static void main(String[] args) { * @param args command-line arguments, like those of {@link #main} */ public static void mainHelper(final String[] args) { - if (args.length != 1) { + String[] files = DaikonGetopt.nonOptionArgs(args, usage); + if (files.length != 1) { throw new daikon.Daikon.UserError(usage); } String outputFilename = - args[0].endsWith(".gz") ? (args[0] + "_fixed.gz") : (args[0] + "_fixed"); + files[0].endsWith(".gz") ? (files[0] + "_fixed.gz") : (files[0] + "_fixed"); - try (BufferedReader br1 = FilesPlume.newBufferedFileReader(args[0]); + try (BufferedReader br1 = FilesPlume.newBufferedFileReader(files[0]); PrintWriter out1 = new PrintWriter(FilesPlume.newBufferedFileWriter(outputFilename))) { // maxNonce - the biggest nonce ever found in the file @@ -93,7 +95,7 @@ public static void mainHelper(final String[] args) { // now go back and add the OBJECT and CLASS invocations String allFixedFilename = - outputFilename.endsWith(".gz") ? (args[0] + "_all_fixed.gz") : (args[0] + "_all_fixed"); + outputFilename.endsWith(".gz") ? (files[0] + "_all_fixed.gz") : (files[0] + "_all_fixed"); try (BufferedReader br2 = FilesPlume.newBufferedFileReader(outputFilename); PrintWriter out2 = new PrintWriter(FilesPlume.newBufferedFileWriter(allFixedFilename))) { diff --git a/java/daikon/tools/ReadTrace.java b/java/daikon/tools/ReadTrace.java index b47369d795..944e3b3609 100644 --- a/java/daikon/tools/ReadTrace.java +++ b/java/daikon/tools/ReadTrace.java @@ -1,5 +1,7 @@ package daikon.tools; +import daikon.Daikon; +import daikon.DaikonGetopt; import daikon.FileIO; import daikon.PptMap; import daikon.PptTopLevel; @@ -32,6 +34,9 @@ */ public class ReadTrace { + /** The usage message for this program. */ + private static final String usage = "Usage: java daikon.tools.ReadTrace file1 file2 ..."; + /** Do not instantiate. */ private ReadTrace() { throw new UnsupportedOperationException("Do not instantiate"); @@ -43,11 +48,30 @@ private ReadTrace() { * @param args data trace file names, read from the command line */ public static void main(String[] args) { + try { + mainHelper(args); + } catch (Daikon.DaikonTerminationException e) { + Daikon.handleDaikonTerminationException(e); + } + } + + /** + * This does the work of {@link #main(String[])}, but it never calls System.exit, so it is + * appropriate to be called programmatically. + * + * @param args command-line arguments, like those of {@link #main} + */ + public static void mainHelper(String[] args) { + String[] traceFiles = DaikonGetopt.nonOptionArgs(args, usage); + if (traceFiles.length == 0) { + throw new Daikon.UserError("No trace files specified" + Daikon.lineSep + usage); + } CollectDataProcessor processor = new CollectDataProcessor(); PptMap ppts = new PptMap(); try { // `read_data_trace_files()` requires the list of files to be modifiable. - FileIO.read_data_trace_files(new ArrayList<>(Arrays.asList(args)), ppts, processor, false); + FileIO.read_data_trace_files( + new ArrayList<>(Arrays.asList(traceFiles)), ppts, processor, false); } catch (Exception e) { throw new Error(e); } From 6380a6a04889ac022cda575bf663d013acd32109 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Tue, 6 Oct 2026 18:06:28 -0700 Subject: [PATCH 03/16] Remove stale comment in DtraceDiff --- java/daikon/tools/DtraceDiff.java | 1 - 1 file changed, 1 deletion(-) diff --git a/java/daikon/tools/DtraceDiff.java b/java/daikon/tools/DtraceDiff.java index e1c7bbce3f..0fe001621e 100644 --- a/java/daikon/tools/DtraceDiff.java +++ b/java/daikon/tools/DtraceDiff.java @@ -225,7 +225,6 @@ public static void mainHelper(final String[] args) { throw new Daikon.BugInDaikon("Unhandled long option " + option_name); } - // short options default: throw new Daikon.BugInDaikon("getopt() returned " + c); } From 056584e41965be9af31a1218082cf2f332d1af47 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Tue, 6 Oct 2026 18:06:35 -0700 Subject: [PATCH 04/16] AnnotateNullable: print usage to stderr on error --- java/daikon/AnnotateNullable.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java/daikon/AnnotateNullable.java b/java/daikon/AnnotateNullable.java index 957fe44e40..17769b8dfd 100644 --- a/java/daikon/AnnotateNullable.java +++ b/java/daikon/AnnotateNullable.java @@ -79,7 +79,7 @@ public static void main(String[] args) throws IOException { } if (inv_files.length != 1) { System.err.println("must specify exactly one invariant file"); - options.printUsage(); + options.printUsage(System.err); System.exit(1); } From 23bf08dae7ae957058512bd2f82270a41ddaf5ad Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Tue, 6 Oct 2026 18:51:13 -0700 Subject: [PATCH 05/16] Address code review: reject "- " with no short options, report instrumenter argument errors on stderr, simplify ambiguity check --- java/daikon/DaikonGetopt.java | 136 ++++-------------- java/daikon/test/BadOptionTest.java | 93 +++++------- .../runtimechecker/InstrumentHandler.java | 73 +++++----- 3 files changed, 101 insertions(+), 201 deletions(-) diff --git a/java/daikon/DaikonGetopt.java b/java/daikon/DaikonGetopt.java index 0f71e31406..a2a196f920 100644 --- a/java/daikon/DaikonGetopt.java +++ b/java/daikon/DaikonGetopt.java @@ -1,9 +1,9 @@ package daikon; +import static daikon.tools.nullness.NullnessUtil.castNonNull; + import gnu.getopt.Getopt; import gnu.getopt.LongOpt; -import java.util.Arrays; -import java.util.function.Supplier; import org.checkerframework.checker.nullness.qual.Nullable; import org.plumelib.util.ArraysPlume; @@ -22,23 +22,22 @@ public class DaikonGetopt extends Getopt { private static final String PROGNAME = "DaikonGetopt"; /** - * Computes the usage message printed for {@code -h} and {@code --help}, or null if the caller - * handles them. + * The usage message printed for {@code -h} and {@code --help}, or null if the caller handles + * them. */ - private final @Nullable Supplier usage; - - /** Text appended to the description of a bad command-line option, or null to append nothing. */ - private @Nullable String usageHint = "run with -h for usage"; + private final @Nullable String usage; /** - * Creates a command-line option processor that recognizes short and long options. + * Creates a command-line option processor that recognizes short and long options. Its description + * of a bad option does not suggest running with {@code -h}, because it does not handle {@code + * -h}. * * @param argv the command-line arguments * @param optstring the short options, in the format of {@link Getopt} * @param longopts the long options */ public DaikonGetopt(String[] argv, String optstring, LongOpt[] longopts) { - super(PROGNAME, argv, optstring, longopts); + super(PROGNAME, argv, nonEmpty(optstring), longopts); this.usage = null; opterr = false; } @@ -53,23 +52,22 @@ public DaikonGetopt(String[] argv, String optstring, LongOpt[] longopts) { * @param usage the usage message to print for {@code -h} and {@code --help} */ public DaikonGetopt(String[] argv, String optstring, LongOpt[] longopts, String usage) { - this(argv, optstring, longopts, () -> usage); + super(PROGNAME, argv, withH(optstring), withHelp(longopts)); + this.usage = usage; + opterr = false; } /** - * Creates a command-line option processor that recognizes short and long options, plus {@code -h} - * and {@code --help}, which print the usage message and throw {@link Daikon.NormalTermination}. - * The usage message is computed only if it is needed. + * Returns short options that are equivalent to the given ones but are not empty. Getopt replaces + * an empty optstring by " ", which makes "- " a valid option. * - * @param argv the command-line arguments - * @param optstring the short options, in the format of {@link Getopt}; must not contain {@code h} - * @param longopts the long options; must not contain {@code help} - * @param usage computes the usage message to print for {@code -h} and {@code --help} + * @param optstring short options, in the format of {@link Getopt} + * @return {@code optstring}, or ":" if {@code optstring} is empty */ - public DaikonGetopt(String[] argv, String optstring, LongOpt[] longopts, Supplier usage) { - super(PROGNAME, argv, withH(optstring), withHelp(longopts)); - this.usage = usage; - opterr = false; + private static String nonEmpty(String optstring) { + // A leading ':' only makes Getopt return ':' rather than '?' for a missing argument, which + // getopt() treats identically. + return optstring.isEmpty() ? ":" : optstring; } /** @@ -101,87 +99,6 @@ private static LongOpt[] withHelp(LongOpt[] longopts) { longopts, new LongOpt(Daikon.help_SWITCH, LongOpt.NO_ARGUMENT, null, 'h')); } - /** - * Processes the command-line arguments of a program that takes no options other than {@code -h} - * and {@code --help}. - * - * @param argv the command-line arguments - * @param usage the usage message to print for {@code -h} and {@code --help} - * @return the arguments that are not options - * @throws Daikon.NormalTermination after printing the usage message, if an argument requests it - * @throws Daikon.UserError if an argument is any other option - */ - public static String[] nonOptionArgs(String[] argv, String usage) { - return argsAfterOptions(argv, "", () -> usage); - } - - /** - * Processes the leading command-line arguments of a program that takes no options other than - * {@code -h} and {@code --help}. Processing stops at the first argument that is not an option, so - * later arguments may be options for some other program. - * - * @param argv the command-line arguments - * @param usage the usage message to print for {@code -h} and {@code --help} - * @return the arguments from the first one that is not an option onward - * @throws Daikon.NormalTermination after printing the usage message, if a leading argument - * requests it - * @throws Daikon.UserError if a leading argument is any other option - */ - public static String[] argsAfterLeadingOptions(String[] argv, String usage) { - return argsAfterLeadingOptions(argv, () -> usage); - } - - /** - * Like {@link #argsAfterLeadingOptions(String[], String)}, but computes the usage message only if - * it is needed. - * - * @param argv the command-line arguments - * @param usage computes the usage message to print for {@code -h} and {@code --help} - * @return the arguments from the first one that is not an option onward - * @throws Daikon.NormalTermination after printing the usage message, if a leading argument - * requests it - * @throws Daikon.UserError if a leading argument is any other option - */ - public static String[] argsAfterLeadingOptions(String[] argv, Supplier usage) { - // A leading "+" tells Getopt to stop at the first argument that is not an option. - return argsAfterOptions(argv, "+", usage); - } - - /** - * Processes command-line arguments, permitting no options other than {@code -h} and {@code - * --help}. - * - * @param argv the command-line arguments - * @param optstring "" to process all the arguments, or "+" to stop at the first non-option - * @param usage computes the usage message to print for {@code -h} and {@code --help} - * @return the arguments that Getopt did not process as options - * @throws Daikon.NormalTermination after printing the usage message, if an argument requests it - * @throws Daikon.UserError if an argument is any other option - */ - private static String[] argsAfterOptions( - String[] argv, String optstring, Supplier usage) { - // Getopt permutes its argument array, so give it a copy to avoid modifying the caller's array. - String[] argvCopy = argv.clone(); - DaikonGetopt g = new DaikonGetopt(argvCopy, optstring, new LongOpt[0], usage); - // Every option other than -h and --help is bad, so getopt() returns only -1 or throws. - int c = g.getopt(); - if (c != -1) { - throw new Daikon.BugInDaikon("getopt() returned " + c); - } - return Arrays.copyOfRange(argvCopy, g.getOptind(), argvCopy.length); - } - - /** - * Sets the text that is appended to the description of a bad command-line option. The default - * tells the user to run the program with -h. - * - * @param usageHint text appended to the description of a bad command-line option, or null to - * append nothing - */ - public void setUsageHint(@Nullable String usageHint) { - this.usageHint = usageHint; - } - /** * Like {@link Getopt#getopt()}, but never returns {@code '?'} or {@code ':'}. Getopt returns * {@code ':'} for a missing argument if the optstring starts with {@code ':'}. If this was @@ -199,7 +116,7 @@ public int getopt() { throw badOptionError(); } if (c == 'h' && usage != null) { - System.out.println(usage.get()); + System.out.println(usage); throw new Daikon.NormalTermination(); } return c; @@ -213,8 +130,8 @@ public int getopt() { */ private Daikon.UserError badOptionError() { String message = badOptionMessage(); - if (usageHint != null) { - message += "; " + usageHint; + if (usage != null) { + message += "; run with -h for usage"; } return new Daikon.UserError(message); } @@ -250,14 +167,15 @@ private String badOptionMessage() { private String longOptionMessage(String arg) { int equalsPos = arg.indexOf('='); String name = (equalsPos == -1) ? arg.substring(2) : arg.substring(2, equalsPos); - LongOpt[] longopts = long_options; // Getopt treats an empty name, as in "--=foo", as a prefix of every long option. if (name.isEmpty()) { return "Unrecognized command-line option " + arg; } - if (longopts == null || longind == -1) { + if (longind == -1) { return "Unrecognized command-line option --" + name; } + // Every constructor passes long options to Getopt. + LongOpt[] longopts = castNonNull(long_options); LongOpt match = longopts[longind]; // For an inexact match, Getopt sets longind to the first long option that has the given // prefix. The match is ambiguous if a later long option also has the prefix. @@ -273,7 +191,7 @@ private String longOptionMessage(String arg) { } else if (equalsPos == -1 && match.getHasArg() == LongOpt.REQUIRED_ARGUMENT) { return "Command-line option --" + match.getName() + " requires an argument"; } else { - return "Bad command-line option " + arg; + throw new Daikon.BugInDaikon("Getopt rejected " + arg + " for no known reason"); } } } diff --git a/java/daikon/test/BadOptionTest.java b/java/daikon/test/BadOptionTest.java index af9b745d24..78f76e8159 100644 --- a/java/daikon/test/BadOptionTest.java +++ b/java/daikon/test/BadOptionTest.java @@ -1,7 +1,6 @@ package daikon.test; import static java.nio.charset.StandardCharsets.UTF_8; -import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertThrows; @@ -57,58 +56,58 @@ private static void consumeAll(DaikonGetopt g) { while (g.getopt() != -1) {} } - /** - * Returns the expected message for a bad option. - * - * @param description a description of the bad option - * @return the expected message for a bad option - */ - private static String expected(String description) { - return description + "; run with -h for usage"; - } - /** Tests an unrecognized long option. */ @Test public void testUnrecognizedLongOption() { - assertEquals(expected("Unrecognized command-line option --bogus"), parse("--bogus")); - assertEquals(expected("Unrecognized command-line option --bogus"), parse("--bogus=3")); - assertEquals(expected("Unrecognized command-line option --=3"), parse("--=3")); - assertEquals( - expected("Unrecognized command-line option --bogus"), parse("-h", "--bogus", "file")); + assertEquals("Unrecognized command-line option --bogus", parse("--bogus")); + assertEquals("Unrecognized command-line option --bogus", parse("--bogus=3")); + assertEquals("Unrecognized command-line option --=3", parse("--=3")); + assertEquals("Unrecognized command-line option --bogus", parse("-h", "--bogus", "file")); } /** Tests an unrecognized short option, alone and combined with a valid one. */ @Test public void testUnrecognizedShortOption() { - assertEquals(expected("Unrecognized command-line option -x"), parse("-x")); - assertEquals(expected("Unrecognized command-line option -x"), parse("-xh")); - assertEquals(expected("Unrecognized command-line option -x"), parse("-hx")); - assertEquals(expected("Unrecognized command-line option -:"), parse("-:")); + assertEquals("Unrecognized command-line option -x", parse("-x")); + assertEquals("Unrecognized command-line option -x", parse("-xh")); + assertEquals("Unrecognized command-line option -x", parse("-hx")); + assertEquals("Unrecognized command-line option -:", parse("-:")); + } + + /** Tests an unrecognized short option when there are no short options. */ + @Test + public void testNoShortOptions() { + for (String arg : new String[] {"- ", "-x", "-:"}) { + DaikonGetopt g = new DaikonGetopt(new String[] {arg}, "", longopts); + Daikon.UserError e = assertThrows(Daikon.UserError.class, g::getopt); + assertEquals("Unrecognized command-line option " + arg, String.valueOf(e.getMessage())); + } } /** Tests an ambiguous abbreviation of a long option. */ @Test public void testAmbiguousLongOption() { - assertEquals(expected("Ambiguous command-line option --conf"), parse("--conf=x")); - assertEquals(expected("Ambiguous command-line option --conf"), parse("--conf")); + assertEquals("Ambiguous command-line option --conf", parse("--conf=x")); + assertEquals("Ambiguous command-line option --conf", parse("--conf")); } - /** Tests that a usage hint of null appends nothing to the description of a bad option. */ + /** Tests that the description of a bad option suggests -h if DaikonGetopt handles -h. */ @Test - public void testNoUsageHint() { - DaikonGetopt g = new DaikonGetopt(new String[] {"--bogus"}, "h", longopts); - g.setUsageHint(null); + public void testUsageHint() { + DaikonGetopt g = new DaikonGetopt(new String[] {"--bogus"}, "o:", new LongOpt[0], "usage"); Daikon.UserError e = assertThrows(Daikon.UserError.class, g::getopt); - assertEquals("Unrecognized command-line option --bogus", String.valueOf(e.getMessage())); + assertEquals( + "Unrecognized command-line option --bogus; run with -h for usage", + String.valueOf(e.getMessage())); } /** Tests options that are missing their required argument. */ @Test public void testMissingArgument() { - assertEquals(expected("Command-line option --config requires an argument"), parse("--config")); - assertEquals(expected("Command-line option --debug requires an argument"), parse("--deb")); - assertEquals(expected("Command-line option -o requires an argument"), parse("-o")); - assertEquals(expected("Command-line option -o requires an argument"), parse("-ho")); + assertEquals("Command-line option --config requires an argument", parse("--config")); + assertEquals("Command-line option --debug requires an argument", parse("--deb")); + assertEquals("Command-line option -o requires an argument", parse("-o")); + assertEquals("Command-line option -o requires an argument", parse("-ho")); } /** Tests options that are missing their required argument, when the optstring starts with ':'. */ @@ -116,22 +115,18 @@ public void testMissingArgument() { public void testMissingArgumentLeadingColon() { DaikonGetopt g = new DaikonGetopt(new String[] {"-o"}, ":ho:", longopts); Daikon.UserError e = assertThrows(Daikon.UserError.class, g::getopt); - assertEquals( - expected("Command-line option -o requires an argument"), String.valueOf(e.getMessage())); + assertEquals("Command-line option -o requires an argument", String.valueOf(e.getMessage())); g = new DaikonGetopt(new String[] {"--config"}, ":ho:", longopts); e = assertThrows(Daikon.UserError.class, g::getopt); assertEquals( - expected("Command-line option --config requires an argument"), - String.valueOf(e.getMessage())); + "Command-line option --config requires an argument", String.valueOf(e.getMessage())); } /** Tests long options that are given an argument they do not take. */ @Test public void testUnexpectedArgument() { - assertEquals( - expected("Command-line option --help does not take an argument"), parse("--help=x")); - assertEquals( - expected("Command-line option --verbose does not take an argument"), parse("--verb=x")); + assertEquals("Command-line option --help does not take an argument", parse("--help=x")); + assertEquals("Command-line option --verbose does not take an argument", parse("--verb=x")); } /** @@ -142,7 +137,7 @@ public void testUnexpectedArgument() { */ private static void assertBadOption(String description, ThrowingRunnable mainCall) { Daikon.UserError e = assertThrows(Daikon.UserError.class, mainCall); - assertEquals(expected(description), String.valueOf(e.getMessage())); + assertEquals(description + "; run with -h for usage", String.valueOf(e.getMessage())); } /** Tests an unrecognized long option in a tool. */ @@ -178,22 +173,4 @@ private static void assertPrintsUsage(ThrowingRunnable code) { } assertNotEquals("", bytes.toString(UTF_8).trim()); } - - /** Tests {@link DaikonGetopt#nonOptionArgs}. */ - @Test - public void testNonOptionArgs() { - assertArrayEquals( - new String[] {"a.dtrace", "b.dtrace"}, - DaikonGetopt.nonOptionArgs(new String[] {"a.dtrace", "b.dtrace"}, "u")); - assertArrayEquals( - new String[] {"-a.dtrace"}, - DaikonGetopt.nonOptionArgs(new String[] {"--", "-a.dtrace"}, "u")); - assertBadOption( - "Unrecognized command-line option --bogus", - () -> DaikonGetopt.nonOptionArgs(new String[] {"x", "--bogus"}, "u")); - assertBadOption( - "Unrecognized command-line option -x", - () -> DaikonGetopt.nonOptionArgs(new String[] {"-x"}, "u")); - assertPrintsUsage(() -> DaikonGetopt.nonOptionArgs(new String[] {"x", "--help"}, "u")); - } } diff --git a/java/daikon/tools/runtimechecker/InstrumentHandler.java b/java/daikon/tools/runtimechecker/InstrumentHandler.java index ffd4e77a48..b5f2ca3007 100644 --- a/java/daikon/tools/runtimechecker/InstrumentHandler.java +++ b/java/daikon/tools/runtimechecker/InstrumentHandler.java @@ -5,11 +5,11 @@ import static java.util.logging.Level.INFO; import daikon.Daikon; +import daikon.DaikonGetopt; import daikon.FileIO; import daikon.Global; import daikon.PptMap; import daikon.tools.jtb.ParseResults; -import gnu.getopt.Getopt; import gnu.getopt.LongOpt; import java.io.File; import java.io.IOException; @@ -213,59 +213,64 @@ private Arguments readArguments(String[] args) { new LongOpt(directory_SWITCH, LongOpt.REQUIRED_ARGUMENT, null, 0), new LongOpt(checkers_directory_SWITCH, LongOpt.REQUIRED_ARGUMENT, null, 0) }; - Getopt g = new Getopt("daikon.tools.runtimechecker.InstrumentHandler", args, "hs", longopts); - int c; - while ((c = g.getopt()) != -1) { - switch (c) { - case 0: - // got a long option - String option_name = longopts[g.getLongind()].getName(); - - if (create_checker_classes_SWITCH.equals(option_name)) { - createCheckerClasses = true; - } else if (output_only_high_conf_invariants_SWITCH.equals(option_name)) { - InstrumentVisitor.outputOnlyHighConfInvariants = true; - } else if (make_all_fields_public_SWITCH.equals(option_name)) { - InstrumentVisitor.makeAllFieldsPublic = true; - } else if (directory_SWITCH.equals(option_name)) { - instrumented_directory = Daikon.getOptarg(g); - } else if (checkers_directory_SWITCH.equals(option_name)) { - checkersOutputDirName = Daikon.getOptarg(g); - } else if (Daikon.debugAll_SWITCH.equals(option_name)) { - Global.debugAll = true; - } else if (Daikon.debug_SWITCH.equals(option_name)) { - daikon.LogHelper.setLevel(Daikon.getOptarg(g), FINE); - } else { - System.err.println("Unknown long option received: " + option_name); - } - break; - default: - System.out.println("unrecognized option" + c); - return errorWhileReadingArguments; + // Main prints the usage message when this tool fails, so DaikonGetopt need not handle -h. + DaikonGetopt g = new DaikonGetopt(args, "", longopts); + try { + int c; + while ((c = g.getopt()) != -1) { + switch (c) { + case 0: + // got a long option + String option_name = longopts[g.getLongind()].getName(); + + if (create_checker_classes_SWITCH.equals(option_name)) { + createCheckerClasses = true; + } else if (output_only_high_conf_invariants_SWITCH.equals(option_name)) { + InstrumentVisitor.outputOnlyHighConfInvariants = true; + } else if (make_all_fields_public_SWITCH.equals(option_name)) { + InstrumentVisitor.makeAllFieldsPublic = true; + } else if (directory_SWITCH.equals(option_name)) { + instrumented_directory = Daikon.getOptarg(g); + } else if (checkers_directory_SWITCH.equals(option_name)) { + checkersOutputDirName = Daikon.getOptarg(g); + } else if (Daikon.debugAll_SWITCH.equals(option_name)) { + Global.debugAll = true; + } else if (Daikon.debug_SWITCH.equals(option_name)) { + daikon.LogHelper.setLevel(Daikon.getOptarg(g), FINE); + } else { + throw new Daikon.BugInDaikon("Unhandled long option " + option_name); + } + break; + default: + throw new Daikon.BugInDaikon("getopt() returned " + c); + } } + } catch (Daikon.UserError e) { + System.err.println("Error: " + e.getMessage()); + return errorWhileReadingArguments; } // The index of the first non-option argument -- the name of the // invariant file. int argindex = g.getOptind(); if (argindex >= args.length) { - System.out.println("Error: No .inv file or .java file arguments supplied."); + System.err.println("Error: No .inv file or .java file arguments supplied."); return errorWhileReadingArguments; } String invfile = args[argindex]; argindex++; if (!(invfile.endsWith(".inv") || invfile.endsWith(".inv.gz"))) { - System.out.println("Error: first argument must be a file ending in .inv or .inv.gz."); + System.err.println("Error: first argument must be a file ending in .inv or .inv.gz."); return errorWhileReadingArguments; } if (argindex >= args.length) { - System.out.println("Error: No .java file arguments supplied."); + System.err.println("Error: No .java file arguments supplied."); return errorWhileReadingArguments; } List javaFileNames = new ArrayList<>(); for (; argindex < args.length; argindex++) { String javafile = args[argindex]; if (!javafile.endsWith(".java")) { - System.out.println("File does not end in .java: " + javafile); + System.err.println("File does not end in .java: " + javafile); return errorWhileReadingArguments; } javaFileNames.add(javafile); From 0242d85cf45cb882e98c0998966c37fb3fdc74a5 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Tue, 6 Oct 2026 22:19:39 -0700 Subject: [PATCH 06/16] Address code review: recognize -h in instrumenter, fix runcluster.pl option, report SplitterFactoryTest failures on stderr, shorten Diff error, align Annotate usage --- java/daikon/diff/Diff.java | 2 +- .../test/split/SplitterFactoryTestUpdater.java | 5 +++-- java/daikon/tools/jtb/Annotate.java | 8 ++++---- .../tools/runtimechecker/InstrumentHandler.java | 16 +++++++++++++--- scripts/runcluster.pl | 2 +- scripts/trace-purge-vars.pl | 2 +- 6 files changed, 23 insertions(+), 12 deletions(-) diff --git a/java/daikon/diff/Diff.java b/java/daikon/diff/Diff.java index 6355ef0892..324406bafb 100644 --- a/java/daikon/diff/Diff.java +++ b/java/daikon/diff/Diff.java @@ -413,7 +413,7 @@ public static void mainHelper(final String[] args) v1.printAll(); return; } else { - throw new Daikon.UserError("No invariant files specified" + Daikon.lineSep + usage); + throw new Daikon.UserError("No invariant files specified; run with -h for usage"); } if (logging) { diff --git a/java/daikon/test/split/SplitterFactoryTestUpdater.java b/java/daikon/test/split/SplitterFactoryTestUpdater.java index c5be608fc7..7f9e1f1016 100644 --- a/java/daikon/test/split/SplitterFactoryTestUpdater.java +++ b/java/daikon/test/split/SplitterFactoryTestUpdater.java @@ -269,12 +269,13 @@ private static String getTestClassText() { ps.println(" }"); ps.println(" Result result = JUnitCore.runClasses(SplitterFactoryTest.class);"); ps.println(" for (Failure failure : result.getFailures()) {"); - ps.println(" System.out.println(failure.getTrace());"); + ps.println(" System.err.println(failure.getTrace());"); ps.println(" }"); ps.println(" if (!result.wasSuccessful()) {"); ps.println( - " throw new Daikon.UserError(StringsPlume.nPlural(result.getFailureCount(), \"test\")" + " System.err.println(StringsPlume.nPlural(result.getFailureCount(), \"test\")" + " + \" failed\");"); + ps.println(" System.exit(1);"); ps.println(" }"); ps.println(" }"); ps.println(); diff --git a/java/daikon/tools/jtb/Annotate.java b/java/daikon/tools/jtb/Annotate.java index cee7292928..b76c70ef97 100644 --- a/java/daikon/tools/jtb/Annotate.java +++ b/java/daikon/tools/jtb/Annotate.java @@ -87,10 +87,10 @@ private Annotate() { private static String usage = StringsPlume.joinLines( "Usage: java daikon.tools.Annotate FILE.inv FILE.java ...", - " -h, --help Display this usage message", - " -i Insert invariants not supported by ESC with \"!\" instead of \"@\";", - " by default these \"inexpressible\" invariants are simply omitted", - " -s Use // comments rather than /* comments", + " -h, --help Display this usage message", + " -i Insert invariants not supported by ESC with \"!\" instead of \"@\";", + " by default these \"inexpressible\" invariants are simply omitted", + " -s Use // comments rather than /* comments", " --format name Insert specifications in the given format: DBC, ESC, JML, Java", " --wrap_xml Wrap each annotation and auxiliary information in XML tags", " --max_invariants_pp N", diff --git a/java/daikon/tools/runtimechecker/InstrumentHandler.java b/java/daikon/tools/runtimechecker/InstrumentHandler.java index b5f2ca3007..0886230f41 100644 --- a/java/daikon/tools/runtimechecker/InstrumentHandler.java +++ b/java/daikon/tools/runtimechecker/InstrumentHandler.java @@ -89,6 +89,9 @@ public boolean handle(String[] args) { if (arguments == errorWhileReadingArguments) { return false; } + if (arguments == helpRequested) { + return true; + } // Set up debug traces; note this comes after reading command line options. daikon.LogHelper.setupLogs(Global.debugAll ? FINE : INFO); @@ -201,6 +204,9 @@ private static class Arguments { private static Arguments errorWhileReadingArguments = new Arguments("error while reading arguments", new ArrayList()); + /** Indicates that the user requested the usage message, which has already been printed. */ + private static Arguments helpRequested = new Arguments("help requested", new ArrayList()); + private Arguments readArguments(String[] args) { LongOpt[] longopts = @@ -211,10 +217,11 @@ private Arguments readArguments(String[] args) { new LongOpt(make_all_fields_public_SWITCH, LongOpt.NO_ARGUMENT, null, 0), new LongOpt(create_checker_classes_SWITCH, LongOpt.NO_ARGUMENT, null, 0), new LongOpt(directory_SWITCH, LongOpt.REQUIRED_ARGUMENT, null, 0), - new LongOpt(checkers_directory_SWITCH, LongOpt.REQUIRED_ARGUMENT, null, 0) + new LongOpt(checkers_directory_SWITCH, LongOpt.REQUIRED_ARGUMENT, null, 0), + new LongOpt(Daikon.help_SWITCH, LongOpt.NO_ARGUMENT, null, 'h') }; - // Main prints the usage message when this tool fails, so DaikonGetopt need not handle -h. - DaikonGetopt g = new DaikonGetopt(args, "", longopts); + // This class handles -h itself, because its usage message is printed by usageMessage(). + DaikonGetopt g = new DaikonGetopt(args, "h", longopts); try { int c; while ((c = g.getopt()) != -1) { @@ -241,6 +248,9 @@ private Arguments readArguments(String[] args) { throw new Daikon.BugInDaikon("Unhandled long option " + option_name); } break; + case 'h': + usageMessage(); + return helpRequested; default: throw new Daikon.BugInDaikon("getopt() returned " + c); } diff --git a/scripts/runcluster.pl b/scripts/runcluster.pl index bf31f6de12..12559cd84c 100755 --- a/scripts/runcluster.pl +++ b/scripts/runcluster.pl @@ -209,7 +209,7 @@ () } my $invfile = "runcluster_temp_$algorithm-$ncluster.inv"; -$command = "java -cp $SCRIPTDIR/../daikon.jar -Xmx7g daikon.Daikon -o $invfile --config_option daikon.PptTopLevel.pairwise_implications=true --var_omit_pattern=\"class\" --no_text_output --no_show_progress $spinfo_file $decls_new " . join(' ', @new_dtraces) . " 2>&1 > runcluster_temp_Daikon_output.txt"; +$command = "java -cp $SCRIPTDIR/../daikon.jar -Xmx7g daikon.Daikon -o $invfile --config_option daikon.PptTopLevel.pairwise_implications=true --var-omit-pattern=\"class\" --no_text_output --no_show_progress $spinfo_file $decls_new " . join(' ', @new_dtraces) . " 2>&1 > runcluster_temp_Daikon_output.txt"; system_or_die($command, $verbose); $invfile =~ /(.*)\.inv/; diff --git a/scripts/trace-purge-vars.pl b/scripts/trace-purge-vars.pl index f3b95d73d9..c75fdc9a7e 100755 --- a/scripts/trace-purge-vars.pl +++ b/scripts/trace-purge-vars.pl @@ -8,7 +8,7 @@ # regular expression. (Its name is taken from grep.) # This script reduces the size of a trace file, but typically, using -# Daikon's --var_omit_pattern flag is a better option. +# Daikon's --var-omit-pattern flag is a better option. # I'm intentionally not operating by paragraphs, because I want the regexp # to only apply to the variable lines. From 9fc85faa8e21ada15ca6fa8047e3f0a99a173372 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Wed, 7 Oct 2026 07:20:27 -0700 Subject: [PATCH 07/16] Address code review: SplitterFactoryTest.mainHelper throws instead of exiting, report instrumenter option errors in one line, make sentinels final --- .../split/SplitterFactoryTestUpdater.java | 3 +- .../runtimechecker/InstrumentHandler.java | 70 +++++++++---------- java/daikon/tools/runtimechecker/Main.java | 6 ++ 3 files changed, 40 insertions(+), 39 deletions(-) diff --git a/java/daikon/test/split/SplitterFactoryTestUpdater.java b/java/daikon/test/split/SplitterFactoryTestUpdater.java index 7f9e1f1016..758c93b4a2 100644 --- a/java/daikon/test/split/SplitterFactoryTestUpdater.java +++ b/java/daikon/test/split/SplitterFactoryTestUpdater.java @@ -273,9 +273,8 @@ private static String getTestClassText() { ps.println(" }"); ps.println(" if (!result.wasSuccessful()) {"); ps.println( - " System.err.println(StringsPlume.nPlural(result.getFailureCount(), \"test\")" + " throw new Daikon.UserError(StringsPlume.nPlural(result.getFailureCount(), \"test\")" + " + \" failed\");"); - ps.println(" System.exit(1);"); ps.println(" }"); ps.println(" }"); ps.println(); diff --git a/java/daikon/tools/runtimechecker/InstrumentHandler.java b/java/daikon/tools/runtimechecker/InstrumentHandler.java index 0886230f41..72597a48a0 100644 --- a/java/daikon/tools/runtimechecker/InstrumentHandler.java +++ b/java/daikon/tools/runtimechecker/InstrumentHandler.java @@ -201,11 +201,12 @@ private static class Arguments { } } - private static Arguments errorWhileReadingArguments = + private static final Arguments errorWhileReadingArguments = new Arguments("error while reading arguments", new ArrayList()); /** Indicates that the user requested the usage message, which has already been printed. */ - private static Arguments helpRequested = new Arguments("help requested", new ArrayList()); + private static final Arguments helpRequested = + new Arguments("help requested", new ArrayList()); private Arguments readArguments(String[] args) { @@ -222,42 +223,37 @@ private Arguments readArguments(String[] args) { }; // This class handles -h itself, because its usage message is printed by usageMessage(). DaikonGetopt g = new DaikonGetopt(args, "h", longopts); - try { - int c; - while ((c = g.getopt()) != -1) { - switch (c) { - case 0: - // got a long option - String option_name = longopts[g.getLongind()].getName(); - - if (create_checker_classes_SWITCH.equals(option_name)) { - createCheckerClasses = true; - } else if (output_only_high_conf_invariants_SWITCH.equals(option_name)) { - InstrumentVisitor.outputOnlyHighConfInvariants = true; - } else if (make_all_fields_public_SWITCH.equals(option_name)) { - InstrumentVisitor.makeAllFieldsPublic = true; - } else if (directory_SWITCH.equals(option_name)) { - instrumented_directory = Daikon.getOptarg(g); - } else if (checkers_directory_SWITCH.equals(option_name)) { - checkersOutputDirName = Daikon.getOptarg(g); - } else if (Daikon.debugAll_SWITCH.equals(option_name)) { - Global.debugAll = true; - } else if (Daikon.debug_SWITCH.equals(option_name)) { - daikon.LogHelper.setLevel(Daikon.getOptarg(g), FINE); - } else { - throw new Daikon.BugInDaikon("Unhandled long option " + option_name); - } - break; - case 'h': - usageMessage(); - return helpRequested; - default: - throw new Daikon.BugInDaikon("getopt() returned " + c); - } + int c; + while ((c = g.getopt()) != -1) { + switch (c) { + case 0: + // got a long option + String option_name = longopts[g.getLongind()].getName(); + + if (create_checker_classes_SWITCH.equals(option_name)) { + createCheckerClasses = true; + } else if (output_only_high_conf_invariants_SWITCH.equals(option_name)) { + InstrumentVisitor.outputOnlyHighConfInvariants = true; + } else if (make_all_fields_public_SWITCH.equals(option_name)) { + InstrumentVisitor.makeAllFieldsPublic = true; + } else if (directory_SWITCH.equals(option_name)) { + instrumented_directory = Daikon.getOptarg(g); + } else if (checkers_directory_SWITCH.equals(option_name)) { + checkersOutputDirName = Daikon.getOptarg(g); + } else if (Daikon.debugAll_SWITCH.equals(option_name)) { + Global.debugAll = true; + } else if (Daikon.debug_SWITCH.equals(option_name)) { + daikon.LogHelper.setLevel(Daikon.getOptarg(g), FINE); + } else { + throw new Daikon.BugInDaikon("Unhandled long option " + option_name); + } + break; + case 'h': + usageMessage(); + return helpRequested; + default: + throw new Daikon.BugInDaikon("getopt() returned " + c); } - } catch (Daikon.UserError e) { - System.err.println("Error: " + e.getMessage()); - return errorWhileReadingArguments; } // The index of the first non-option argument -- the name of the // invariant file. diff --git a/java/daikon/tools/runtimechecker/Main.java b/java/daikon/tools/runtimechecker/Main.java index 9259e07f45..4f401bc165 100644 --- a/java/daikon/tools/runtimechecker/Main.java +++ b/java/daikon/tools/runtimechecker/Main.java @@ -1,5 +1,6 @@ package daikon.tools.runtimechecker; +import daikon.Daikon; import java.util.Collections; import java.util.List; import java.util.Locale; @@ -57,6 +58,11 @@ public void nonStaticMain(String[] args) { } } + } catch (Daikon.UserError e) { + // A user error, such as a bad command-line option, is reported in one line. System.exit + // prevents the finally block from printing generic failure text and the usage message. + System.err.println("Error: " + e.getMessage()); + System.exit(1); } catch (Throwable e) { System.out.println("Throwable thrown while handling command:" + e); e.printStackTrace(); From ada0caf4e0200eefcf333717bba169ab856b951e Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Wed, 7 Oct 2026 07:55:12 -0700 Subject: [PATCH 08/16] Provide DaikonGetopt helpers that the per-tool PRs use; leave instrumenter -h to runtimechecker-options DaikonGetopt again provides nonOptionArgs, argsAfterLeadingOptions, a Supplier-based constructor, and setUsageHint, which #885-#888 use. The instrumenter's -h and --help handling belongs to #888. --- java/daikon/DaikonGetopt.java | 135 +++++++++++++++--- .../runtimechecker/InstrumentHandler.java | 16 +-- 2 files changed, 120 insertions(+), 31 deletions(-) diff --git a/java/daikon/DaikonGetopt.java b/java/daikon/DaikonGetopt.java index a2a196f920..11a7807ac3 100644 --- a/java/daikon/DaikonGetopt.java +++ b/java/daikon/DaikonGetopt.java @@ -4,6 +4,8 @@ import gnu.getopt.Getopt; import gnu.getopt.LongOpt; +import java.util.Arrays; +import java.util.function.Supplier; import org.checkerframework.checker.nullness.qual.Nullable; import org.plumelib.util.ArraysPlume; @@ -22,10 +24,13 @@ public class DaikonGetopt extends Getopt { private static final String PROGNAME = "DaikonGetopt"; /** - * The usage message printed for {@code -h} and {@code --help}, or null if the caller handles - * them. + * Computes the usage message printed for {@code -h} and {@code --help}, or null if the caller + * handles them. */ - private final @Nullable String usage; + private final @Nullable Supplier usage; + + /** Text appended to the description of a bad command-line option, or null to append nothing. */ + private @Nullable String usageHint = "run with -h for usage"; /** * Creates a command-line option processor that recognizes short and long options. Its description @@ -39,9 +44,23 @@ public class DaikonGetopt extends Getopt { public DaikonGetopt(String[] argv, String optstring, LongOpt[] longopts) { super(PROGNAME, argv, nonEmpty(optstring), longopts); this.usage = null; + usageHint = null; opterr = false; } + /** + * Returns short options that are equivalent to the given ones but are not empty. Getopt replaces + * an empty optstring by " ", which makes "- " a valid option. + * + * @param optstring short options, in the format of {@link Getopt} + * @return {@code optstring}, or ":" if {@code optstring} is empty + */ + private static String nonEmpty(String optstring) { + // A leading ':' only makes Getopt return ':' rather than '?' for a missing argument, which + // getopt() treats identically. + return optstring.isEmpty() ? ":" : optstring; + } + /** * Creates a command-line option processor that recognizes short and long options, plus {@code -h} * and {@code --help}, which print the usage message and throw {@link Daikon.NormalTermination}. @@ -52,22 +71,23 @@ public DaikonGetopt(String[] argv, String optstring, LongOpt[] longopts) { * @param usage the usage message to print for {@code -h} and {@code --help} */ public DaikonGetopt(String[] argv, String optstring, LongOpt[] longopts, String usage) { - super(PROGNAME, argv, withH(optstring), withHelp(longopts)); - this.usage = usage; - opterr = false; + this(argv, optstring, longopts, () -> usage); } /** - * Returns short options that are equivalent to the given ones but are not empty. Getopt replaces - * an empty optstring by " ", which makes "- " a valid option. + * Creates a command-line option processor that recognizes short and long options, plus {@code -h} + * and {@code --help}, which print the usage message and throw {@link Daikon.NormalTermination}. + * The usage message is computed only if it is needed. * - * @param optstring short options, in the format of {@link Getopt} - * @return {@code optstring}, or ":" if {@code optstring} is empty + * @param argv the command-line arguments + * @param optstring the short options, in the format of {@link Getopt}; must not contain {@code h} + * @param longopts the long options; must not contain {@code help} + * @param usage computes the usage message to print for {@code -h} and {@code --help} */ - private static String nonEmpty(String optstring) { - // A leading ':' only makes Getopt return ':' rather than '?' for a missing argument, which - // getopt() treats identically. - return optstring.isEmpty() ? ":" : optstring; + public DaikonGetopt(String[] argv, String optstring, LongOpt[] longopts, Supplier usage) { + super(PROGNAME, argv, withH(optstring), withHelp(longopts)); + this.usage = usage; + opterr = false; } /** @@ -99,6 +119,87 @@ private static LongOpt[] withHelp(LongOpt[] longopts) { longopts, new LongOpt(Daikon.help_SWITCH, LongOpt.NO_ARGUMENT, null, 'h')); } + /** + * Processes the command-line arguments of a program that takes no options other than {@code -h} + * and {@code --help}. + * + * @param argv the command-line arguments + * @param usage the usage message to print for {@code -h} and {@code --help} + * @return the arguments that are not options + * @throws Daikon.NormalTermination after printing the usage message, if an argument requests it + * @throws Daikon.UserError if an argument is any other option + */ + public static String[] nonOptionArgs(String[] argv, String usage) { + return argsAfterOptions(argv, "", () -> usage); + } + + /** + * Processes the leading command-line arguments of a program that takes no options other than + * {@code -h} and {@code --help}. Processing stops at the first argument that is not an option, so + * later arguments may be options for some other program. + * + * @param argv the command-line arguments + * @param usage the usage message to print for {@code -h} and {@code --help} + * @return the arguments from the first one that is not an option onward + * @throws Daikon.NormalTermination after printing the usage message, if a leading argument + * requests it + * @throws Daikon.UserError if a leading argument is any other option + */ + public static String[] argsAfterLeadingOptions(String[] argv, String usage) { + return argsAfterLeadingOptions(argv, () -> usage); + } + + /** + * Like {@link #argsAfterLeadingOptions(String[], String)}, but computes the usage message only if + * it is needed. + * + * @param argv the command-line arguments + * @param usage computes the usage message to print for {@code -h} and {@code --help} + * @return the arguments from the first one that is not an option onward + * @throws Daikon.NormalTermination after printing the usage message, if a leading argument + * requests it + * @throws Daikon.UserError if a leading argument is any other option + */ + public static String[] argsAfterLeadingOptions(String[] argv, Supplier usage) { + // A leading "+" tells Getopt to stop at the first argument that is not an option. + return argsAfterOptions(argv, "+", usage); + } + + /** + * Processes command-line arguments, permitting no options other than {@code -h} and {@code + * --help}. + * + * @param argv the command-line arguments + * @param optstring "" to process all the arguments, or "+" to stop at the first non-option + * @param usage computes the usage message to print for {@code -h} and {@code --help} + * @return the arguments that Getopt did not process as options + * @throws Daikon.NormalTermination after printing the usage message, if an argument requests it + * @throws Daikon.UserError if an argument is any other option + */ + private static String[] argsAfterOptions( + String[] argv, String optstring, Supplier usage) { + // Getopt permutes its argument array, so give it a copy to avoid modifying the caller's array. + String[] argvCopy = argv.clone(); + DaikonGetopt g = new DaikonGetopt(argvCopy, optstring, new LongOpt[0], usage); + // Every option other than -h and --help is bad, so getopt() returns only -1 or throws. + int c = g.getopt(); + if (c != -1) { + throw new Daikon.BugInDaikon("getopt() returned " + c); + } + return Arrays.copyOfRange(argvCopy, g.getOptind(), argvCopy.length); + } + + /** + * Sets the text that is appended to the description of a bad command-line option. The default + * tells the user to run the program with -h. + * + * @param usageHint text appended to the description of a bad command-line option, or null to + * append nothing + */ + public void setUsageHint(@Nullable String usageHint) { + this.usageHint = usageHint; + } + /** * Like {@link Getopt#getopt()}, but never returns {@code '?'} or {@code ':'}. Getopt returns * {@code ':'} for a missing argument if the optstring starts with {@code ':'}. If this was @@ -116,7 +217,7 @@ public int getopt() { throw badOptionError(); } if (c == 'h' && usage != null) { - System.out.println(usage); + System.out.println(usage.get()); throw new Daikon.NormalTermination(); } return c; @@ -130,8 +231,8 @@ public int getopt() { */ private Daikon.UserError badOptionError() { String message = badOptionMessage(); - if (usage != null) { - message += "; run with -h for usage"; + if (usageHint != null) { + message += "; " + usageHint; } return new Daikon.UserError(message); } diff --git a/java/daikon/tools/runtimechecker/InstrumentHandler.java b/java/daikon/tools/runtimechecker/InstrumentHandler.java index 72597a48a0..06ed933a62 100644 --- a/java/daikon/tools/runtimechecker/InstrumentHandler.java +++ b/java/daikon/tools/runtimechecker/InstrumentHandler.java @@ -89,9 +89,6 @@ public boolean handle(String[] args) { if (arguments == errorWhileReadingArguments) { return false; } - if (arguments == helpRequested) { - return true; - } // Set up debug traces; note this comes after reading command line options. daikon.LogHelper.setupLogs(Global.debugAll ? FINE : INFO); @@ -204,10 +201,6 @@ private static class Arguments { private static final Arguments errorWhileReadingArguments = new Arguments("error while reading arguments", new ArrayList()); - /** Indicates that the user requested the usage message, which has already been printed. */ - private static final Arguments helpRequested = - new Arguments("help requested", new ArrayList()); - private Arguments readArguments(String[] args) { LongOpt[] longopts = @@ -218,11 +211,9 @@ private Arguments readArguments(String[] args) { new LongOpt(make_all_fields_public_SWITCH, LongOpt.NO_ARGUMENT, null, 0), new LongOpt(create_checker_classes_SWITCH, LongOpt.NO_ARGUMENT, null, 0), new LongOpt(directory_SWITCH, LongOpt.REQUIRED_ARGUMENT, null, 0), - new LongOpt(checkers_directory_SWITCH, LongOpt.REQUIRED_ARGUMENT, null, 0), - new LongOpt(Daikon.help_SWITCH, LongOpt.NO_ARGUMENT, null, 'h') + new LongOpt(checkers_directory_SWITCH, LongOpt.REQUIRED_ARGUMENT, null, 0) }; - // This class handles -h itself, because its usage message is printed by usageMessage(). - DaikonGetopt g = new DaikonGetopt(args, "h", longopts); + DaikonGetopt g = new DaikonGetopt(args, "", longopts); int c; while ((c = g.getopt()) != -1) { switch (c) { @@ -248,9 +239,6 @@ private Arguments readArguments(String[] args) { throw new Daikon.BugInDaikon("Unhandled long option " + option_name); } break; - case 'h': - usageMessage(); - return helpRequested; default: throw new Daikon.BugInDaikon("getopt() returned " + c); } From e8abaccb8662c0f04e093571cde06908da1083e6 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sat, 10 Oct 2026 13:07:05 -0700 Subject: [PATCH 09/16] Move the runtimechecker changes to the runtimechecker-options branch --- .../runtimechecker/InstrumentHandler.java | 19 ++++++++++--------- java/daikon/tools/runtimechecker/Main.java | 6 ------ 2 files changed, 10 insertions(+), 15 deletions(-) diff --git a/java/daikon/tools/runtimechecker/InstrumentHandler.java b/java/daikon/tools/runtimechecker/InstrumentHandler.java index 06ed933a62..ffd4e77a48 100644 --- a/java/daikon/tools/runtimechecker/InstrumentHandler.java +++ b/java/daikon/tools/runtimechecker/InstrumentHandler.java @@ -5,11 +5,11 @@ import static java.util.logging.Level.INFO; import daikon.Daikon; -import daikon.DaikonGetopt; import daikon.FileIO; import daikon.Global; import daikon.PptMap; import daikon.tools.jtb.ParseResults; +import gnu.getopt.Getopt; import gnu.getopt.LongOpt; import java.io.File; import java.io.IOException; @@ -198,7 +198,7 @@ private static class Arguments { } } - private static final Arguments errorWhileReadingArguments = + private static Arguments errorWhileReadingArguments = new Arguments("error while reading arguments", new ArrayList()); private Arguments readArguments(String[] args) { @@ -213,7 +213,7 @@ private Arguments readArguments(String[] args) { new LongOpt(directory_SWITCH, LongOpt.REQUIRED_ARGUMENT, null, 0), new LongOpt(checkers_directory_SWITCH, LongOpt.REQUIRED_ARGUMENT, null, 0) }; - DaikonGetopt g = new DaikonGetopt(args, "", longopts); + Getopt g = new Getopt("daikon.tools.runtimechecker.InstrumentHandler", args, "hs", longopts); int c; while ((c = g.getopt()) != -1) { switch (c) { @@ -236,35 +236,36 @@ private Arguments readArguments(String[] args) { } else if (Daikon.debug_SWITCH.equals(option_name)) { daikon.LogHelper.setLevel(Daikon.getOptarg(g), FINE); } else { - throw new Daikon.BugInDaikon("Unhandled long option " + option_name); + System.err.println("Unknown long option received: " + option_name); } break; default: - throw new Daikon.BugInDaikon("getopt() returned " + c); + System.out.println("unrecognized option" + c); + return errorWhileReadingArguments; } } // The index of the first non-option argument -- the name of the // invariant file. int argindex = g.getOptind(); if (argindex >= args.length) { - System.err.println("Error: No .inv file or .java file arguments supplied."); + System.out.println("Error: No .inv file or .java file arguments supplied."); return errorWhileReadingArguments; } String invfile = args[argindex]; argindex++; if (!(invfile.endsWith(".inv") || invfile.endsWith(".inv.gz"))) { - System.err.println("Error: first argument must be a file ending in .inv or .inv.gz."); + System.out.println("Error: first argument must be a file ending in .inv or .inv.gz."); return errorWhileReadingArguments; } if (argindex >= args.length) { - System.err.println("Error: No .java file arguments supplied."); + System.out.println("Error: No .java file arguments supplied."); return errorWhileReadingArguments; } List javaFileNames = new ArrayList<>(); for (; argindex < args.length; argindex++) { String javafile = args[argindex]; if (!javafile.endsWith(".java")) { - System.err.println("File does not end in .java: " + javafile); + System.out.println("File does not end in .java: " + javafile); return errorWhileReadingArguments; } javaFileNames.add(javafile); diff --git a/java/daikon/tools/runtimechecker/Main.java b/java/daikon/tools/runtimechecker/Main.java index 4f401bc165..9259e07f45 100644 --- a/java/daikon/tools/runtimechecker/Main.java +++ b/java/daikon/tools/runtimechecker/Main.java @@ -1,6 +1,5 @@ package daikon.tools.runtimechecker; -import daikon.Daikon; import java.util.Collections; import java.util.List; import java.util.Locale; @@ -58,11 +57,6 @@ public void nonStaticMain(String[] args) { } } - } catch (Daikon.UserError e) { - // A user error, such as a bad command-line option, is reported in one line. System.exit - // prevents the finally block from printing generic failure text and the usage message. - System.err.println("Error: " + e.getMessage()); - System.exit(1); } catch (Throwable e) { System.out.println("Throwable thrown while handling command:" + e); e.printStackTrace(); From 2b46b306889dda6ecce10febf65ecfe4a673be59 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sat, 10 Oct 2026 18:37:28 -0700 Subject: [PATCH 10/16] Address code review: remove unused DaikonGetopt helpers, reject stray arguments in SampleTester and SplitterFactoryTest, fix --user-defined-invariant spelling --- doc/developer.texinfo | 2 +- java/daikon/Daikon.java | 2 +- java/daikon/DaikonGetopt.java | 110 ++---------------- java/daikon/test/SampleTester.java | 4 + .../split/SplitterFactoryTestUpdater.java | 6 + 5 files changed, 19 insertions(+), 105 deletions(-) diff --git a/doc/developer.texinfo b/doc/developer.texinfo index 0951936384..52bbd5591a 100644 --- a/doc/developer.texinfo +++ b/doc/developer.texinfo @@ -259,7 +259,7 @@ call the new invariant's @code{get_proto} method and recompile Daikon. @item If you do not wish to edit the Daikon source code, then compile the new invariant and put its @file{.class} file on your classpath. Then, invoke -Daikon with the @option{--user_defined_invariant} command-line argument +Daikon with the @option{--user-defined-invariant} command-line argument (@pxref{Options to control invariant detection,,,daikon,Daikon User Manual}). @end itemize diff --git a/java/daikon/Daikon.java b/java/daikon/Daikon.java index aaa2b3f3d6..5cde424fb4 100644 --- a/java/daikon/Daikon.java +++ b/java/daikon/Daikon.java @@ -1486,7 +1486,7 @@ public static String getOptarg(Getopt g) { } /** - * Invariants passed on the command line with the {@code --user_defined_invariant} option. A list + * Invariants passed on the command line with the {@code --user-defined-invariant} option. A list * of class names in the format required by {@link Class#forName(String)}. */ private static List<@ClassGetName String> userDefinedInvariants = diff --git a/java/daikon/DaikonGetopt.java b/java/daikon/DaikonGetopt.java index 11a7807ac3..47d387c0f9 100644 --- a/java/daikon/DaikonGetopt.java +++ b/java/daikon/DaikonGetopt.java @@ -4,8 +4,6 @@ import gnu.getopt.Getopt; import gnu.getopt.LongOpt; -import java.util.Arrays; -import java.util.function.Supplier; import org.checkerframework.checker.nullness.qual.Nullable; import org.plumelib.util.ArraysPlume; @@ -24,13 +22,13 @@ public class DaikonGetopt extends Getopt { private static final String PROGNAME = "DaikonGetopt"; /** - * Computes the usage message printed for {@code -h} and {@code --help}, or null if the caller - * handles them. + * The usage message printed for {@code -h} and {@code --help}, or null if the caller handles + * them. */ - private final @Nullable Supplier usage; + private final @Nullable String usage; /** Text appended to the description of a bad command-line option, or null to append nothing. */ - private @Nullable String usageHint = "run with -h for usage"; + private final @Nullable String usageHint; /** * Creates a command-line option processor that recognizes short and long options. Its description @@ -44,7 +42,7 @@ public class DaikonGetopt extends Getopt { public DaikonGetopt(String[] argv, String optstring, LongOpt[] longopts) { super(PROGNAME, argv, nonEmpty(optstring), longopts); this.usage = null; - usageHint = null; + this.usageHint = null; opterr = false; } @@ -71,22 +69,9 @@ private static String nonEmpty(String optstring) { * @param usage the usage message to print for {@code -h} and {@code --help} */ public DaikonGetopt(String[] argv, String optstring, LongOpt[] longopts, String usage) { - this(argv, optstring, longopts, () -> usage); - } - - /** - * Creates a command-line option processor that recognizes short and long options, plus {@code -h} - * and {@code --help}, which print the usage message and throw {@link Daikon.NormalTermination}. - * The usage message is computed only if it is needed. - * - * @param argv the command-line arguments - * @param optstring the short options, in the format of {@link Getopt}; must not contain {@code h} - * @param longopts the long options; must not contain {@code help} - * @param usage computes the usage message to print for {@code -h} and {@code --help} - */ - public DaikonGetopt(String[] argv, String optstring, LongOpt[] longopts, Supplier usage) { super(PROGNAME, argv, withH(optstring), withHelp(longopts)); this.usage = usage; + this.usageHint = "run with -h for usage"; opterr = false; } @@ -119,87 +104,6 @@ private static LongOpt[] withHelp(LongOpt[] longopts) { longopts, new LongOpt(Daikon.help_SWITCH, LongOpt.NO_ARGUMENT, null, 'h')); } - /** - * Processes the command-line arguments of a program that takes no options other than {@code -h} - * and {@code --help}. - * - * @param argv the command-line arguments - * @param usage the usage message to print for {@code -h} and {@code --help} - * @return the arguments that are not options - * @throws Daikon.NormalTermination after printing the usage message, if an argument requests it - * @throws Daikon.UserError if an argument is any other option - */ - public static String[] nonOptionArgs(String[] argv, String usage) { - return argsAfterOptions(argv, "", () -> usage); - } - - /** - * Processes the leading command-line arguments of a program that takes no options other than - * {@code -h} and {@code --help}. Processing stops at the first argument that is not an option, so - * later arguments may be options for some other program. - * - * @param argv the command-line arguments - * @param usage the usage message to print for {@code -h} and {@code --help} - * @return the arguments from the first one that is not an option onward - * @throws Daikon.NormalTermination after printing the usage message, if a leading argument - * requests it - * @throws Daikon.UserError if a leading argument is any other option - */ - public static String[] argsAfterLeadingOptions(String[] argv, String usage) { - return argsAfterLeadingOptions(argv, () -> usage); - } - - /** - * Like {@link #argsAfterLeadingOptions(String[], String)}, but computes the usage message only if - * it is needed. - * - * @param argv the command-line arguments - * @param usage computes the usage message to print for {@code -h} and {@code --help} - * @return the arguments from the first one that is not an option onward - * @throws Daikon.NormalTermination after printing the usage message, if a leading argument - * requests it - * @throws Daikon.UserError if a leading argument is any other option - */ - public static String[] argsAfterLeadingOptions(String[] argv, Supplier usage) { - // A leading "+" tells Getopt to stop at the first argument that is not an option. - return argsAfterOptions(argv, "+", usage); - } - - /** - * Processes command-line arguments, permitting no options other than {@code -h} and {@code - * --help}. - * - * @param argv the command-line arguments - * @param optstring "" to process all the arguments, or "+" to stop at the first non-option - * @param usage computes the usage message to print for {@code -h} and {@code --help} - * @return the arguments that Getopt did not process as options - * @throws Daikon.NormalTermination after printing the usage message, if an argument requests it - * @throws Daikon.UserError if an argument is any other option - */ - private static String[] argsAfterOptions( - String[] argv, String optstring, Supplier usage) { - // Getopt permutes its argument array, so give it a copy to avoid modifying the caller's array. - String[] argvCopy = argv.clone(); - DaikonGetopt g = new DaikonGetopt(argvCopy, optstring, new LongOpt[0], usage); - // Every option other than -h and --help is bad, so getopt() returns only -1 or throws. - int c = g.getopt(); - if (c != -1) { - throw new Daikon.BugInDaikon("getopt() returned " + c); - } - return Arrays.copyOfRange(argvCopy, g.getOptind(), argvCopy.length); - } - - /** - * Sets the text that is appended to the description of a bad command-line option. The default - * tells the user to run the program with -h. - * - * @param usageHint text appended to the description of a bad command-line option, or null to - * append nothing - */ - public void setUsageHint(@Nullable String usageHint) { - this.usageHint = usageHint; - } - /** * Like {@link Getopt#getopt()}, but never returns {@code '?'} or {@code ':'}. Getopt returns * {@code ':'} for a missing argument if the optstring starts with {@code ':'}. If this was @@ -217,7 +121,7 @@ public int getopt() { throw badOptionError(); } if (c == 'h' && usage != null) { - System.out.println(usage.get()); + System.out.println(usage); throw new Daikon.NormalTermination(); } return c; diff --git a/java/daikon/test/SampleTester.java b/java/daikon/test/SampleTester.java index b984841454..adde5344b0 100644 --- a/java/daikon/test/SampleTester.java +++ b/java/daikon/test/SampleTester.java @@ -144,6 +144,10 @@ public static void mainHelper(String[] args) throws IOException { throw new Daikon.BugInDaikon("getopt() returned " + c); } } + if (g.getOptind() < args.length) { + throw new Daikon.UserError( + "Unexpected argument " + args[g.getOptind()] + "; run with -h for usage"); + } daikon.LogHelper.setupLogs(Global.debugAll ? FINE : INFO); diff --git a/java/daikon/test/split/SplitterFactoryTestUpdater.java b/java/daikon/test/split/SplitterFactoryTestUpdater.java index 758c93b4a2..b5dfc175e3 100644 --- a/java/daikon/test/split/SplitterFactoryTestUpdater.java +++ b/java/daikon/test/split/SplitterFactoryTestUpdater.java @@ -267,6 +267,12 @@ private static String getTestClassText() { ps.println(" throw new Daikon.BugInDaikon(\"getopt() returned \" + c);"); ps.println(" }"); ps.println(" }"); + ps.println(" if (g.getOptind() < args.length) {"); + ps.println(" throw new Daikon.UserError("); + ps.println( + " \"Unexpected argument \" + args[g.getOptind()] + \"; run with -h for" + + " usage\");"); + ps.println(" }"); ps.println(" Result result = JUnitCore.runClasses(SplitterFactoryTest.class);"); ps.println(" for (Failure failure : result.getFailures()) {"); ps.println(" System.err.println(failure.getTrace());"); From 50e3e2aa99ed1713b7f585257aa1fdfd49967a69 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sat, 10 Oct 2026 18:56:22 -0700 Subject: [PATCH 11/16] Simplify DaikonGetopt: one constructor, which always handles -h and --help --- java/daikon/DaikonGetopt.java | 109 ++++------------------------ java/daikon/test/BadOptionTest.java | 64 ++++++++-------- 2 files changed, 48 insertions(+), 125 deletions(-) diff --git a/java/daikon/DaikonGetopt.java b/java/daikon/DaikonGetopt.java index 47d387c0f9..26bf668530 100644 --- a/java/daikon/DaikonGetopt.java +++ b/java/daikon/DaikonGetopt.java @@ -4,15 +4,13 @@ import gnu.getopt.Getopt; import gnu.getopt.LongOpt; -import org.checkerframework.checker.nullness.qual.Nullable; import org.plumelib.util.ArraysPlume; /** * A command-line option processor that throws a {@link Daikon.UserError} that describes a bad - * command-line option, instead of printing a message and returning {@code '?'} or {@code ':'}. - * - *

If constructed with a usage message, it also handles {@code -h} and {@code --help}: it prints - * the usage message and throws {@link Daikon.NormalTermination}. + * command-line option, instead of printing a message and returning {@code '?'} or {@code ':'}. It + * also handles {@code -h} and {@code --help}: it prints the usage message and throws {@link + * Daikon.NormalTermination}. */ public class DaikonGetopt extends Getopt { @@ -21,43 +19,8 @@ public class DaikonGetopt extends Getopt { */ private static final String PROGNAME = "DaikonGetopt"; - /** - * The usage message printed for {@code -h} and {@code --help}, or null if the caller handles - * them. - */ - private final @Nullable String usage; - - /** Text appended to the description of a bad command-line option, or null to append nothing. */ - private final @Nullable String usageHint; - - /** - * Creates a command-line option processor that recognizes short and long options. Its description - * of a bad option does not suggest running with {@code -h}, because it does not handle {@code - * -h}. - * - * @param argv the command-line arguments - * @param optstring the short options, in the format of {@link Getopt} - * @param longopts the long options - */ - public DaikonGetopt(String[] argv, String optstring, LongOpt[] longopts) { - super(PROGNAME, argv, nonEmpty(optstring), longopts); - this.usage = null; - this.usageHint = null; - opterr = false; - } - - /** - * Returns short options that are equivalent to the given ones but are not empty. Getopt replaces - * an empty optstring by " ", which makes "- " a valid option. - * - * @param optstring short options, in the format of {@link Getopt} - * @return {@code optstring}, or ":" if {@code optstring} is empty - */ - private static String nonEmpty(String optstring) { - // A leading ':' only makes Getopt return ':' rather than '?' for a missing argument, which - // getopt() treats identically. - return optstring.isEmpty() ? ":" : optstring; - } + /** The usage message printed for {@code -h} and {@code --help}. */ + private final String usage; /** * Creates a command-line option processor that recognizes short and long options, plus {@code -h} @@ -69,78 +32,38 @@ private static String nonEmpty(String optstring) { * @param usage the usage message to print for {@code -h} and {@code --help} */ public DaikonGetopt(String[] argv, String optstring, LongOpt[] longopts, String usage) { - super(PROGNAME, argv, withH(optstring), withHelp(longopts)); + super( + PROGNAME, + argv, + optstring + "h", + ArraysPlume.append( + longopts, new LongOpt(Daikon.help_SWITCH, LongOpt.NO_ARGUMENT, null, 'h'))); this.usage = usage; - this.usageHint = "run with -h for usage"; opterr = false; } /** - * Returns the given short options plus {@code -h}. - * - * @param optstring short options, in the format of {@link Getopt}; must not contain {@code h} - * @return {@code optstring} plus {@code -h} - */ - private static String withH(String optstring) { - if (optstring.indexOf('h') != -1) { - throw new IllegalArgumentException("optstring already contains h: " + optstring); - } - return optstring + "h"; - } - - /** - * Returns the given long options plus {@code --help}. - * - * @param longopts long options; must not contain {@code help} - * @return {@code longopts} plus {@code --help} - */ - private static LongOpt[] withHelp(LongOpt[] longopts) { - for (LongOpt longopt : longopts) { - if (longopt.getName().equals(Daikon.help_SWITCH)) { - throw new IllegalArgumentException("longopts already contains " + Daikon.help_SWITCH); - } - } - return ArraysPlume.append( - longopts, new LongOpt(Daikon.help_SWITCH, LongOpt.NO_ARGUMENT, null, 'h')); - } - - /** - * Like {@link Getopt#getopt()}, but never returns {@code '?'} or {@code ':'}. Getopt returns - * {@code ':'} for a missing argument if the optstring starts with {@code ':'}. If this was - * constructed with a usage message, also never returns {@code 'h'}. + * Like {@link Getopt#getopt()}, but never returns {@code '?'}, {@code ':'}, or {@code 'h'}. + * Getopt returns {@code ':'} for a missing argument if the optstring starts with {@code ':'}. * * @return the next option, as described in {@link Getopt#getopt()} * @throws Daikon.UserError if the next option is unrecognized, ambiguous, or malformed * @throws Daikon.NormalTermination after printing the usage message, if the next option is {@code - * -h} or {@code --help} and this was constructed with a usage message + * -h} or {@code --help} */ @Override public int getopt() { int c = super.getopt(); if (c == '?' || c == ':') { - throw badOptionError(); + throw new Daikon.UserError(badOptionMessage() + "; run with -h for usage"); } - if (c == 'h' && usage != null) { + if (c == 'h') { System.out.println(usage); throw new Daikon.NormalTermination(); } return c; } - /** - * Returns an exception that describes the bad command-line option that {@link Getopt#getopt()} - * just rejected. - * - * @return an exception that describes the bad command-line option - */ - private Daikon.UserError badOptionError() { - String message = badOptionMessage(); - if (usageHint != null) { - message += "; " + usageHint; - } - return new Daikon.UserError(message); - } - /** * Returns a description of the bad command-line option that {@link Getopt#getopt()} just * rejected. diff --git a/java/daikon/test/BadOptionTest.java b/java/daikon/test/BadOptionTest.java index 78f76e8159..0f50ea31e2 100644 --- a/java/daikon/test/BadOptionTest.java +++ b/java/daikon/test/BadOptionTest.java @@ -4,6 +4,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; import daikon.Daikon; import daikon.DaikonGetopt; @@ -24,27 +25,43 @@ */ public class BadOptionTest { - /** The long options used by {@link #parse}. */ + /** The long options used by {@link #parse}. DaikonGetopt adds {@code --help}. */ private static final LongOpt[] longopts = new LongOpt[] { - new LongOpt("help", LongOpt.NO_ARGUMENT, null, 0), new LongOpt("config", LongOpt.REQUIRED_ARGUMENT, null, 0), new LongOpt("config_option", LongOpt.REQUIRED_ARGUMENT, null, 0), new LongOpt("debug", LongOpt.REQUIRED_ARGUMENT, null, 'd'), new LongOpt("verbose", LongOpt.NO_ARGUMENT, null, 'v'), }; + /** The suffix of every description of a bad command-line option. */ + private static final String USAGE_HINT = "; run with -h for usage"; + /** * Parses the given command-line arguments, which must contain a bad option, and returns the - * resulting error message. + * resulting error message, without its suffix that suggests running with -h. * + * @param optstring the short options, in the format of Getopt * @param args command-line arguments - * @return the message of the UserError for the bad option + * @return the message of the UserError for the bad option, without {@link #USAGE_HINT} */ - private static String parse(String... args) { - DaikonGetopt g = new DaikonGetopt(args, "ho:", longopts); + private static String parseWith(String optstring, String... args) { + DaikonGetopt g = new DaikonGetopt(args, optstring, longopts, "usage"); Daikon.UserError e = assertThrows(Daikon.UserError.class, () -> consumeAll(g)); - return String.valueOf(e.getMessage()); + String message = String.valueOf(e.getMessage()); + assertTrue(message, message.endsWith(USAGE_HINT)); + return message.substring(0, message.length() - USAGE_HINT.length()); + } + + /** + * Parses the given command-line arguments, which must contain a bad option, and returns the + * resulting error message, without its suffix that suggests running with -h. + * + * @param args command-line arguments + * @return the message of the UserError for the bad option, without {@link #USAGE_HINT} + */ + private static String parse(String... args) { + return parseWith("vo:", args); } /** @@ -62,15 +79,15 @@ public void testUnrecognizedLongOption() { assertEquals("Unrecognized command-line option --bogus", parse("--bogus")); assertEquals("Unrecognized command-line option --bogus", parse("--bogus=3")); assertEquals("Unrecognized command-line option --=3", parse("--=3")); - assertEquals("Unrecognized command-line option --bogus", parse("-h", "--bogus", "file")); + assertEquals("Unrecognized command-line option --bogus", parse("-v", "--bogus", "file")); } /** Tests an unrecognized short option, alone and combined with a valid one. */ @Test public void testUnrecognizedShortOption() { assertEquals("Unrecognized command-line option -x", parse("-x")); - assertEquals("Unrecognized command-line option -x", parse("-xh")); - assertEquals("Unrecognized command-line option -x", parse("-hx")); + assertEquals("Unrecognized command-line option -x", parse("-xv")); + assertEquals("Unrecognized command-line option -x", parse("-vx")); assertEquals("Unrecognized command-line option -:", parse("-:")); } @@ -78,9 +95,7 @@ public void testUnrecognizedShortOption() { @Test public void testNoShortOptions() { for (String arg : new String[] {"- ", "-x", "-:"}) { - DaikonGetopt g = new DaikonGetopt(new String[] {arg}, "", longopts); - Daikon.UserError e = assertThrows(Daikon.UserError.class, g::getopt); - assertEquals("Unrecognized command-line option " + arg, String.valueOf(e.getMessage())); + assertEquals("Unrecognized command-line option " + arg, parseWith("", arg)); } } @@ -91,35 +106,20 @@ public void testAmbiguousLongOption() { assertEquals("Ambiguous command-line option --conf", parse("--conf")); } - /** Tests that the description of a bad option suggests -h if DaikonGetopt handles -h. */ - @Test - public void testUsageHint() { - DaikonGetopt g = new DaikonGetopt(new String[] {"--bogus"}, "o:", new LongOpt[0], "usage"); - Daikon.UserError e = assertThrows(Daikon.UserError.class, g::getopt); - assertEquals( - "Unrecognized command-line option --bogus; run with -h for usage", - String.valueOf(e.getMessage())); - } - /** Tests options that are missing their required argument. */ @Test public void testMissingArgument() { assertEquals("Command-line option --config requires an argument", parse("--config")); assertEquals("Command-line option --debug requires an argument", parse("--deb")); assertEquals("Command-line option -o requires an argument", parse("-o")); - assertEquals("Command-line option -o requires an argument", parse("-ho")); + assertEquals("Command-line option -o requires an argument", parse("-vo")); } /** Tests options that are missing their required argument, when the optstring starts with ':'. */ @Test public void testMissingArgumentLeadingColon() { - DaikonGetopt g = new DaikonGetopt(new String[] {"-o"}, ":ho:", longopts); - Daikon.UserError e = assertThrows(Daikon.UserError.class, g::getopt); - assertEquals("Command-line option -o requires an argument", String.valueOf(e.getMessage())); - g = new DaikonGetopt(new String[] {"--config"}, ":ho:", longopts); - e = assertThrows(Daikon.UserError.class, g::getopt); - assertEquals( - "Command-line option --config requires an argument", String.valueOf(e.getMessage())); + assertEquals("Command-line option -o requires an argument", parseWith(":o:", "-o")); + assertEquals("Command-line option --config requires an argument", parseWith(":o:", "--config")); } /** Tests long options that are given an argument they do not take. */ @@ -137,7 +137,7 @@ public void testUnexpectedArgument() { */ private static void assertBadOption(String description, ThrowingRunnable mainCall) { Daikon.UserError e = assertThrows(Daikon.UserError.class, mainCall); - assertEquals(description + "; run with -h for usage", String.valueOf(e.getMessage())); + assertEquals(description + USAGE_HINT, String.valueOf(e.getMessage())); } /** Tests an unrecognized long option in a tool. */ From 7df7f238d03bb540bc3b3730e619b4570453a062 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sat, 10 Oct 2026 18:59:32 -0700 Subject: [PATCH 12/16] Move test-driver fixes and doc spelling fixes to separate pull requests --- doc/developer.texinfo | 2 +- java/daikon/Daikon.java | 2 +- java/daikon/test/SampleTester.java | 29 +----------- .../split/SplitterFactoryTestUpdater.java | 44 +++++-------------- scripts/runcluster.pl | 2 +- scripts/trace-purge-vars.pl | 2 +- 6 files changed, 16 insertions(+), 65 deletions(-) diff --git a/doc/developer.texinfo b/doc/developer.texinfo index 52bbd5591a..0951936384 100644 --- a/doc/developer.texinfo +++ b/doc/developer.texinfo @@ -259,7 +259,7 @@ call the new invariant's @code{get_proto} method and recompile Daikon. @item If you do not wish to edit the Daikon source code, then compile the new invariant and put its @file{.class} file on your classpath. Then, invoke -Daikon with the @option{--user-defined-invariant} command-line argument +Daikon with the @option{--user_defined_invariant} command-line argument (@pxref{Options to control invariant detection,,,daikon,Daikon User Manual}). @end itemize diff --git a/java/daikon/Daikon.java b/java/daikon/Daikon.java index 5cde424fb4..aaa2b3f3d6 100644 --- a/java/daikon/Daikon.java +++ b/java/daikon/Daikon.java @@ -1486,7 +1486,7 @@ public static String getOptarg(Getopt g) { } /** - * Invariants passed on the command line with the {@code --user-defined-invariant} option. A list + * Invariants passed on the command line with the {@code --user_defined_invariant} option. A list * of class names in the format required by {@link Class#forName(String)}. */ private static List<@ClassGetName String> userDefinedInvariants = diff --git a/java/daikon/test/SampleTester.java b/java/daikon/test/SampleTester.java index adde5344b0..7373ba7cdf 100644 --- a/java/daikon/test/SampleTester.java +++ b/java/daikon/test/SampleTester.java @@ -67,7 +67,7 @@ public class SampleTester { /** The usage message for this program. */ private static String usage = StringsPlume.joinLines( - "Usage: java daikon.test.SampleTester [OPTION]...", + "Usage: java daikon.PrintInvariants [OPTION]... FILE", " -h, --" + Daikon.help_SWITCH, " Display this usage message", " --" + Daikon.config_option_SWITCH, @@ -78,29 +78,8 @@ public class SampleTester { " Specify a class, varinfos, and ppt to debug track.", " Format is class@ppt"); - /** - * Runs the tests without JUnit. - * - * @param args command-line arguments, like those of {@link #mainHelper} - * @throws IOException if there is a problem reading a test file - */ + @SuppressWarnings("JUnitMethodInvoked") // main() runs the tests without JUnit public static void main(String[] args) throws IOException { - try { - mainHelper(args); - } catch (Daikon.DaikonTerminationException e) { - Daikon.handleDaikonTerminationException(e); - } - } - - /** - * This does the work of {@link #main(String[])}, but it never calls System.exit, so it is - * appropriate to be called programmatically. - * - * @param args command-line arguments, like those of {@link #main} - * @throws IOException if there is a problem reading a test file - */ - @SuppressWarnings("JUnitMethodInvoked") // mainHelper() runs the tests without JUnit - public static void mainHelper(String[] args) throws IOException { LongOpt[] longopts = new LongOpt[] { @@ -144,10 +123,6 @@ public static void mainHelper(String[] args) throws IOException { throw new Daikon.BugInDaikon("getopt() returned " + c); } } - if (g.getOptind() < args.length) { - throw new Daikon.UserError( - "Unexpected argument " + args[g.getOptind()] + "; run with -h for usage"); - } daikon.LogHelper.setupLogs(Global.debugAll ? FINE : INFO); diff --git a/java/daikon/test/split/SplitterFactoryTestUpdater.java b/java/daikon/test/split/SplitterFactoryTestUpdater.java index b5dfc175e3..5025e8c145 100644 --- a/java/daikon/test/split/SplitterFactoryTestUpdater.java +++ b/java/daikon/test/split/SplitterFactoryTestUpdater.java @@ -195,11 +195,7 @@ private static String getTestClassText() { ps.println("import java.io.*;"); ps.println("import java.util.*;"); ps.println("import junit.framework.*;"); - ps.println("import org.junit.BeforeClass;"); ps.println("import org.junit.Test;"); - ps.println("import org.junit.runner.JUnitCore;"); - ps.println("import org.junit.runner.Result;"); - ps.println("import org.junit.runner.notification.Failure;"); ps.println("import org.plumelib.util.FilesPlume;"); ps.println("import org.plumelib.util.StringsPlume;"); ps.println("import org.plumelib.util.UtilPlume;"); @@ -233,6 +229,11 @@ private static String getTestClassText() { ps.println(" // java files it produces, changing the order that the setUpTests"); ps.println(" // commands are run will cause the tests to fail."); ps.println(); + ps.println(" /** Do not instantiate. */"); + ps.println(" private SplitterFactoryTest() {"); + ps.println(" throw new Error(\"Do not instantiate\");"); + ps.println(" }"); + ps.println(); ps.println(" private static String targetDir = \"" + targetDir + "\";"); ps.println(); ps.println(" private static @Nullable String tempDir = null;"); @@ -241,21 +242,12 @@ private static String getTestClassText() { ps.println(); ps.println(" private static String usage ="); ps.println(" StringsPlume.joinLines("); - ps.println(" \"Usage: java daikon.test.split.SplitterFactoryTest [OPTION]...\","); + ps.println(" \"Usage: java daikon.tools.CreateSpinfo FILE.java ...\","); ps.println( - " \" -s Save (do not delete) the splitter java files in the temp" - + " directory\","); - ps.println(" \" -h, --help Display this usage message\");"); + " \" -s Save (do not delete) the splitter java files in the temp directory\","); + ps.println(" \" -h Display this usage message\");"); ps.println(); ps.println(" public static void main(String[] args) {"); - ps.println(" try {"); - ps.println(" mainHelper(args);"); - ps.println(" } catch (Daikon.DaikonTerminationException e) {"); - ps.println(" Daikon.handleDaikonTerminationException(e);"); - ps.println(" }"); - ps.println(" }"); - ps.println(); - ps.println(" public static void mainHelper(String[] args) {"); ps.println(" DaikonGetopt g = new DaikonGetopt(args, \"s\", new LongOpt[0], usage);"); ps.println(" int c;"); ps.println(" while ((c = g.getopt()) != -1) {"); @@ -267,21 +259,6 @@ private static String getTestClassText() { ps.println(" throw new Daikon.BugInDaikon(\"getopt() returned \" + c);"); ps.println(" }"); ps.println(" }"); - ps.println(" if (g.getOptind() < args.length) {"); - ps.println(" throw new Daikon.UserError("); - ps.println( - " \"Unexpected argument \" + args[g.getOptind()] + \"; run with -h for" - + " usage\");"); - ps.println(" }"); - ps.println(" Result result = JUnitCore.runClasses(SplitterFactoryTest.class);"); - ps.println(" for (Failure failure : result.getFailures()) {"); - ps.println(" System.err.println(failure.getTrace());"); - ps.println(" }"); - ps.println(" if (!result.wasSuccessful()) {"); - ps.println( - " throw new Daikon.UserError(StringsPlume.nPlural(result.getFailureCount(), \"test\")" - + " + \" failed\");"); - ps.println(" }"); ps.println(" }"); ps.println(); @@ -335,8 +312,7 @@ private static String getTestClassText() { * SplitterFactoryTest to set up the needed files to run the tests on. */ public static void appendSetUpTest(PrintStream ps) { - ps.println(" @BeforeClass"); - ps.println(" public static void setUpTests() {"); + ps.println(" private static void setUpTests() {"); ps.println(" List spinfoFiles;"); ps.println(" List declsFiles;"); for (int i = 0; i < spinfoFileLists.size(); i++) { @@ -366,7 +342,7 @@ private static void appendTests(PrintStream ps) { ps.println(); for (String className : classNames) { ps.println(" @Test"); - ps.println(" public void test" + className + "() {"); + ps.println(" public static void test" + className + "() {"); ps.println(" assertEqualFiles(\"" + className + ".java\");"); ps.println(" }"); ps.println(); diff --git a/scripts/runcluster.pl b/scripts/runcluster.pl index 12559cd84c..bf31f6de12 100755 --- a/scripts/runcluster.pl +++ b/scripts/runcluster.pl @@ -209,7 +209,7 @@ () } my $invfile = "runcluster_temp_$algorithm-$ncluster.inv"; -$command = "java -cp $SCRIPTDIR/../daikon.jar -Xmx7g daikon.Daikon -o $invfile --config_option daikon.PptTopLevel.pairwise_implications=true --var-omit-pattern=\"class\" --no_text_output --no_show_progress $spinfo_file $decls_new " . join(' ', @new_dtraces) . " 2>&1 > runcluster_temp_Daikon_output.txt"; +$command = "java -cp $SCRIPTDIR/../daikon.jar -Xmx7g daikon.Daikon -o $invfile --config_option daikon.PptTopLevel.pairwise_implications=true --var_omit_pattern=\"class\" --no_text_output --no_show_progress $spinfo_file $decls_new " . join(' ', @new_dtraces) . " 2>&1 > runcluster_temp_Daikon_output.txt"; system_or_die($command, $verbose); $invfile =~ /(.*)\.inv/; diff --git a/scripts/trace-purge-vars.pl b/scripts/trace-purge-vars.pl index c75fdc9a7e..f3b95d73d9 100755 --- a/scripts/trace-purge-vars.pl +++ b/scripts/trace-purge-vars.pl @@ -8,7 +8,7 @@ # regular expression. (Its name is taken from grep.) # This script reduces the size of a trace file, but typically, using -# Daikon's --var-omit-pattern flag is a better option. +# Daikon's --var_omit_pattern flag is a better option. # I'm intentionally not operating by paragraphs, because I want the regexp # to only apply to the variable lines. From 4f54694b9d02587021bb74eaecf194324bf0d5df Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sat, 10 Oct 2026 19:10:01 -0700 Subject: [PATCH 13/16] Handle DaikonTerminationException in SampleTester and SplitterFactoryTest main methods --- java/daikon/test/SampleTester.java | 23 ++++++++++++++++++- .../split/SplitterFactoryTestUpdater.java | 20 ++++++++++++++++ 2 files changed, 42 insertions(+), 1 deletion(-) diff --git a/java/daikon/test/SampleTester.java b/java/daikon/test/SampleTester.java index 7373ba7cdf..ee6c5eda2e 100644 --- a/java/daikon/test/SampleTester.java +++ b/java/daikon/test/SampleTester.java @@ -78,8 +78,29 @@ public class SampleTester { " Specify a class, varinfos, and ppt to debug track.", " Format is class@ppt"); - @SuppressWarnings("JUnitMethodInvoked") // main() runs the tests without JUnit + /** + * Runs the sample tests. + * + * @param args command-line arguments + * @throws IOException if there is trouble reading a file + */ public static void main(String[] args) throws IOException { + try { + mainHelper(args); + } catch (Daikon.DaikonTerminationException e) { + Daikon.handleDaikonTerminationException(e); + } + } + + /** + * Does the work of {@link #main}, but throws an exception rather than calling {@code + * System.exit}. + * + * @param args command-line arguments + * @throws IOException if there is trouble reading a file + */ + @SuppressWarnings("JUnitMethodInvoked") // mainHelper() runs the tests without JUnit + public static void mainHelper(String[] args) throws IOException { LongOpt[] longopts = new LongOpt[] { diff --git a/java/daikon/test/split/SplitterFactoryTestUpdater.java b/java/daikon/test/split/SplitterFactoryTestUpdater.java index 5025e8c145..5391293804 100644 --- a/java/daikon/test/split/SplitterFactoryTestUpdater.java +++ b/java/daikon/test/split/SplitterFactoryTestUpdater.java @@ -247,7 +247,27 @@ private static String getTestClassText() { " \" -s Save (do not delete) the splitter java files in the temp directory\","); ps.println(" \" -h Display this usage message\");"); ps.println(); + ps.println(" /**"); + ps.println(" * Processes command-line options."); + ps.println(" *"); + ps.println(" * @param args command-line arguments"); + ps.println(" */"); ps.println(" public static void main(String[] args) {"); + ps.println(" try {"); + ps.println(" mainHelper(args);"); + ps.println(" } catch (Daikon.DaikonTerminationException e) {"); + ps.println(" Daikon.handleDaikonTerminationException(e);"); + ps.println(" }"); + ps.println(" }"); + ps.println(); + ps.println(" /**"); + ps.println( + " * Does the work of {@link #main}, but throws an exception rather than calling {@code"); + ps.println(" * System.exit}."); + ps.println(" *"); + ps.println(" * @param args command-line arguments"); + ps.println(" */"); + ps.println(" public static void mainHelper(String[] args) {"); ps.println(" DaikonGetopt g = new DaikonGetopt(args, \"s\", new LongOpt[0], usage);"); ps.println(" int c;"); ps.println(" while ((c = g.getopt()) != -1) {"); From 117da2eab375853c545c55e55dd61d2286e431e3 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sun, 11 Oct 2026 10:45:55 -0700 Subject: [PATCH 14/16] Brevity --- doc/CHANGELOG.md | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 6aa334f3e8..5787f9dd1f 100644 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -23,10 +23,7 @@ Further documentation can be found in: ## Version 5.9.1 (???, 2026) -* Daikon and its tools now reject an unrecognized, ambiguous, or malformed - command-line option: they describe the problem and exit with a non-zero - status. Previously, Daikon printed its usage message and exited with - status 0, and most other tools ignored the bad option and continued. +* Daikon and its tools now reject a malformed command-line option. * `daikon.diff.Diff` no longer accepts the `-u` and `-z` options, which had no effect. From b1c773d06a8926ca16629e456151780df293875f Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sun, 11 Oct 2026 17:59:33 -0700 Subject: [PATCH 15/16] Add the DaikonGetopt helper that this pull request uses: nonOptionArgs --- java/daikon/DaikonGetopt.java | 38 +++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/java/daikon/DaikonGetopt.java b/java/daikon/DaikonGetopt.java index 26bf668530..0d2fb61b9b 100644 --- a/java/daikon/DaikonGetopt.java +++ b/java/daikon/DaikonGetopt.java @@ -4,6 +4,7 @@ import gnu.getopt.Getopt; import gnu.getopt.LongOpt; +import java.util.Arrays; import org.plumelib.util.ArraysPlume; /** @@ -42,6 +43,43 @@ public DaikonGetopt(String[] argv, String optstring, LongOpt[] longopts, String opterr = false; } + /** + * Processes the command-line arguments of a program that takes no options other than {@code -h} + * and {@code --help}. + * + * @param argv the command-line arguments + * @param usage the usage message to print for {@code -h} and {@code --help} + * @return the arguments that are not options + * @throws Daikon.NormalTermination after printing the usage message, if an argument requests it + * @throws Daikon.UserError if an argument is any other option + */ + public static String[] nonOptionArgs(String[] argv, String usage) { + return argsAfterOptions(argv, "", usage); + } + + /** + * Processes command-line arguments, permitting no options other than {@code -h} and {@code + * --help}. + * + * @param argv the command-line arguments + * @param optstring "" to process all the arguments, or "+" to stop at the first non-option + * @param usage the usage message to print for {@code -h} and {@code --help} + * @return the arguments that Getopt did not process as options + * @throws Daikon.NormalTermination after printing the usage message, if an argument requests it + * @throws Daikon.UserError if an argument is any other option + */ + private static String[] argsAfterOptions(String[] argv, String optstring, String usage) { + // Getopt permutes its argument array, so give it a copy to avoid modifying the caller's array. + String[] argvCopy = argv.clone(); + DaikonGetopt g = new DaikonGetopt(argvCopy, optstring, new LongOpt[0], usage); + // Every option other than -h and --help is bad, so getopt() returns only -1 or throws. + int c = g.getopt(); + if (c != -1) { + throw new Daikon.BugInDaikon("getopt() returned " + c); + } + return Arrays.copyOfRange(argvCopy, g.getOptind(), argvCopy.length); + } + /** * Like {@link Getopt#getopt()}, but never returns {@code '?'}, {@code ':'}, or {@code 'h'}. * Getopt returns {@code ':'} for a missing argument if the optstring starts with {@code ':'}. From 5b001bedbf13a0338981eb1006f55302b2ad8d39 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sun, 11 Oct 2026 21:31:55 -0700 Subject: [PATCH 16/16] Report trace-reading errors in ReadTrace and SplitDtrace as user errors --- java/daikon/SplitDtrace.java | 6 ++++++ java/daikon/tools/ReadTrace.java | 3 ++- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/java/daikon/SplitDtrace.java b/java/daikon/SplitDtrace.java index aff7705ba9..6a7ae08666 100644 --- a/java/daikon/SplitDtrace.java +++ b/java/daikon/SplitDtrace.java @@ -5,6 +5,7 @@ import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; +import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; @@ -74,6 +75,9 @@ public static void mainHelper(String[] args) throws IOException { ArrayList rec = new ArrayList<>(); while (true) { readRec(reader, rec); + if (rec.isEmpty()) { + throw new Daikon.UserError("No DECLARE record in " + filename); + } if (isDeclare(rec)) { break; } @@ -89,6 +93,8 @@ public static void mainHelper(String[] args) throws IOException { recNum++; } } + } catch (FileNotFoundException e) { + throw new Daikon.UserError(e, "File not found"); } System.out.println( diff --git a/java/daikon/tools/ReadTrace.java b/java/daikon/tools/ReadTrace.java index 944e3b3609..994e354cd0 100644 --- a/java/daikon/tools/ReadTrace.java +++ b/java/daikon/tools/ReadTrace.java @@ -7,6 +7,7 @@ import daikon.PptTopLevel; import daikon.ValueTuple; import daikon.VarInfo; +import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedHashMap; @@ -72,7 +73,7 @@ public static void mainHelper(String[] args) { // `read_data_trace_files()` requires the list of files to be modifiable. FileIO.read_data_trace_files( new ArrayList<>(Arrays.asList(traceFiles)), ppts, processor, false); - } catch (Exception e) { + } catch (IOException e) { throw new Error(e); }