• R/O
  • HTTP
  • SSH
  • HTTPS

提交

標籤
無標籤

Frequently used words (click to add to your profile)

javac++androidlinuxc#windowsobjective-ccocoa誰得qtpythonphprubygameguibathyscaphec計画中(planning stage)翻訳omegatframeworktwitterdomtestvb.netdirectxゲームエンジンbtronarduinopreviewer

GNU Binutils with patches for OS216


Commit MetaInfo

修訂b6b79e4c2cbfd4872d273545751ef91ec214276d (tree)
時間2019-06-05 07:30:02
作者Pedro Alves <palves@redh...>
CommiterPedro Alves

Log Message

Introduce generic command options framework

This commit adds a generic command options framework, that makes it
easy enough to add '-'-style options to commands in a uniform way,
instead of each command implementing option parsing in its own way.

Options are defined in arrays of option_def objects (for option
definition), and the same options definitions are used for supporting
TAB completion, and also for generating the relevant help fragment of
the "help" command. See the gdb::options::build_help function, which
returns a string with the result of replacing %OPTIONS% in a template
string with an auto-generated "help" string fragment for all the
passed-in options.

Since most options in GDB are in the form of "-OPT", with a single
dash, this is the format that the framework supports.

I like to think of gdb's "-OPT" as the equivalent to getopt's long
options format ("--OPT"), and gdb's "/" as the equivalent to getopt's
short options format. getopt's short options format allows mixing
several one-character options, like "ls -als", kind of similar to
gdb's "x /FMT" and "disassemble /MOD", etc. While with gdb's "-"
options, the option is expected to have a full name, and to be
abbreviatable. E.g., "watch -location", "break -function main", etc.

This patch only deals with "-" options. The above comment serves more
to disclose why I don't think we should support mixing several
unrelated options in a single "-" option invocation, like "thread
apply -qcs" instead of "thread apply -q -c -s".

The following patches will add uses of the infrastructure to several
key commands. Most notably, "print", "compile print", "backtrace",
"frame apply" and "thread apply". I tried to add options to several
commands in order to make sure the framework didn't leave that many
open holes open.

Options use the same type as set commands -- enum var_types. So
boolean options are var_boolean, enum options are var_enum, etc. The
idea is to share code between settings commands and command options.
The "print" options will be based on the "set print" commands, and
their names will be the same. Actually, their definitions will be the
same too. There is a function to create "set/show" commands from an
array for option definitions:

/* Install set/show commands for options defined in OPTIONS. DATA is
a pointer to the structure that holds the data associated with the
OPTIONS array. */
extern void add_setshow_cmds_for_options (command_class cmd_class, void *data,

gdb::array_view<const option_def> options,
struct cmd_list_element **set_list,
struct cmd_list_element **show_list);

That will be used by several following patches.

Other features:

- You can use the "--" delimiter to explicitly indicate end of
    1. Several existing commands use this token sequence for
      this effect already, so this just standardizes it.
- You can shorten option names, as long as unambiguous. Currently,
some commands allow this (e.g., break -function), while others do
not (thread apply all -ascending). As GDB allows abbreviating
command names and other things, it feels more GDB-ish to allow
abbreviating option names too, to me.
- For boolean options, 0/1 stands for off/on, just like with boolean
"set" commands.
- For boolean options, "true" is implied, just like with boolean "set
commands.

These are the option types supported, with a few examples:

- boolean options (var_boolean). The option's argument is optional.
(gdb) print -pretty on -- *obj
(gdb) print -pretty off -- *obj
(gdb) print -p -- *obj
(gdb) print -p 0 -- *obj
- flag options (like var_boolean, but no option argument (on/off))
(gdb) thread apply all -s COMMAND
- enum options (var_enum)
(gdb) bt -entry-values compact
(gdb) bt -e c
- uinteger options (var_uinteger)
(gdb) print -elements 100 -- *obj
(gdb) print -e 100 -- *obj
(gdb) print -elements unlimited -- *obj
(gdb) print -e u -- *obj
- zuinteger-unlimited options (var_zuinteger_unlimited)
(gdb) print -max-depth 100 -- obj
(gdb) print -max-depth -1 -- obj
(gdb) print -max-depth unlimited -- obj

Other var_types could be supported, of course. These were just the
types that I needed for the commands that I ported over, in the
following patches.

It was interesting (and unfortunate) to find that we need at least 3
different modes to cover the existing commands:

- Commands that require ending options with "--" if you specify any

option: "print" and "compile print".

- Commands that do not want to require "--", and want to error out if

you specify an unknown option (i.e., an unknown argument that starts
with '-'): "compile code" / "compile file".

- Commands that do not want to require "--", and want to process

unknown options themselves: "bt", because of "bt -COUNT",
"thread/frame apply", because "-" is a valid command.

The different behavior is encoded in the process_options_mode enum,
passed to process_options/complete_options.

For testing, this patch adds one representative maintenance command
for each of the process_options_mode values, that are used by the
testsuite to exercise the options framework:

(gdb) maint test-options require-delimiter
(gdb) maint test-options unknown-is-error
(gdb) maint test-options unknown-is-operand

and adds another command to help with TAB-completion testing:

(gdb) maint show test-options-completion-result

See their description at the top of the maint-test-options.c file.

Docs/NEWS are in a patch later in the series.

gdb/testsuite/ChangeLog:
yyyy-mm-dd Pedro Alves <palves@redhat.com>

* Makefile.in (SUBDIR_CLI_SRCS): Add cli/cli-option.c.
(COMMON_SFILES): Add maint-test-settings.c.
* cli/cli-decode.c (boolean_enums): New global, factored out from
...
(add_setshow_boolean_cmd): ... here.
* cli/cli-decode.h (boolean_enums): Declare.
* cli/cli-option.c: New file.
* cli/cli-option.h: New file.
* cli/cli-setshow.c (parse_cli_boolean_value(const char **)): New,
factored out from ...
(parse_cli_boolean_value(const char *)): ... this.
(is_unlimited_literal): Change parameter type to pointer to
pointer. Adjust and advance ARG pointer.
(parse_cli_var_uinteger, parse_cli_var_zuinteger_unlimited)
(parse_cli_var_enum): New, factored out from ...
(do_set_command): ... this. Adjust.
* cli/cli-setshow.h (parse_cli_boolean_value)
(parse_cli_var_uinteger, parse_cli_var_zuinteger_unlimited)
(parse_cli_var_enum): Declare.
* cli/cli-utils.c: Include "cli/cli-option.h".
(get_ulongest): New.
* cli/cli-utils.h (get_ulongest): Declare.
(check_for_argument): New overloads.
* maint-test-options.c: New file.

gdb/testsuite/ChangeLog:
yyyy-mm-dd Pedro Alves <palves@redhat.com>

* gdb.base/options.c: New file.
* gdb.base/options.exp: New file.

Change Summary

差異

