From a95b881bd126714aae5bd562ec4bd532768ebe30 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Tue, 6 Oct 2026 17:06:41 -0700 Subject: [PATCH 01/21] 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 2a6f52f325c8d17746a1cd614395967dade53a35 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Tue, 6 Oct 2026 17:07:09 -0700 Subject: [PATCH 02/21] runtimechecker: reject bad options; accept -h and --help The instrumenter and WriteViolationFile use DaikonGetopt. The instrument command reports a bad option and its usage message rather than ignoring the option. A missing .doc file is reported as a bug. Co-Authored-By: Claude Opus 5.5 --- .../tools/runtimechecker/CommandHandler.java | 30 +++++++++++-- .../runtimechecker/InstrumentHandler.doc | 1 + .../runtimechecker/InstrumentHandler.java | 26 ++++++++---- java/daikon/tools/runtimechecker/Main.java | 42 +++++++++++++++---- .../runtimechecker/WriteViolationFile.java | 34 ++++++++++----- 5 files changed, 101 insertions(+), 32 deletions(-) diff --git a/java/daikon/tools/runtimechecker/CommandHandler.java b/java/daikon/tools/runtimechecker/CommandHandler.java index 7097f6ac9d..f54877aa81 100644 --- a/java/daikon/tools/runtimechecker/CommandHandler.java +++ b/java/daikon/tools/runtimechecker/CommandHandler.java @@ -2,10 +2,13 @@ import static java.nio.charset.StandardCharsets.UTF_8; +import daikon.Daikon; import java.io.BufferedReader; +import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; +import java.io.PrintStream; import java.io.UncheckedIOException; /** @@ -22,20 +25,41 @@ public boolean handle(String[] args) { throw new UnsupportedOperationException(); } + /** Prints the usage message to standard error. */ public void usageMessage() { + usageMessage(System.err); + } + + /** + * Returns the usage message. + * + * @return the usage message + */ + public String usageMessageString() { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + usageMessage(new PrintStream(bytes, true, UTF_8)); + return bytes.toString(UTF_8).stripTrailing(); + } + + /** + * Prints the usage message. + * + * @param out where to print the usage message + * @throws Daikon.BugInDaikon if the documentation file is missing + */ + public void usageMessage(PrintStream out) { String[] classnameArray = getClass().getName().split("\\."); String simpleClassname = classnameArray[classnameArray.length - 1]; String docFile = simpleClassname + ".doc"; InputStream in = getClass().getResourceAsStream(docFile); if (in == null) { - System.err.println("Didn't find documentation for " + getClass()); - return; + throw new Daikon.BugInDaikon("Didn't find documentation " + docFile + " for " + getClass()); } try (BufferedReader reader = new BufferedReader(new InputStreamReader(in, UTF_8))) { String line; while ((line = reader.readLine()) != null) { - System.err.println(line); + out.println(line); } } catch (IOException e) { throw new UncheckedIOException("problem reading " + docFile, e); diff --git a/java/daikon/tools/runtimechecker/InstrumentHandler.doc b/java/daikon/tools/runtimechecker/InstrumentHandler.doc index 84ddec8845..b4d7089ab5 100644 --- a/java/daikon/tools/runtimechecker/InstrumentHandler.doc +++ b/java/daikon/tools/runtimechecker/InstrumentHandler.doc @@ -7,6 +7,7 @@ instrument [OPTIONS] INV_FILE JAVA_FILES INV_FILE is an invariant file (suffix .inv or .inv.gz) created by Daikon. JAVA_FILES is one or more Java files that will be instrumented. OPTIONS: + -h, --help Display this usage message. --make_all_fields_public Make all declared fields public. --directory=DIRNAME Output directory; default: instrumented-classes --output_only_high_conf_invariants diff --git a/java/daikon/tools/runtimechecker/InstrumentHandler.java b/java/daikon/tools/runtimechecker/InstrumentHandler.java index ffd4e77a48..39f5a375a9 100644 --- a/java/daikon/tools/runtimechecker/InstrumentHandler.java +++ b/java/daikon/tools/runtimechecker/InstrumentHandler.java @@ -5,17 +5,18 @@ 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; import java.io.Writer; import java.nio.file.Files; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import java.util.logging.Logger; import jtb.syntaxtree.*; @@ -81,11 +82,17 @@ public boolean handle(String[] args) { return false; } - String[] realArgs = new String[args.length - 1]; - for (int i = 0; i < realArgs.length; i++) { - realArgs[i] = args[i + 1]; + String[] realArgs = Arrays.copyOfRange(args, 1, args.length); + Arguments arguments; + try { + arguments = readArguments(realArgs); + } catch (Daikon.NormalTermination e) { + // The user requested the usage message, which has been printed. + return true; + } catch (Daikon.UserError e) { + System.err.println(e.getMessage()); + return false; } - Arguments arguments = readArguments(realArgs); if (arguments == errorWhileReadingArguments) { return false; } @@ -213,7 +220,9 @@ 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); + DaikonGetopt g = new DaikonGetopt(args, "", longopts, this::usageMessageString); + // The caller prints the usage message when this command fails. + g.setUsageHint(null); int c; while ((c = g.getopt()) != -1) { switch (c) { @@ -236,12 +245,11 @@ private Arguments readArguments(String[] args) { } 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); + throw new Daikon.BugInDaikon("Unhandled long option " + option_name); } break; default: - System.out.println("unrecognized option" + c); - return errorWhileReadingArguments; + throw new Daikon.BugInDaikon("getopt() returned " + c); } } // The index of the first non-option argument -- the name of the diff --git a/java/daikon/tools/runtimechecker/Main.java b/java/daikon/tools/runtimechecker/Main.java index 9259e07f45..188b747947 100644 --- a/java/daikon/tools/runtimechecker/Main.java +++ b/java/daikon/tools/runtimechecker/Main.java @@ -1,8 +1,11 @@ package daikon.tools.runtimechecker; +import daikon.Daikon; +import daikon.DaikonGetopt; import java.util.Collections; import java.util.List; import java.util.Locale; +import java.util.StringJoiner; /** * Main entrypoint for the instrumenter. Passes control to whichever handler can handle the @@ -10,10 +13,19 @@ */ public class Main extends CommandHandler { - protected void usageMessage(List handlers) { + /** + * Returns the usage message of this and of each handler. + * + * @param handlers the handlers whose usage messages to include + * @return the usage message of this and of each handler + */ + private String usageMessage(List handlers) { + StringJoiner result = new StringJoiner(Daikon.lineSep); + result.add(usageMessageString()); for (CommandHandler h : handlers) { - h.usageMessage(); + result.add(h.usageMessageString()); } + return result.toString(); } /** @@ -27,19 +39,26 @@ public void nonStaticMain(String[] args) { List handlers = Collections.singletonList((CommandHandler) new InstrumentHandler()); - if (args.length < 1) { + String[] commandAndArgs; + try { + commandAndArgs = DaikonGetopt.argsAfterLeadingOptions(args, () -> usageMessage(handlers)); + } catch (Daikon.DaikonTerminationException e) { + Daikon.handleDaikonTerminationException(e); + return; + } + if (commandAndArgs.length < 1) { System.err.println("ERROR: No command given."); System.err.println( "For more help, invoke the instrumenter with \"help\" as its sole argument."); System.exit(1); } - if (args[0].toUpperCase(Locale.ENGLISH).equals("HELP") || args[0].equals("?")) { - usageMessage(); - usageMessage(handlers); + if (commandAndArgs[0].toUpperCase(Locale.ENGLISH).equals("HELP") + || commandAndArgs[0].equals("?")) { + System.out.println(usageMessage(handlers)); System.exit(0); } - String command = args[0]; + String command = commandAndArgs[0]; boolean success = false; @@ -49,7 +68,7 @@ public void nonStaticMain(String[] args) { for (CommandHandler handler : handlers) { if (handler.handles(command)) { h = handler; - success = h.handle(args); + success = h.handle(commandAndArgs); if (!success) { System.err.println("The command you issued returned a failing status flag."); } @@ -69,7 +88,12 @@ public void nonStaticMain(String[] args) { System.err.println( "For more help, invoke the instrumenter with \"help\" as its sole argument."); } else { - h.usageMessage(); + // Don't let a problem printing the usage message prevent the exit below. + try { + h.usageMessage(); + } catch (RuntimeException e) { + System.err.println(e.getMessage()); + } } System.exit(1); } else { diff --git a/java/daikon/tools/runtimechecker/WriteViolationFile.java b/java/daikon/tools/runtimechecker/WriteViolationFile.java index dcfb548648..ee16a07420 100644 --- a/java/daikon/tools/runtimechecker/WriteViolationFile.java +++ b/java/daikon/tools/runtimechecker/WriteViolationFile.java @@ -2,6 +2,8 @@ import static java.nio.charset.StandardCharsets.UTF_8; +import daikon.Daikon; +import daikon.DaikonGetopt; import java.io.BufferedWriter; import java.io.IOException; import java.io.UncheckedIOException; @@ -11,8 +13,10 @@ import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; +import java.util.Arrays; import java.util.List; import org.checkerframework.checker.signature.qual.BinaryName; +import org.plumelib.util.StringsPlume; /** * This program runs a given program (which is assumed to contain some classes that have been @@ -26,27 +30,35 @@ private WriteViolationFile() { throw new UnsupportedOperationException("Do not instantiate"); } + /** The usage message for this program. */ + private static final String usageMessage = + StringsPlume.joinLines( + "Usage: java WriteViolationFile CLASS ARGS", + " CLASS and ARGS are just as they would be when being run directly,", + " except that CLASS is written as a binary name, not a fully-qualified name", + "Output is written to file \"violations.txt\" in the current directory."); + public static void usage() { - System.out.println("Usage: java WriteViolationFile CLASS ARGS"); - System.out.println(" CLASS and ARGS are just as they would be when being run directly,"); - System.out.println( - " except that CLASS is written as a binary name, not a fully-qualified name"); - System.out.println("Output is written to file \"violations.txt\" in the current directory."); + System.out.println(usageMessage); } @SuppressWarnings("Finally") public static void main(String[] args) { - if (args.length == 0) { + String[] classAndArgs; + try { + classAndArgs = DaikonGetopt.argsAfterLeadingOptions(args, usageMessage); + } catch (Daikon.DaikonTerminationException e) { + Daikon.handleDaikonTerminationException(e); + return; + } + if (classAndArgs.length == 0) { System.out.println("Error: no class specified"); usage(); System.exit(1); } @SuppressWarnings("signature") // will be checked immediately below, and exception is caught - @BinaryName String class_name = args[0]; - String[] main_args = new String[args.length - 1]; - for (int i = 0; i < main_args.length; i++) { - main_args[i] = args[i + 1]; - } + @BinaryName String class_name = classAndArgs[0]; + String[] main_args = Arrays.copyOfRange(classAndArgs, 1, classAndArgs.length); Class cls; try { cls = Class.forName(class_name); From 6380a6a04889ac022cda575bf663d013acd32109 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Tue, 6 Oct 2026 18:06:28 -0700 Subject: [PATCH 03/21] 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 23bf08dae7ae957058512bd2f82270a41ddaf5ad Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Tue, 6 Oct 2026 18:51:13 -0700 Subject: [PATCH 04/21] 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 05/21] 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 06/21] 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 07/21] 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 4f58740fcc3a8dd8d8e92c3a6190191a50a0da07 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Wed, 7 Oct 2026 08:18:01 -0700 Subject: [PATCH 08/21] Restore bad-option-core's changes to InstrumentHandler that the merge dropped Report argument errors on standard error, and make the sentinel final. --- .../daikon/tools/runtimechecker/InstrumentHandler.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/java/daikon/tools/runtimechecker/InstrumentHandler.java b/java/daikon/tools/runtimechecker/InstrumentHandler.java index 39f5a375a9..aa70f0a8b4 100644 --- a/java/daikon/tools/runtimechecker/InstrumentHandler.java +++ b/java/daikon/tools/runtimechecker/InstrumentHandler.java @@ -205,7 +205,7 @@ private static class Arguments { } } - private static Arguments errorWhileReadingArguments = + private static final Arguments errorWhileReadingArguments = new Arguments("error while reading arguments", new ArrayList()); private Arguments readArguments(String[] args) { @@ -256,24 +256,24 @@ private Arguments readArguments(String[] args) { // 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 e8abaccb8662c0f04e093571cde06908da1083e6 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sat, 10 Oct 2026 13:07:05 -0700 Subject: [PATCH 09/21] 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/21] 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/21] 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/21] 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/21] 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/21] 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 91ae719ef38989078f7c947b6c09ef3f2731ac2b Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sun, 11 Oct 2026 17:58:47 -0700 Subject: [PATCH 15/21] Add the DaikonGetopt helpers that this pull request uses: argsAfterLeadingOptions, a lazily computed usage message, and setUsageHint --- java/daikon/DaikonGetopt.java | 98 +++++++++++++++++++++++++++++++++-- 1 file changed, 94 insertions(+), 4 deletions(-) diff --git a/java/daikon/DaikonGetopt.java b/java/daikon/DaikonGetopt.java index 26bf668530..683a63433c 100644 --- a/java/daikon/DaikonGetopt.java +++ b/java/daikon/DaikonGetopt.java @@ -4,6 +4,9 @@ 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; /** @@ -19,8 +22,11 @@ public class DaikonGetopt extends Getopt { */ private static final String PROGNAME = "DaikonGetopt"; - /** The usage message printed for {@code -h} and {@code --help}. */ - private final String usage; + /** Computes the usage message printed for {@code -h} and {@code --help}. */ + private final 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, plus {@code -h} @@ -32,6 +38,20 @@ public class DaikonGetopt extends Getopt { * @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, @@ -42,6 +62,72 @@ public DaikonGetopt(String[] argv, String optstring, LongOpt[] longopts, String opterr = false; } + /** + * 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 '?'}, {@code ':'}, or {@code 'h'}. * Getopt returns {@code ':'} for a missing argument if the optstring starts with {@code ':'}. @@ -55,10 +141,14 @@ public DaikonGetopt(String[] argv, String optstring, LongOpt[] longopts, String public int getopt() { int c = super.getopt(); if (c == '?' || c == ':') { - throw new Daikon.UserError(badOptionMessage() + "; run with -h for usage"); + String message = badOptionMessage(); + if (usageHint != null) { + message += "; " + usageHint; + } + throw new Daikon.UserError(message); } if (c == 'h') { - System.out.println(usage); + System.out.println(usage.get()); throw new Daikon.NormalTermination(); } return c; From 7d1655219f3de3050cd09c6615081a013b9a5215 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sun, 11 Oct 2026 20:50:18 -0700 Subject: [PATCH 16/21] Handle DaikonTerminationException once in runtimechecker Main; simplify usage-message reading Send WriteViolationFile errors to stderr, document -h/--help in Main.doc, make "help" and -h produce identical output, and fix formatting. --- java/daikon/DaikonGetopt.java | 3 +- .../tools/runtimechecker/CommandHandler.java | 32 +++----- .../runtimechecker/InstrumentHandler.java | 14 +--- java/daikon/tools/runtimechecker/Main.doc | 2 +- java/daikon/tools/runtimechecker/Main.java | 75 +++++++------------ .../runtimechecker/WriteViolationFile.java | 8 +- 6 files changed, 42 insertions(+), 92 deletions(-) diff --git a/java/daikon/DaikonGetopt.java b/java/daikon/DaikonGetopt.java index 683a63433c..2d66863572 100644 --- a/java/daikon/DaikonGetopt.java +++ b/java/daikon/DaikonGetopt.java @@ -105,7 +105,8 @@ public static String[] argsAfterLeadingOptions(String[] argv, Supplier u * @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) { + 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); diff --git a/java/daikon/tools/runtimechecker/CommandHandler.java b/java/daikon/tools/runtimechecker/CommandHandler.java index f54877aa81..d09ab6d481 100644 --- a/java/daikon/tools/runtimechecker/CommandHandler.java +++ b/java/daikon/tools/runtimechecker/CommandHandler.java @@ -3,12 +3,8 @@ import static java.nio.charset.StandardCharsets.UTF_8; import daikon.Daikon; -import java.io.BufferedReader; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.PrintStream; import java.io.UncheckedIOException; /** @@ -25,29 +21,22 @@ public boolean handle(String[] args) { throw new UnsupportedOperationException(); } - /** Prints the usage message to standard error. */ - public void usageMessage() { - usageMessage(System.err); - } - /** - * Returns the usage message. + * Prints the usage message to standard error. * - * @return the usage message + * @throws Daikon.BugInDaikon if the documentation file is missing */ - public String usageMessageString() { - ByteArrayOutputStream bytes = new ByteArrayOutputStream(); - usageMessage(new PrintStream(bytes, true, UTF_8)); - return bytes.toString(UTF_8).stripTrailing(); + public void usageMessage() { + System.err.println(usageMessageString()); } /** - * Prints the usage message. + * Returns the usage message, which is the contents of this class's documentation file. * - * @param out where to print the usage message + * @return the usage message * @throws Daikon.BugInDaikon if the documentation file is missing */ - public void usageMessage(PrintStream out) { + public String usageMessageString() { String[] classnameArray = getClass().getName().split("\\."); String simpleClassname = classnameArray[classnameArray.length - 1]; @@ -56,11 +45,8 @@ public void usageMessage(PrintStream out) { if (in == null) { throw new Daikon.BugInDaikon("Didn't find documentation " + docFile + " for " + getClass()); } - try (BufferedReader reader = new BufferedReader(new InputStreamReader(in, UTF_8))) { - String line; - while ((line = reader.readLine()) != null) { - out.println(line); - } + try (in) { + return new String(in.readAllBytes(), UTF_8).stripTrailing(); } catch (IOException e) { throw new UncheckedIOException("problem reading " + docFile, e); } diff --git a/java/daikon/tools/runtimechecker/InstrumentHandler.java b/java/daikon/tools/runtimechecker/InstrumentHandler.java index aa70f0a8b4..d1a6270fb0 100644 --- a/java/daikon/tools/runtimechecker/InstrumentHandler.java +++ b/java/daikon/tools/runtimechecker/InstrumentHandler.java @@ -83,16 +83,7 @@ public boolean handle(String[] args) { } String[] realArgs = Arrays.copyOfRange(args, 1, args.length); - Arguments arguments; - try { - arguments = readArguments(realArgs); - } catch (Daikon.NormalTermination e) { - // The user requested the usage message, which has been printed. - return true; - } catch (Daikon.UserError e) { - System.err.println(e.getMessage()); - return false; - } + Arguments arguments = readArguments(realArgs); if (arguments == errorWhileReadingArguments) { return false; } @@ -221,8 +212,7 @@ private Arguments readArguments(String[] args) { new LongOpt(checkers_directory_SWITCH, LongOpt.REQUIRED_ARGUMENT, null, 0) }; DaikonGetopt g = new DaikonGetopt(args, "", longopts, this::usageMessageString); - // The caller prints the usage message when this command fails. - g.setUsageHint(null); + g.setUsageHint("run with \"instrument -h\" for usage"); int c; while ((c = g.getopt()) != -1) { switch (c) { diff --git a/java/daikon/tools/runtimechecker/Main.doc b/java/daikon/tools/runtimechecker/Main.doc index 5ddee5b1f5..b3814203a9 100644 --- a/java/daikon/tools/runtimechecker/Main.doc +++ b/java/daikon/tools/runtimechecker/Main.doc @@ -6,5 +6,5 @@ invariant properties are checked at run time. The instrumenter can operate in the following modes, indicated by the first argument to the daikon.tools.runtimecheker.Main class: -help +help, -h, --help Print a usage message diff --git a/java/daikon/tools/runtimechecker/Main.java b/java/daikon/tools/runtimechecker/Main.java index 188b747947..346e39f23f 100644 --- a/java/daikon/tools/runtimechecker/Main.java +++ b/java/daikon/tools/runtimechecker/Main.java @@ -28,81 +28,58 @@ private String usageMessage(List handlers) { return result.toString(); } + /** The hint printed after an error message. */ + private static final String helpHint = "For more help, run the instrumenter with -h."; + /** * Entry point for the instrumenter. Passes control to whichever handler can handle the * user-specified command. * * @param args the arguments to the program + * @throws Daikon.DaikonTerminationException if the instrumenter should exit */ public void nonStaticMain(String[] args) { List handlers = Collections.singletonList((CommandHandler) new InstrumentHandler()); - String[] commandAndArgs; - try { - commandAndArgs = DaikonGetopt.argsAfterLeadingOptions(args, () -> usageMessage(handlers)); - } catch (Daikon.DaikonTerminationException e) { - Daikon.handleDaikonTerminationException(e); - return; - } + String[] commandAndArgs = + DaikonGetopt.argsAfterLeadingOptions(args, () -> usageMessage(handlers)); if (commandAndArgs.length < 1) { - System.err.println("ERROR: No command given."); - System.err.println( - "For more help, invoke the instrumenter with \"help\" as its sole argument."); - System.exit(1); + throw new Daikon.UserError("ERROR: No command given." + Daikon.lineSep + helpHint); } if (commandAndArgs[0].toUpperCase(Locale.ENGLISH).equals("HELP") || commandAndArgs[0].equals("?")) { System.out.println(usageMessage(handlers)); - System.exit(0); + throw new Daikon.NormalTermination(); } String command = commandAndArgs[0]; - boolean success = false; - CommandHandler h = null; - try { - - for (CommandHandler handler : handlers) { - if (handler.handles(command)) { - h = handler; - success = h.handle(commandAndArgs); - if (!success) { - System.err.println("The command you issued returned a failing status flag."); - } - break; - } + for (CommandHandler handler : handlers) { + if (handler.handles(command)) { + h = handler; + break; } + } + if (h == null) { + throw new Daikon.UserError("Unknown command: " + command + Daikon.lineSep + helpHint); + } - } catch (Throwable e) { - System.out.println("Throwable thrown while handling command:" + e); - e.printStackTrace(); - success = false; - } finally { - if (!success) { - System.err.println("The instrumenter failed."); - if (h == null) { - System.err.println("Unknown command: " + command); - System.err.println( - "For more help, invoke the instrumenter with \"help\" as its sole argument."); - } else { - // Don't let a problem printing the usage message prevent the exit below. - try { - h.usageMessage(); - } catch (RuntimeException e) { - System.err.println(e.getMessage()); - } - } - System.exit(1); - } else { - } + if (!h.handle(commandAndArgs)) { + System.err.println("The command you issued returned a failing status flag."); + System.err.println("The instrumenter failed."); + h.usageMessage(); + System.exit(1); } } public static void main(String[] args) { - Main main = new Main(); - main.nonStaticMain(args); + try { + new Main().nonStaticMain(args); + } catch (Daikon.DaikonTerminationException e) { + Daikon.handleDaikonTerminationException(e); + } } } diff --git a/java/daikon/tools/runtimechecker/WriteViolationFile.java b/java/daikon/tools/runtimechecker/WriteViolationFile.java index ee16a07420..c4f2ed3f18 100644 --- a/java/daikon/tools/runtimechecker/WriteViolationFile.java +++ b/java/daikon/tools/runtimechecker/WriteViolationFile.java @@ -38,10 +38,6 @@ private WriteViolationFile() { " except that CLASS is written as a binary name, not a fully-qualified name", "Output is written to file \"violations.txt\" in the current directory."); - public static void usage() { - System.out.println(usageMessage); - } - @SuppressWarnings("Finally") public static void main(String[] args) { String[] classAndArgs; @@ -52,8 +48,8 @@ public static void main(String[] args) { return; } if (classAndArgs.length == 0) { - System.out.println("Error: no class specified"); - usage(); + System.err.println("Error: no class specified"); + System.err.println(usageMessage); System.exit(1); } @SuppressWarnings("signature") // will be checked immediately below, and exception is caught From 77e0e9dad4a617605639478b691dcba56e00c4f4 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sun, 11 Oct 2026 21:25:31 -0700 Subject: [PATCH 17/21] Report instrument argument errors and handler failures via UserError readArguments throws UserError instead of returning a sentinel, and Main throws UserError instead of calling System.exit when a handler fails. --- .../tools/runtimechecker/CommandHandler.java | 9 ----- .../runtimechecker/InstrumentHandler.java | 34 +++++++++---------- java/daikon/tools/runtimechecker/Main.java | 6 ++-- 3 files changed, 19 insertions(+), 30 deletions(-) diff --git a/java/daikon/tools/runtimechecker/CommandHandler.java b/java/daikon/tools/runtimechecker/CommandHandler.java index d09ab6d481..17c9748243 100644 --- a/java/daikon/tools/runtimechecker/CommandHandler.java +++ b/java/daikon/tools/runtimechecker/CommandHandler.java @@ -21,15 +21,6 @@ public boolean handle(String[] args) { throw new UnsupportedOperationException(); } - /** - * Prints the usage message to standard error. - * - * @throws Daikon.BugInDaikon if the documentation file is missing - */ - public void usageMessage() { - System.err.println(usageMessageString()); - } - /** * Returns the usage message, which is the contents of this class's documentation file. * diff --git a/java/daikon/tools/runtimechecker/InstrumentHandler.java b/java/daikon/tools/runtimechecker/InstrumentHandler.java index d1a6270fb0..c41c8144e9 100644 --- a/java/daikon/tools/runtimechecker/InstrumentHandler.java +++ b/java/daikon/tools/runtimechecker/InstrumentHandler.java @@ -22,7 +22,6 @@ import jtb.syntaxtree.*; import jtb.visitor.TreeDumper; import jtb.visitor.TreeFormatter; -import org.checkerframework.checker.interning.qual.UsesObjectEquals; /** * Instruments a file to check invariant violations at run time. Violated invariants are stored in a @@ -84,9 +83,6 @@ public boolean handle(String[] args) { String[] realArgs = Arrays.copyOfRange(args, 1, args.length); Arguments arguments = readArguments(realArgs); - if (arguments == errorWhileReadingArguments) { - return false; - } // Set up debug traces; note this comes after reading command line options. daikon.LogHelper.setupLogs(Global.debugAll ? FINE : INFO); @@ -185,7 +181,6 @@ public boolean handle(String[] args) { return true; } - @UsesObjectEquals private static class Arguments { String invFile; List javaFileNames; @@ -196,9 +191,17 @@ private static class Arguments { } } - private static final Arguments errorWhileReadingArguments = - new Arguments("error while reading arguments", new ArrayList()); - + /** Text appended to the description of a bad command-line argument. */ + private static final String usageHint = "run with \"instrument -h\" for usage"; + + /** + * Parses the command-line arguments of the {@code instrument} command. + * + * @param args the arguments that follow the command name + * @return the parsed arguments + * @throws Daikon.NormalTermination after printing the usage message, if an argument requests it + * @throws Daikon.UserError if an argument is malformed or missing + */ private Arguments readArguments(String[] args) { LongOpt[] longopts = @@ -212,7 +215,7 @@ private Arguments readArguments(String[] args) { new LongOpt(checkers_directory_SWITCH, LongOpt.REQUIRED_ARGUMENT, null, 0) }; DaikonGetopt g = new DaikonGetopt(args, "", longopts, this::usageMessageString); - g.setUsageHint("run with \"instrument -h\" for usage"); + g.setUsageHint(usageHint); int c; while ((c = g.getopt()) != -1) { switch (c) { @@ -246,25 +249,22 @@ private Arguments readArguments(String[] args) { // invariant file. int argindex = g.getOptind(); if (argindex >= args.length) { - System.err.println("Error: No .inv file or .java file arguments supplied."); - return errorWhileReadingArguments; + throw new Daikon.UserError("No .inv file or .java file arguments supplied; " + usageHint); } 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."); - return errorWhileReadingArguments; + throw new Daikon.UserError( + "First argument must be a file ending in .inv or .inv.gz; " + usageHint); } if (argindex >= args.length) { - System.err.println("Error: No .java file arguments supplied."); - return errorWhileReadingArguments; + throw new Daikon.UserError("No .java file arguments supplied; " + usageHint); } 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); - return errorWhileReadingArguments; + throw new Daikon.UserError("File does not end in .java: " + javafile + "; " + usageHint); } javaFileNames.add(javafile); } diff --git a/java/daikon/tools/runtimechecker/Main.java b/java/daikon/tools/runtimechecker/Main.java index 346e39f23f..a38ff32e2d 100644 --- a/java/daikon/tools/runtimechecker/Main.java +++ b/java/daikon/tools/runtimechecker/Main.java @@ -67,11 +67,9 @@ public void nonStaticMain(String[] args) { throw new Daikon.UserError("Unknown command: " + command + Daikon.lineSep + helpHint); } + // A handler that returns false has already printed a description of the problem. if (!h.handle(commandAndArgs)) { - System.err.println("The command you issued returned a failing status flag."); - System.err.println("The instrumenter failed."); - h.usageMessage(); - System.exit(1); + throw new Daikon.UserError("The instrumenter failed."); } } From 31bedbc14bb45e83b93665353c1689af34f103f5 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sun, 11 Oct 2026 21:28:40 -0700 Subject: [PATCH 18/21] Inline argsAfterOptions, rename Main.usageMessageString, report WriteViolationFile errors via UserError --- java/daikon/DaikonGetopt.java | 20 ++----------------- java/daikon/tools/runtimechecker/Main.java | 6 +++--- .../runtimechecker/WriteViolationFile.java | 8 +++----- 3 files changed, 8 insertions(+), 26 deletions(-) diff --git a/java/daikon/DaikonGetopt.java b/java/daikon/DaikonGetopt.java index 2d66863572..02602cd90f 100644 --- a/java/daikon/DaikonGetopt.java +++ b/java/daikon/DaikonGetopt.java @@ -90,26 +90,10 @@ public static String[] argsAfterLeadingOptions(String[] argv, String usage) { * @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); + // A leading "+" tells Getopt to stop at the first argument that is not an option. + DaikonGetopt g = new DaikonGetopt(argvCopy, "+", 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) { diff --git a/java/daikon/tools/runtimechecker/Main.java b/java/daikon/tools/runtimechecker/Main.java index a38ff32e2d..8170959ffa 100644 --- a/java/daikon/tools/runtimechecker/Main.java +++ b/java/daikon/tools/runtimechecker/Main.java @@ -19,7 +19,7 @@ public class Main extends CommandHandler { * @param handlers the handlers whose usage messages to include * @return the usage message of this and of each handler */ - private String usageMessage(List handlers) { + private String usageMessageString(List handlers) { StringJoiner result = new StringJoiner(Daikon.lineSep); result.add(usageMessageString()); for (CommandHandler h : handlers) { @@ -44,13 +44,13 @@ public void nonStaticMain(String[] args) { Collections.singletonList((CommandHandler) new InstrumentHandler()); String[] commandAndArgs = - DaikonGetopt.argsAfterLeadingOptions(args, () -> usageMessage(handlers)); + DaikonGetopt.argsAfterLeadingOptions(args, () -> usageMessageString(handlers)); if (commandAndArgs.length < 1) { throw new Daikon.UserError("ERROR: No command given." + Daikon.lineSep + helpHint); } if (commandAndArgs[0].toUpperCase(Locale.ENGLISH).equals("HELP") || commandAndArgs[0].equals("?")) { - System.out.println(usageMessage(handlers)); + System.out.println(usageMessageString(handlers)); throw new Daikon.NormalTermination(); } diff --git a/java/daikon/tools/runtimechecker/WriteViolationFile.java b/java/daikon/tools/runtimechecker/WriteViolationFile.java index c4f2ed3f18..e541ca1a23 100644 --- a/java/daikon/tools/runtimechecker/WriteViolationFile.java +++ b/java/daikon/tools/runtimechecker/WriteViolationFile.java @@ -43,15 +43,13 @@ public static void main(String[] args) { String[] classAndArgs; try { classAndArgs = DaikonGetopt.argsAfterLeadingOptions(args, usageMessage); + if (classAndArgs.length == 0) { + throw new Daikon.UserError("Error: no class specified" + Daikon.lineSep + usageMessage); + } } catch (Daikon.DaikonTerminationException e) { Daikon.handleDaikonTerminationException(e); return; } - if (classAndArgs.length == 0) { - System.err.println("Error: no class specified"); - System.err.println(usageMessage); - System.exit(1); - } @SuppressWarnings("signature") // will be checked immediately below, and exception is caught @BinaryName String class_name = classAndArgs[0]; String[] main_args = Arrays.copyOfRange(classAndArgs, 1, classAndArgs.length); From b9ae8d83c4c5459777d7305750928a4228609b05 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sun, 11 Oct 2026 21:38:17 -0700 Subject: [PATCH 19/21] Report class-lookup and I/O errors via UserError; make CommandHandler.handle void; rename Main.fullUsageMessage; don't copy argv WriteViolationFile.main now delegates to mainHelper, like other Daikon programs. --- java/daikon/DaikonGetopt.java | 9 ++- .../tools/runtimechecker/CommandHandler.java | 8 ++- .../runtimechecker/InstrumentHandler.java | 19 +---- java/daikon/tools/runtimechecker/Main.java | 13 ++-- .../runtimechecker/WriteViolationFile.java | 71 +++++++++++-------- 5 files changed, 62 insertions(+), 58 deletions(-) diff --git a/java/daikon/DaikonGetopt.java b/java/daikon/DaikonGetopt.java index 02602cd90f..5785c1121d 100644 --- a/java/daikon/DaikonGetopt.java +++ b/java/daikon/DaikonGetopt.java @@ -90,16 +90,15 @@ public static String[] argsAfterLeadingOptions(String[] argv, String usage) { * @throws Daikon.UserError if a leading argument is any other option */ public static String[] argsAfterLeadingOptions(String[] argv, Supplier usage) { - // Getopt permutes its argument array, so give it a copy to avoid modifying the caller's array. - String[] argvCopy = argv.clone(); - // A leading "+" tells Getopt to stop at the first argument that is not an option. - DaikonGetopt g = new DaikonGetopt(argvCopy, "+", new LongOpt[0], usage); + // A leading "+" tells Getopt to stop at the first argument that is not an option. In that mode, + // Getopt does not permute argv. + DaikonGetopt g = new DaikonGetopt(argv, "+", 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); + return Arrays.copyOfRange(argv, g.getOptind(), argv.length); } /** diff --git a/java/daikon/tools/runtimechecker/CommandHandler.java b/java/daikon/tools/runtimechecker/CommandHandler.java index 17c9748243..1932b1bc34 100644 --- a/java/daikon/tools/runtimechecker/CommandHandler.java +++ b/java/daikon/tools/runtimechecker/CommandHandler.java @@ -17,7 +17,13 @@ public boolean handles(String command) { throw new UnsupportedOperationException(); } - public boolean handle(String[] args) { + /** + * Performs the command. + * + * @param args the command, followed by its arguments + * @throws Daikon.DaikonTerminationException if the program should exit + */ + public void handle(String[] args) { throw new UnsupportedOperationException(); } diff --git a/java/daikon/tools/runtimechecker/InstrumentHandler.java b/java/daikon/tools/runtimechecker/InstrumentHandler.java index c41c8144e9..3dd1510198 100644 --- a/java/daikon/tools/runtimechecker/InstrumentHandler.java +++ b/java/daikon/tools/runtimechecker/InstrumentHandler.java @@ -71,16 +71,11 @@ public boolean handles(String command) { // oneFile.roots) {" ) @Override - public boolean handle(String[] args) { + public void handle(String[] args) { Daikon.output_format = daikon.inv.OutputFormat.JAVA; daikon.PrintInvariants.wrap_xml = true; - if (!args[0].equals("instrument")) { - System.err.println("Command (first argument) to instrumenter was not recognized."); - return false; - } - String[] realArgs = Arrays.copyOfRange(args, 1, args.length); Arguments arguments = readArguments(realArgs); @@ -96,10 +91,7 @@ public boolean handle(String[] args) { ppts = FileIO.read_serialized_pptmap(new File(arguments.invFile), true /* use saved config */); } catch (IOException e) { - System.err.println("Exception while reading invariant file " + arguments.invFile); - System.err.println(e.getMessage()); - e.printStackTrace(); - return false; + throw new Daikon.UserError(e, "Problem while reading invariant file " + arguments.invFile); } // Compile original sources (because daikon.tools.jtb.Ast accesses @@ -171,14 +163,9 @@ public boolean handle(String[] args) { } } catch (IOException e) { - System.err.println("Exception while instrumenting " + oneFile.fileName); - System.err.println(e.getMessage()); - e.printStackTrace(); - return false; + throw new Daikon.UserError(e, "Problem while writing output for " + oneFile.fileName); } } - - return true; } private static class Arguments { diff --git a/java/daikon/tools/runtimechecker/Main.java b/java/daikon/tools/runtimechecker/Main.java index 8170959ffa..7404ef6ba1 100644 --- a/java/daikon/tools/runtimechecker/Main.java +++ b/java/daikon/tools/runtimechecker/Main.java @@ -19,7 +19,7 @@ public class Main extends CommandHandler { * @param handlers the handlers whose usage messages to include * @return the usage message of this and of each handler */ - private String usageMessageString(List handlers) { + private String fullUsageMessage(List handlers) { StringJoiner result = new StringJoiner(Daikon.lineSep); result.add(usageMessageString()); for (CommandHandler h : handlers) { @@ -44,13 +44,13 @@ public void nonStaticMain(String[] args) { Collections.singletonList((CommandHandler) new InstrumentHandler()); String[] commandAndArgs = - DaikonGetopt.argsAfterLeadingOptions(args, () -> usageMessageString(handlers)); + DaikonGetopt.argsAfterLeadingOptions(args, () -> fullUsageMessage(handlers)); if (commandAndArgs.length < 1) { - throw new Daikon.UserError("ERROR: No command given." + Daikon.lineSep + helpHint); + throw new Daikon.UserError("No command given." + Daikon.lineSep + helpHint); } if (commandAndArgs[0].toUpperCase(Locale.ENGLISH).equals("HELP") || commandAndArgs[0].equals("?")) { - System.out.println(usageMessageString(handlers)); + System.out.println(fullUsageMessage(handlers)); throw new Daikon.NormalTermination(); } @@ -67,10 +67,7 @@ public void nonStaticMain(String[] args) { throw new Daikon.UserError("Unknown command: " + command + Daikon.lineSep + helpHint); } - // A handler that returns false has already printed a description of the problem. - if (!h.handle(commandAndArgs)) { - throw new Daikon.UserError("The instrumenter failed."); - } + h.handle(commandAndArgs); } public static void main(String[] args) { diff --git a/java/daikon/tools/runtimechecker/WriteViolationFile.java b/java/daikon/tools/runtimechecker/WriteViolationFile.java index e541ca1a23..4acb68dcaa 100644 --- a/java/daikon/tools/runtimechecker/WriteViolationFile.java +++ b/java/daikon/tools/runtimechecker/WriteViolationFile.java @@ -38,41 +38,56 @@ private WriteViolationFile() { " except that CLASS is written as a binary name, not a fully-qualified name", "Output is written to file \"violations.txt\" in the current directory."); - @SuppressWarnings("Finally") - public static void main(String[] args) { - String[] classAndArgs; - try { - classAndArgs = DaikonGetopt.argsAfterLeadingOptions(args, usageMessage); - if (classAndArgs.length == 0) { - throw new Daikon.UserError("Error: no class specified" + Daikon.lineSep + usageMessage); - } - } catch (Daikon.DaikonTerminationException e) { - Daikon.handleDaikonTerminationException(e); - return; - } - @SuppressWarnings("signature") // will be checked immediately below, and exception is caught - @BinaryName String class_name = classAndArgs[0]; - String[] main_args = Arrays.copyOfRange(classAndArgs, 1, classAndArgs.length); + /** + * Returns the main method of the given class. + * + * @param className the binary name of a class + * @return the main method of the class + * @throws Daikon.UserError if the class does not exist or has no public static main method + */ + private static Method getMainMethod(String className) { Class cls; try { - cls = Class.forName(class_name); - } catch (Exception e) { - e.printStackTrace(); - throw new Error("Cannot find class " + class_name); + @SuppressWarnings("signature") // checked by Class.forName, which throws if it is malformed + @BinaryName String binaryName = className; + cls = Class.forName(binaryName); + } catch (ClassNotFoundException e) { + throw new Daikon.UserError(e, "Cannot find class " + className); } - Method main_method; + Method mainMethod; try { - main_method = cls.getMethod("main", new Class[] {String[].class}); - } catch (Exception e) { - throw new Error("Cannot find main method in class " + class_name); + mainMethod = cls.getMethod("main", new Class[] {String[].class}); + } catch (NoSuchMethodException e) { + throw new Daikon.UserError("Cannot find public main method in class " + className); } - int mods = main_method.getModifiers(); - if (!Modifier.isPublic(mods)) { - throw new Error("main method is not public in class " + class_name); + if (!Modifier.isStatic(mainMethod.getModifiers())) { + throw new Daikon.UserError("main method is not static in class " + className); } - if (!Modifier.isStatic(mods)) { - throw new Error("main method is not static in class " + class_name); + return mainMethod; + } + + 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. + * + * @param args the command-line arguments + * @throws Daikon.DaikonTerminationException if the arguments are malformed or request help + */ + @SuppressWarnings("Finally") + private static void mainHelper(String[] args) { + String[] classAndArgs = DaikonGetopt.argsAfterLeadingOptions(args, usageMessage); + if (classAndArgs.length == 0) { + throw new Daikon.UserError("No class specified" + Daikon.lineSep + usageMessage); + } + Method main_method = getMainMethod(classAndArgs[0]); + String[] main_args = Arrays.copyOfRange(classAndArgs, 1, classAndArgs.length); // This will produce no output if the program under test calls // System.exit(1). Let's hope it doesn't (and fix this later). From 9429a2d3e1ee98003627a05d16101909dae5a73a Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Mon, 12 Oct 2026 04:23:06 -0700 Subject: [PATCH 20/21] Preserve cause when main method is missing in WriteViolationFile --- java/daikon/tools/runtimechecker/WriteViolationFile.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java/daikon/tools/runtimechecker/WriteViolationFile.java b/java/daikon/tools/runtimechecker/WriteViolationFile.java index 4acb68dcaa..4d4c7b9ee8 100644 --- a/java/daikon/tools/runtimechecker/WriteViolationFile.java +++ b/java/daikon/tools/runtimechecker/WriteViolationFile.java @@ -58,7 +58,7 @@ private static Method getMainMethod(String className) { try { mainMethod = cls.getMethod("main", new Class[] {String[].class}); } catch (NoSuchMethodException e) { - throw new Daikon.UserError("Cannot find public main method in class " + className); + throw new Daikon.UserError(e, "Cannot find public main method in class " + className); } if (!Modifier.isStatic(mainMethod.getModifiers())) { throw new Daikon.UserError("main method is not static in class " + className); From 05c563729bb1874ed5dccaa69be1f321dcdf5a41 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Mon, 12 Oct 2026 12:16:27 -0700 Subject: [PATCH 21/21] CommandHandler: avoid Java 9+ syntax and APIs --- .../tools/runtimechecker/CommandHandler.java | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/java/daikon/tools/runtimechecker/CommandHandler.java b/java/daikon/tools/runtimechecker/CommandHandler.java index 1932b1bc34..31c17e44b5 100644 --- a/java/daikon/tools/runtimechecker/CommandHandler.java +++ b/java/daikon/tools/runtimechecker/CommandHandler.java @@ -3,9 +3,12 @@ import static java.nio.charset.StandardCharsets.UTF_8; import daikon.Daikon; +import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; +import java.io.InputStreamReader; import java.io.UncheckedIOException; +import java.util.stream.Collectors; /** * A command handler handles a set of commands. A command is the first argument given to the @@ -42,8 +45,16 @@ public String usageMessageString() { if (in == null) { throw new Daikon.BugInDaikon("Didn't find documentation " + docFile + " for " + getClass()); } - try (in) { - return new String(in.readAllBytes(), UTF_8).stripTrailing(); + // When Daikon requires Java 11 or later, simplify this to: + // try (in) { + // return new String(in.readAllBytes(), UTF_8).stripTrailing(); + // } + // and remove the imports of BufferedReader, InputStreamReader, and Collectors. + try (BufferedReader reader = new BufferedReader(new InputStreamReader(in, UTF_8))) { + return reader + .lines() + .collect(Collectors.joining(System.lineSeparator())) + .replaceAll("\\s+$", ""); } catch (IOException e) { throw new UncheckedIOException("problem reading " + docFile, e); }