--- a/gdb/Makefile.in
+++ b/gdb/Makefile.in
@@ -241,6 +241,7 @@ SUBDIR_CLI_SRCS = \
241241 cli/cli-dump.c \
242242 cli/cli-interp.c \
243243 cli/cli-logging.c \
244+ cli/cli-option.c \
244245 cli/cli-script.c \
245246 cli/cli-setshow.c \
246247 cli/cli-style.c \
@@ -1062,6 +1063,7 @@ COMMON_SFILES = \
10621063 macrotab.c \
10631064 main.c \
10641065 maint.c \
1066+ maint-test-options.c \
10651067 maint-test-settings.c \
10661068 mdebugread.c \
10671069 mem-break.c \
--- a/gdb/cli/cli-decode.c
+++ b/gdb/cli/cli-decode.c
@@ -551,6 +551,7 @@ add_setshow_enum_cmd (const char *name,
551551 set_cmd_context (show, context);
552552 }
553553
554+/* See cli-decode.h. */
554555 const char * const auto_boolean_enums[] = { "on", "off", "auto", NULL };
555556
556557 /* Add an auto-boolean command named NAME to both the set and show
@@ -578,6 +579,9 @@ add_setshow_auto_boolean_cmd (const char *name,
578579 c->enums = auto_boolean_enums;
579580 }
580581
582+/* See cli-decode.h. */
583+const char * const boolean_enums[] = { "on", "off", NULL };
584+
581585 /* Add element named NAME to both the set and show command LISTs (the
582586 list for set/show or some sublist thereof). CLASS is as in
583587 add_cmd. VAR is address of the variable which will contain the
@@ -591,7 +595,6 @@ add_setshow_boolean_cmd (const char *name, enum command_class theclass, int *var
591595 struct cmd_list_element **set_list,
592596 struct cmd_list_element **show_list)
593597 {
594- static const char *boolean_enums[] = { "on", "off", NULL };
595598 struct cmd_list_element *c;
596599
597600 add_setshow_cmd_full (name, theclass, var_boolean, var,
--- a/gdb/cli/cli-decode.h
+++ b/gdb/cli/cli-decode.h
@@ -261,6 +261,10 @@ extern void not_just_help_class_command (const char *arg, int from_tty);
261261
262262 extern void print_doc_line (struct ui_file *, const char *);
263263
264+/* The enums of boolean commands. */
265+extern const char * const boolean_enums[];
266+
267+/* The enums of auto-boolean commands. */
264268 extern const char * const auto_boolean_enums[];
265269
266270 /* Verify whether a given cmd_list_element is a user-defined command.
--- /dev/null
+++ b/gdb/cli/cli-option.c
@@ -0,0 +1,724 @@
1+/* CLI options framework, for GDB.
2+
3+ Copyright (C) 2017-2019 Free Software Foundation, Inc.
4+
5+ This file is part of GDB.
6+
7+ This program is free software; you can redistribute it and/or modify
8+ it under the terms of the GNU General Public License as published by
9+ the Free Software Foundation; either version 3 of the License, or
10+ (at your option) any later version.
11+
12+ This program is distributed in the hope that it will be useful,
13+ but WITHOUT ANY WARRANTY; without even the implied warranty of
14+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15+ GNU General Public License for more details.
16+
17+ You should have received a copy of the GNU General Public License
18+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
19+
20+#include "defs.h"
21+#include "cli/cli-option.h"
22+#include "cli/cli-decode.h"
23+#include "cli/cli-utils.h"
24+#include "cli/cli-setshow.h"
25+#include "command.h"
26+#include <vector>
27+
28+namespace gdb {
29+namespace option {
30+
31+/* An option's value. Which field is active depends on the option's
32+ type. */
33+union option_value
34+{
35+ /* For var_boolean options. */
36+ bool boolean;
37+
38+ /* For var_uinteger options. */
39+ unsigned int uinteger;
40+
41+ /* For var_zuinteger_unlimited options. */
42+ int integer;
43+
44+ /* For var_enum options. */
45+ const char *enumeration;
46+};
47+
48+/* Holds an options definition and its value. */
49+struct option_def_and_value
50+{
51+ /* The option definition. */
52+ const option_def &option;
53+
54+ /* A context. */
55+ void *ctx;
56+
57+ /* The option's value, if any. */
58+ gdb::optional<option_value> value;
59+};
60+
61+/* Info passed around when handling completion. */
62+struct parse_option_completion_info
63+{
64+ /* The completion word. */
65+ const char *word;
66+
67+ /* The tracker. */
68+ completion_tracker &tracker;
69+};
70+
71+/* If ARGS starts with "-", look for a "--" delimiter. If one is
72+ found, then interpret everything up until the "--" as command line
73+ options. Otherwise, interpret unknown input as the beginning of
74+ the command's operands. */
75+
76+static const char *
77+find_end_options_delimiter (const char *args)
78+{
79+ if (args[0] == '-')
80+ {
81+ const char *p = args;
82+
83+ p = skip_spaces (p);
84+ while (*p)
85+ {
86+ if (check_for_argument (&p, "--"))
87+ return p;
88+ else
89+ p = skip_to_space (p);
90+ p = skip_spaces (p);
91+ }
92+ }
93+
94+ return nullptr;
95+}
96+
97+/* Complete TEXT/WORD on all options in OPTIONS_GROUP. */
98+
99+static void
100+complete_on_options (gdb::array_view<const option_def_group> options_group,
101+ completion_tracker &tracker,
102+ const char *text, const char *word)
103+{
104+ size_t textlen = strlen (text);
105+ for (const auto &grp : options_group)
106+ for (const auto &opt : grp.options)
107+ if (strncmp (opt.name, text, textlen) == 0)
108+ {
109+ tracker.add_completion
110+ (make_completion_match_str (opt.name, text, word));
111+ }
112+}
113+
114+/* See cli-option.h. */
115+
116+void
117+complete_on_all_options (completion_tracker &tracker,
118+ gdb::array_view<const option_def_group> options_group)
119+{
120+ static const char opt[] = "-";
121+ complete_on_options (options_group, tracker, opt + 1, opt);
122+}
123+
124+/* Parse ARGS, guided by OPTIONS_GROUP. HAVE_DELIMITER is true if the
125+ whole ARGS line included the "--" options-terminator delimiter. */
126+
127+static gdb::optional<option_def_and_value>
128+parse_option (gdb::array_view<const option_def_group> options_group,
129+ process_options_mode mode,
130+ bool have_delimiter,
131+ const char **args,
132+ parse_option_completion_info *completion = nullptr)
133+{
134+ if (*args == nullptr)
135+ return {};
136+ else if (**args != '-')
137+ {
138+ if (have_delimiter)
139+ error (_("Unrecognized option at: %s"), *args);
140+ return {};
141+ }
142+ else if (check_for_argument (args, "--"))
143+ return {};
144+
145+ /* Skip the initial '-'. */
146+ const char *arg = *args + 1;
147+
148+ const char *after = skip_to_space (arg);
149+ size_t len = after - arg;
150+ const option_def *match = nullptr;
151+ void *match_ctx = nullptr;
152+
153+ for (const auto &grp : options_group)
154+ {
155+ for (const auto &o : grp.options)
156+ {
157+ if (strncmp (o.name, arg, len) == 0)
158+ {
159+ if (match != nullptr)
160+ {
161+ if (completion != nullptr && arg[len] == '\0')
162+ {
163+ complete_on_options (options_group,
164+ completion->tracker,
165+ arg, completion->word);
166+ return {};
167+ }
168+
169+ error (_("Ambiguous option at: -%s"), arg);
170+ }
171+
172+ match = &o;
173+ match_ctx = grp.ctx;
174+
175+ if ((isspace (arg[len]) || arg[len] == '\0')
176+ && strlen (o.name) == len)
177+ break; /* Exact match. */
178+ }
179+ }
180+ }
181+
182+ if (match == nullptr)
183+ {
184+ if (have_delimiter || mode != PROCESS_OPTIONS_UNKNOWN_IS_OPERAND)
185+ error (_("Unrecognized option at: %s"), *args);
186+
187+ return {};
188+ }
189+
190+ if (completion != nullptr && arg[len] == '\0')
191+ {
192+ complete_on_options (options_group, completion->tracker,
193+ arg, completion->word);
194+ return {};
195+ }
196+
197+ *args += 1 + len;
198+ *args = skip_spaces (*args);
199+ if (completion != nullptr)
200+ completion->word = *args;
201+
202+ switch (match->type)
203+ {
204+ case var_boolean:
205+ {
206+ if (!match->have_argument)
207+ {
208+ option_value val;
209+ val.boolean = true;
210+ return option_def_and_value {*match, match_ctx, val};
211+ }
212+
213+ const char *val_str = *args;
214+ int res;
215+
216+ if (**args == '\0' && completion != nullptr)
217+ {
218+ /* Complete on both "on/off" and more options. */
219+
220+ if (mode == PROCESS_OPTIONS_REQUIRE_DELIMITER)
221+ {
222+ complete_on_enum (completion->tracker,
223+ boolean_enums, val_str, val_str);
224+ complete_on_all_options (completion->tracker, options_group);
225+ }
226+ return option_def_and_value {*match, match_ctx};
227+ }
228+ else if (**args == '-')
229+ {
230+ /* Treat:
231+ "cmd -boolean-option -another-opt..."
232+ as:
233+ "cmd -boolean-option on -another-opt..."
234+ */
235+ res = 1;
236+ }
237+ else if (**args == '\0')
238+ {
239+ /* Treat:
240+ (1) "cmd -boolean-option "
241+ as:
242+ (1) "cmd -boolean-option on"
243+ */
244+ res = 1;
245+ }
246+ else
247+ {
248+ res = parse_cli_boolean_value (args);
249+ if (res < 0)
250+ {
251+ const char *end = skip_to_space (*args);
252+ if (completion != nullptr)
253+ {
254+ if (*end == '\0')
255+ {
256+ complete_on_enum (completion->tracker,
257+ boolean_enums, val_str, val_str);
258+ return option_def_and_value {*match, match_ctx};
259+ }
260+ }
261+
262+ if (have_delimiter)
263+ error (_("Value given for `-%s' is not a boolean: %.*s"),
264+ match->name, (int) (end - val_str), val_str);
265+ /* The user didn't separate options from operands
266+ using "--", so treat this unrecognized value as the
267+ start of the operands. This makes "frame apply all
268+ -past-main CMD" work. */
269+ return option_def_and_value {*match, match_ctx};
270+ }
271+ else if (completion != nullptr && **args == '\0')
272+ {
273+ /* While "cmd -boolean [TAB]" only offers "on" and
274+ "off", the boolean option actually accepts "1",
275+ "yes", etc. as boolean values. We complete on all
276+ of those instead of BOOLEAN_ENUMS here to make
277+ these work:
278+
279+ "p -object 1[TAB]" -> "p -object 1 "
280+ "p -object ye[TAB]" -> "p -object yes "
281+
282+ Etc. Note that it's important that the space is
283+ auto-appended. Otherwise, if we only completed on
284+ on/off here, then it might look to the user like
285+ "1" isn't valid, like:
286+ "p -object 1[TAB]" -> "p -object 1" (i.e., nothing happens).
287+ */
288+ static const char *const all_boolean_enums[] = {
289+ "on", "off",
290+ "yes", "no",
291+ "enable", "disable",
292+ "0", "1",
293+ nullptr,
294+ };
295+ complete_on_enum (completion->tracker, all_boolean_enums,
296+ val_str, val_str);
297+ return {};
298+ }
299+ }
300+
301+ option_value val;
302+ val.boolean = res;
303+ return option_def_and_value {*match, match_ctx, val};
304+ }
305+ case var_uinteger:
306+ case var_zuinteger_unlimited:
307+ {
308+ if (completion != nullptr)
309+ {
310+ if (**args == '\0')
311+ {
312+ /* Convenience to let the user know what the option
313+ can accept. Note there's no common prefix between
314+ the strings on purpose, so that readline doesn't do
315+ a partial match. */
316+ completion->tracker.add_completion
317+ (make_unique_xstrdup ("NUMBER"));
318+ completion->tracker.add_completion
319+ (make_unique_xstrdup ("unlimited"));
320+ return {};
321+ }
322+ else if (startswith ("unlimited", *args))
323+ {
324+ completion->tracker.add_completion
325+ (make_unique_xstrdup ("unlimited"));
326+ return {};
327+ }
328+ }
329+
330+ if (match->type == var_zuinteger_unlimited)
331+ {
332+ option_value val;
333+ val.integer = parse_cli_var_zuinteger_unlimited (args, false);
334+ return option_def_and_value {*match, match_ctx, val};
335+ }
336+ else
337+ {
338+ option_value val;
339+ val.uinteger = parse_cli_var_uinteger (match->type, args, false);
340+ return option_def_and_value {*match, match_ctx, val};
341+ }
342+ }
343+ case var_enum:
344+ {
345+ if (completion != nullptr)
346+ {
347+ const char *after_arg = skip_to_space (*args);
348+ if (*after_arg == '\0')
349+ {
350+ complete_on_enum (completion->tracker,
351+ match->enums, *args, *args);
352+ *args = after_arg;
353+
354+ option_value val;
355+ val.enumeration = nullptr;
356+ return option_def_and_value {*match, match_ctx, val};
357+ }
358+ }
359+
360+ if (check_for_argument (args, "--"))
361+ {
362+ /* Treat e.g., "backtrace -entry-values --" as if there
363+ was no argument after "-entry-values". This makes
364+ parse_cli_var_enum throw an error with a suggestion of
365+ what are the valid options. */
366+ args = nullptr;
367+ }
368+
369+ option_value val;
370+ val.enumeration = parse_cli_var_enum (args, match->enums);
371+ return option_def_and_value {*match, match_ctx, val};
372+ }
373+
374+ default:
375+ /* Not yet. */
376+ gdb_assert_not_reached (_("option type not supported"));
377+ }
378+
379+ return {};
380+}
381+
382+/* See cli-option.h. */
383+
384+bool
385+complete_options (completion_tracker &tracker,
386+ const char **args,
387+ process_options_mode mode,
388+ gdb::array_view<const option_def_group> options_group)
389+{
390+ const char *text = *args;
391+
392+ tracker.set_use_custom_word_point (true);
393+
394+ const char *delimiter = find_end_options_delimiter (text);
395+ bool have_delimiter = delimiter != nullptr;
396+
397+ if (text[0] == '-' && (!have_delimiter || *delimiter == '\0'))
398+ {
399+ parse_option_completion_info completion_info {nullptr, tracker};
400+
401+ while (1)
402+ {
403+ *args = skip_spaces (*args);
404+ completion_info.word = *args;
405+
406+ if (strcmp (*args, "-") == 0)
407+ {
408+ complete_on_options (options_group, tracker, *args + 1,
409+ completion_info.word);
410+ }
411+ else if (strcmp (*args, "--") == 0)
412+ {
413+ tracker.add_completion (make_unique_xstrdup (*args));
414+ }
415+ else if (**args == '-')
416+ {
417+ gdb::optional<option_def_and_value> ov
418+ = parse_option (options_group, mode, have_delimiter,
419+ args, &completion_info);
420+ if (!ov && !tracker.have_completions ())
421+ {
422+ tracker.advance_custom_word_point_by (*args - text);
423+ return mode == PROCESS_OPTIONS_REQUIRE_DELIMITER;
424+ }
425+
426+ if (ov
427+ && ov->option.type == var_boolean
428+ && !ov->value.has_value ())
429+ {
430+ /* Looked like a boolean option, but we failed to
431+ parse the value. If this command requires a
432+ delimiter, this value can't be the start of the
433+ operands, so return true. Otherwise, if the
434+ command doesn't require a delimiter return false
435+ so that the caller tries to complete on the
436+ operand. */
437+ tracker.advance_custom_word_point_by (*args - text);
438+ return mode == PROCESS_OPTIONS_REQUIRE_DELIMITER;
439+ }
440+
441+ /* If we parsed an option with an argument, and reached
442+ the end of the input string with no trailing space,
443+ return true, so that our callers don't try to
444+ complete anything by themselves. E.g., this makes it
445+ so that with:
446+
447+ (gdb) frame apply all -limit 10[TAB]
448+
449+ we don't try to complete on command names. */
450+ if (ov
451+ && !tracker.have_completions ()
452+ && **args == '\0'
453+ && *args > text && !isspace ((*args)[-1]))
454+ {
455+ tracker.advance_custom_word_point_by
456+ (*args - text);
457+ return true;
458+ }
459+ }
460+ else
461+ {
462+ tracker.advance_custom_word_point_by
463+ (completion_info.word - text);
464+
465+ /* If the command requires a delimiter, but we haven't
466+ seen one, then return true, so that the caller
467+ doesn't try to complete on whatever follows options,
468+ which for these commands should only be done if
469+ there's a delimiter. */
470+ if (mode == PROCESS_OPTIONS_REQUIRE_DELIMITER
471+ && !have_delimiter)
472+ {
473+ /* If we reached the end of the input string, then
474+ offer all options, since that's all the user can
475+ type (plus "--"). */
476+ if (completion_info.word[0] == '\0')
477+ complete_on_all_options (tracker, options_group);
478+ return true;
479+ }
480+ else
481+ return false;
482+ }
483+
484+ if (tracker.have_completions ())
485+ {
486+ tracker.advance_custom_word_point_by
487+ (completion_info.word - text);
488+ return true;
489+ }
490+ }
491+ }
492+ else if (delimiter != nullptr)
493+ {
494+ tracker.advance_custom_word_point_by (delimiter - text);
495+ *args = delimiter;
496+ return false;
497+ }
498+
499+ return false;
500+}
501+
502+/* See cli-option.h. */
503+
504+bool
505+process_options (const char **args,
506+ process_options_mode mode,
507+ gdb::array_view<const option_def_group> options_group)
508+{
509+ if (*args == nullptr)
510+ return false;
511+
512+ /* If ARGS starts with "-", look for a "--" sequence. If one is
513+ found, then interpret everything up until the "--" as
514+ 'gdb::option'-style command line options. Otherwise, interpret
515+ ARGS as possibly the command's operands. */
516+ bool have_delimiter = find_end_options_delimiter (*args) != nullptr;
517+
518+ if (mode == PROCESS_OPTIONS_REQUIRE_DELIMITER && !have_delimiter)
519+ return false;
520+
521+ bool processed_any = false;
522+
523+ while (1)
524+ {
525+ *args = skip_spaces (*args);
526+
527+ auto ov = parse_option (options_group, mode, have_delimiter, args);
528+ if (!ov)
529+ {
530+ if (processed_any)
531+ return true;
532+ return false;
533+ }
534+
535+ processed_any = true;
536+
537+ switch (ov->option.type)
538+ {
539+ case var_boolean:
540+ {
541+ bool value = ov->value.has_value () ? ov->value->boolean : true;
542+ *ov->option.var_address.boolean (ov->option, ov->ctx) = value;
543+ }
544+ break;
545+ case var_uinteger:
546+ *ov->option.var_address.uinteger (ov->option, ov->ctx)
547+ = ov->value->uinteger;
548+ break;
549+ case var_zuinteger_unlimited:
550+ *ov->option.var_address.integer (ov->option, ov->ctx)
551+ = ov->value->integer;
552+ break;
553+ case var_enum:
554+ *ov->option.var_address.enumeration (ov->option, ov->ctx)
555+ = ov->value->enumeration;
556+ break;
557+ default:
558+ gdb_assert_not_reached ("unhandled option type");
559+ }
560+ }
561+}
562+
563+/* Helper for build_help. Return a fragment of a help string showing
564+ OPT's possible values. Returns NULL if OPT doesn't take an
565+ argument. */
566+
567+static const char *
568+get_val_type_str (const option_def &opt, std::string &buffer)
569+{
570+ if (!opt.have_argument)
571+ return nullptr;
572+
573+ switch (opt.type)
574+ {
575+ case var_boolean:
576+ return "[on|off]";
577+ case var_uinteger:
578+ case var_zuinteger_unlimited:
579+ return "NUMBER|unlimited";
580+ case var_enum:
581+ {
582+ buffer = "";
583+ for (size_t i = 0; opt.enums[i] != nullptr; i++)
584+ {
585+ if (i != 0)
586+ buffer += "|";
587+ buffer += opt.enums[i];
588+ }
589+ return buffer.c_str ();
590+ }
591+ default:
592+ return nullptr;
593+ }
594+}
595+
596+/* Helper for build_help. Appends an indented version of DOC into
597+ HELP. */
598+
599+static void
600+append_indented_doc (const char *doc, std::string &help)
601+{
602+ const char *p = doc;
603+ const char *n = strchr (p, '\n');
604+
605+ while (n != nullptr)
606+ {
607+ help += " ";
608+ help.append (p, n - p + 1);
609+ p = n + 1;
610+ n = strchr (p, '\n');
611+ }
612+ help += " ";
613+ help += p;
614+ help += '\n';
615+}
616+
617+/* Fill HELP with an auto-generated "help" string fragment for
618+ OPTIONS. */
619+
620+static void
621+build_help_option (gdb::array_view<const option_def> options,
622+ std::string &help)
623+{
624+ std::string buffer;
625+
626+ for (const auto &o : options)
627+ {
628+ if (o.set_doc == nullptr)
629+ continue;
630+
631+ help += " -";
632+ help += o.name;
633+
634+ const char *val_type_str = get_val_type_str (o, buffer);
635+ if (val_type_str != nullptr)
636+ {
637+ help += ' ';
638+ help += val_type_str;
639+ }
640+ help += "\n";
641+ append_indented_doc (o.set_doc, help);
642+ if (o.help_doc != nullptr)
643+ append_indented_doc (o.help_doc, help);
644+ help += '\n';
645+ }
646+}
647+
648+/* See cli-option.h. */
649+
650+std::string
651+build_help (const char *help_tmpl,
652+ gdb::array_view<const option_def_group> options_group)
653+{
654+ std::string help_str;
655+
656+ const char *p = strstr (help_tmpl, "%OPTIONS%");
657+ help_str.assign (help_tmpl, p);
658+
659+ for (const auto &grp : options_group)
660+ for (const auto &opt : grp.options)
661+ build_help_option (opt, help_str);
662+
663+ p += strlen ("%OPTIONS%");
664+ help_str.append (p);
665+
666+ return help_str;
667+}
668+
669+/* See cli-option.h. */
670+
671+void
672+add_setshow_cmds_for_options (command_class cmd_class,
673+ void *data,
674+ gdb::array_view<const option_def> options,
675+ struct cmd_list_element **set_list,
676+ struct cmd_list_element **show_list)
677+{
678+ for (const auto &option : options)
679+ {
680+ if (option.type == var_boolean)
681+ {
682+ add_setshow_boolean_cmd (option.name, cmd_class,
683+ option.var_address.boolean (option, data),
684+ option.set_doc, option.show_doc,
685+ option.help_doc,
686+ nullptr, option.show_cmd_cb,
687+ set_list, show_list);
688+ }
689+ else if (option.type == var_uinteger)
690+ {
691+ add_setshow_uinteger_cmd (option.name, cmd_class,
692+ option.var_address.uinteger (option, data),
693+ option.set_doc, option.show_doc,
694+ option.help_doc,
695+ nullptr, option.show_cmd_cb,
696+ set_list, show_list);
697+ }
698+ else if (option.type == var_zuinteger_unlimited)
699+ {
700+ add_setshow_zuinteger_unlimited_cmd
701+ (option.name, cmd_class,
702+ option.var_address.integer (option, data),
703+ option.set_doc, option.show_doc,
704+ option.help_doc,
705+ nullptr, option.show_cmd_cb,
706+ set_list, show_list);
707+ }
708+ else if (option.type == var_enum)
709+ {
710+ add_setshow_enum_cmd (option.name, cmd_class,
711+ option.enums,
712+ option.var_address.enumeration (option, data),
713+ option.set_doc, option.show_doc,
714+ option.help_doc,
715+ nullptr, option.show_cmd_cb,
716+ set_list, show_list);
717+ }
718+ else
719+ gdb_assert_not_reached (_("option type not handled"));
720+ }
721+}
722+
723+} /* namespace option */
724+} /* namespace gdb */
--- /dev/null
+++ b/gdb/cli/cli-option.h
@@ -0,0 +1,335 @@
1+/* CLI options framework, for GDB.
2+
3+ Copyright (C) 2017-2019 Free Software Foundation, Inc.
4+
5+ This file is part of GDB.
6+
7+ This program is free software; you can redistribute it and/or modify
8+ it under the terms of the GNU General Public License as published by
9+ the Free Software Foundation; either version 3 of the License, or
10+ (at your option) any later version.
11+
12+ This program is distributed in the hope that it will be useful,
13+ but WITHOUT ANY WARRANTY; without even the implied warranty of
14+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15+ GNU General Public License for more details.
16+
17+ You should have received a copy of the GNU General Public License
18+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
19+
20+#ifndef CLI_OPTION_H
21+#define CLI_OPTION_H 1
22+
23+#include "common/gdb_optional.h"
24+#include "common/array-view.h"
25+#include "completer.h"
26+#include <string>
27+#include "command.h"
28+
29+namespace gdb {
30+namespace option {
31+
32+/* A type-erased option definition. The actual type of the option is
33+ stored in the TYPE field. Client code cannot define objects of
34+ this type directly (the ctor is protected). Instead, one of the
35+ wrapper types below that extends this (boolean_option_def,
36+ flag_option_def, uinteger_option_def, etc.) should be defined. */
37+struct option_def
38+{
39+ /* The ctor is protected because you're supposed to construct using
40+ one of bool_option_def, etc. below. */
41+protected:
42+ typedef void *(erased_get_var_address_ftype) ();
43+
44+ /* Construct an option. NAME_ is the option's name. VAR_TYPE_
45+ defines the option's type. ERASED_GET_VAR_ADDRESS_ is a pointer
46+ to a function that returns the option's control variable.
47+ SHOW_CMD_CB_ is a pointer to callback for the "show" command that
48+ is installed for this option. SET_DOC_, SHOW_DOC_, HELP_DOC_ are
49+ used to create the option's "set/show" commands. */
50+ constexpr option_def (const char *name_,
51+ var_types var_type_,
52+ erased_get_var_address_ftype *erased_get_var_address_,
53+ show_value_ftype *show_cmd_cb_,
54+ const char *set_doc_,
55+ const char *show_doc_,
56+ const char *help_doc_)
57+ : name (name_), type (var_type_),
58+ erased_get_var_address (erased_get_var_address_),
59+ var_address {},
60+ show_cmd_cb (show_cmd_cb_),
61+ set_doc (set_doc_), show_doc (show_doc_), help_doc (help_doc_)
62+ {}
63+
64+public:
65+ /* The option's name. */
66+ const char *name;
67+
68+ /* The option's type. */
69+ var_types type;
70+
71+ /* A function that gets the controlling variable's address, type
72+ erased. */
73+ erased_get_var_address_ftype *erased_get_var_address;
74+
75+ /* Get the controlling variable's address. Each type of variable
76+ uses a different union member. We do this instead of having a
77+ single hook that return a "void *", for better type safety. This
78+ way, actual instances of concrete option_def types
79+ (boolean_option_def, etc.) fail to compile if you pass in a
80+ function with incorrect return type. CTX here is the aggregate
81+ object that groups the option variables from which the callback
82+ returns the address of some member. */
83+ union
84+ {
85+ int *(*boolean) (const option_def &, void *ctx);
86+ unsigned int *(*uinteger) (const option_def &, void *ctx);
87+ int *(*integer) (const option_def &, void *ctx);
88+ const char **(*enumeration) (const option_def &, void *ctx);
89+ }
90+ var_address;
91+
92+ /* Pointer to null terminated list of enumerated values (like argv).
93+ Only used by var_enum options. */
94+ const char *const *enums = nullptr;
95+
96+ /* True if the option takes an argument. */
97+ bool have_argument = true;
98+
99+ /* The "show" callback to use in the associated "show" command.
100+ E.g., "show print elements". */
101+ show_value_ftype *show_cmd_cb;
102+
103+ /* The set/show/help strings. These are shown in both the help of
104+ commands that use the option group this option belongs to (e.g.,
105+ "help print"), and in the associated commands (e.g., "set/show
106+ print elements", "help set print elements"). */
107+ const char *set_doc;
108+ const char *show_doc;
109+ const char *help_doc;
110+
111+ /* Convenience method that returns THIS as an option_def. Useful
112+ when you're putting an option_def subclass in an option_def
113+ array_view. */
114+ const option_def &def () const
115+ {
116+ return *this;
117+ }
118+};
119+
120+namespace detail
121+{
122+
123+/* Get the address of the option's value, cast to the right type.
124+ RetType is the restored type of the variable, and Context is the
125+ restored type of the context pointer. */
126+template<typename RetType, typename Context>
127+static inline RetType *
128+get_var_address (const option_def &option, void *ctx)
129+{
130+ using unerased_ftype = RetType *(Context *);
131+ unerased_ftype *fun = (unerased_ftype *) option.erased_get_var_address;
132+ return fun ((Context *) ctx);
133+}
134+
135+/* Convenience identity helper that just returns SELF. */
136+
137+template<typename T>
138+static T *
139+return_self (T *self)
140+{
141+ return self;
142+}
143+
144+} /* namespace detail */
145+
146+/* Follows the definitions of the option types that client code should
147+ define. Note that objects of these types are placed in option_def
148+ arrays, by design, so they must not have data fields of their
149+ own. */
150+
151+/* A var_boolean command line option. */
152+
153+template<typename Context>
154+struct boolean_option_def : option_def
155+{
156+ boolean_option_def (const char *long_option_,
157+ int *(*get_var_address_cb_) (Context *),
158+ show_value_ftype *show_cmd_cb_,
159+ const char *set_doc_,
160+ const char *show_doc_ = nullptr,
161+ const char *help_doc_ = nullptr)
162+ : option_def (long_option_, var_boolean,
163+ (erased_get_var_address_ftype *) get_var_address_cb_,
164+ show_cmd_cb_,
165+ set_doc_, show_doc_, help_doc_)
166+ {
167+ var_address.boolean = detail::get_var_address<int, Context>;
168+ }
169+};
170+
171+/* A flag command line option. This is a var_boolean option under the
172+ hood, but unlike boolean options, flag options don't take an on/off
173+ argument. */
174+
175+template<typename Context = int>
176+struct flag_option_def : boolean_option_def<Context>
177+{
178+ flag_option_def (const char *long_option_,
179+ int *(*var_address_cb_) (Context *),
180+ const char *set_doc_,
181+ const char *help_doc_ = nullptr)
182+ : boolean_option_def<Context> (long_option_,
183+ var_address_cb_,
184+ NULL,
185+ set_doc_, NULL, help_doc_)
186+ {
187+ this->have_argument = false;
188+ }
189+
190+ flag_option_def (const char *long_option_,
191+ const char *set_doc_,
192+ const char *help_doc_ = nullptr)
193+ : boolean_option_def<Context> (long_option_,
194+ gdb::option::detail::return_self,
195+ NULL,
196+ set_doc_, nullptr, help_doc_)
197+ {
198+ this->have_argument = false;
199+ }
200+};
201+
202+/* A var_uinteger command line option. */
203+
204+template<typename Context>
205+struct uinteger_option_def : option_def
206+{
207+ uinteger_option_def (const char *long_option_,
208+ unsigned int *(*get_var_address_cb_) (Context *),
209+ show_value_ftype *show_cmd_cb_,
210+ const char *set_doc_,
211+ const char *show_doc_ = nullptr,
212+ const char *help_doc_ = nullptr)
213+ : option_def (long_option_, var_uinteger,
214+ (erased_get_var_address_ftype *) get_var_address_cb_,
215+ show_cmd_cb_,
216+ set_doc_, show_doc_, help_doc_)
217+ {
218+ var_address.uinteger = detail::get_var_address<unsigned int, Context>;
219+ }
220+};
221+
222+/* A var_zuinteger_unlimited command line option. */
223+
224+template<typename Context>
225+struct zuinteger_unlimited_option_def : option_def
226+{
227+ zuinteger_unlimited_option_def (const char *long_option_,
228+ int *(*get_var_address_cb_) (Context *),
229+ show_value_ftype *show_cmd_cb_,
230+ const char *set_doc_,
231+ const char *show_doc_ = nullptr,
232+ const char *help_doc_ = nullptr)
233+ : option_def (long_option_, var_zuinteger_unlimited,
234+ (erased_get_var_address_ftype *) get_var_address_cb_,
235+ show_cmd_cb_,
236+ set_doc_, show_doc_, help_doc_)
237+ {
238+ var_address.integer = detail::get_var_address<int, Context>;
239+ }
240+};
241+
242+/* An var_enum command line option. */
243+
244+template<typename Context>
245+struct enum_option_def : option_def
246+{
247+ enum_option_def (const char *long_option_,
248+ const char *const *enumlist,
249+ const char **(*get_var_address_cb_) (Context *),
250+ show_value_ftype *show_cmd_cb_,
251+ const char *set_doc_,
252+ const char *show_doc_ = nullptr,
253+ const char *help_doc_ = nullptr)
254+ : option_def (long_option_, var_enum,
255+ (erased_get_var_address_ftype *) get_var_address_cb_,
256+ show_cmd_cb_,
257+ set_doc_, show_doc_, help_doc_)
258+ {
259+ var_address.enumeration = detail::get_var_address<const char *, Context>;
260+ this->enums = enumlist;
261+ }
262+};
263+
264+/* A group of options that all share the same context pointer to pass
265+ to the options' get-current-value callbacks. */
266+struct option_def_group
267+{
268+ /* The list of options. */
269+ gdb::array_view<const option_def> options;
270+
271+ /* The context pointer to pass to the options' get-current-value
272+ callbacks. */
273+ void *ctx;
274+};
275+
276+/* Modes of operation for process_options. */
277+enum process_options_mode
278+{
279+ /* In this mode, options are only processed if we find a "--"
280+ delimiter. Throws an error if unknown options are found. */
281+ PROCESS_OPTIONS_REQUIRE_DELIMITER,
282+
283+ /* In this mode, a "--" delimiter is not required. Throws an error
284+ if unknown options are found, regardless of whether a delimiter
285+ is present. */
286+ PROCESS_OPTIONS_UNKNOWN_IS_ERROR,
287+
288+ /* In this mode, a "--" delimiter is not required. If an unknown
289+ option is found, assume it is the command's argument/operand. */
290+ PROCESS_OPTIONS_UNKNOWN_IS_OPERAND,
291+};
292+
293+/* Process ARGS, using OPTIONS_GROUP as valid options. Returns true
294+ if the string has been fully parsed and there are no operands to
295+ handle by the caller. Return false if options were parsed, and
296+ *ARGS now points at the first operand. */
297+extern bool process_options
298+ (const char **args,
299+ process_options_mode mode,
300+ gdb::array_view<const option_def_group> options_group);
301+
302+/* Complete ARGS on options listed by OPTIONS_GROUP. Returns true if
303+ the string has been fully parsed and there are no operands to
304+ handle by the caller. Return false if options were parsed, and
305+ *ARGS now points at the first operand. */
306+extern bool complete_options
307+ (completion_tracker &tracker,
308+ const char **args,
309+ process_options_mode mode,
310+ gdb::array_view<const option_def_group> options_group);
311+
312+/* Complete on all options listed by OPTIONS_GROUP. */
313+extern void
314+ complete_on_all_options (completion_tracker &tracker,
315+ gdb::array_view<const option_def_group> options_group);
316+
317+/* Return a string with the result of replacing %OPTIONS% in HELP_TMLP
318+ with an auto-generated "help" string fragment for all the options
319+ in OPTIONS_GROUP. */
320+extern std::string build_help
321+ (const char *help_tmpl,
322+ gdb::array_view<const option_def_group> options_group);
323+
324+/* Install set/show commands for options defined in OPTIONS. DATA is
325+ a pointer to the structure that holds the data associated with the
326+ OPTIONS array. */
327+extern void add_setshow_cmds_for_options (command_class cmd_class, void *data,
328+ gdb::array_view<const option_def> options,
329+ struct cmd_list_element **set_list,
330+ struct cmd_list_element **show_list);
331+
332+} /* namespace option */
333+} /* namespace gdb */
334+
335+#endif /* CLI_OPTION_H */
--- a/gdb/cli/cli-setshow.c
+++ b/gdb/cli/cli-setshow.c
@@ -78,33 +78,48 @@ parse_auto_binary_operation (const char *arg)
7878 /* See cli-setshow.h. */
7979
8080 int
81-parse_cli_boolean_value (const char *arg)
81+parse_cli_boolean_value (const char **arg)
8282 {
83- int length;
84-
85- if (!arg || !*arg)
86- return 1;
83+ const char *p = skip_to_space (*arg);
84+ size_t length = p - *arg;
8785
88- length = strlen (arg);
86+ /* Note that "o" is ambiguous. */
8987
90- while (arg[length - 1] == ' ' || arg[length - 1] == '\t')
91- length--;
88+ if ((length == 2 && strncmp (*arg, "on", length) == 0)
89+ || strncmp (*arg, "1", length) == 0
90+ || strncmp (*arg, "yes", length) == 0
91+ || strncmp (*arg, "enable", length) == 0)
92+ {
93+ *arg = skip_spaces (*arg + length);
94+ return 1;
95+ }
96+ else if ((length >= 2 && strncmp (*arg, "off", length) == 0)
97+ || strncmp (*arg, "0", length) == 0
98+ || strncmp (*arg, "no", length) == 0
99+ || strncmp (*arg, "disable", length) == 0)
100+ {
101+ *arg = skip_spaces (*arg + length);
102+ return 0;
103+ }
104+ else
105+ return -1;
106+}
92107
93- /* Note that "o" is ambiguous. */
108+/* See cli-setshow.h. */
94109
95- if ((length == 2 && strncmp (arg, "on", length) == 0)
96- || strncmp (arg, "1", length) == 0
97- || strncmp (arg, "yes", length) == 0
98- || strncmp (arg, "enable", length) == 0)
110+int
111+parse_cli_boolean_value (const char *arg)
112+{
113+ if (!arg || !*arg)
99114 return 1;
100- else if ((length >= 2 && strncmp (arg, "off", length) == 0)
101- || strncmp (arg, "0", length) == 0
102- || strncmp (arg, "no", length) == 0
103- || strncmp (arg, "disable", length) == 0)
104- return 0;
105- else
115+
116+ int b = parse_cli_boolean_value (&arg);
117+ if (b >= 0 && *arg != '\0')
106118 return -1;
119+
120+ return b;
107121 }
122+
108123
109124 void
110125 deprecated_show_value_hack (struct ui_file *ignore_file,
@@ -134,21 +149,136 @@ deprecated_show_value_hack (struct ui_file *ignore_file,
134149
135150 /* Returns true if ARG is "unlimited". */
136151
137-static int
138-is_unlimited_literal (const char *arg)
152+static bool
153+is_unlimited_literal (const char **arg)
139154 {
140- arg = skip_spaces (arg);
155+ *arg = skip_spaces (*arg);
141156
142- const char *p = skip_to_space (arg);
157+ const char *p = skip_to_space (*arg);
143158
144- size_t len = p - arg;
159+ size_t len = p - *arg;
145160
146- if (len > 0 && strncmp ("unlimited", arg, len) == 0)
147- return true;
161+ if (len > 0 && strncmp ("unlimited", *arg, len) == 0)
162+ {
163+ *arg += len;
164+ return true;
165+ }
148166
149167 return false;
150168 }
151169
170+/* See cli-setshow.h. */
171+
172+unsigned int
173+parse_cli_var_uinteger (var_types var_type, const char **arg,
174+ bool expression)
175+{
176+ LONGEST val;
177+
178+ if (*arg == nullptr)
179+ {
180+ if (var_type == var_uinteger)
181+ error_no_arg (_("integer to set it to, or \"unlimited\"."));
182+ else
183+ error_no_arg (_("integer to set it to."));
184+ }
185+
186+ if (var_type == var_uinteger && is_unlimited_literal (arg))
187+ val = 0;
188+ else if (expression)
189+ val = parse_and_eval_long (*arg);
190+ else
191+ val = get_ulongest (arg);
192+
193+ if (var_type == var_uinteger && val == 0)
194+ val = UINT_MAX;
195+ else if (val < 0
196+ /* For var_uinteger, don't let the user set the value
197+ to UINT_MAX directly, as that exposes an
198+ implementation detail to the user interface. */
199+ || (var_type == var_uinteger && val >= UINT_MAX)
200+ || (var_type == var_zuinteger && val > UINT_MAX))
201+ error (_("integer %s out of range"), plongest (val));
202+
203+ return val;
204+}
205+
206+/* See cli-setshow.h. */
207+
208+int
209+parse_cli_var_zuinteger_unlimited (const char **arg, bool expression)
210+{
211+ LONGEST val;
212+
213+ if (arg == nullptr)
214+ error_no_arg (_("integer to set it to, or \"unlimited\"."));
215+
216+ if (is_unlimited_literal (arg))
217+ val = -1;
218+ else if (expression)
219+ val = parse_and_eval_long (*arg);
220+ else
221+ val = get_ulongest (arg);
222+
223+ if (val > INT_MAX)
224+ error (_("integer %s out of range"), plongest (val));
225+ else if (val < -1)
226+ error (_("only -1 is allowed to set as unlimited"));
227+
228+ return val;
229+}
230+
231+/* See cli-setshow.h. */
232+
233+const char *
234+parse_cli_var_enum (const char **args, const char *const *enums)
235+{
236+ /* If no argument was supplied, print an informative error
237+ message. */
238+ if (args == NULL || *args == NULL || **args == '\0')
239+ {
240+ std::string msg;
241+
242+ for (size_t i = 0; enums[i]; i++)
243+ {
244+ if (i != 0)
245+ msg += ", ";
246+ msg += enums[i];
247+ }
248+ error (_("Requires an argument. Valid arguments are %s."),
249+ msg.c_str ());
250+ }
251+
252+ const char *p = skip_to_space (*args);
253+ size_t len = p - *args;
254+
255+ int nmatches = 0;
256+ const char *match = NULL;
257+ for (size_t i = 0; enums[i]; i++)
258+ if (strncmp (*args, enums[i], len) == 0)
259+ {
260+ if (enums[i][len] == '\0')
261+ {
262+ match = enums[i];
263+ nmatches = 1;
264+ break; /* Exact match. */
265+ }
266+ else
267+ {
268+ match = enums[i];
269+ nmatches++;
270+ }
271+ }
272+
273+ if (nmatches == 0)
274+ error (_("Undefined item: \"%.*s\"."), (int) len, *args);
275+
276+ if (nmatches > 1)
277+ error (_("Ambiguous item \"%.*s\"."), (int) len, *args);
278+
279+ *args += len;
280+ return match;
281+}
152282
153283 /* Do a "set" command. ARG is NULL if no argument, or the
154284 text of the argument, and FROM_TTY is nonzero if this command is
@@ -295,30 +425,7 @@ do_set_command (const char *arg, int from_tty, struct cmd_list_element *c)
295425 case var_uinteger:
296426 case var_zuinteger:
297427 {
298- LONGEST val;
299-
300- if (arg == NULL)
301- {
302- if (c->var_type == var_uinteger)
303- error_no_arg (_("integer to set it to, or \"unlimited\"."));
304- else
305- error_no_arg (_("integer to set it to."));
306- }
307-
308- if (c->var_type == var_uinteger && is_unlimited_literal (arg))
309- val = 0;
310- else
311- val = parse_and_eval_long (arg);
312-
313- if (c->var_type == var_uinteger && val == 0)
314- val = UINT_MAX;
315- else if (val < 0
316- /* For var_uinteger, don't let the user set the value
317- to UINT_MAX directly, as that exposes an
318- implementation detail to the user interface. */
319- || (c->var_type == var_uinteger && val >= UINT_MAX)
320- || (c->var_type == var_zuinteger && val > UINT_MAX))
321- error (_("integer %s out of range"), plongest (val));
428+ unsigned int val = parse_cli_var_uinteger (c->var_type, &arg, true);
322429
323430 if (*(unsigned int *) c->var != val)
324431 {
@@ -341,7 +448,7 @@ do_set_command (const char *arg, int from_tty, struct cmd_list_element *c)
341448 error_no_arg (_("integer to set it to."));
342449 }
343450
344- if (c->var_type == var_integer && is_unlimited_literal (arg))
451+ if (c->var_type == var_integer && is_unlimited_literal (&arg))
345452 val = 0;
346453 else
347454 val = parse_and_eval_long (arg);
@@ -366,59 +473,11 @@ do_set_command (const char *arg, int from_tty, struct cmd_list_element *c)
366473 }
367474 case var_enum:
368475 {
369- int i;
370- int len;
371- int nmatches;
372- const char *match = NULL;
373- const char *p;
374-
375- /* If no argument was supplied, print an informative error
376- message. */
377- if (arg == NULL)
378- {
379- std::string msg;
380-
381- for (i = 0; c->enums[i]; i++)
382- {
383- if (i != 0)
384- msg += ", ";
385- msg += c->enums[i];
386- }
387- error (_("Requires an argument. Valid arguments are %s."),
388- msg.c_str ());
389- }
390-
391- p = strchr (arg, ' ');
476+ const char *end_arg = arg;
477+ const char *match = parse_cli_var_enum (&end_arg, c->enums);
392478
393- if (p)
394- len = p - arg;
395- else
396- len = strlen (arg);
397-
398- nmatches = 0;
399- for (i = 0; c->enums[i]; i++)
400- if (strncmp (arg, c->enums[i], len) == 0)
401- {
402- if (c->enums[i][len] == '\0')
403- {
404- match = c->enums[i];
405- nmatches = 1;
406- break; /* Exact match. */
407- }
408- else
409- {
410- match = c->enums[i];
411- nmatches++;
412- }
413- }
414-
415- if (nmatches <= 0)
416- error (_("Undefined item: \"%s\"."), arg);
417-
418- if (nmatches > 1)
419- error (_("Ambiguous item \"%s\"."), arg);
420-
421- const char *after = skip_spaces (arg + len);
479+ int len = end_arg - arg;
480+ const char *after = skip_spaces (end_arg);
422481 if (*after != '\0')
423482 error (_("Junk after item \"%.*s\": %s"), len, arg, after);
424483
@@ -432,20 +491,7 @@ do_set_command (const char *arg, int from_tty, struct cmd_list_element *c)
432491 break;
433492 case var_zuinteger_unlimited:
434493 {
435- LONGEST val;
436-
437- if (arg == NULL)
438- error_no_arg (_("integer to set it to, or \"unlimited\"."));
439-
440- if (is_unlimited_literal (arg))
441- val = -1;
442- else
443- val = parse_and_eval_long (arg);
444-
445- if (val > INT_MAX)
446- error (_("integer %s out of range"), plongest (val));
447- else if (val < -1)
448- error (_("only -1 is allowed to set as unlimited"));
494+ int val = parse_cli_var_zuinteger_unlimited (&arg, true);
449495
450496 if (*(int *) c->var != val)
451497 {
--- a/gdb/cli/cli-setshow.h
+++ b/gdb/cli/cli-setshow.h
@@ -23,6 +23,33 @@ struct cmd_list_element;
2323 Returns 1 for true, 0 for false, and -1 if invalid. */
2424 extern int parse_cli_boolean_value (const char *arg);
2525
26+/* Same as above, but work with a pointer to pointer. ARG is advanced
27+ past a successfully parsed value. */
28+extern int parse_cli_boolean_value (const char **arg);
29+
30+/* Parse ARG, an option to a var_uinteger or var_zuinteger variable.
31+ Either returns the parsed value on success or throws an error. If
32+ EXPRESSION is true, *ARG is parsed as an expression; otherwise, it
33+ is parsed with get_ulongest. It's not possible to parse the
34+ integer as an expression when there may be valid input after the
35+ integer, such as when parsing command options. E.g., "print
36+ -elements NUMBER -obj --". In such case, parsing as an expression
37+ would parse "-obj --" as part of the expression as well. */
38+extern unsigned int parse_cli_var_uinteger (var_types var_type,
39+ const char **arg,
40+ bool expression);
41+
42+/* Like parse_cli_var_uinteger, for var_zuinteger_unlimited. */
43+extern int parse_cli_var_zuinteger_unlimited (const char **arg,
44+ bool expression);
45+
46+/* Parse ARG, an option to a var_enum variable. ENUM is a
47+ null-terminated array of possible values. Either returns the parsed
48+ value on success or throws an error. ARG is advanced past the
49+ parsed value. */
50+const char *parse_cli_var_enum (const char **args,
51+ const char *const *enums);
52+
2653 extern void do_set_command (const char *arg, int from_tty,
2754 struct cmd_list_element *c);
2855 extern void do_show_command (const char *arg, int from_tty,
--- a/gdb/cli/cli-utils.c
+++ b/gdb/cli/cli-utils.c
@@ -27,6 +27,57 @@ static std::string extract_arg_maybe_quoted (const char **arg);
2727
2828 /* See documentation in cli-utils.h. */
2929
30+ULONGEST
31+get_ulongest (const char **pp, int trailer)
32+{
33+ LONGEST retval = 0; /* default */
34+ const char *p = *pp;
35+
36+ if (*p == '$')
37+ {
38+ value *val = value_from_history_ref (p, &p);
39+
40+ if (val != NULL) /* Value history reference */
41+ {
42+ if (TYPE_CODE (value_type (val)) == TYPE_CODE_INT)
43+ retval = value_as_long (val);
44+ else
45+ error (_("History value must have integer type."));
46+ }
47+ else /* Convenience variable */
48+ {
49+ /* Internal variable. Make a copy of the name, so we can
50+ null-terminate it to pass to lookup_internalvar(). */
51+ const char *start = ++p;
52+ while (isalnum (*p) || *p == '_')
53+ p++;
54+ std::string varname (start, p - start);
55+ if (!get_internalvar_integer (lookup_internalvar (varname.c_str ()),
56+ &retval))
57+ error (_("Convenience variable $%s does not have integer value."),
58+ varname.c_str ());
59+ }
60+ }
61+ else
62+ {
63+ retval = strtoulst (p, pp, 0);
64+ if (p == *pp)
65+ {
66+ /* There is no number here. (e.g. "cond a == b"). */
67+ error (_("Expected integer at: %s"), p);
68+ }
69+ p = *pp;
70+ }
71+
72+ if (!(isspace (*p) || *p == '\0' || *p == trailer))
73+ error (_("Trailing junk at: %s"), p);
74+ p = skip_spaces (p);
75+ *pp = p;
76+ return retval;
77+}
78+
79+/* See documentation in cli-utils.h. */
80+
3081 int
3182 get_number_trailer (const char **pp, int trailer)
3283 {
--- a/gdb/cli/cli-utils.h
+++ b/gdb/cli/cli-utils.h
@@ -39,6 +39,10 @@ extern int get_number (const char **);
3939
4040 extern int get_number (char **);
4141
42+/* Like get_number_trailer, but works with ULONGEST, and throws on
43+ error instead of returning 0. */
44+extern ULONGEST get_ulongest (const char **pp, int trailer = '\0');
45+
4246 /* Extract from ARGS the arguments [-q] [-t TYPEREGEXP] [--] NAMEREGEXP.
4347
4448 The caller is responsible to initialize *QUIET to false, *REGEXP
@@ -193,6 +197,14 @@ extern std::string extract_arg (const char **arg);
193197 argument. */
194198 extern int check_for_argument (const char **str, const char *arg, int arg_len);
195199
200+/* Same as above, but ARG's length is computed. */
201+
202+static inline int
203+check_for_argument (const char **str, const char *arg)
204+{
205+ return check_for_argument (str, arg, strlen (arg));
206+}
207+
196208 /* Same, for non-const STR. */
197209
198210 static inline int
@@ -202,6 +214,12 @@ check_for_argument (char **str, const char *arg, int arg_len)
202214 arg, arg_len);
203215 }
204216
217+static inline int
218+check_for_argument (char **str, const char *arg)
219+{
220+ return check_for_argument (str, arg, strlen (arg));
221+}
222+
205223 /* A helper function that looks for a set of flags at the start of a
206224 string. The possible flags are given as a null terminated string.
207225 A flag in STR must either be at the end of the string,
--- /dev/null
+++ b/gdb/maint-test-options.c
@@ -0,0 +1,461 @@
1+/* Maintenance commands for testing the options framework.
2+
3+ Copyright (C) 2019 Free Software Foundation, Inc.
4+
5+ This file is part of GDB.
6+
7+ This program is free software; you can redistribute it and/or modify
8+ it under the terms of the GNU General Public License as published by
9+ the Free Software Foundation; either version 3 of the License, or
10+ (at your option) any later version.
11+
12+ This program is distributed in the hope that it will be useful,
13+ but WITHOUT ANY WARRANTY; without even the implied warranty of
14+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15+ GNU General Public License for more details.
16+
17+ You should have received a copy of the GNU General Public License
18+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
19+
20+#include "defs.h"
21+#include "gdbcmd.h"
22+#include "cli/cli-option.h"
23+
24+/* This file defines three "maintenance test-options" subcommands to
25+ exercise TAB-completion and option processing:
26+
27+ (gdb) maint test-options require-delimiter
28+ (gdb) maint test-options unknown-is-error
29+ (gdb) maint test-options unknown-is-operand
30+
31+ And a fourth one to help with TAB-completion testing.
32+
33+ (gdb) maint show test-options-completion-result
34+
35+ Each of the test-options subcommands exercise
36+ gdb::option::process_options with a different enum
37+ process_options_mode value. Examples for commands they model:
38+
39+ - "print" and "compile print", are like "require-delimiter",
40+ because they accept random expressions as argument.
41+
42+ - "backtrace" and "frame/thread apply" are like
43+ "unknown-is-operand", because "-" is a valid command.
44+
45+ - "compile file" and "compile code" are like "unknown-is-error".
46+
47+ These commands allow exercising all aspects of option processing
48+ without having to pick some existing command. That should be more
49+ stable going forward than relying on an existing user command,
50+ since if we picked say "print", that command or its options could
51+ change in future, and then we'd be left with having to pick some
52+ other command or option to exercise some non-command-specific
53+ option processing detail. Also, actual user commands have side
54+ effects that we're not interested in when we're focusing on unit
55+ testing the options machinery. BTW, a maintenance command is used
56+ as a sort of unit test driver instead of actual "maint selftest"
57+ unit tests, since we need to go all the way via gdb including
58+ readline, for proper testing of TAB completion.
59+
60+ These maintenance commands support options of all the different
61+ available kinds of commands (boolean, enum, flag, uinteger):
62+
63+ (gdb) maint test-options require-delimiter -[TAB]
64+ -bool -enum -flag -uinteger -xx1 -xx2
65+
66+ (gdb) maint test-options require-delimiter -bool o[TAB]
67+ off on
68+ (gdb) maint test-options require-delimiter -enum [TAB]
69+ xxx yyy zzz
70+ (gdb) maint test-options require-delimiter -uinteger [TAB]
71+ NUMBER unlimited
72+
73+ '-xx1' and '-xx2' are flag options too. They exist in order to
74+ test ambiguous option names, like '-xx'.
75+
76+ Invoking the commands makes them print out the options parsed:
77+
78+ (gdb) maint test-options unknown-is-error -flag -enum yyy cmdarg
79+ -flag 1 -xx1 0 -xx2 0 -bool 0 -enum yyy -uint 0 -zuint-unl 0 -- cmdarg
80+
81+ (gdb) maint test-options require-delimiter -flag -enum yyy cmdarg
82+ -flag 0 -xx1 0 -xx2 0 -bool 0 -enum xxx -uint 0 -zuint-unl 0 -- -flag -enum yyy cmdarg
83+ (gdb) maint test-options require-delimiter -flag -enum yyy cmdarg --
84+ Unrecognized option at: cmdarg --
85+ (gdb) maint test-options require-delimiter -flag -enum yyy -- cmdarg
86+ -flag 1 -xx1 0 -xx2 0 -bool 0 -enum yyy -uint 0 -zuint-unl 0 -- cmdarg
87+
88+ The "maint show test-options-completion-result" command exists in
89+ order to do something similar for completion:
90+
91+ (gdb) maint test-options unknown-is-error -flag -b 0 -enum yyy OPERAND[TAB]
92+ (gdb) maint show test-options-completion-result
93+ 0 OPERAND
94+
95+ (gdb) maint test-options unknown-is-error -flag -b 0 -enum yyy[TAB]
96+ (gdb) maint show test-options-completion-result
97+ 1
98+
99+ (gdb) maint test-options require-dash -unknown[TAB]
100+ (gdb) maint show test-options-completion-result
101+ 1
102+
103+ Here, "1" means the completion function processed the whole input
104+ line, and that the command shouldn't do anything with the arguments,
105+ since there are no operands. While "0" indicates that there are
106+ operands after options. The text after "0" is the operands.
107+
108+ This level of detail is particularly important because getting the
109+ completion function's entry point to return back to the caller the
110+ right pointer into the operand is quite tricky in several
111+ scenarios. */
112+
113+/* Enum values for the "maintenance test-options" commands. */
114+const char test_options_enum_values_xxx[] = "xxx";
115+const char test_options_enum_values_yyy[] = "yyy";
116+const char test_options_enum_values_zzz[] = "zzz";
117+static const char *const test_options_enum_values_choices[] =
118+{
119+ test_options_enum_values_xxx,
120+ test_options_enum_values_yyy,
121+ test_options_enum_values_zzz,
122+ NULL
123+};
124+
125+/* Option data for the "maintenance test-options" commands. */
126+
127+struct test_options_opts
128+{
129+ int flag_opt = 0;
130+ int xx1_opt = 0;
131+ int xx2_opt = 0;
132+ int boolean_opt = 0;
133+ const char *enum_opt = test_options_enum_values_xxx;
134+ unsigned int uint_opt = 0;
135+ int zuint_unl_opt = 0;
136+};
137+
138+/* Option definitions for the "maintenance test-options" commands. */
139+
140+static const gdb::option::option_def test_options_option_defs[] = {
141+
142+ /* A flag option. */
143+ gdb::option::flag_option_def<test_options_opts> {
144+ "flag",
145+ [] (test_options_opts *opts) { return &opts->flag_opt; },
146+ N_("A flag option."),
147+ },
148+
149+ /* A couple flags with similar names, for "ambiguous option names"
150+ testing. */
151+ gdb::option::flag_option_def<test_options_opts> {
152+ "xx1",
153+ [] (test_options_opts *opts) { return &opts->xx1_opt; },
154+ N_("A flag option."),
155+ },
156+ gdb::option::flag_option_def<test_options_opts> {
157+ "xx2",
158+ [] (test_options_opts *opts) { return &opts->xx2_opt; },
159+ N_("A flag option."),
160+ },
161+
162+ /* A boolean option. */
163+ gdb::option::boolean_option_def<test_options_opts> {
164+ "bool",
165+ [] (test_options_opts *opts) { return &opts->boolean_opt; },
166+ nullptr, /* show_cmd_cb */
167+ N_("A boolean option."),
168+ },
169+
170+ /* An enum option. */
171+ gdb::option::enum_option_def<test_options_opts> {
172+ "enum",
173+ test_options_enum_values_choices,
174+ [] (test_options_opts *opts) { return &opts->enum_opt; },
175+ nullptr, /* show_cmd_cb */
176+ N_("An enum option."),
177+ },
178+
179+ /* A uinteger option. */
180+ gdb::option::uinteger_option_def<test_options_opts> {
181+ "uinteger",
182+ [] (test_options_opts *opts) { return &opts->uint_opt; },
183+ nullptr, /* show_cmd_cb */
184+ N_("A uinteger option."),
185+ nullptr, /* show_doc */
186+ N_("A help doc that spawns\nmultiple lines."),
187+ },
188+
189+ /* A zuinteger_unlimited option. */
190+ gdb::option::zuinteger_unlimited_option_def<test_options_opts> {
191+ "zuinteger-unlimited",
192+ [] (test_options_opts *opts) { return &opts->zuint_unl_opt; },
193+ nullptr, /* show_cmd_cb */
194+ N_("A zuinteger-unlimited option."),
195+ nullptr, /* show_doc */
196+ nullptr, /* help_doc */
197+ },
198+};
199+
200+/* Create an option_def_group for the test_options_opts options, with
201+ OPTS as context. */
202+
203+static inline gdb::option::option_def_group
204+make_test_options_options_def_group (test_options_opts *opts)
205+{
206+ return {{test_options_option_defs}, opts};
207+}
208+
209+/* Implementation of the "maintenance test-options
210+ require-delimiter/unknown-is-error/unknown-is-operand" commands.
211+ Each of the commands maps to a different enum process_options_mode
212+ enumerator. The test strategy is simply processing the options in
213+ a number of scenarios, and printing back the parsed result. */
214+
215+static void
216+maintenance_test_options_command_mode (const char *args,
217+ gdb::option::process_options_mode mode)
218+{
219+ test_options_opts opts;
220+
221+ gdb::option::process_options (&args, mode,
222+ make_test_options_options_def_group (&opts));
223+
224+ if (args == nullptr)
225+ args = "";
226+ else
227+ args = skip_spaces (args);
228+
229+ printf_unfiltered (_("-flag %d -xx1 %d -xx2 %d -bool %d "
230+ "-enum %s -uint %s -zuint-unl %s -- %s\n"),
231+ opts.flag_opt,
232+ opts.xx1_opt,
233+ opts.xx2_opt,
234+ opts.boolean_opt,
235+ opts.enum_opt,
236+ (opts.uint_opt == UINT_MAX
237+ ? "unlimited"
238+ : pulongest (opts.uint_opt)),
239+ (opts.zuint_unl_opt == -1
240+ ? "unlimited"
241+ : plongest (opts.zuint_unl_opt)),
242+ args);
243+}
244+
245+/* Variables used by the "maintenance show
246+ test-options-completion-result" command. These variables are
247+ stored by the completer of the "maint test-options"
248+ subcommands. */
249+
250+/* The result of gdb::option::complete_options. */
251+static int maintenance_test_options_command_completion_result;
252+/* The text at the word point after gdb::option::complete_options
253+ returns. */
254+static std::string maintenance_test_options_command_completion_text;
255+
256+/* The "maintenance show test-options-completion-result" command. */
257+
258+static void
259+maintenance_show_test_options_completion_result
260+ (struct ui_file *file, int from_tty,
261+ struct cmd_list_element *c, const char *value)
262+{
263+ if (maintenance_test_options_command_completion_result)
264+ fprintf_filtered (file, "1\n");
265+ else
266+ fprintf_filtered
267+ (file, _("0 %s\n"),
268+ maintenance_test_options_command_completion_text.c_str ());
269+}
270+
271+/* Implementation of completer for the "maintenance test-options
272+ require-delimiter/unknown-is-error/unknown-is-operand" commands.
273+ Each of the commands maps to a different enum process_options_mode
274+ enumerator. */
275+
276+static void
277+maintenance_test_options_completer_mode (completion_tracker &tracker,
278+ const char *text,
279+ gdb::option::process_options_mode mode)
280+{
281+ try
282+ {
283+ maintenance_test_options_command_completion_result
284+ = gdb::option::complete_options
285+ (tracker, &text, mode,
286+ make_test_options_options_def_group (nullptr));
287+ maintenance_test_options_command_completion_text = text;
288+ }
289+ catch (const gdb_exception_error &ex)
290+ {
291+ maintenance_test_options_command_completion_result = 1;
292+ throw;
293+ }
294+}
295+
296+/* Implementation of the "maintenance test-options require-delimiter"
297+ command. */
298+
299+static void
300+maintenance_test_options_require_delimiter_command (const char *args,
301+ int from_tty)
302+{
303+ maintenance_test_options_command_mode
304+ (args, gdb::option::PROCESS_OPTIONS_REQUIRE_DELIMITER);
305+}
306+
307+/* Implementation of the "maintenance test-options
308+ unknown-is-error" command. */
309+
310+static void
311+maintenance_test_options_unknown_is_error_command (const char *args,
312+ int from_tty)
313+{
314+ maintenance_test_options_command_mode
315+ (args, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_ERROR);
316+}
317+
318+/* Implementation of the "maintenance test-options
319+ unknown-is-operand" command. */
320+
321+static void
322+maintenance_test_options_unknown_is_operand_command (const char *args,
323+ int from_tty)
324+{
325+ maintenance_test_options_command_mode
326+ (args, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND);
327+}
328+
329+/* Completer for the "maintenance test-options require-delimiter"
330+ command. */
331+
332+static void
333+maintenance_test_options_require_delimiter_command_completer
334+ (cmd_list_element *ignore, completion_tracker &tracker,
335+ const char *text, const char *word)
336+{
337+ maintenance_test_options_completer_mode
338+ (tracker, text, gdb::option::PROCESS_OPTIONS_REQUIRE_DELIMITER);
339+}
340+
341+/* Completer for the "maintenance test-options unknown-is-error"
342+ command. */
343+
344+static void
345+maintenance_test_options_unknown_is_error_command_completer
346+ (cmd_list_element *ignore, completion_tracker &tracker,
347+ const char *text, const char *word)
348+{
349+ maintenance_test_options_completer_mode
350+ (tracker, text, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_ERROR);
351+}
352+
353+/* Completer for the "maintenance test-options unknown-is-operand"
354+ command. */
355+
356+static void
357+maintenance_test_options_unknown_is_operand_command_completer
358+ (cmd_list_element *ignore, completion_tracker &tracker,
359+ const char *text, const char *word)
360+{
361+ maintenance_test_options_completer_mode
362+ (tracker, text, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_OPERAND);
363+}
364+
365+/* Command list for maint test-options. */
366+struct cmd_list_element *maintenance_test_options_list;
367+
368+/* The "maintenance test-options" prefix command. */
369+
370+static void
371+maintenance_test_options_command (const char *arg, int from_tty)
372+{
373+ printf_unfiltered
374+ (_("\"maintenance test-options\" must be followed "
375+ "by the name of a subcommand.\n"));
376+ help_list (maintenance_test_options_list, "maintenance test-options ",
377+ all_commands, gdb_stdout);
378+}
379+
380+
381+void
382+_initialize_maint_test_options ()
383+{
384+ cmd_list_element *cmd;
385+
386+ add_prefix_cmd ("test-options", no_class, maintenance_test_options_command,
387+ _("\
388+Generic command for testing the options infrastructure."),
389+ &maintenance_test_options_list,
390+ "maintenance test-options ", 0,
391+ &maintenancelist);
392+
393+ const auto def_group = make_test_options_options_def_group (nullptr);
394+
395+ static const std::string help_require_delim_str
396+ = gdb::option::build_help (_("\
397+Command used for testing options processing.\n\
398+Usage: maint test-options require-delimiter [[OPTION]... --] [OPERAND]...\n\
399+\n\
400+Options:\n\
401+\n\
402+%OPTIONS%\n\
403+If you specify any command option, you must use a double dash (\"--\")\n\
404+to mark the end of option processing."),
405+ def_group);
406+
407+ static const std::string help_unknown_is_error_str
408+ = gdb::option::build_help (_("\
409+Command used for testing options processing.\n\
410+Usage: maint test-options unknown-is-error [OPTION]... [OPERAND]...\n\
411+\n\
412+Options:\n\
413+\n\
414+%OPTIONS%"),
415+ def_group);
416+
417+ static const std::string help_unknown_is_operand_str
418+ = gdb::option::build_help (_("\
419+Command used for testing options processing.\n\
420+Usage: maint test-options unknown-is-operand [OPTION]... [OPERAND]...\n\
421+\n\
422+Options:\n\
423+\n\
424+%OPTIONS%"),
425+ def_group);
426+
427+ cmd = add_cmd ("require-delimiter", class_maintenance,
428+ maintenance_test_options_require_delimiter_command,
429+ help_require_delim_str.c_str (),
430+ &maintenance_test_options_list);
431+ set_cmd_completer_handle_brkchars
432+ (cmd, maintenance_test_options_require_delimiter_command_completer);
433+
434+ cmd = add_cmd ("unknown-is-error", class_maintenance,
435+ maintenance_test_options_unknown_is_error_command,
436+ help_unknown_is_error_str.c_str (),
437+ &maintenance_test_options_list);
438+ set_cmd_completer_handle_brkchars
439+ (cmd, maintenance_test_options_unknown_is_error_command_completer);
440+
441+ cmd = add_cmd ("unknown-is-operand", class_maintenance,
442+ maintenance_test_options_unknown_is_operand_command,
443+ help_unknown_is_operand_str.c_str (),
444+ &maintenance_test_options_list);
445+ set_cmd_completer_handle_brkchars
446+ (cmd, maintenance_test_options_unknown_is_operand_command_completer);
447+
448+ add_setshow_zinteger_cmd ("test-options-completion-result", class_maintenance,
449+ &maintenance_test_options_command_completion_result,
450+ _("\
451+Set maintenance test-options completion result."), _("\
452+Show maintenance test-options completion result."), _("\
453+Show the results of completing\n\
454+\"maint test-options require-delimiter\",\n\
455+\"maint test-options unknown-is-error\", or\n\
456+\"maint test-options unknown-is-operand\"."),
457+ NULL,
458+ maintenance_show_test_options_completion_result,
459+ &maintenance_set_cmdlist,
460+ &maintenance_show_cmdlist);
461+}
--- /dev/null
+++ b/gdb/testsuite/gdb.base/options.c
@@ -0,0 +1,33 @@
1+/* This testcase is part of GDB, the GNU debugger.
2+
3+ Copyright 2019 Free Software Foundation, Inc.
4+
5+ This program is free software; you can redistribute it and/or modify
6+ it under the terms of the GNU General Public License as published by
7+ the Free Software Foundation; either version 3 of the License, or
8+ (at your option) any later version.
9+
10+ This program is distributed in the hope that it will be useful,
11+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13+ GNU General Public License for more details.
14+
15+ You should have received a copy of the GNU General Public License
16+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
17+
18+int xxx1= 123;
19+
20+struct S
21+{
22+ int a;
23+ int b;
24+ int c;
25+};
26+
27+struct S g_s = {1, 2, 3};
28+
29+int
30+main ()
31+{
32+ return 0;
33+}
--- /dev/null
+++ b/gdb/testsuite/gdb.base/options.exp
@@ -0,0 +1,554 @@
1+# This testcase is part of GDB, the GNU debugger.
2+
3+# Copyright 2019 Free Software Foundation, Inc.
4+
5+# This program is free software; you can redistribute it and/or modify
6+# it under the terms of the GNU General Public License as published by
7+# the Free Software Foundation; either version 3 of the License, or
8+# (at your option) any later version.
9+#
10+# This program is distributed in the hope that it will be useful,
11+# but WITHOUT ANY WARRANTY; without even the implied warranty of
12+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13+# GNU General Public License for more details.
14+#
15+# You should have received a copy of the GNU General Public License
16+# along with this program. If not, see <http://www.gnu.org/licenses/>.
17+
18+# Test the gdb::option framework.
19+
20+# The test uses the "maintenance test-options" subcommands to exercise
21+# TAB-completion and option processing.
22+
23+load_lib completion-support.exp
24+
25+clean_restart
26+
27+if { ![readline_is_used] } {
28+ untested "no tab completion support without readline"
29+ return -1
30+}
31+
32+# Check the completion result, as returned by the "maintenance show
33+# test-options-completion-result" command. TEST is used as test name.
34+proc check_completion_result {expected test} {
35+ gdb_test "maintenance show test-options-completion-result" \
36+ "$expected" \
37+ "$test: res=$expected"
38+}
39+
40+# Like test_gdb_complete_unique, but the expected output is expected
41+# to be the input line. I.e., the line is already complete. We're
42+# just checking whether GDB recognizes the option and auto-appends a
43+# space.
44+proc test_completer_recognizes {res input_line} {
45+ set expected_re [string_to_regexp $input_line]
46+ test_gdb_complete_unique $input_line $expected_re
47+ check_completion_result $res $input_line
48+}
49+
50+# Wrapper around test_gdb_complete_multiple that also checks the
51+# completion result is RES.
52+proc res_test_gdb_complete_multiple {res cmd_prefix completion_word args} {
53+ test_gdb_complete_multiple $cmd_prefix $completion_word {*}$args
54+ check_completion_result $res "$cmd_prefix$completion_word"
55+}
56+
57+# Wrapper around test_gdb_complete_none that also checks the
58+# completion result is RES.
59+proc res_test_gdb_complete_none { res input_line } {
60+ test_gdb_complete_none $input_line
61+ check_completion_result $res "$input_line"
62+}
63+
64+# Wrapper around test_gdb_complete_unique that also checks the
65+# completion result is RES.
66+proc res_test_gdb_complete_unique { res input_line args} {
67+ test_gdb_complete_unique $input_line {*}$args
68+ check_completion_result $res "$input_line"
69+}
70+
71+# Make a full command name from VARIANT. VARIANT is either
72+# "require-delimiter", "unknown-is-error" or "unknown-is-operand".
73+proc make_cmd {variant} {
74+ return "maint test-options $variant"
75+}
76+
77+# Return a string for the expected result of running "maint
78+# test-options xxx", with no flag/option set. OPERAND is the expected
79+# operand.
80+proc expect_none {operand} {
81+ return "-flag 0 -xx1 0 -xx2 0 -bool 0 -enum xxx -uint 0 -zuint-unl 0 -- $operand"
82+}
83+
84+# Return a string for the expected result of running "maint
85+# test-options xxx", with -flag set. OPERAND is the expected operand.
86+proc expect_flag {operand} {
87+ return "-flag 1 -xx1 0 -xx2 0 -bool 0 -enum xxx -uint 0 -zuint-unl 0 -- $operand"
88+}
89+
90+# Return a string for the expected result of running "maint
91+# test-options xxx", with -bool set. OPERAND is the expected operand.
92+proc expect_bool {operand} {
93+ return "-flag 0 -xx1 0 -xx2 0 -bool 1 -enum xxx -uint 0 -zuint-unl 0 -- $operand"
94+}
95+
96+# Return a string for the expected result of running "maint
97+# test-options xxx", with one of the integer options set to $VAL.
98+# OPTION determines which option to expect set. OPERAND is the
99+# expected operand.
100+proc expect_integer {option val operand} {
101+ if {$option == "uinteger"} {
102+ return "-flag 0 -xx1 0 -xx2 0 -bool 0 -enum xxx -uint $val -zuint-unl 0 -- $operand"
103+ } elseif {$option == "zuinteger-unlimited"} {
104+ return "-flag 0 -xx1 0 -xx2 0 -bool 0 -enum xxx -uint 0 -zuint-unl $val -- $operand"
105+ } else {
106+ error "unsupported option: $option"
107+ }
108+}
109+
110+set all_options {
111+ "-bool"
112+ "-enum"
113+ "-flag"
114+ "-uinteger"
115+ "-xx1"
116+ "-xx2"
117+ "-zuinteger-unlimited"
118+}
119+
120+# Miscellaneous tests.
121+proc_with_prefix test-misc {variant} {
122+ global all_options
123+
124+ set cmd [make_cmd $variant]
125+
126+ # Call test command with no arguments at all.
127+ gdb_test "$cmd" [expect_none ""]
128+
129+ # Now with a single dash.
130+ if {$variant == "require-delimiter"} {
131+ gdb_test "$cmd -" [expect_none "-"]
132+ } else {
133+ gdb_test "$cmd -" "Ambiguous option at: -"
134+ }
135+
136+ # Completing at "-" should list all options.
137+ res_test_gdb_complete_multiple "1" "$cmd " "-" "" $all_options
138+
139+ # Now with a double dash.
140+ gdb_test "$cmd --" [expect_none ""]
141+
142+ # "--" is recognized by options completer, gdb auto-appends a
143+ # space.
144+ test_completer_recognizes 1 "$cmd --"
145+
146+ # Now with a double dash, plus a dash as operand.
147+ gdb_test "$cmd -- -" [expect_none "-"]
148+ res_test_gdb_complete_none "0 -" "$cmd -- -"
149+
150+ # Completing an unambiguous option just appends an empty space.
151+ test_completer_recognizes 1 "$cmd -flag"
152+
153+ # Try running an ambiguous option.
154+ if {$variant == "require-delimiter"} {
155+ gdb_test "$cmd -xx" [expect_none "-xx"]
156+ } else {
157+ gdb_test "$cmd -xx" "Ambiguous option at: -xx"
158+ }
159+
160+ # Check that options are not case insensitive.
161+ gdb_test "$cmd -flag --" [expect_flag ""]
162+
163+ # Check how the different modes behave on unknown option, with a
164+ # delimiter.
165+ gdb_test "$cmd -FLAG --" \
166+ "Unrecognized option at: -FLAG --"
167+
168+ # Check how the different modes behave on unknown option, without
169+ # a delimiter.
170+ if {$variant == "unknown-is-error"} {
171+ gdb_test "$cmd -FLAG" \
172+ "Unrecognized option at: -FLAG"
173+ } else {
174+ gdb_test "$cmd -FLAG" [expect_none "-FLAG"]
175+ }
176+
177+ # Test parsing stops at a negative integer.
178+ gdb_test "$cmd -1 --" \
179+ "Unrecognized option at: -1 --"
180+ gdb_test "$cmd -2 --" \
181+ "Unrecognized option at: -2 --"
182+}
183+
184+# Flag option tests.
185+proc_with_prefix test-flag {variant} {
186+ global all_options
187+
188+ set cmd [make_cmd $variant]
189+
190+ # Completing a flag just appends a space.
191+ test_completer_recognizes 1 "$cmd -flag"
192+
193+ # Add a dash, and all options should be shown.
194+ test_gdb_complete_multiple "$cmd -flag " "-" "" $all_options
195+
196+ # Basic smoke tests of accepted / not accepted values.
197+
198+ # Check all the different variants a bool option may be specified.
199+ if {$variant == "require-delimiter"} {
200+ gdb_test "$cmd -flag 999" [expect_none "-flag 999"]
201+ } else {
202+ gdb_test "$cmd -flag 999" [expect_flag "999"]
203+ }
204+ gdb_test "$cmd -flag -- 999" [expect_flag "999"]
205+
206+ # If the "--" separator is present, then GDB errors out if the
207+ # flag option is passed some value -- check that too.
208+ gdb_test "$cmd -flag xxx 999 --" "Unrecognized option at: xxx 999 --"
209+ gdb_test "$cmd -flag o 999 --" "Unrecognized option at: o 999 --"
210+ gdb_test "$cmd -flag 1 999 --" "Unrecognized option at: 1 999 --"
211+
212+ # Extract twice the same flag, separated by one space.
213+ gdb_test "$cmd -flag -flag -- non flags args" \
214+ [expect_flag "non flags args"]
215+
216+ # Extract twice the same flag, separated by one space.
217+ gdb_test "$cmd -xx1 -xx2 -xx1 -xx2 -xx1 -- non flags args" \
218+ "-flag 0 -xx1 1 -xx2 1 -bool 0 -enum xxx -uint 0 -zuint-unl 0 -- non flags args"
219+
220+ # Extract 2 known flags in front of unknown flags.
221+ gdb_test "$cmd -xx1 -xx2 -a -b -c -xx1 --" \
222+ "Unrecognized option at: -a -b -c -xx1 --"
223+
224+ # Check that combined flags are not recognised.
225+ gdb_test "$cmd -xx1 -xx1xx2 -xx1 --" \
226+ "Unrecognized option at: -xx1xx2 -xx1 --"
227+
228+ # Make sure the completer don't confuse a flag option with a
229+ # boolean option. Specifically, "o" should not complete to
230+ # "on/off".
231+
232+ if {$variant == "require-delimiter"} {
233+ res_test_gdb_complete_none "1" "$cmd -flag o"
234+
235+ gdb_test "$cmd -flag o" [expect_none "-flag o"]
236+ } else {
237+ res_test_gdb_complete_none "0 o" "$cmd -flag o"
238+
239+ gdb_test "$cmd -flag o" [expect_flag "o"]
240+ }
241+}
242+
243+# Boolean option tests.
244+proc_with_prefix test-boolean {variant} {
245+ global all_options
246+
247+ set cmd [make_cmd $variant]
248+
249+ # Boolean option's values are optional -- "on" is implied. Check
250+ # that:
251+ #
252+ # - For require-delimiter commands, completing after a boolean
253+ # option lists all other options, plus "on/off". This is
254+ # because operands won't be processed until we see a "--"
255+ # delimiter.
256+ #
257+ # - For !require-delimiter commands, completing after a boolean
258+ # option completes as an operand, since that will tend to be
259+ # more common than typing "on/off".
260+ # E.g., "frame apply all -past-main COMMAND".
261+
262+ if {$variant == "require-delimiter"} {
263+ res_test_gdb_complete_multiple 1 "$cmd -bool " "" "" {
264+ "-bool"
265+ "-enum"
266+ "-flag"
267+ "-uinteger"
268+ "-xx1"
269+ "-xx2"
270+ "-zuinteger-unlimited"
271+ "off"
272+ "on"
273+ }
274+ } else {
275+ res_test_gdb_complete_none "0 " "$cmd -bool "
276+ }
277+
278+ # Add another dash, and "on/off" are no longer offered:
279+ res_test_gdb_complete_multiple 1 "$cmd -bool " "-" "" $all_options
280+
281+ # Basic smoke tests of accepted / not accepted values.
282+
283+ # The command accepts all of "1/0/enable/disable/yes/no" too, even
284+ # though like the "set" command, we don't offer those as
285+ # completion candidates if you complete right after the boolean
286+ # command's name, like:
287+ #
288+ # (gdb) maint test-options require-delimiter -bool [TAB]
289+ # off on
290+ #
291+ # However, the completer does recognize them if you start typing
292+ # the boolean value.
293+ foreach value {"0" "1"} {
294+ test_completer_recognizes 1 "$cmd -bool $value"
295+ }
296+ foreach value {"of" "off"} {
297+ res_test_gdb_complete_unique 1 \
298+ "$cmd -bool $value" \
299+ "$cmd -bool off"
300+ }
301+ foreach value {"y" "ye" "yes"} {
302+ res_test_gdb_complete_unique 1 \
303+ "$cmd -bool $value" \
304+ "$cmd -bool yes"
305+ }
306+ foreach value {"n" "no"} {
307+ res_test_gdb_complete_unique 1 \
308+ "$cmd -bool $value" \
309+ "$cmd -bool no"
310+ }
311+ foreach value {
312+ "e"
313+ "en"
314+ "ena"
315+ "enab"
316+ "enabl"
317+ "enable"
318+ } {
319+ res_test_gdb_complete_unique 1 \
320+ "$cmd -bool $value" \
321+ "$cmd -bool enable"
322+ }
323+ foreach value {
324+ "d"
325+ "di"
326+ "dis"
327+ "disa"
328+ "disab"
329+ "disabl"
330+ "disable"
331+ } {
332+ res_test_gdb_complete_unique 1 \
333+ "$cmd -bool $value" \
334+ "$cmd -bool disable"
335+ }
336+
337+ if {$variant == "require-delimiter"} {
338+ res_test_gdb_complete_none "1" "$cmd -bool xxx"
339+ } else {
340+ res_test_gdb_complete_none "0 xxx" "$cmd -bool xxx"
341+ }
342+
343+ # The command accepts abbreviations of "enable/disable/yes/no",
344+ # even though we don't offer those for completion.
345+ foreach value {
346+ "1"
347+ "y" "ye" "yes"
348+ "e"
349+ "en"
350+ "ena"
351+ "enab"
352+ "enabl"
353+ "enable"} {
354+ gdb_test "$cmd -bool $value --" [expect_bool ""]
355+ }
356+ foreach value {
357+ "0"
358+ "of" "off"
359+ "n" "no"
360+ "d"
361+ "di"
362+ "dis"
363+ "disa"
364+ "disab"
365+ "disabl"
366+ "disable"} {
367+ gdb_test "$cmd -bool $value --" [expect_none ""]
368+ }
369+
370+ if {$variant == "require-delimiter"} {
371+ gdb_test "$cmd -bool 999" [expect_none "-bool 999"]
372+ } else {
373+ gdb_test "$cmd -bool 999" [expect_bool "999"]
374+ }
375+ gdb_test "$cmd -bool -- 999" [expect_bool "999"]
376+
377+ # Since "on" is implied after a boolean option, for
378+ # !require-delimiter commands, anything that is not
379+ # yes/no/1/0/on/off/enable/disable should be considered as the raw
380+ # input after the last option. Also check "o", which might look
381+ # like "on" or "off", but it's treated the same.
382+
383+ foreach arg {"xxx" "o"} {
384+ if {$variant == "require-delimiter"} {
385+ gdb_test "$cmd -bool $arg" [expect_none "-bool $arg"]
386+ } else {
387+ gdb_test "$cmd -bool $arg" [expect_bool "$arg"]
388+ }
389+ }
390+ # Also try -1. "unknown-is-error" commands error out saying that
391+ # that's not a valid option.
392+ if {$variant == "require-delimiter"} {
393+ gdb_test "$cmd -bool -1" \
394+ [expect_none "-bool -1"]
395+ } elseif {$variant == "unknown-is-error"} {
396+ gdb_test "$cmd -bool -1" \
397+ "Unrecognized option at: -1"
398+ } else {
399+ gdb_test "$cmd -bool -1" [expect_bool "-1"]
400+ }
401+
402+ # OTOH, if the "--" separator is present, then GDB errors out if
403+ # the boolean option is passed an invalid value -- check that too.
404+ gdb_test "$cmd -bool -1 999 --" \
405+ "Unrecognized option at: -1 999 --"
406+ gdb_test "$cmd -bool xxx 999 --" \
407+ "Value given for `-bool' is not a boolean: xxx"
408+ gdb_test "$cmd -bool o 999 --" \
409+ "Value given for `-bool' is not a boolean: o"
410+
411+ # Completing after a boolean option + "o" does list "on/off",
412+ # though.
413+ if {$variant == "require-delimiter"} {
414+ res_test_gdb_complete_multiple 1 "$cmd -bool " "o" "" {
415+ "off"
416+ "on"
417+ }
418+ } else {
419+ res_test_gdb_complete_multiple "0 o" "$cmd -bool " "o" "" {
420+ "off"
421+ "on"
422+ }
423+ }
424+}
425+
426+# Uinteger option tests. OPTION is which integer option we're
427+# testing. Can be "uinteger" or "zuinteger-unlimited".
428+proc_with_prefix test-uinteger {variant option} {
429+ global all_options
430+
431+ set cmd "[make_cmd $variant] -$option"
432+
433+ # Test completing a uinteger option:
434+ res_test_gdb_complete_multiple 1 "$cmd " "" "" {
435+ "NUMBER"
436+ "unlimited"
437+ }
438+
439+ # NUMBER above is just a placeholder, make sure we don't complete
440+ # it as a valid option.
441+ res_test_gdb_complete_none 1 "$cmd NU"
442+
443+ # "unlimited" is valid though.
444+ res_test_gdb_complete_unique 1 \
445+ "$cmd u" \
446+ "$cmd unlimited"
447+
448+ # Basic smoke test of accepted / not accepted values.
449+ gdb_test "$cmd 1 -- 999" [expect_integer $option "1" "999"]
450+ gdb_test "$cmd unlimited -- 999" \
451+ [expect_integer $option "unlimited" "999"]
452+ if {$option == "zuinteger-unlimited"} {
453+ gdb_test "$cmd -1 --" [expect_integer $option "unlimited" ""]
454+ gdb_test "$cmd 0 --" [expect_integer $option "0" ""]
455+ } else {
456+ gdb_test "$cmd -1 --" "integer -1 out of range"
457+ gdb_test "$cmd 0 --" [expect_integer $option "unlimited" ""]
458+ }
459+ gdb_test "$cmd xxx --" \
460+ "Expected integer at: xxx --"
461+ gdb_test "$cmd unlimitedx --" \
462+ "Expected integer at: unlimitedx --"
463+
464+ # Don't offer completions until we're past the
465+ # -uinteger/-zuinteger-unlimited argument.
466+ res_test_gdb_complete_none 1 "$cmd 1"
467+
468+ # A number of invalid values.
469+ foreach value {"x" "x " "1a" "1a " "1-" "1- " "unlimitedx"} {
470+ res_test_gdb_complete_none 1 "$cmd $value"
471+ }
472+
473+ # Try "-1".
474+ if {$option == "uinteger"} {
475+ # -1 is invalid uinteger.
476+ foreach value {"-1" "-1 "} {
477+ res_test_gdb_complete_none 1 "$cmd $value"
478+ }
479+ } else {
480+ # -1 is valid for zuinteger-unlimited.
481+ res_test_gdb_complete_none 1 "$cmd -1"
482+ if {$variant == "require-delimiter"} {
483+ res_test_gdb_complete_multiple 1 "$cmd -1 " "" "-" $all_options
484+ } else {
485+ res_test_gdb_complete_none "0 " "$cmd -1 "
486+ }
487+ }
488+
489+ # Check that after a fully parsed option:
490+ #
491+ # - for require-delimiter commands, completion offers all
492+ # options.
493+ #
494+ # - for !require-delimiter commands, completion offers nothing
495+ # and returns false.
496+ if {$variant == "require-delimiter"} {
497+ res_test_gdb_complete_multiple 1 "$cmd 1 " "" "-" $all_options
498+ } else {
499+ res_test_gdb_complete_none "0 " "$cmd 1 "
500+ }
501+
502+ # Test completing non-option arguments after "-uinteger 1 ".
503+ foreach operand {"x" "x " "1a" "1a " "1-" "1- "} {
504+ if {$variant == "require-delimiter"} {
505+ res_test_gdb_complete_none 1 "$cmd 1 $operand"
506+ } else {
507+ res_test_gdb_complete_none "0 $operand" "$cmd 1 $operand"
508+ }
509+ }
510+ # These look like options, but they aren't.
511+ foreach operand {"-1" "-1 "} {
512+ if {$variant == "unknown-is-operand"} {
513+ res_test_gdb_complete_none "0 $operand" "$cmd 1 $operand"
514+ } else {
515+ res_test_gdb_complete_none 1 "$cmd 1 $operand"
516+ }
517+ }
518+}
519+
520+# Enum option tests.
521+proc_with_prefix test-enum {variant} {
522+ set cmd [make_cmd $variant]
523+
524+ res_test_gdb_complete_multiple 1 "$cmd -enum " "" "" {
525+ "xxx"
526+ "yyy"
527+ "zzz"
528+ }
529+
530+ # Check that "-" where a value is expected does not show the
531+ # command's options. I.e., an enum's value is not optional.
532+ # Check both completion and running the command.
533+ res_test_gdb_complete_none 1 "$cmd -enum -"
534+ gdb_test "$cmd -enum --"\
535+ "Requires an argument. Valid arguments are xxx, yyy, zzz\\."
536+
537+ # Try passing an undefined item to an enum option.
538+ gdb_test "$cmd -enum www --" "Undefined item: \"www\"."
539+}
540+
541+# Run the options framework tests first.
542+foreach_with_prefix cmd {
543+ "require-delimiter"
544+ "unknown-is-error"
545+ "unknown-is-operand"
546+} {
547+ test-misc $cmd
548+ test-flag $cmd
549+ test-boolean $cmd
550+ foreach subcmd {"uinteger" "zuinteger-unlimited" } {
551+ test-uinteger $cmd $subcmd
552+ }
553+ test-enum $cmd
554+}