gdbsupport: make use of safe-ctype functions from libiberty
[deliverable/binutils-gdb.git] / gdb / completer.c
CommitLineData
c5f0f3d0 1/* Line completion stuff for GDB, the GNU debugger.
b811d2c2 2 Copyright (C) 2000-2020 Free Software Foundation, Inc.
c5f0f3d0
FN
3
4 This file is part of GDB.
5
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
a9762ec7 8 the Free Software Foundation; either version 3 of the License, or
c5f0f3d0
FN
9 (at your option) any later version.
10
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
a9762ec7 17 along with this program. If not, see <http://www.gnu.org/licenses/>. */
c5f0f3d0
FN
18
19#include "defs.h"
4de283e4 20#include "symtab.h"
d55e5aa6 21#include "gdbtypes.h"
4de283e4
TT
22#include "expression.h"
23#include "filenames.h" /* For DOSish file names. */
51065942 24#include "language.h"
268a13a5 25#include "gdbsupport/gdb_signals.h"
d55e5aa6 26#include "target.h"
4de283e4 27#include "reggroups.h"
71c24708 28#include "user-regs.h"
4de283e4
TT
29#include "arch-utils.h"
30#include "location.h"
31#include <algorithm>
32#include "linespec.h"
33#include "cli/cli-decode.h"
18a642a1 34
03717487
MS
35/* FIXME: This is needed because of lookup_cmd_1 (). We should be
36 calling a hook instead so we eliminate the CLI dependency. */
c5f0f3d0
FN
37#include "gdbcmd.h"
38
c94fdfd0 39/* Needed for rl_completer_word_break_characters() and for
38017ce8 40 rl_filename_completion_function. */
dbda9972 41#include "readline/readline.h"
c5f0f3d0
FN
42
43/* readline defines this. */
44#undef savestring
45
46#include "completer.h"
47
724fd9ba
AB
48/* See completer.h. */
49
50class completion_tracker::completion_hash_entry
51{
52public:
53 /* Constructor. */
54 completion_hash_entry (gdb::unique_xmalloc_ptr<char> name,
55 gdb::unique_xmalloc_ptr<char> lcd)
56 : m_name (std::move (name)),
57 m_lcd (std::move (lcd))
58 {
59 /* Nothing. */
60 }
61
62 /* Returns a pointer to the lowest common denominator string. This
63 string will only be valid while this hash entry is still valid as the
64 string continues to be owned by this hash entry and will be released
65 when this entry is deleted. */
66 char *get_lcd () const
67 {
68 return m_lcd.get ();
69 }
70
71 /* Get, and release the name field from this hash entry. This can only
72 be called once, after which the name field is no longer valid. This
73 should be used to pass ownership of the name to someone else. */
74 char *release_name ()
75 {
76 return m_name.release ();
77 }
78
79 /* Return true of the name in this hash entry is STR. */
80 bool is_name_eq (const char *str) const
81 {
82 return strcmp (m_name.get (), str) == 0;
83 }
84
99f1bc6a
AB
85 /* Return the hash value based on the name of the entry. */
86 hashval_t hash_name () const
87 {
88 return htab_hash_string (m_name.get ());
89 }
90
724fd9ba
AB
91 /* A static function that can be passed to the htab hash system to be
92 used as a callback that deletes an item from the hash. */
93 static void deleter (void *arg)
94 {
95 completion_hash_entry *entry = (completion_hash_entry *) arg;
96 delete entry;
97 }
98
99private:
100
101 /* The symbol name stored in this hash entry. */
102 gdb::unique_xmalloc_ptr<char> m_name;
103
104 /* The lowest common denominator string computed for this hash entry. */
105 gdb::unique_xmalloc_ptr<char> m_lcd;
106};
107
eb3ff9a5
PA
108/* Misc state that needs to be tracked across several different
109 readline completer entry point calls, all related to a single
110 completion invocation. */
111
112struct gdb_completer_state
113{
114 /* The current completion's completion tracker. This is a global
115 because a tracker can be shared between the handle_brkchars and
116 handle_completion phases, which involves different readline
117 callbacks. */
118 completion_tracker *tracker = NULL;
119
120 /* Whether the current completion was aborted. */
121 bool aborted = false;
122};
123
124/* The current completion state. */
125static gdb_completer_state current_completion;
126
c6756f62
PA
127/* An enumeration of the various things a user might attempt to
128 complete for a location. If you change this, remember to update
129 the explicit_options array below too. */
87f0e720
KS
130
131enum explicit_location_match_type
132{
133 /* The filename of a source file. */
134 MATCH_SOURCE,
135
136 /* The name of a function or method. */
137 MATCH_FUNCTION,
138
a20714ff
PA
139 /* The fully-qualified name of a function or method. */
140 MATCH_QUALIFIED,
141
c6756f62
PA
142 /* A line number. */
143 MATCH_LINE,
144
87f0e720
KS
145 /* The name of a label. */
146 MATCH_LABEL
147};
148
9c3f90bd 149/* Prototypes for local functions. */
c5f0f3d0
FN
150
151/* readline uses the word breaks for two things:
152 (1) In figuring out where to point the TEXT parameter to the
153 rl_completion_entry_function. Since we don't use TEXT for much,
aff410f1
MS
154 it doesn't matter a lot what the word breaks are for this purpose,
155 but it does affect how much stuff M-? lists.
c5f0f3d0
FN
156 (2) If one of the matches contains a word break character, readline
157 will quote it. That's why we switch between
53fc67f8 158 current_language->word_break_characters () and
c5f0f3d0 159 gdb_completer_command_word_break_characters. I'm not sure when
aff410f1
MS
160 we need this behavior (perhaps for funky characters in C++
161 symbols?). */
c5f0f3d0
FN
162
163/* Variables which are necessary for fancy command line editing. */
c5f0f3d0 164
be09caf1 165/* When completing on command names, we remove '-' and '.' from the list of
c5f0f3d0
FN
166 word break characters, since we use it in command names. If the
167 readline library sees one in any of the current completion strings,
aff410f1
MS
168 it thinks that the string needs to be quoted and automatically
169 supplies a leading quote. */
67cb5b2d 170static const char gdb_completer_command_word_break_characters[] =
be09caf1 171" \t\n!@#$%^&*()+=|~`}{[]\"';:?/><,";
c5f0f3d0
FN
172
173/* When completing on file names, we remove from the list of word
174 break characters any characters that are commonly used in file
175 names, such as '-', '+', '~', etc. Otherwise, readline displays
176 incorrect completion candidates. */
7830cf6f
EZ
177/* MS-DOS and MS-Windows use colon as part of the drive spec, and most
178 programs support @foo style response files. */
67cb5b2d
PA
179static const char gdb_completer_file_name_break_characters[] =
180#ifdef HAVE_DOS_BASED_FILE_SYSTEM
181 " \t\n*|\"';?><@";
7830cf6f 182#else
67cb5b2d 183 " \t\n*|\"';:?><";
7830cf6f 184#endif
c5f0f3d0 185
aff410f1
MS
186/* Characters that can be used to quote completion strings. Note that
187 we can't include '"' because the gdb C parser treats such quoted
188 sequences as strings. */
67cb5b2d 189static const char gdb_completer_quote_characters[] = "'";
c5f0f3d0 190\f
9c3f90bd 191/* Accessor for some completer data that may interest other files. */
c5f0f3d0 192
67cb5b2d 193const char *
c5f0f3d0
FN
194get_gdb_completer_quote_characters (void)
195{
196 return gdb_completer_quote_characters;
197}
198
aff410f1
MS
199/* This can be used for functions which don't want to complete on
200 symbols but don't want to complete on anything else either. */
eb3ff9a5
PA
201
202void
aff410f1 203noop_completer (struct cmd_list_element *ignore,
eb3ff9a5 204 completion_tracker &tracker,
6f937416 205 const char *text, const char *prefix)
d75b5104 206{
d75b5104
EZ
207}
208
c5f0f3d0 209/* Complete on filenames. */
6e1dbf8c 210
eb3ff9a5
PA
211void
212filename_completer (struct cmd_list_element *ignore,
213 completion_tracker &tracker,
6f937416 214 const char *text, const char *word)
c5f0f3d0 215{
c5f0f3d0 216 int subsequent_name;
c5f0f3d0
FN
217
218 subsequent_name = 0;
219 while (1)
220 {
60a20c19
PA
221 gdb::unique_xmalloc_ptr<char> p_rl
222 (rl_filename_completion_function (text, subsequent_name));
223 if (p_rl == NULL)
49c4e619 224 break;
c5f0f3d0 225 /* We need to set subsequent_name to a non-zero value before the
aff410f1
MS
226 continue line below, because otherwise, if the first file
227 seen by GDB is a backup file whose name ends in a `~', we
228 will loop indefinitely. */
c5f0f3d0 229 subsequent_name = 1;
aff410f1 230 /* Like emacs, don't complete on old versions. Especially
dda83cd7 231 useful in the "source" command. */
60a20c19 232 const char *p = p_rl.get ();
c5f0f3d0 233 if (p[strlen (p) - 1] == '~')
60a20c19 234 continue;
c5f0f3d0 235
60a20c19
PA
236 tracker.add_completion
237 (make_completion_match_str (std::move (p_rl), text, word));
c5f0f3d0
FN
238 }
239#if 0
aff410f1
MS
240 /* There is no way to do this just long enough to affect quote
241 inserting without also affecting the next completion. This
242 should be fixed in readline. FIXME. */
489f0516 243 /* Ensure that readline does the right thing
c5f0f3d0
FN
244 with respect to inserting quotes. */
245 rl_completer_word_break_characters = "";
246#endif
c5f0f3d0
FN
247}
248
6e1dbf8c
PA
249/* The corresponding completer_handle_brkchars
250 implementation. */
251
252static void
253filename_completer_handle_brkchars (struct cmd_list_element *ignore,
eb3ff9a5 254 completion_tracker &tracker,
6e1dbf8c
PA
255 const char *text, const char *word)
256{
257 set_rl_completer_word_break_characters
258 (gdb_completer_file_name_break_characters);
259}
260
6a2c1b87
PA
261/* Possible values for the found_quote flags word used by the completion
262 functions. It says what kind of (shell-like) quoting we found anywhere
263 in the line. */
264#define RL_QF_SINGLE_QUOTE 0x01
265#define RL_QF_DOUBLE_QUOTE 0x02
266#define RL_QF_BACKSLASH 0x04
267#define RL_QF_OTHER_QUOTE 0x08
268
269/* Find the bounds of the current word for completion purposes, and
270 return a pointer to the end of the word. This mimics (and is a
271 modified version of) readline's _rl_find_completion_word internal
272 function.
273
274 This function skips quoted substrings (characters between matched
275 pairs of characters in rl_completer_quote_characters). We try to
276 find an unclosed quoted substring on which to do matching. If one
277 is not found, we use the word break characters to find the
278 boundaries of the current word. QC, if non-null, is set to the
279 opening quote character if we found an unclosed quoted substring,
280 '\0' otherwise. DP, if non-null, is set to the value of the
281 delimiter character that caused a word break. */
282
283struct gdb_rl_completion_word_info
284{
285 const char *word_break_characters;
286 const char *quote_characters;
287 const char *basic_quote_characters;
288};
289
290static const char *
291gdb_rl_find_completion_word (struct gdb_rl_completion_word_info *info,
292 int *qc, int *dp,
293 const char *line_buffer)
294{
295 int scan, end, found_quote, delimiter, pass_next, isbrk;
296 char quote_char;
297 const char *brkchars;
298 int point = strlen (line_buffer);
299
300 /* The algorithm below does '--point'. Avoid buffer underflow with
301 the empty string. */
302 if (point == 0)
303 {
304 if (qc != NULL)
305 *qc = '\0';
306 if (dp != NULL)
307 *dp = '\0';
308 return line_buffer;
309 }
310
311 end = point;
312 found_quote = delimiter = 0;
313 quote_char = '\0';
314
315 brkchars = info->word_break_characters;
316
317 if (info->quote_characters != NULL)
318 {
319 /* We have a list of characters which can be used in pairs to
320 quote substrings for the completer. Try to find the start of
321 an unclosed quoted substring. */
322 /* FOUND_QUOTE is set so we know what kind of quotes we
323 found. */
324 for (scan = pass_next = 0;
325 scan < end;
326 scan++)
327 {
328 if (pass_next)
329 {
330 pass_next = 0;
331 continue;
332 }
333
334 /* Shell-like semantics for single quotes -- don't allow
335 backslash to quote anything in single quotes, especially
336 not the closing quote. If you don't like this, take out
337 the check on the value of quote_char. */
338 if (quote_char != '\'' && line_buffer[scan] == '\\')
339 {
340 pass_next = 1;
341 found_quote |= RL_QF_BACKSLASH;
342 continue;
343 }
344
345 if (quote_char != '\0')
346 {
347 /* Ignore everything until the matching close quote
348 char. */
349 if (line_buffer[scan] == quote_char)
350 {
351 /* Found matching close. Abandon this
352 substring. */
353 quote_char = '\0';
354 point = end;
355 }
356 }
357 else if (strchr (info->quote_characters, line_buffer[scan]))
358 {
359 /* Found start of a quoted substring. */
360 quote_char = line_buffer[scan];
361 point = scan + 1;
362 /* Shell-like quoting conventions. */
363 if (quote_char == '\'')
364 found_quote |= RL_QF_SINGLE_QUOTE;
365 else if (quote_char == '"')
366 found_quote |= RL_QF_DOUBLE_QUOTE;
367 else
368 found_quote |= RL_QF_OTHER_QUOTE;
369 }
370 }
371 }
372
373 if (point == end && quote_char == '\0')
374 {
375 /* We didn't find an unclosed quoted substring upon which to do
376 completion, so use the word break characters to find the
377 substring on which to complete. */
378 while (--point)
379 {
380 scan = line_buffer[point];
381
382 if (strchr (brkchars, scan) != 0)
383 break;
384 }
385 }
386
387 /* If we are at an unquoted word break, then advance past it. */
388 scan = line_buffer[point];
389
390 if (scan)
391 {
392 isbrk = strchr (brkchars, scan) != 0;
393
394 if (isbrk)
395 {
396 /* If the character that caused the word break was a quoting
397 character, then remember it as the delimiter. */
398 if (info->basic_quote_characters
399 && strchr (info->basic_quote_characters, scan)
400 && (end - point) > 1)
401 delimiter = scan;
402
403 point++;
404 }
405 }
406
407 if (qc != NULL)
408 *qc = quote_char;
409 if (dp != NULL)
410 *dp = delimiter;
411
412 return line_buffer + point;
413}
414
e6ed716c
PA
415/* Find the completion word point for TEXT, emulating the algorithm
416 readline uses to find the word point, using WORD_BREAK_CHARACTERS
417 as word break characters. */
c6756f62 418
e6ed716c
PA
419static const char *
420advance_to_completion_word (completion_tracker &tracker,
421 const char *word_break_characters,
422 const char *text)
c6756f62
PA
423{
424 gdb_rl_completion_word_info info;
425
e6ed716c 426 info.word_break_characters = word_break_characters;
c6756f62
PA
427 info.quote_characters = gdb_completer_quote_characters;
428 info.basic_quote_characters = rl_basic_quote_characters;
429
00b56dbe 430 int delimiter;
c6756f62 431 const char *start
00b56dbe 432 = gdb_rl_find_completion_word (&info, NULL, &delimiter, text);
c6756f62
PA
433
434 tracker.advance_custom_word_point_by (start - text);
435
00b56dbe
PA
436 if (delimiter)
437 {
438 tracker.set_quote_char (delimiter);
439 tracker.set_suppress_append_ws (true);
440 }
441
c6756f62
PA
442 return start;
443}
444
445/* See completer.h. */
446
e6ed716c
PA
447const char *
448advance_to_expression_complete_word_point (completion_tracker &tracker,
449 const char *text)
450{
53fc67f8 451 const char *brk_chars = current_language->word_break_characters ();
e6ed716c
PA
452 return advance_to_completion_word (tracker, brk_chars, text);
453}
454
455/* See completer.h. */
456
457const char *
458advance_to_filename_complete_word_point (completion_tracker &tracker,
459 const char *text)
460{
461 const char *brk_chars = gdb_completer_file_name_break_characters;
462 return advance_to_completion_word (tracker, brk_chars, text);
463}
464
465/* See completer.h. */
466
c6756f62
PA
467bool
468completion_tracker::completes_to_completion_word (const char *word)
469{
724fd9ba 470 recompute_lowest_common_denominator ();
c6756f62
PA
471 if (m_lowest_common_denominator_unique)
472 {
473 const char *lcd = m_lowest_common_denominator;
474
475 if (strncmp_iw (word, lcd, strlen (lcd)) == 0)
476 {
477 /* Maybe skip the function and complete on keywords. */
478 size_t wordlen = strlen (word);
479 if (word[wordlen - 1] == ' ')
480 return true;
481 }
482 }
483
484 return false;
485}
486
272d4594
PA
487/* See completer.h. */
488
489void
490complete_nested_command_line (completion_tracker &tracker, const char *text)
491{
492 /* Must be called from a custom-word-point completer. */
493 gdb_assert (tracker.use_custom_word_point ());
494
495 /* Disable the custom word point temporarily, because we want to
496 probe whether the command we're completing itself uses a custom
497 word point. */
498 tracker.set_use_custom_word_point (false);
499 size_t save_custom_word_point = tracker.custom_word_point ();
500
501 int quote_char = '\0';
502 const char *word = completion_find_completion_word (tracker, text,
503 &quote_char);
504
505 if (tracker.use_custom_word_point ())
506 {
507 /* The command we're completing uses a custom word point, so the
508 tracker already contains the matches. We're done. */
509 return;
510 }
511
512 /* Restore the custom word point settings. */
513 tracker.set_custom_word_point (save_custom_word_point);
514 tracker.set_use_custom_word_point (true);
515
516 /* Run the handle_completions completer phase. */
517 complete_line (tracker, word, text, strlen (text));
518}
519
87f0e720 520/* Complete on linespecs, which might be of two possible forms:
c94fdfd0
EZ
521
522 file:line
523 or
524 symbol+offset
525
aff410f1
MS
526 This is intended to be used in commands that set breakpoints
527 etc. */
528
eb3ff9a5
PA
529static void
530complete_files_symbols (completion_tracker &tracker,
531 const char *text, const char *word)
c94fdfd0 532{
eb3ff9a5 533 completion_list fn_list;
6f937416 534 const char *p;
c94fdfd0
EZ
535 int quote_found = 0;
536 int quoted = *text == '\'' || *text == '"';
537 int quote_char = '\0';
6f937416 538 const char *colon = NULL;
c94fdfd0 539 char *file_to_match = NULL;
6f937416
PA
540 const char *symbol_start = text;
541 const char *orig_text = text;
c94fdfd0 542
59be2b6a 543 /* Do we have an unquoted colon, as in "break foo.c:bar"? */
c94fdfd0
EZ
544 for (p = text; *p != '\0'; ++p)
545 {
546 if (*p == '\\' && p[1] == '\'')
547 p++;
548 else if (*p == '\'' || *p == '"')
549 {
550 quote_found = *p;
551 quote_char = *p++;
552 while (*p != '\0' && *p != quote_found)
553 {
554 if (*p == '\\' && p[1] == quote_found)
555 p++;
556 p++;
557 }
558
559 if (*p == quote_found)
560 quote_found = 0;
561 else
9c3f90bd 562 break; /* Hit the end of text. */
c94fdfd0
EZ
563 }
564#if HAVE_DOS_BASED_FILE_SYSTEM
565 /* If we have a DOS-style absolute file name at the beginning of
566 TEXT, and the colon after the drive letter is the only colon
567 we found, pretend the colon is not there. */
568 else if (p < text + 3 && *p == ':' && p == text + 1 + quoted)
569 ;
570#endif
571 else if (*p == ':' && !colon)
572 {
573 colon = p;
574 symbol_start = p + 1;
575 }
53fc67f8 576 else if (strchr (current_language->word_break_characters (), *p))
c94fdfd0
EZ
577 symbol_start = p + 1;
578 }
579
580 if (quoted)
581 text++;
c94fdfd0
EZ
582
583 /* Where is the file name? */
584 if (colon)
585 {
586 char *s;
587
588 file_to_match = (char *) xmalloc (colon - text + 1);
bbfa2517
YQ
589 strncpy (file_to_match, text, colon - text);
590 file_to_match[colon - text] = '\0';
c94fdfd0
EZ
591 /* Remove trailing colons and quotes from the file name. */
592 for (s = file_to_match + (colon - text);
593 s > file_to_match;
594 s--)
595 if (*s == ':' || *s == quote_char)
596 *s = '\0';
597 }
598 /* If the text includes a colon, they want completion only on a
599 symbol name after the colon. Otherwise, we need to complete on
600 symbols as well as on files. */
601 if (colon)
602 {
c6756f62
PA
603 collect_file_symbol_completion_matches (tracker,
604 complete_symbol_mode::EXPRESSION,
b5ec771e 605 symbol_name_match_type::EXPRESSION,
c6756f62 606 symbol_start, word,
eb3ff9a5 607 file_to_match);
c94fdfd0
EZ
608 xfree (file_to_match);
609 }
610 else
611 {
eb3ff9a5
PA
612 size_t text_len = strlen (text);
613
c6756f62
PA
614 collect_symbol_completion_matches (tracker,
615 complete_symbol_mode::EXPRESSION,
b5ec771e 616 symbol_name_match_type::EXPRESSION,
c6756f62 617 symbol_start, word);
c94fdfd0
EZ
618 /* If text includes characters which cannot appear in a file
619 name, they cannot be asking for completion on files. */
eb3ff9a5 620 if (strcspn (text,
1f20ed91 621 gdb_completer_file_name_break_characters) == text_len)
c94fdfd0
EZ
622 fn_list = make_source_files_completion_list (text, text);
623 }
624
eb3ff9a5 625 if (!fn_list.empty () && !tracker.have_completions ())
c94fdfd0
EZ
626 {
627 /* If we only have file names as possible completion, we should
628 bring them in sync with what rl_complete expects. The
629 problem is that if the user types "break /foo/b TAB", and the
630 possible completions are "/foo/bar" and "/foo/baz"
631 rl_complete expects us to return "bar" and "baz", without the
632 leading directories, as possible completions, because `word'
633 starts at the "b". But we ignore the value of `word' when we
634 call make_source_files_completion_list above (because that
635 would not DTRT when the completion results in both symbols
636 and file names), so make_source_files_completion_list returns
637 the full "/foo/bar" and "/foo/baz" strings. This produces
638 wrong results when, e.g., there's only one possible
639 completion, because rl_complete will prepend "/foo/" to each
640 candidate completion. The loop below removes that leading
641 part. */
eb3ff9a5 642 for (const auto &fn_up: fn_list)
c94fdfd0 643 {
eb3ff9a5
PA
644 char *fn = fn_up.get ();
645 memmove (fn, fn + (word - text), strlen (fn) + 1 - (word - text));
c94fdfd0 646 }
c94fdfd0 647 }
eb3ff9a5
PA
648
649 tracker.add_completions (std::move (fn_list));
650
651 if (!tracker.have_completions ())
c94fdfd0
EZ
652 {
653 /* No completions at all. As the final resort, try completing
654 on the entire text as a symbol. */
eb3ff9a5 655 collect_symbol_completion_matches (tracker,
c6756f62 656 complete_symbol_mode::EXPRESSION,
b5ec771e 657 symbol_name_match_type::EXPRESSION,
eb3ff9a5 658 orig_text, word);
c94fdfd0 659 }
eb3ff9a5
PA
660}
661
c45ec17c
PA
662/* See completer.h. */
663
664completion_list
665complete_source_filenames (const char *text)
666{
667 size_t text_len = strlen (text);
668
669 /* If text includes characters which cannot appear in a file name,
670 the user cannot be asking for completion on files. */
671 if (strcspn (text,
672 gdb_completer_file_name_break_characters)
673 == text_len)
674 return make_source_files_completion_list (text, text);
675
676 return {};
677}
678
679/* Complete address and linespec locations. */
680
681static void
682complete_address_and_linespec_locations (completion_tracker &tracker,
a20714ff
PA
683 const char *text,
684 symbol_name_match_type match_type)
c45ec17c
PA
685{
686 if (*text == '*')
687 {
688 tracker.advance_custom_word_point_by (1);
689 text++;
690 const char *word
691 = advance_to_expression_complete_word_point (tracker, text);
692 complete_expression (tracker, text, word);
693 }
694 else
695 {
a20714ff 696 linespec_complete (tracker, text, match_type);
c45ec17c
PA
697 }
698}
699
c6756f62
PA
700/* The explicit location options. Note that indexes into this array
701 must match the explicit_location_match_type enumerators. */
c45ec17c 702
c6756f62
PA
703static const char *const explicit_options[] =
704 {
705 "-source",
706 "-function",
a20714ff 707 "-qualified",
c6756f62
PA
708 "-line",
709 "-label",
710 NULL
711 };
712
713/* The probe modifier options. These can appear before a location in
714 breakpoint commands. */
715static const char *const probe_options[] =
716 {
717 "-probe",
718 "-probe-stap",
719 "-probe-dtrace",
720 NULL
721 };
722
eb3ff9a5 723/* Returns STRING if not NULL, the empty string otherwise. */
c94fdfd0 724
eb3ff9a5
PA
725static const char *
726string_or_empty (const char *string)
727{
728 return string != NULL ? string : "";
c94fdfd0
EZ
729}
730
87f0e720
KS
731/* A helper function to collect explicit location matches for the given
732 LOCATION, which is attempting to match on WORD. */
733
eb3ff9a5
PA
734static void
735collect_explicit_location_matches (completion_tracker &tracker,
736 struct event_location *location,
87f0e720 737 enum explicit_location_match_type what,
c6756f62
PA
738 const char *word,
739 const struct language_defn *language)
87f0e720 740{
67994074
KS
741 const struct explicit_location *explicit_loc
742 = get_explicit_location (location);
87f0e720 743
a20714ff
PA
744 /* True if the option expects an argument. */
745 bool needs_arg = true;
746
c6756f62
PA
747 /* Note, in the various MATCH_* below, we complete on
748 explicit_loc->foo instead of WORD, because only the former will
749 have already skipped past any quote char. */
87f0e720
KS
750 switch (what)
751 {
752 case MATCH_SOURCE:
753 {
eb3ff9a5
PA
754 const char *source = string_or_empty (explicit_loc->source_filename);
755 completion_list matches
c6756f62 756 = make_source_files_completion_list (source, source);
eb3ff9a5 757 tracker.add_completions (std::move (matches));
87f0e720
KS
758 }
759 break;
760
761 case MATCH_FUNCTION:
762 {
eb3ff9a5 763 const char *function = string_or_empty (explicit_loc->function_name);
c6756f62 764 linespec_complete_function (tracker, function,
a20714ff 765 explicit_loc->func_name_match_type,
c6756f62 766 explicit_loc->source_filename);
87f0e720
KS
767 }
768 break;
769
a20714ff
PA
770 case MATCH_QUALIFIED:
771 needs_arg = false;
772 break;
c6756f62
PA
773 case MATCH_LINE:
774 /* Nothing to offer. */
775 break;
776
87f0e720 777 case MATCH_LABEL:
a2459270
PA
778 {
779 const char *label = string_or_empty (explicit_loc->label_name);
780 linespec_complete_label (tracker, language,
781 explicit_loc->source_filename,
782 explicit_loc->function_name,
a20714ff 783 explicit_loc->func_name_match_type,
a2459270
PA
784 label);
785 }
87f0e720
KS
786 break;
787
788 default:
789 gdb_assert_not_reached ("unhandled explicit_location_match_type");
790 }
c6756f62 791
a20714ff 792 if (!needs_arg || tracker.completes_to_completion_word (word))
c6756f62
PA
793 {
794 tracker.discard_completions ();
795 tracker.advance_custom_word_point_by (strlen (word));
796 complete_on_enum (tracker, explicit_options, "", "");
797 complete_on_enum (tracker, linespec_keywords, "", "");
798 }
799 else if (!tracker.have_completions ())
800 {
801 /* Maybe we have an unterminated linespec keyword at the tail of
802 the string. Try completing on that. */
803 size_t wordlen = strlen (word);
804 const char *keyword = word + wordlen;
805
806 if (wordlen > 0 && keyword[-1] != ' ')
807 {
808 while (keyword > word && *keyword != ' ')
809 keyword--;
810 /* Don't complete on keywords if we'd be completing on the
811 whole explicit linespec option. E.g., "b -function
812 thr<tab>" should not complete to the "thread"
813 keyword. */
814 if (keyword != word)
815 {
f1735a53 816 keyword = skip_spaces (keyword);
c6756f62
PA
817
818 tracker.advance_custom_word_point_by (keyword - word);
819 complete_on_enum (tracker, linespec_keywords, keyword, keyword);
820 }
821 }
822 else if (wordlen > 0 && keyword[-1] == ' ')
823 {
824 /* Assume that we're maybe past the explicit location
825 argument, and we didn't manage to find any match because
826 the user wants to create a pending breakpoint. Offer the
827 keyword and explicit location options as possible
828 completions. */
829 tracker.advance_custom_word_point_by (keyword - word);
830 complete_on_enum (tracker, linespec_keywords, keyword, keyword);
831 complete_on_enum (tracker, explicit_options, keyword, keyword);
832 }
833 }
87f0e720
KS
834}
835
c6756f62
PA
836/* If the next word in *TEXT_P is any of the keywords in KEYWORDS,
837 then advance both TEXT_P and the word point in the tracker past the
838 keyword and return the (0-based) index in the KEYWORDS array that
839 matched. Otherwise, return -1. */
87f0e720 840
c6756f62
PA
841static int
842skip_keyword (completion_tracker &tracker,
843 const char * const *keywords, const char **text_p)
87f0e720 844{
c6756f62 845 const char *text = *text_p;
f1735a53 846 const char *after = skip_to_space (text);
c6756f62 847 size_t len = after - text;
87f0e720 848
c6756f62
PA
849 if (text[len] != ' ')
850 return -1;
851
852 int found = -1;
853 for (int i = 0; keywords[i] != NULL; i++)
854 {
855 if (strncmp (keywords[i], text, len) == 0)
856 {
857 if (found == -1)
858 found = i;
859 else
860 return -1;
861 }
862 }
863
864 if (found != -1)
865 {
866 tracker.advance_custom_word_point_by (len + 1);
867 text += len + 1;
868 *text_p = text;
869 return found;
870 }
871
872 return -1;
87f0e720
KS
873}
874
875/* A completer function for explicit locations. This function
c6756f62
PA
876 completes both options ("-source", "-line", etc) and values. If
877 completing a quoted string, then QUOTED_ARG_START and
878 QUOTED_ARG_END point to the quote characters. LANGUAGE is the
879 current language. */
87f0e720 880
eb3ff9a5
PA
881static void
882complete_explicit_location (completion_tracker &tracker,
883 struct event_location *location,
c6756f62
PA
884 const char *text,
885 const language_defn *language,
886 const char *quoted_arg_start,
887 const char *quoted_arg_end)
87f0e720 888{
c6756f62
PA
889 if (*text != '-')
890 return;
87f0e720 891
c6756f62 892 int keyword = skip_keyword (tracker, explicit_options, &text);
87f0e720 893
c6756f62 894 if (keyword == -1)
1f58f6c2
TBA
895 {
896 complete_on_enum (tracker, explicit_options, text, text);
897 /* There are keywords that start with "-". Include them, too. */
898 complete_on_enum (tracker, linespec_keywords, text, text);
899 }
c6756f62 900 else
87f0e720 901 {
c6756f62
PA
902 /* Completing on value. */
903 enum explicit_location_match_type what
904 = (explicit_location_match_type) keyword;
905
906 if (quoted_arg_start != NULL && quoted_arg_end != NULL)
87f0e720 907 {
c6756f62
PA
908 if (quoted_arg_end[1] == '\0')
909 {
910 /* If completing a quoted string with the cursor right
911 at the terminating quote char, complete the
912 completion word without interpretation, so that
913 readline advances the cursor one whitespace past the
914 quote, even if there's no match. This makes these
915 cases behave the same:
916
917 before: "b -function function()"
918 after: "b -function function() "
919
920 before: "b -function 'function()'"
921 after: "b -function 'function()' "
922
923 and trusts the user in this case:
924
925 before: "b -function 'not_loaded_function_yet()'"
926 after: "b -function 'not_loaded_function_yet()' "
927 */
b02f78f9 928 tracker.add_completion (make_unique_xstrdup (text));
c6756f62
PA
929 }
930 else if (quoted_arg_end[1] == ' ')
931 {
932 /* We're maybe past the explicit location argument.
30baf67b 933 Skip the argument without interpretation, assuming the
c6756f62
PA
934 user may want to create pending breakpoint. Offer
935 the keyword and explicit location options as possible
936 completions. */
937 tracker.advance_custom_word_point_by (strlen (text));
938 complete_on_enum (tracker, linespec_keywords, "", "");
939 complete_on_enum (tracker, explicit_options, "", "");
940 }
941 return;
942 }
943
944 /* Now gather matches */
945 collect_explicit_location_matches (tracker, location, what, text,
946 language);
947 }
948}
87f0e720 949
c6756f62 950/* A completer for locations. */
87f0e720 951
c6756f62
PA
952void
953location_completer (struct cmd_list_element *ignore,
954 completion_tracker &tracker,
c45ec17c 955 const char *text, const char * /* word */)
c6756f62
PA
956{
957 int found_probe_option = -1;
958
959 /* If we have a probe modifier, skip it. This can only appear as
960 first argument. Until we have a specific completer for probes,
961 falling back to the linespec completer for the remainder of the
962 line is better than nothing. */
963 if (text[0] == '-' && text[1] == 'p')
964 found_probe_option = skip_keyword (tracker, probe_options, &text);
965
966 const char *option_text = text;
967 int saved_word_point = tracker.custom_word_point ();
968
969 const char *copy = text;
970
971 explicit_completion_info completion_info;
972 event_location_up location
973 = string_to_explicit_location (&copy, current_language,
974 &completion_info);
975 if (completion_info.quoted_arg_start != NULL
976 && completion_info.quoted_arg_end == NULL)
977 {
978 /* Found an unbalanced quote. */
979 tracker.set_quote_char (*completion_info.quoted_arg_start);
980 tracker.advance_custom_word_point_by (1);
87f0e720 981 }
c6756f62 982
a20714ff 983 if (completion_info.saw_explicit_location_option)
87f0e720 984 {
c6756f62 985 if (*copy != '\0')
87f0e720 986 {
c6756f62
PA
987 tracker.advance_custom_word_point_by (copy - text);
988 text = copy;
989
990 /* We found a terminator at the tail end of the string,
991 which means we're past the explicit location options. We
992 may have a keyword to complete on. If we have a whole
993 keyword, then complete whatever comes after as an
994 expression. This is mainly for the "if" keyword. If the
995 "thread" and "task" keywords gain their own completers,
996 they should be used here. */
997 int keyword = skip_keyword (tracker, linespec_keywords, &text);
998
999 if (keyword == -1)
1000 {
1001 complete_on_enum (tracker, linespec_keywords, text, text);
1002 }
1003 else
1004 {
1005 const char *word
1006 = advance_to_expression_complete_word_point (tracker, text);
1007 complete_expression (tracker, text, word);
1008 }
87f0e720 1009 }
c6756f62 1010 else
87f0e720 1011 {
c6756f62
PA
1012 tracker.advance_custom_word_point_by (completion_info.last_option
1013 - text);
1014 text = completion_info.last_option;
1015
1016 complete_explicit_location (tracker, location.get (), text,
1017 current_language,
1018 completion_info.quoted_arg_start,
1019 completion_info.quoted_arg_end);
1020
87f0e720 1021 }
c6756f62 1022 }
a20714ff
PA
1023 /* This is an address or linespec location. */
1024 else if (location != NULL)
1025 {
1026 /* Handle non-explicit location options. */
1027
1028 int keyword = skip_keyword (tracker, explicit_options, &text);
1029 if (keyword == -1)
1030 complete_on_enum (tracker, explicit_options, text, text);
1031 else
1032 {
1033 tracker.advance_custom_word_point_by (copy - text);
1034 text = copy;
1035
1036 symbol_name_match_type match_type
1037 = get_explicit_location (location.get ())->func_name_match_type;
1038 complete_address_and_linespec_locations (tracker, text, match_type);
1039 }
1040 }
c6756f62
PA
1041 else
1042 {
a20714ff
PA
1043 /* No options. */
1044 complete_address_and_linespec_locations (tracker, text,
1045 symbol_name_match_type::WILD);
c6756f62 1046 }
87f0e720 1047
c6756f62 1048 /* Add matches for option names, if either:
87f0e720 1049
c6756f62
PA
1050 - Some completer above found some matches, but the word point did
1051 not advance (e.g., "b <tab>" finds all functions, or "b -<tab>"
1052 matches all objc selectors), or;
1053
1054 - Some completer above advanced the word point, but found no
1055 matches.
1056 */
1057 if ((text[0] == '-' || text[0] == '\0')
1058 && (!tracker.have_completions ()
1059 || tracker.custom_word_point () == saved_word_point))
1060 {
1061 tracker.set_custom_word_point (saved_word_point);
1062 text = option_text;
1063
1064 if (found_probe_option == -1)
1065 complete_on_enum (tracker, probe_options, text, text);
1066 complete_on_enum (tracker, explicit_options, text, text);
87f0e720 1067 }
87f0e720
KS
1068}
1069
c6756f62
PA
1070/* The corresponding completer_handle_brkchars
1071 implementation. */
87f0e720 1072
c6756f62
PA
1073static void
1074location_completer_handle_brkchars (struct cmd_list_element *ignore,
1075 completion_tracker &tracker,
1076 const char *text,
1077 const char *word_ignored)
87f0e720 1078{
c6756f62 1079 tracker.set_use_custom_word_point (true);
87f0e720 1080
c6756f62 1081 location_completer (ignore, tracker, text, NULL);
87f0e720
KS
1082}
1083
1c71341a 1084/* Helper for expression_completer which recursively adds field and
eb3ff9a5
PA
1085 method names from TYPE, a struct or union type, to the OUTPUT
1086 list. */
1087
65d12d83 1088static void
eb3ff9a5 1089add_struct_fields (struct type *type, completion_list &output,
3eac2b65 1090 const char *fieldname, int namelen)
65d12d83
TT
1091{
1092 int i;
b32d97f3 1093 int computed_type_name = 0;
0d5cff50 1094 const char *type_name = NULL;
65d12d83 1095
f168693b 1096 type = check_typedef (type);
1f704f76 1097 for (i = 0; i < type->num_fields (); ++i)
65d12d83
TT
1098 {
1099 if (i < TYPE_N_BASECLASSES (type))
49c4e619 1100 add_struct_fields (TYPE_BASECLASS (type, i),
aff410f1 1101 output, fieldname, namelen);
9ae8282d 1102 else if (TYPE_FIELD_NAME (type, i))
65d12d83 1103 {
9ae8282d
TT
1104 if (TYPE_FIELD_NAME (type, i)[0] != '\0')
1105 {
aff410f1
MS
1106 if (! strncmp (TYPE_FIELD_NAME (type, i),
1107 fieldname, namelen))
eb3ff9a5 1108 output.emplace_back (xstrdup (TYPE_FIELD_NAME (type, i)));
9ae8282d 1109 }
940da03e 1110 else if (type->field (i).type ()->code () == TYPE_CODE_UNION)
9ae8282d
TT
1111 {
1112 /* Recurse into anonymous unions. */
940da03e 1113 add_struct_fields (type->field (i).type (),
aff410f1 1114 output, fieldname, namelen);
9ae8282d 1115 }
65d12d83
TT
1116 }
1117 }
1c71341a
TT
1118
1119 for (i = TYPE_NFN_FIELDS (type) - 1; i >= 0; --i)
1120 {
0d5cff50 1121 const char *name = TYPE_FN_FIELDLIST_NAME (type, i);
c5504eaf 1122
1c71341a
TT
1123 if (name && ! strncmp (name, fieldname, namelen))
1124 {
b32d97f3
TT
1125 if (!computed_type_name)
1126 {
7d93a1e0 1127 type_name = type->name ();
b32d97f3
TT
1128 computed_type_name = 1;
1129 }
1c71341a 1130 /* Omit constructors from the completion list. */
907af001 1131 if (!type_name || strcmp (type_name, name))
eb3ff9a5 1132 output.emplace_back (xstrdup (name));
1c71341a
TT
1133 }
1134 }
65d12d83
TT
1135}
1136
c45ec17c 1137/* See completer.h. */
eb3ff9a5 1138
c45ec17c 1139void
eb3ff9a5
PA
1140complete_expression (completion_tracker &tracker,
1141 const char *text, const char *word)
65d12d83 1142{
c92817ce 1143 struct type *type = NULL;
3eac2b65 1144 gdb::unique_xmalloc_ptr<char> fieldname;
2f68a895 1145 enum type_code code = TYPE_CODE_UNDEF;
65d12d83
TT
1146
1147 /* Perform a tentative parse of the expression, to see whether a
1148 field completion is required. */
a70b8144 1149 try
c92817ce 1150 {
2f68a895 1151 type = parse_expression_for_completion (text, &fieldname, &code);
c92817ce 1152 }
230d2906 1153 catch (const gdb_exception_error &except)
492d29ea 1154 {
eb3ff9a5 1155 return;
492d29ea 1156 }
492d29ea 1157
3eac2b65 1158 if (fieldname != nullptr && type)
65d12d83
TT
1159 {
1160 for (;;)
1161 {
f168693b 1162 type = check_typedef (type);
78134374 1163 if (type->code () != TYPE_CODE_PTR && !TYPE_IS_REFERENCE (type))
65d12d83
TT
1164 break;
1165 type = TYPE_TARGET_TYPE (type);
1166 }
1167
78134374
SM
1168 if (type->code () == TYPE_CODE_UNION
1169 || type->code () == TYPE_CODE_STRUCT)
65d12d83 1170 {
eb3ff9a5 1171 completion_list result;
65d12d83 1172
3eac2b65
TT
1173 add_struct_fields (type, result, fieldname.get (),
1174 strlen (fieldname.get ()));
eb3ff9a5
PA
1175 tracker.add_completions (std::move (result));
1176 return;
65d12d83
TT
1177 }
1178 }
3eac2b65 1179 else if (fieldname != nullptr && code != TYPE_CODE_UNDEF)
2f68a895 1180 {
3eac2b65
TT
1181 collect_symbol_completion_matches_type (tracker, fieldname.get (),
1182 fieldname.get (), code);
eb3ff9a5 1183 return;
2f68a895 1184 }
65d12d83 1185
eb3ff9a5
PA
1186 complete_files_symbols (tracker, text, word);
1187}
1188
1189/* Complete on expressions. Often this means completing on symbol
1190 names, but some language parsers also have support for completing
1191 field names. */
1192
1193void
1194expression_completer (struct cmd_list_element *ignore,
1195 completion_tracker &tracker,
1196 const char *text, const char *word)
1197{
1198 complete_expression (tracker, text, word);
65d12d83
TT
1199}
1200
7d793aa9
SDJ
1201/* See definition in completer.h. */
1202
67cb5b2d
PA
1203void
1204set_rl_completer_word_break_characters (const char *break_chars)
1205{
1206 rl_completer_word_break_characters = (char *) break_chars;
1207}
1208
78b13106
PA
1209/* Complete on symbols. */
1210
eb3ff9a5 1211void
78b13106 1212symbol_completer (struct cmd_list_element *ignore,
eb3ff9a5 1213 completion_tracker &tracker,
78b13106
PA
1214 const char *text, const char *word)
1215{
c6756f62 1216 collect_symbol_completion_matches (tracker, complete_symbol_mode::EXPRESSION,
b5ec771e 1217 symbol_name_match_type::EXPRESSION,
c6756f62 1218 text, word);
78b13106
PA
1219}
1220
aff410f1
MS
1221/* Here are some useful test cases for completion. FIXME: These
1222 should be put in the test suite. They should be tested with both
1223 M-? and TAB.
c5f0f3d0
FN
1224
1225 "show output-" "radix"
1226 "show output" "-radix"
1227 "p" ambiguous (commands starting with p--path, print, printf, etc.)
1228 "p " ambiguous (all symbols)
1229 "info t foo" no completions
1230 "info t " no completions
1231 "info t" ambiguous ("info target", "info terminal", etc.)
1232 "info ajksdlfk" no completions
1233 "info ajksdlfk " no completions
1234 "info" " "
1235 "info " ambiguous (all info commands)
1236 "p \"a" no completions (string constant)
1237 "p 'a" ambiguous (all symbols starting with a)
1238 "p b-a" ambiguous (all symbols starting with a)
1239 "p b-" ambiguous (all symbols)
1240 "file Make" "file" (word break hard to screw up here)
1241 "file ../gdb.stabs/we" "ird" (needs to not break word at slash)
1242 */
1243
eb3ff9a5 1244enum complete_line_internal_reason
67c296a2 1245{
eb3ff9a5 1246 /* Preliminary phase, called by gdb_completion_word_break_characters
c6756f62
PA
1247 function, is used to either:
1248
1249 #1 - Determine the set of chars that are word delimiters
1250 depending on the current command in line_buffer.
1251
1252 #2 - Manually advance RL_POINT to the "word break" point instead
1253 of letting readline do it (based on too-simple character
1254 matching).
1255
1256 Simpler completers that just pass a brkchars array to readline
1257 (#1 above) must defer generating the completions to the main
1258 phase (below). No completion list should be generated in this
1259 phase.
1260
1261 OTOH, completers that manually advance the word point(#2 above)
1262 must set "use_custom_word_point" in the tracker and generate
1263 their completion in this phase. Note that this is the convenient
1264 thing to do since they'll be parsing the input line anyway. */
67c296a2 1265 handle_brkchars,
eb3ff9a5
PA
1266
1267 /* Main phase, called by complete_line function, is used to get the
1268 list of possible completions. */
67c296a2 1269 handle_completions,
eb3ff9a5
PA
1270
1271 /* Special case when completing a 'help' command. In this case,
1272 once sub-command completions are exhausted, we simply return
1273 NULL. */
1274 handle_help,
1275};
67c296a2 1276
6e1dbf8c
PA
1277/* Helper for complete_line_internal to simplify it. */
1278
eb3ff9a5
PA
1279static void
1280complete_line_internal_normal_command (completion_tracker &tracker,
1281 const char *command, const char *word,
6e1dbf8c
PA
1282 const char *cmd_args,
1283 complete_line_internal_reason reason,
1284 struct cmd_list_element *c)
1285{
1286 const char *p = cmd_args;
1287
1288 if (c->completer == filename_completer)
1289 {
1290 /* Many commands which want to complete on file names accept
1291 several file names, as in "run foo bar >>baz". So we don't
1292 want to complete the entire text after the command, just the
1293 last word. To this end, we need to find the beginning of the
1294 file name by starting at `word' and going backwards. */
1295 for (p = word;
1296 p > command
1297 && strchr (gdb_completer_file_name_break_characters,
1298 p[-1]) == NULL;
1299 p--)
1300 ;
1301 }
1302
1303 if (reason == handle_brkchars)
1304 {
1305 completer_handle_brkchars_ftype *brkchars_fn;
1306
1307 if (c->completer_handle_brkchars != NULL)
1308 brkchars_fn = c->completer_handle_brkchars;
1309 else
1310 {
1311 brkchars_fn
1312 = (completer_handle_brkchars_func_for_completer
1313 (c->completer));
1314 }
1315
eb3ff9a5 1316 brkchars_fn (c, tracker, p, word);
6e1dbf8c
PA
1317 }
1318
1319 if (reason != handle_brkchars && c->completer != NULL)
eb3ff9a5 1320 (*c->completer) (c, tracker, p, word);
6e1dbf8c 1321}
67c296a2
PM
1322
1323/* Internal function used to handle completions.
1324
c5f0f3d0
FN
1325
1326 TEXT is the caller's idea of the "word" we are looking at.
1327
aff410f1
MS
1328 LINE_BUFFER is available to be looked at; it contains the entire
1329 text of the line. POINT is the offset in that line of the cursor.
1330 You should pretend that the line ends at POINT.
67c296a2 1331
eb3ff9a5 1332 See complete_line_internal_reason for description of REASON. */
14032a66 1333
eb3ff9a5
PA
1334static void
1335complete_line_internal_1 (completion_tracker &tracker,
1336 const char *text,
1337 const char *line_buffer, int point,
1338 complete_line_internal_reason reason)
c5f0f3d0 1339{
6f937416
PA
1340 char *tmp_command;
1341 const char *p;
ace21957 1342 int ignore_help_classes;
c5f0f3d0 1343 /* Pointer within tmp_command which corresponds to text. */
eb3ff9a5 1344 const char *word;
c5f0f3d0
FN
1345 struct cmd_list_element *c, *result_list;
1346
aff410f1
MS
1347 /* Choose the default set of word break characters to break
1348 completions. If we later find out that we are doing completions
1349 on command strings (as opposed to strings supplied by the
1350 individual command completer functions, which can be any string)
1351 then we will switch to the special word break set for command
be09caf1 1352 strings, which leaves out the '-' and '.' character used in some
aff410f1 1353 commands. */
67cb5b2d 1354 set_rl_completer_word_break_characters
53fc67f8 1355 (current_language->word_break_characters ());
c5f0f3d0 1356
aff410f1
MS
1357 /* Decide whether to complete on a list of gdb commands or on
1358 symbols. */
83d31a92
TT
1359 tmp_command = (char *) alloca (point + 1);
1360 p = tmp_command;
c5f0f3d0 1361
ace21957
MF
1362 /* The help command should complete help aliases. */
1363 ignore_help_classes = reason != handle_help;
1364
83d31a92
TT
1365 strncpy (tmp_command, line_buffer, point);
1366 tmp_command[point] = '\0';
eb3ff9a5
PA
1367 if (reason == handle_brkchars)
1368 {
1369 gdb_assert (text == NULL);
1370 word = NULL;
1371 }
1372 else
1373 {
1374 /* Since text always contains some number of characters leading up
1375 to point, we can find the equivalent position in tmp_command
1376 by subtracting that many characters from the end of tmp_command. */
1377 word = tmp_command + point - strlen (text);
1378 }
c5f0f3d0 1379
a81aaca0
PA
1380 /* Move P up to the start of the command. */
1381 p = skip_spaces (p);
1382
1383 if (*p == '\0')
83d31a92 1384 {
a81aaca0
PA
1385 /* An empty line is ambiguous; that is, it could be any
1386 command. */
1427fe5e 1387 c = CMD_LIST_AMBIGUOUS;
83d31a92
TT
1388 result_list = 0;
1389 }
1390 else
1391 {
cf00cd6f 1392 c = lookup_cmd_1 (&p, cmdlist, &result_list, NULL, ignore_help_classes);
83d31a92 1393 }
c5f0f3d0 1394
83d31a92
TT
1395 /* Move p up to the next interesting thing. */
1396 while (*p == ' ' || *p == '\t')
1397 {
1398 p++;
1399 }
c5f0f3d0 1400
c6756f62
PA
1401 tracker.advance_custom_word_point_by (p - tmp_command);
1402
83d31a92
TT
1403 if (!c)
1404 {
1405 /* It is an unrecognized command. So there are no
1406 possible completions. */
83d31a92 1407 }
1427fe5e 1408 else if (c == CMD_LIST_AMBIGUOUS)
83d31a92 1409 {
6f937416 1410 const char *q;
83d31a92
TT
1411
1412 /* lookup_cmd_1 advances p up to the first ambiguous thing, but
1413 doesn't advance over that thing itself. Do so now. */
1414 q = p;
be09caf1 1415 while (valid_cmd_char_p (*q))
83d31a92
TT
1416 ++q;
1417 if (q != tmp_command + point)
c5f0f3d0 1418 {
83d31a92
TT
1419 /* There is something beyond the ambiguous
1420 command, so there are no possible completions. For
1421 example, "info t " or "info t foo" does not complete
1422 to anything, because "info t" can be "info target" or
1423 "info terminal". */
c5f0f3d0 1424 }
83d31a92 1425 else
c5f0f3d0 1426 {
83d31a92
TT
1427 /* We're trying to complete on the command which was ambiguous.
1428 This we can deal with. */
1429 if (result_list)
c5f0f3d0 1430 {
67c296a2 1431 if (reason != handle_brkchars)
eb3ff9a5
PA
1432 complete_on_cmdlist (*result_list->prefixlist, tracker, p,
1433 word, ignore_help_classes);
c5f0f3d0
FN
1434 }
1435 else
1436 {
67c296a2 1437 if (reason != handle_brkchars)
eb3ff9a5
PA
1438 complete_on_cmdlist (cmdlist, tracker, p, word,
1439 ignore_help_classes);
c5f0f3d0 1440 }
489f0516 1441 /* Ensure that readline does the right thing with respect to
83d31a92 1442 inserting quotes. */
67cb5b2d
PA
1443 set_rl_completer_word_break_characters
1444 (gdb_completer_command_word_break_characters);
c5f0f3d0 1445 }
83d31a92
TT
1446 }
1447 else
1448 {
1449 /* We've recognized a full command. */
1450
1451 if (p == tmp_command + point)
c5f0f3d0 1452 {
aff410f1
MS
1453 /* There is no non-whitespace in the line beyond the
1454 command. */
c5f0f3d0 1455
83d31a92 1456 if (p[-1] == ' ' || p[-1] == '\t')
c5f0f3d0 1457 {
aff410f1
MS
1458 /* The command is followed by whitespace; we need to
1459 complete on whatever comes after command. */
83d31a92 1460 if (c->prefixlist)
c5f0f3d0 1461 {
83d31a92
TT
1462 /* It is a prefix command; what comes after it is
1463 a subcommand (e.g. "info "). */
67c296a2 1464 if (reason != handle_brkchars)
eb3ff9a5
PA
1465 complete_on_cmdlist (*c->prefixlist, tracker, p, word,
1466 ignore_help_classes);
c5f0f3d0 1467
489f0516 1468 /* Ensure that readline does the right thing
9c3f90bd 1469 with respect to inserting quotes. */
67cb5b2d
PA
1470 set_rl_completer_word_break_characters
1471 (gdb_completer_command_word_break_characters);
c5f0f3d0 1472 }
67c296a2 1473 else if (reason == handle_help)
eb3ff9a5 1474 ;
c5f0f3d0
FN
1475 else if (c->enums)
1476 {
67c296a2 1477 if (reason != handle_brkchars)
eb3ff9a5 1478 complete_on_enum (tracker, c->enums, p, word);
67cb5b2d
PA
1479 set_rl_completer_word_break_characters
1480 (gdb_completer_command_word_break_characters);
c5f0f3d0
FN
1481 }
1482 else
1483 {
83d31a92
TT
1484 /* It is a normal command; what comes after it is
1485 completed by the command's completer function. */
eb3ff9a5
PA
1486 complete_line_internal_normal_command (tracker,
1487 tmp_command, word, p,
1488 reason, c);
c5f0f3d0
FN
1489 }
1490 }
83d31a92
TT
1491 else
1492 {
1493 /* The command is not followed by whitespace; we need to
aff410f1 1494 complete on the command itself, e.g. "p" which is a
83d31a92
TT
1495 command itself but also can complete to "print", "ptype"
1496 etc. */
6f937416 1497 const char *q;
83d31a92
TT
1498
1499 /* Find the command we are completing on. */
1500 q = p;
1501 while (q > tmp_command)
1502 {
be09caf1 1503 if (valid_cmd_char_p (q[-1]))
83d31a92
TT
1504 --q;
1505 else
1506 break;
1507 }
1508
3844e605
PA
1509 /* Move the custom word point back too. */
1510 tracker.advance_custom_word_point_by (q - p);
1511
67c296a2 1512 if (reason != handle_brkchars)
eb3ff9a5
PA
1513 complete_on_cmdlist (result_list, tracker, q, word,
1514 ignore_help_classes);
83d31a92 1515
489f0516 1516 /* Ensure that readline does the right thing
9c3f90bd 1517 with respect to inserting quotes. */
67cb5b2d
PA
1518 set_rl_completer_word_break_characters
1519 (gdb_completer_command_word_break_characters);
83d31a92
TT
1520 }
1521 }
67c296a2 1522 else if (reason == handle_help)
eb3ff9a5 1523 ;
83d31a92
TT
1524 else
1525 {
1526 /* There is non-whitespace beyond the command. */
1527
1528 if (c->prefixlist && !c->allow_unknown)
1529 {
1530 /* It is an unrecognized subcommand of a prefix command,
1531 e.g. "info adsfkdj". */
83d31a92
TT
1532 }
1533 else if (c->enums)
1534 {
67c296a2 1535 if (reason != handle_brkchars)
eb3ff9a5 1536 complete_on_enum (tracker, c->enums, p, word);
83d31a92
TT
1537 }
1538 else
1539 {
1540 /* It is a normal command. */
eb3ff9a5
PA
1541 complete_line_internal_normal_command (tracker,
1542 tmp_command, word, p,
1543 reason, c);
83d31a92
TT
1544 }
1545 }
1546 }
83d31a92 1547}
ef0b411a 1548
eb3ff9a5
PA
1549/* Wrapper around complete_line_internal_1 to handle
1550 MAX_COMPLETIONS_REACHED_ERROR. */
ef0b411a 1551
eb3ff9a5
PA
1552static void
1553complete_line_internal (completion_tracker &tracker,
1554 const char *text,
1555 const char *line_buffer, int point,
1556 complete_line_internal_reason reason)
1557{
a70b8144 1558 try
eb3ff9a5
PA
1559 {
1560 complete_line_internal_1 (tracker, text, line_buffer, point, reason);
1561 }
230d2906 1562 catch (const gdb_exception_error &except)
eb3ff9a5
PA
1563 {
1564 if (except.error != MAX_COMPLETIONS_REACHED_ERROR)
eedc3f4f 1565 throw;
eb3ff9a5
PA
1566 }
1567}
ef0b411a
GB
1568
1569/* See completer.h. */
1570
eb3ff9a5 1571int max_completions = 200;
ef0b411a 1572
eb3ff9a5
PA
1573/* Initial size of the table. It automagically grows from here. */
1574#define INITIAL_COMPLETION_HTAB_SIZE 200
ef0b411a 1575
eb3ff9a5 1576/* See completer.h. */
ef0b411a 1577
eb3ff9a5 1578completion_tracker::completion_tracker ()
ef0b411a 1579{
724fd9ba 1580 discard_completions ();
ef0b411a
GB
1581}
1582
1583/* See completer.h. */
1584
c6756f62
PA
1585void
1586completion_tracker::discard_completions ()
1587{
1588 xfree (m_lowest_common_denominator);
1589 m_lowest_common_denominator = NULL;
1590
1591 m_lowest_common_denominator_unique = false;
724fd9ba
AB
1592 m_lowest_common_denominator_valid = false;
1593
32580f6d 1594 m_entries_hash.reset (nullptr);
724fd9ba
AB
1595
1596 /* A callback used by the hash table to compare new entries with existing
1597 entries. We can't use the standard streq_hash function here as the
1598 key to our hash is just a single string, while the values we store in
1599 the hash are a struct containing multiple strings. */
1600 static auto entry_eq_func
1601 = [] (const void *first, const void *second) -> int
1602 {
1603 /* The FIRST argument is the entry already in the hash table, and
1604 the SECOND argument is the new item being inserted. */
1605 const completion_hash_entry *entry
1606 = (const completion_hash_entry *) first;
1607 const char *name_str = (const char *) second;
c6756f62 1608
724fd9ba
AB
1609 return entry->is_name_eq (name_str);
1610 };
c6756f62 1611
99f1bc6a
AB
1612 /* Callback used by the hash table to compute the hash value for an
1613 existing entry. This is needed when expanding the hash table. */
1614 static auto entry_hash_func
1615 = [] (const void *arg) -> hashval_t
1616 {
1617 const completion_hash_entry *entry
1618 = (const completion_hash_entry *) arg;
1619 return entry->hash_name ();
1620 };
1621
32580f6d
TT
1622 m_entries_hash.reset (htab_create_alloc (INITIAL_COMPLETION_HTAB_SIZE,
1623 entry_hash_func, entry_eq_func,
1624 completion_hash_entry::deleter,
1625 xcalloc, xfree));
c6756f62
PA
1626}
1627
1628/* See completer.h. */
1629
eb3ff9a5 1630completion_tracker::~completion_tracker ()
ef0b411a 1631{
eb3ff9a5 1632 xfree (m_lowest_common_denominator);
ef0b411a
GB
1633}
1634
1635/* See completer.h. */
1636
eb3ff9a5 1637bool
a207cff2
PA
1638completion_tracker::maybe_add_completion
1639 (gdb::unique_xmalloc_ptr<char> name,
a22ecf70
PA
1640 completion_match_for_lcd *match_for_lcd,
1641 const char *text, const char *word)
ef0b411a
GB
1642{
1643 void **slot;
1644
ef0b411a 1645 if (max_completions == 0)
eb3ff9a5 1646 return false;
ef0b411a 1647
32580f6d 1648 if (htab_elements (m_entries_hash.get ()) >= max_completions)
eb3ff9a5 1649 return false;
ef0b411a 1650
724fd9ba 1651 hashval_t hash = htab_hash_string (name.get ());
32580f6d
TT
1652 slot = htab_find_slot_with_hash (m_entries_hash.get (), name.get (),
1653 hash, INSERT);
eb3ff9a5
PA
1654 if (*slot == HTAB_EMPTY_ENTRY)
1655 {
a207cff2
PA
1656 const char *match_for_lcd_str = NULL;
1657
1658 if (match_for_lcd != NULL)
1659 match_for_lcd_str = match_for_lcd->finish ();
1660
1661 if (match_for_lcd_str == NULL)
1662 match_for_lcd_str = name.get ();
ef0b411a 1663
a22ecf70
PA
1664 gdb::unique_xmalloc_ptr<char> lcd
1665 = make_completion_match_str (match_for_lcd_str, text, word);
1666
724fd9ba
AB
1667 size_t lcd_len = strlen (lcd.get ());
1668 *slot = new completion_hash_entry (std::move (name), std::move (lcd));
ef0b411a 1669
724fd9ba
AB
1670 m_lowest_common_denominator_valid = false;
1671 m_lowest_common_denominator_max_length
1672 = std::max (m_lowest_common_denominator_max_length, lcd_len);
eb3ff9a5 1673 }
ef0b411a 1674
eb3ff9a5
PA
1675 return true;
1676}
1677
1678/* See completer.h. */
ef0b411a 1679
eb3ff9a5 1680void
a207cff2 1681completion_tracker::add_completion (gdb::unique_xmalloc_ptr<char> name,
a22ecf70
PA
1682 completion_match_for_lcd *match_for_lcd,
1683 const char *text, const char *word)
eb3ff9a5 1684{
a22ecf70 1685 if (!maybe_add_completion (std::move (name), match_for_lcd, text, word))
eb3ff9a5 1686 throw_error (MAX_COMPLETIONS_REACHED_ERROR, _("Max completions reached."));
ef0b411a
GB
1687}
1688
eb3ff9a5
PA
1689/* See completer.h. */
1690
ef0b411a 1691void
eb3ff9a5 1692completion_tracker::add_completions (completion_list &&list)
ef0b411a 1693{
eb3ff9a5
PA
1694 for (auto &candidate : list)
1695 add_completion (std::move (candidate));
ef0b411a
GB
1696}
1697
19a2740f
AB
1698/* See completer.h. */
1699
1700void
1701completion_tracker::remove_completion (const char *name)
1702{
1703 hashval_t hash = htab_hash_string (name);
32580f6d 1704 if (htab_find_slot_with_hash (m_entries_hash.get (), name, hash, NO_INSERT)
19a2740f
AB
1705 != NULL)
1706 {
32580f6d 1707 htab_remove_elt_with_hash (m_entries_hash.get (), name, hash);
19a2740f
AB
1708 m_lowest_common_denominator_valid = false;
1709 }
1710}
1711
60a20c19
PA
1712/* Helper for the make_completion_match_str overloads. Returns NULL
1713 as an indication that we want MATCH_NAME exactly. It is up to the
1714 caller to xstrdup that string if desired. */
1715
1716static char *
1717make_completion_match_str_1 (const char *match_name,
1718 const char *text, const char *word)
1719{
1720 char *newobj;
1721
1722 if (word == text)
1723 {
1724 /* Return NULL as an indication that we want MATCH_NAME
1725 exactly. */
1726 return NULL;
1727 }
1728 else if (word > text)
1729 {
1730 /* Return some portion of MATCH_NAME. */
1731 newobj = xstrdup (match_name + (word - text));
1732 }
1733 else
1734 {
1735 /* Return some of WORD plus MATCH_NAME. */
1736 size_t len = strlen (match_name);
1737 newobj = (char *) xmalloc (text - word + len + 1);
1738 memcpy (newobj, word, text - word);
1739 memcpy (newobj + (text - word), match_name, len + 1);
1740 }
1741
1742 return newobj;
1743}
1744
1745/* See completer.h. */
1746
1747gdb::unique_xmalloc_ptr<char>
1748make_completion_match_str (const char *match_name,
1749 const char *text, const char *word)
1750{
1751 char *newobj = make_completion_match_str_1 (match_name, text, word);
1752 if (newobj == NULL)
1753 newobj = xstrdup (match_name);
1754 return gdb::unique_xmalloc_ptr<char> (newobj);
1755}
1756
1757/* See completer.h. */
1758
1759gdb::unique_xmalloc_ptr<char>
1760make_completion_match_str (gdb::unique_xmalloc_ptr<char> &&match_name,
1761 const char *text, const char *word)
1762{
1763 char *newobj = make_completion_match_str_1 (match_name.get (), text, word);
1764 if (newobj == NULL)
1765 return std::move (match_name);
1766 return gdb::unique_xmalloc_ptr<char> (newobj);
1767}
1768
6e035501
JV
1769/* See complete.h. */
1770
1771completion_result
1772complete (const char *line, char const **word, int *quote_char)
1773{
1774 completion_tracker tracker_handle_brkchars;
1775 completion_tracker tracker_handle_completions;
1776 completion_tracker *tracker;
1777
0ef209f2
JV
1778 /* The WORD should be set to the end of word to complete. We initialize
1779 to the completion point which is assumed to be at the end of LINE.
1780 This leaves WORD to be initialized to a sensible value in cases
1781 completion_find_completion_word() fails i.e., throws an exception.
1782 See bug 24587. */
1783 *word = line + strlen (line);
1784
6e035501
JV
1785 try
1786 {
1787 *word = completion_find_completion_word (tracker_handle_brkchars,
1788 line, quote_char);
1789
1790 /* Completers that provide a custom word point in the
1791 handle_brkchars phase also compute their completions then.
1792 Completers that leave the completion word handling to readline
1793 must be called twice. */
1794 if (tracker_handle_brkchars.use_custom_word_point ())
1795 tracker = &tracker_handle_brkchars;
1796 else
1797 {
1798 complete_line (tracker_handle_completions, *word, line, strlen (line));
1799 tracker = &tracker_handle_completions;
1800 }
1801 }
1802 catch (const gdb_exception &ex)
1803 {
1804 return {};
1805 }
1806
1807 return tracker->build_completion_result (*word, *word - line, strlen (line));
1808}
1809
1810
eb3ff9a5
PA
1811/* Generate completions all at once. Does nothing if max_completions
1812 is 0. If max_completions is non-negative, this will collect at
1813 most max_completions strings.
83d31a92 1814
67c296a2
PM
1815 TEXT is the caller's idea of the "word" we are looking at.
1816
aff410f1
MS
1817 LINE_BUFFER is available to be looked at; it contains the entire
1818 text of the line.
67c296a2
PM
1819
1820 POINT is the offset in that line of the cursor. You
1821 should pretend that the line ends at POINT. */
14032a66 1822
eb3ff9a5
PA
1823void
1824complete_line (completion_tracker &tracker,
1825 const char *text, const char *line_buffer, int point)
14032a66 1826{
ef0b411a 1827 if (max_completions == 0)
eb3ff9a5
PA
1828 return;
1829 complete_line_internal (tracker, text, line_buffer, point,
1830 handle_completions);
14032a66
TT
1831}
1832
1833/* Complete on command names. Used by "help". */
6e1dbf8c 1834
eb3ff9a5 1835void
aff410f1 1836command_completer (struct cmd_list_element *ignore,
eb3ff9a5 1837 completion_tracker &tracker,
6f937416 1838 const char *text, const char *word)
14032a66 1839{
eb3ff9a5
PA
1840 complete_line_internal (tracker, word, text,
1841 strlen (text), handle_help);
67c296a2
PM
1842}
1843
6e1dbf8c
PA
1844/* The corresponding completer_handle_brkchars implementation. */
1845
1846static void
1847command_completer_handle_brkchars (struct cmd_list_element *ignore,
eb3ff9a5 1848 completion_tracker &tracker,
6e1dbf8c
PA
1849 const char *text, const char *word)
1850{
1851 set_rl_completer_word_break_characters
1852 (gdb_completer_command_word_break_characters);
1853}
1854
de0bea00
MF
1855/* Complete on signals. */
1856
eb3ff9a5 1857void
de0bea00 1858signal_completer (struct cmd_list_element *ignore,
eb3ff9a5 1859 completion_tracker &tracker,
6f937416 1860 const char *text, const char *word)
de0bea00 1861{
de0bea00 1862 size_t len = strlen (word);
570dc176 1863 int signum;
de0bea00
MF
1864 const char *signame;
1865
1866 for (signum = GDB_SIGNAL_FIRST; signum != GDB_SIGNAL_LAST; ++signum)
1867 {
1868 /* Can't handle this, so skip it. */
1869 if (signum == GDB_SIGNAL_0)
1870 continue;
1871
570dc176 1872 signame = gdb_signal_to_name ((enum gdb_signal) signum);
de0bea00
MF
1873
1874 /* Ignore the unknown signal case. */
1875 if (!signame || strcmp (signame, "?") == 0)
1876 continue;
1877
1878 if (strncasecmp (signame, word, len) == 0)
b02f78f9 1879 tracker.add_completion (make_unique_xstrdup (signame));
de0bea00 1880 }
de0bea00
MF
1881}
1882
51f0e40d
AB
1883/* Bit-flags for selecting what the register and/or register-group
1884 completer should complete on. */
71c24708 1885
8d297bbf 1886enum reg_completer_target
51f0e40d
AB
1887 {
1888 complete_register_names = 0x1,
1889 complete_reggroup_names = 0x2
1890 };
8d297bbf 1891DEF_ENUM_FLAGS_TYPE (enum reg_completer_target, reg_completer_targets);
51f0e40d
AB
1892
1893/* Complete register names and/or reggroup names based on the value passed
1894 in TARGETS. At least one bit in TARGETS must be set. */
1895
eb3ff9a5
PA
1896static void
1897reg_or_group_completer_1 (completion_tracker &tracker,
51f0e40d 1898 const char *text, const char *word,
8d297bbf 1899 reg_completer_targets targets)
71c24708 1900{
71c24708
AA
1901 size_t len = strlen (word);
1902 struct gdbarch *gdbarch;
71c24708 1903 const char *name;
71c24708 1904
51f0e40d
AB
1905 gdb_assert ((targets & (complete_register_names
1906 | complete_reggroup_names)) != 0);
1907 gdbarch = get_current_arch ();
71c24708 1908
51f0e40d 1909 if ((targets & complete_register_names) != 0)
71c24708 1910 {
51f0e40d
AB
1911 int i;
1912
1913 for (i = 0;
1914 (name = user_reg_map_regnum_to_name (gdbarch, i)) != NULL;
1915 i++)
1916 {
1917 if (*name != '\0' && strncmp (word, name, len) == 0)
b02f78f9 1918 tracker.add_completion (make_unique_xstrdup (name));
51f0e40d 1919 }
71c24708
AA
1920 }
1921
51f0e40d 1922 if ((targets & complete_reggroup_names) != 0)
71c24708 1923 {
51f0e40d
AB
1924 struct reggroup *group;
1925
1926 for (group = reggroup_next (gdbarch, NULL);
1927 group != NULL;
1928 group = reggroup_next (gdbarch, group))
1929 {
1930 name = reggroup_name (group);
1931 if (strncmp (word, name, len) == 0)
b02f78f9 1932 tracker.add_completion (make_unique_xstrdup (name));
51f0e40d 1933 }
71c24708 1934 }
71c24708
AA
1935}
1936
51f0e40d
AB
1937/* Perform completion on register and reggroup names. */
1938
eb3ff9a5 1939void
51f0e40d 1940reg_or_group_completer (struct cmd_list_element *ignore,
eb3ff9a5 1941 completion_tracker &tracker,
51f0e40d
AB
1942 const char *text, const char *word)
1943{
eb3ff9a5
PA
1944 reg_or_group_completer_1 (tracker, text, word,
1945 (complete_register_names
1946 | complete_reggroup_names));
51f0e40d
AB
1947}
1948
1949/* Perform completion on reggroup names. */
1950
eb3ff9a5 1951void
51f0e40d 1952reggroup_completer (struct cmd_list_element *ignore,
eb3ff9a5 1953 completion_tracker &tracker,
51f0e40d
AB
1954 const char *text, const char *word)
1955{
eb3ff9a5
PA
1956 reg_or_group_completer_1 (tracker, text, word,
1957 complete_reggroup_names);
51f0e40d 1958}
71c24708 1959
6e1dbf8c
PA
1960/* The default completer_handle_brkchars implementation. */
1961
1962static void
1963default_completer_handle_brkchars (struct cmd_list_element *ignore,
eb3ff9a5 1964 completion_tracker &tracker,
6e1dbf8c
PA
1965 const char *text, const char *word)
1966{
1967 set_rl_completer_word_break_characters
53fc67f8 1968 (current_language->word_break_characters ());
6e1dbf8c
PA
1969}
1970
1971/* See definition in completer.h. */
1972
1973completer_handle_brkchars_ftype *
1974completer_handle_brkchars_func_for_completer (completer_ftype *fn)
1975{
1976 if (fn == filename_completer)
1977 return filename_completer_handle_brkchars;
1978
c6756f62
PA
1979 if (fn == location_completer)
1980 return location_completer_handle_brkchars;
1981
6e1dbf8c
PA
1982 if (fn == command_completer)
1983 return command_completer_handle_brkchars;
1984
1985 return default_completer_handle_brkchars;
1986}
1987
c6756f62
PA
1988/* Used as brkchars when we want to tell readline we have a custom
1989 word point. We do that by making our rl_completion_word_break_hook
1990 set RL_POINT to the desired word point, and return the character at
1991 the word break point as the break char. This is two bytes in order
1992 to fit one break character plus the terminating null. */
1993static char gdb_custom_word_point_brkchars[2];
1994
1995/* Since rl_basic_quote_characters is not completer-specific, we save
1996 its original value here, in order to be able to restore it in
1997 gdb_rl_attempted_completion_function. */
1998static const char *gdb_org_rl_basic_quote_characters = rl_basic_quote_characters;
1999
67c296a2
PM
2000/* Get the list of chars that are considered as word breaks
2001 for the current command. */
2002
eb3ff9a5
PA
2003static char *
2004gdb_completion_word_break_characters_throw ()
67c296a2 2005{
eb3ff9a5
PA
2006 /* New completion starting. Get rid of the previous tracker and
2007 start afresh. */
2008 delete current_completion.tracker;
2009 current_completion.tracker = new completion_tracker ();
2010
2011 completion_tracker &tracker = *current_completion.tracker;
2012
2013 complete_line_internal (tracker, NULL, rl_line_buffer,
2014 rl_point, handle_brkchars);
c5504eaf 2015
c6756f62
PA
2016 if (tracker.use_custom_word_point ())
2017 {
2018 gdb_assert (tracker.custom_word_point () > 0);
2019 rl_point = tracker.custom_word_point () - 1;
272d4594
PA
2020
2021 gdb_assert (rl_point >= 0 && rl_point < strlen (rl_line_buffer));
2022
c6756f62
PA
2023 gdb_custom_word_point_brkchars[0] = rl_line_buffer[rl_point];
2024 rl_completer_word_break_characters = gdb_custom_word_point_brkchars;
2025 rl_completer_quote_characters = NULL;
2026
2027 /* Clear this too, so that if we're completing a quoted string,
2028 readline doesn't consider the quote character a delimiter.
2029 If we didn't do this, readline would auto-complete {b
2030 'fun<tab>} to {'b 'function()'}, i.e., add the terminating
2031 \', but, it wouldn't append the separator space either, which
2032 is not desirable. So instead we take care of appending the
2033 quote character to the LCD ourselves, in
2034 gdb_rl_attempted_completion_function. Since this global is
2035 not just completer-specific, we'll restore it back to the
2036 default in gdb_rl_attempted_completion_function. */
2037 rl_basic_quote_characters = NULL;
2038 }
2039
67c296a2 2040 return rl_completer_word_break_characters;
14032a66
TT
2041}
2042
eb3ff9a5
PA
2043char *
2044gdb_completion_word_break_characters ()
2045{
2046 /* New completion starting. */
2047 current_completion.aborted = false;
83d31a92 2048
a70b8144 2049 try
eb3ff9a5
PA
2050 {
2051 return gdb_completion_word_break_characters_throw ();
2052 }
230d2906 2053 catch (const gdb_exception &ex)
eb3ff9a5
PA
2054 {
2055 /* Set this to that gdb_rl_attempted_completion_function knows
2056 to abort early. */
2057 current_completion.aborted = true;
2058 }
83d31a92 2059
eb3ff9a5
PA
2060 return NULL;
2061}
83d31a92 2062
eb3ff9a5 2063/* See completer.h. */
83d31a92 2064
6a2c1b87
PA
2065const char *
2066completion_find_completion_word (completion_tracker &tracker, const char *text,
2067 int *quote_char)
2068{
2069 size_t point = strlen (text);
2070
2071 complete_line_internal (tracker, NULL, text, point, handle_brkchars);
2072
c6756f62
PA
2073 if (tracker.use_custom_word_point ())
2074 {
2075 gdb_assert (tracker.custom_word_point () > 0);
2076 *quote_char = tracker.quote_char ();
2077 return text + tracker.custom_word_point ();
2078 }
2079
6a2c1b87
PA
2080 gdb_rl_completion_word_info info;
2081
2082 info.word_break_characters = rl_completer_word_break_characters;
2083 info.quote_characters = gdb_completer_quote_characters;
2084 info.basic_quote_characters = rl_basic_quote_characters;
2085
2086 return gdb_rl_find_completion_word (&info, quote_char, NULL, text);
2087}
2088
2089/* See completer.h. */
2090
eb3ff9a5 2091void
724fd9ba 2092completion_tracker::recompute_lcd_visitor (completion_hash_entry *entry)
83d31a92 2093{
724fd9ba 2094 if (!m_lowest_common_denominator_valid)
eb3ff9a5 2095 {
724fd9ba
AB
2096 /* This is the first lowest common denominator that we are
2097 considering, just copy it in. */
2098 strcpy (m_lowest_common_denominator, entry->get_lcd ());
eb3ff9a5 2099 m_lowest_common_denominator_unique = true;
724fd9ba 2100 m_lowest_common_denominator_valid = true;
eb3ff9a5
PA
2101 }
2102 else
83d31a92 2103 {
724fd9ba
AB
2104 /* Find the common denominator between the currently-known lowest
2105 common denominator and NEW_MATCH_UP. That becomes the new lowest
2106 common denominator. */
eb3ff9a5 2107 size_t i;
724fd9ba 2108 const char *new_match = entry->get_lcd ();
83d31a92 2109
eb3ff9a5
PA
2110 for (i = 0;
2111 (new_match[i] != '\0'
2112 && new_match[i] == m_lowest_common_denominator[i]);
2113 i++)
2114 ;
2115 if (m_lowest_common_denominator[i] != new_match[i])
83d31a92 2116 {
eb3ff9a5
PA
2117 m_lowest_common_denominator[i] = '\0';
2118 m_lowest_common_denominator_unique = false;
c5f0f3d0
FN
2119 }
2120 }
eb3ff9a5
PA
2121}
2122
c6756f62
PA
2123/* See completer.h. */
2124
724fd9ba
AB
2125void
2126completion_tracker::recompute_lowest_common_denominator ()
2127{
2128 /* We've already done this. */
2129 if (m_lowest_common_denominator_valid)
2130 return;
2131
2132 /* Resize the storage to ensure we have enough space, the plus one gives
2133 us space for the trailing null terminator we will include. */
2134 m_lowest_common_denominator
2135 = (char *) xrealloc (m_lowest_common_denominator,
2136 m_lowest_common_denominator_max_length + 1);
2137
2138 /* Callback used to visit each entry in the m_entries_hash. */
2139 auto visitor_func
2140 = [] (void **slot, void *info) -> int
2141 {
2142 completion_tracker *obj = (completion_tracker *) info;
2143 completion_hash_entry *entry = (completion_hash_entry *) *slot;
2144 obj->recompute_lcd_visitor (entry);
2145 return 1;
2146 };
2147
32580f6d 2148 htab_traverse (m_entries_hash.get (), visitor_func, this);
724fd9ba
AB
2149 m_lowest_common_denominator_valid = true;
2150}
2151
2152/* See completer.h. */
2153
c6756f62 2154void
3844e605 2155completion_tracker::advance_custom_word_point_by (int len)
c6756f62
PA
2156{
2157 m_custom_word_point += len;
2158}
2159
eb3ff9a5
PA
2160/* Build a new C string that is a copy of LCD with the whitespace of
2161 ORIG/ORIG_LEN preserved.
2162
2163 Say the user is completing a symbol name, with spaces, like:
2164
2165 "foo ( i"
2166
2167 and the resulting completion match is:
2168
2169 "foo(int)"
2170
2171 we want to end up with an input line like:
2172
2173 "foo ( int)"
2174 ^^^^^^^ => text from LCD [1], whitespace from ORIG preserved.
2175 ^^ => new text from LCD
2176
2177 [1] - We must take characters from the LCD instead of the original
2178 text, since some completions want to change upper/lowercase. E.g.:
c5f0f3d0 2179
eb3ff9a5 2180 "handle sig<>"
c5f0f3d0 2181
eb3ff9a5
PA
2182 completes to:
2183
2184 "handle SIG[QUIT|etc.]"
2185*/
2186
2187static char *
2188expand_preserving_ws (const char *orig, size_t orig_len,
2189 const char *lcd)
2190{
2191 const char *p_orig = orig;
2192 const char *orig_end = orig + orig_len;
2193 const char *p_lcd = lcd;
2194 std::string res;
2195
2196 while (p_orig < orig_end)
c5f0f3d0 2197 {
eb3ff9a5
PA
2198 if (*p_orig == ' ')
2199 {
2200 while (p_orig < orig_end && *p_orig == ' ')
2201 res += *p_orig++;
f1735a53 2202 p_lcd = skip_spaces (p_lcd);
eb3ff9a5
PA
2203 }
2204 else
c5f0f3d0 2205 {
eb3ff9a5
PA
2206 /* Take characters from the LCD instead of the original
2207 text, since some completions change upper/lowercase.
2208 E.g.:
2209 "handle sig<>"
2210 completes to:
2211 "handle SIG[QUIT|etc.]"
2212 */
2213 res += *p_lcd;
2214 p_orig++;
2215 p_lcd++;
c5f0f3d0
FN
2216 }
2217 }
2218
eb3ff9a5
PA
2219 while (*p_lcd != '\0')
2220 res += *p_lcd++;
2221
2222 return xstrdup (res.c_str ());
2223}
2224
2225/* See completer.h. */
2226
2227completion_result
2228completion_tracker::build_completion_result (const char *text,
2229 int start, int end)
2230{
32580f6d 2231 size_t element_count = htab_elements (m_entries_hash.get ());
eb3ff9a5 2232
724fd9ba 2233 if (element_count == 0)
eb3ff9a5
PA
2234 return {};
2235
2236 /* +1 for the LCD, and +1 for NULL termination. */
724fd9ba 2237 char **match_list = XNEWVEC (char *, 1 + element_count + 1);
eb3ff9a5
PA
2238
2239 /* Build replacement word, based on the LCD. */
2240
724fd9ba 2241 recompute_lowest_common_denominator ();
eb3ff9a5
PA
2242 match_list[0]
2243 = expand_preserving_ws (text, end - start,
2244 m_lowest_common_denominator);
2245
2246 if (m_lowest_common_denominator_unique)
2247 {
c6756f62
PA
2248 /* We don't rely on readline appending the quote char as
2249 delimiter as then readline wouldn't append the ' ' after the
2250 completion. */
896a7aa6 2251 char buf[2] = { (char) quote_char () };
c6756f62
PA
2252
2253 match_list[0] = reconcat (match_list[0], match_list[0],
2254 buf, (char *) NULL);
eb3ff9a5
PA
2255 match_list[1] = NULL;
2256
c45ec17c
PA
2257 /* If the tracker wants to, or we already have a space at the
2258 end of the match, tell readline to skip appending
2259 another. */
aafdfb4e 2260 char *match = match_list[0];
eb3ff9a5 2261 bool completion_suppress_append
c45ec17c 2262 = (suppress_append_ws ()
aafdfb4e
TV
2263 || (match[0] != '\0'
2264 && match[strlen (match) - 1] == ' '));
eb3ff9a5
PA
2265
2266 return completion_result (match_list, 1, completion_suppress_append);
2267 }
2268 else
2269 {
724fd9ba
AB
2270 /* State object used while building the completion list. */
2271 struct list_builder
2272 {
2273 list_builder (char **ml)
2274 : match_list (ml),
2275 index (1)
2276 { /* Nothing. */ }
2277
2278 /* The list we are filling. */
2279 char **match_list;
2280
2281 /* The next index in the list to write to. */
2282 int index;
2283 };
2284 list_builder builder (match_list);
2285
2286 /* Visit each entry in m_entries_hash and add it to the completion
2287 list, updating the builder state object. */
2288 auto func
2289 = [] (void **slot, void *info) -> int
2290 {
2291 completion_hash_entry *entry = (completion_hash_entry *) *slot;
2292 list_builder *state = (list_builder *) info;
2293
2294 state->match_list[state->index] = entry->release_name ();
2295 state->index++;
2296 return 1;
2297 };
2298
2299 /* Build the completion list and add a null at the end. */
32580f6d 2300 htab_traverse_noresize (m_entries_hash.get (), func, &builder);
724fd9ba
AB
2301 match_list[builder.index] = NULL;
2302
2303 return completion_result (match_list, builder.index - 1, false);
eb3ff9a5
PA
2304 }
2305}
2306
2307/* See completer.h */
2308
2309completion_result::completion_result ()
2310 : match_list (NULL), number_matches (0),
2311 completion_suppress_append (false)
2312{}
2313
2314/* See completer.h */
2315
2316completion_result::completion_result (char **match_list_,
2317 size_t number_matches_,
2318 bool completion_suppress_append_)
2319 : match_list (match_list_),
2320 number_matches (number_matches_),
2321 completion_suppress_append (completion_suppress_append_)
2322{}
2323
2324/* See completer.h */
2325
2326completion_result::~completion_result ()
2327{
2328 reset_match_list ();
2329}
2330
2331/* See completer.h */
2332
0fa7617d
TT
2333completion_result::completion_result (completion_result &&rhs) noexcept
2334 : match_list (rhs.match_list),
2335 number_matches (rhs.number_matches)
eb3ff9a5 2336{
eb3ff9a5 2337 rhs.match_list = NULL;
eb3ff9a5
PA
2338 rhs.number_matches = 0;
2339}
2340
2341/* See completer.h */
2342
2343char **
2344completion_result::release_match_list ()
2345{
2346 char **ret = match_list;
2347 match_list = NULL;
2348 return ret;
2349}
2350
eb3ff9a5
PA
2351/* See completer.h */
2352
2353void
2354completion_result::sort_match_list ()
2355{
2356 if (number_matches > 1)
2357 {
2358 /* Element 0 is special (it's the common prefix), leave it
2359 be. */
2360 std::sort (&match_list[1],
2361 &match_list[number_matches + 1],
2362 compare_cstrings);
2363 }
2364}
2365
2366/* See completer.h */
2367
2368void
2369completion_result::reset_match_list ()
2370{
2371 if (match_list != NULL)
2372 {
2373 for (char **p = match_list; *p != NULL; p++)
2374 xfree (*p);
2375 xfree (match_list);
2376 match_list = NULL;
2377 }
2378}
2379
2380/* Helper for gdb_rl_attempted_completion_function, which does most of
2381 the work. This is called by readline to build the match list array
2382 and to determine the lowest common denominator. The real matches
2383 list starts at match[1], while match[0] is the slot holding
2384 readline's idea of the lowest common denominator of all matches,
2385 which is what readline replaces the completion "word" with.
2386
2387 TEXT is the caller's idea of the "word" we are looking at, as
2388 computed in the handle_brkchars phase.
2389
2390 START is the offset from RL_LINE_BUFFER where TEXT starts. END is
2391 the offset from RL_LINE_BUFFER where TEXT ends (i.e., where
2392 rl_point is).
2393
2394 You should thus pretend that the line ends at END (relative to
2395 RL_LINE_BUFFER).
2396
2397 RL_LINE_BUFFER contains the entire text of the line. RL_POINT is
2398 the offset in that line of the cursor. You should pretend that the
2399 line ends at POINT.
2400
2401 Returns NULL if there are no completions. */
2402
2403static char **
2404gdb_rl_attempted_completion_function_throw (const char *text, int start, int end)
2405{
c6756f62
PA
2406 /* Completers that provide a custom word point in the
2407 handle_brkchars phase also compute their completions then.
2408 Completers that leave the completion word handling to readline
2409 must be called twice. If rl_point (i.e., END) is at column 0,
2410 then readline skips the handle_brkchars phase, and so we create a
2411 tracker now in that case too. */
2412 if (end == 0 || !current_completion.tracker->use_custom_word_point ())
2413 {
2414 delete current_completion.tracker;
2415 current_completion.tracker = new completion_tracker ();
eb3ff9a5 2416
c6756f62
PA
2417 complete_line (*current_completion.tracker, text,
2418 rl_line_buffer, rl_point);
2419 }
c5f0f3d0 2420
eb3ff9a5
PA
2421 completion_tracker &tracker = *current_completion.tracker;
2422
2423 completion_result result
2424 = tracker.build_completion_result (text, start, end);
2425
2426 rl_completion_suppress_append = result.completion_suppress_append;
2427 return result.release_match_list ();
2428}
2429
2430/* Function installed as "rl_attempted_completion_function" readline
2431 hook. Wrapper around gdb_rl_attempted_completion_function_throw
2432 that catches C++ exceptions, which can't cross readline. */
2433
2434char **
2435gdb_rl_attempted_completion_function (const char *text, int start, int end)
2436{
c6756f62
PA
2437 /* Restore globals that might have been tweaked in
2438 gdb_completion_word_break_characters. */
2439 rl_basic_quote_characters = gdb_org_rl_basic_quote_characters;
2440
eb3ff9a5
PA
2441 /* If we end up returning NULL, either on error, or simple because
2442 there are no matches, inhibit readline's default filename
2443 completer. */
2444 rl_attempted_completion_over = 1;
2445
2446 /* If the handle_brkchars phase was aborted, don't try
2447 completing. */
2448 if (current_completion.aborted)
2449 return NULL;
2450
a70b8144 2451 try
eb3ff9a5
PA
2452 {
2453 return gdb_rl_attempted_completion_function_throw (text, start, end);
2454 }
230d2906 2455 catch (const gdb_exception &ex)
eb3ff9a5
PA
2456 {
2457 }
eb3ff9a5
PA
2458
2459 return NULL;
c5f0f3d0 2460}
4e87b832
KD
2461
2462/* Skip over the possibly quoted word STR (as defined by the quote
b021a221
MS
2463 characters QUOTECHARS and the word break characters BREAKCHARS).
2464 Returns pointer to the location after the "word". If either
2465 QUOTECHARS or BREAKCHARS is NULL, use the same values used by the
2466 completer. */
c5f0f3d0 2467
d7561cbb
KS
2468const char *
2469skip_quoted_chars (const char *str, const char *quotechars,
2470 const char *breakchars)
c5f0f3d0
FN
2471{
2472 char quote_char = '\0';
d7561cbb 2473 const char *scan;
c5f0f3d0 2474
4e87b832
KD
2475 if (quotechars == NULL)
2476 quotechars = gdb_completer_quote_characters;
2477
2478 if (breakchars == NULL)
53fc67f8 2479 breakchars = current_language->word_break_characters ();
4e87b832 2480
c5f0f3d0
FN
2481 for (scan = str; *scan != '\0'; scan++)
2482 {
2483 if (quote_char != '\0')
2484 {
9c3f90bd 2485 /* Ignore everything until the matching close quote char. */
c5f0f3d0
FN
2486 if (*scan == quote_char)
2487 {
9c3f90bd 2488 /* Found matching close quote. */
c5f0f3d0
FN
2489 scan++;
2490 break;
2491 }
2492 }
4e87b832 2493 else if (strchr (quotechars, *scan))
c5f0f3d0 2494 {
aff410f1 2495 /* Found start of a quoted string. */
c5f0f3d0
FN
2496 quote_char = *scan;
2497 }
4e87b832 2498 else if (strchr (breakchars, *scan))
c5f0f3d0
FN
2499 {
2500 break;
2501 }
2502 }
4e87b832 2503
c5f0f3d0
FN
2504 return (scan);
2505}
2506
4e87b832
KD
2507/* Skip over the possibly quoted word STR (as defined by the quote
2508 characters and word break characters used by the completer).
9c3f90bd 2509 Returns pointer to the location after the "word". */
4e87b832 2510
d7561cbb
KS
2511const char *
2512skip_quoted (const char *str)
4e87b832
KD
2513{
2514 return skip_quoted_chars (str, NULL, NULL);
2515}
ef0b411a
GB
2516
2517/* Return a message indicating that the maximum number of completions
2518 has been reached and that there may be more. */
2519
2520const char *
2521get_max_completions_reached_message (void)
2522{
2523 return _("*** List may be truncated, max-completions reached. ***");
2524}
82083d6d
DE
2525\f
2526/* GDB replacement for rl_display_match_list.
2527 Readline doesn't provide a clean interface for TUI(curses).
2528 A hack previously used was to send readline's rl_outstream through a pipe
2529 and read it from the event loop. Bleah. IWBN if readline abstracted
2530 away all the necessary bits, and this is what this code does. It
2531 replicates the parts of readline we need and then adds an abstraction
2532 layer, currently implemented as struct match_list_displayer, so that both
2533 CLI and TUI can use it. We copy all this readline code to minimize
2534 GDB-specific mods to readline. Once this code performs as desired then
2535 we can submit it to the readline maintainers.
2536
2537 N.B. A lot of the code is the way it is in order to minimize differences
2538 from readline's copy. */
2539
2540/* Not supported here. */
2541#undef VISIBLE_STATS
2542
2543#if defined (HANDLE_MULTIBYTE)
2544#define MB_INVALIDCH(x) ((x) == (size_t)-1 || (x) == (size_t)-2)
2545#define MB_NULLWCH(x) ((x) == 0)
2546#endif
2547
2548#define ELLIPSIS_LEN 3
2549
2550/* gdb version of readline/complete.c:get_y_or_n.
2551 'y' -> returns 1, and 'n' -> returns 0.
2552 Also supported: space == 'y', RUBOUT == 'n', ctrl-g == start over.
2553 If FOR_PAGER is non-zero, then also supported are:
2554 NEWLINE or RETURN -> returns 2, and 'q' -> returns 0. */
2555
2556static int
2557gdb_get_y_or_n (int for_pager, const struct match_list_displayer *displayer)
2558{
2559 int c;
2560
2561 for (;;)
2562 {
2563 RL_SETSTATE (RL_STATE_MOREINPUT);
2564 c = displayer->read_key (displayer);
2565 RL_UNSETSTATE (RL_STATE_MOREINPUT);
2566
2567 if (c == 'y' || c == 'Y' || c == ' ')
2568 return 1;
2569 if (c == 'n' || c == 'N' || c == RUBOUT)
2570 return 0;
2571 if (c == ABORT_CHAR || c < 0)
2572 {
2573 /* Readline doesn't erase_entire_line here, but without it the
2574 --More-- prompt isn't erased and neither is the text entered
2575 thus far redisplayed. */
2576 displayer->erase_entire_line (displayer);
2577 /* Note: The arguments to rl_abort are ignored. */
2578 rl_abort (0, 0);
2579 }
2580 if (for_pager && (c == NEWLINE || c == RETURN))
2581 return 2;
2582 if (for_pager && (c == 'q' || c == 'Q'))
2583 return 0;
2584 displayer->beep (displayer);
2585 }
2586}
2587
2588/* Pager function for tab-completion.
2589 This is based on readline/complete.c:_rl_internal_pager.
2590 LINES is the number of lines of output displayed thus far.
2591 Returns:
2592 -1 -> user pressed 'n' or equivalent,
2593 0 -> user pressed 'y' or equivalent,
2594 N -> user pressed NEWLINE or equivalent and N is LINES - 1. */
2595
2596static int
2597gdb_display_match_list_pager (int lines,
2598 const struct match_list_displayer *displayer)
2599{
2600 int i;
2601
2602 displayer->puts (displayer, "--More--");
2603 displayer->flush (displayer);
2604 i = gdb_get_y_or_n (1, displayer);
2605 displayer->erase_entire_line (displayer);
2606 if (i == 0)
2607 return -1;
2608 else if (i == 2)
2609 return (lines - 1);
2610 else
2611 return 0;
2612}
2613
2614/* Return non-zero if FILENAME is a directory.
2615 Based on readline/complete.c:path_isdir. */
2616
2617static int
2618gdb_path_isdir (const char *filename)
2619{
2620 struct stat finfo;
2621
2622 return (stat (filename, &finfo) == 0 && S_ISDIR (finfo.st_mode));
2623}
2624
2625/* Return the portion of PATHNAME that should be output when listing
2626 possible completions. If we are hacking filename completion, we
2627 are only interested in the basename, the portion following the
2628 final slash. Otherwise, we return what we were passed. Since
2629 printing empty strings is not very informative, if we're doing
2630 filename completion, and the basename is the empty string, we look
2631 for the previous slash and return the portion following that. If
2632 there's no previous slash, we just return what we were passed.
2633
2634 Based on readline/complete.c:printable_part. */
2635
2636static char *
2637gdb_printable_part (char *pathname)
2638{
2639 char *temp, *x;
2640
2641 if (rl_filename_completion_desired == 0) /* don't need to do anything */
2642 return (pathname);
2643
2644 temp = strrchr (pathname, '/');
5836a818 2645#if defined (__MSDOS__)
82083d6d
DE
2646 if (temp == 0 && ISALPHA ((unsigned char)pathname[0]) && pathname[1] == ':')
2647 temp = pathname + 1;
2648#endif
2649
2650 if (temp == 0 || *temp == '\0')
2651 return (pathname);
2652 /* If the basename is NULL, we might have a pathname like '/usr/src/'.
2653 Look for a previous slash and, if one is found, return the portion
2654 following that slash. If there's no previous slash, just return the
2655 pathname we were passed. */
2656 else if (temp[1] == '\0')
2657 {
2658 for (x = temp - 1; x > pathname; x--)
dda83cd7
SM
2659 if (*x == '/')
2660 break;
82083d6d
DE
2661 return ((*x == '/') ? x + 1 : pathname);
2662 }
2663 else
2664 return ++temp;
2665}
2666
2667/* Compute width of STRING when displayed on screen by print_filename.
2668 Based on readline/complete.c:fnwidth. */
2669
2670static int
2671gdb_fnwidth (const char *string)
2672{
2673 int width, pos;
2674#if defined (HANDLE_MULTIBYTE)
2675 mbstate_t ps;
2676 int left, w;
2677 size_t clen;
2678 wchar_t wc;
2679
2680 left = strlen (string) + 1;
2681 memset (&ps, 0, sizeof (mbstate_t));
2682#endif
2683
2684 width = pos = 0;
2685 while (string[pos])
2686 {
2687 if (CTRL_CHAR (string[pos]) || string[pos] == RUBOUT)
2688 {
2689 width += 2;
2690 pos++;
2691 }
2692 else
2693 {
2694#if defined (HANDLE_MULTIBYTE)
2695 clen = mbrtowc (&wc, string + pos, left - pos, &ps);
2696 if (MB_INVALIDCH (clen))
2697 {
2698 width++;
2699 pos++;
2700 memset (&ps, 0, sizeof (mbstate_t));
2701 }
2702 else if (MB_NULLWCH (clen))
2703 break;
2704 else
2705 {
2706 pos += clen;
2707 w = wcwidth (wc);
2708 width += (w >= 0) ? w : 1;
2709 }
2710#else
2711 width++;
2712 pos++;
2713#endif
2714 }
2715 }
2716
2717 return width;
2718}
2719
2720/* Print TO_PRINT, one matching completion.
2721 PREFIX_BYTES is number of common prefix bytes.
2722 Based on readline/complete.c:fnprint. */
2723
2724static int
2725gdb_fnprint (const char *to_print, int prefix_bytes,
2726 const struct match_list_displayer *displayer)
2727{
0a4f5f8c 2728 int printed_len, w;
82083d6d
DE
2729 const char *s;
2730#if defined (HANDLE_MULTIBYTE)
2731 mbstate_t ps;
2732 const char *end;
2733 size_t tlen;
2734 int width;
2735 wchar_t wc;
2736
2737 end = to_print + strlen (to_print) + 1;
2738 memset (&ps, 0, sizeof (mbstate_t));
2739#endif
2740
0a4f5f8c 2741 printed_len = 0;
82083d6d
DE
2742
2743 /* Don't print only the ellipsis if the common prefix is one of the
2744 possible completions */
2745 if (to_print[prefix_bytes] == '\0')
2746 prefix_bytes = 0;
2747
0a4f5f8c 2748 if (prefix_bytes)
82083d6d
DE
2749 {
2750 char ellipsis;
2751
2752 ellipsis = (to_print[prefix_bytes] == '.') ? '_' : '.';
2753 for (w = 0; w < ELLIPSIS_LEN; w++)
2754 displayer->putch (displayer, ellipsis);
2755 printed_len = ELLIPSIS_LEN;
2756 }
2757
2758 s = to_print + prefix_bytes;
2759 while (*s)
2760 {
2761 if (CTRL_CHAR (*s))
dda83cd7
SM
2762 {
2763 displayer->putch (displayer, '^');
2764 displayer->putch (displayer, UNCTRL (*s));
2765 printed_len += 2;
2766 s++;
82083d6d
DE
2767#if defined (HANDLE_MULTIBYTE)
2768 memset (&ps, 0, sizeof (mbstate_t));
2769#endif
dda83cd7 2770 }
82083d6d
DE
2771 else if (*s == RUBOUT)
2772 {
2773 displayer->putch (displayer, '^');
2774 displayer->putch (displayer, '?');
2775 printed_len += 2;
2776 s++;
2777#if defined (HANDLE_MULTIBYTE)
2778 memset (&ps, 0, sizeof (mbstate_t));
2779#endif
2780 }
2781 else
2782 {
2783#if defined (HANDLE_MULTIBYTE)
2784 tlen = mbrtowc (&wc, s, end - s, &ps);
2785 if (MB_INVALIDCH (tlen))
2786 {
2787 tlen = 1;
2788 width = 1;
2789 memset (&ps, 0, sizeof (mbstate_t));
2790 }
2791 else if (MB_NULLWCH (tlen))
2792 break;
2793 else
2794 {
2795 w = wcwidth (wc);
2796 width = (w >= 0) ? w : 1;
2797 }
2798 for (w = 0; w < tlen; ++w)
2799 displayer->putch (displayer, s[w]);
2800 s += tlen;
2801 printed_len += width;
2802#else
2803 displayer->putch (displayer, *s);
2804 s++;
2805 printed_len++;
2806#endif
2807 }
2808 }
2809
2810 return printed_len;
2811}
2812
2813/* Output TO_PRINT to rl_outstream. If VISIBLE_STATS is defined and we
2814 are using it, check for and output a single character for `special'
2815 filenames. Return the number of characters we output.
2816 Based on readline/complete.c:print_filename. */
2817
2818static int
2819gdb_print_filename (char *to_print, char *full_pathname, int prefix_bytes,
2820 const struct match_list_displayer *displayer)
2821{
2822 int printed_len, extension_char, slen, tlen;
a121b7c1
PA
2823 char *s, c, *new_full_pathname;
2824 const char *dn;
82083d6d
DE
2825 extern int _rl_complete_mark_directories;
2826
2827 extension_char = 0;
2828 printed_len = gdb_fnprint (to_print, prefix_bytes, displayer);
2829
2830#if defined (VISIBLE_STATS)
2831 if (rl_filename_completion_desired && (rl_visible_stats || _rl_complete_mark_directories))
2832#else
2833 if (rl_filename_completion_desired && _rl_complete_mark_directories)
2834#endif
2835 {
2836 /* If to_print != full_pathname, to_print is the basename of the
2837 path passed. In this case, we try to expand the directory
2838 name before checking for the stat character. */
2839 if (to_print != full_pathname)
2840 {
2841 /* Terminate the directory name. */
2842 c = to_print[-1];
2843 to_print[-1] = '\0';
2844
2845 /* If setting the last slash in full_pathname to a NUL results in
2846 full_pathname being the empty string, we are trying to complete
2847 files in the root directory. If we pass a null string to the
2848 bash directory completion hook, for example, it will expand it
2849 to the current directory. We just want the `/'. */
2850 if (full_pathname == 0 || *full_pathname == 0)
2851 dn = "/";
2852 else if (full_pathname[0] != '/')
2853 dn = full_pathname;
2854 else if (full_pathname[1] == 0)
2855 dn = "//"; /* restore trailing slash to `//' */
2856 else if (full_pathname[1] == '/' && full_pathname[2] == 0)
2857 dn = "/"; /* don't turn /// into // */
2858 else
2859 dn = full_pathname;
2860 s = tilde_expand (dn);
2861 if (rl_directory_completion_hook)
2862 (*rl_directory_completion_hook) (&s);
2863
2864 slen = strlen (s);
2865 tlen = strlen (to_print);
2866 new_full_pathname = (char *)xmalloc (slen + tlen + 2);
2867 strcpy (new_full_pathname, s);
2868 if (s[slen - 1] == '/')
2869 slen--;
2870 else
2871 new_full_pathname[slen] = '/';
2872 new_full_pathname[slen] = '/';
2873 strcpy (new_full_pathname + slen + 1, to_print);
2874
2875#if defined (VISIBLE_STATS)
2876 if (rl_visible_stats)
2877 extension_char = stat_char (new_full_pathname);
2878 else
2879#endif
2880 if (gdb_path_isdir (new_full_pathname))
2881 extension_char = '/';
2882
2883 xfree (new_full_pathname);
2884 to_print[-1] = c;
2885 }
2886 else
2887 {
2888 s = tilde_expand (full_pathname);
2889#if defined (VISIBLE_STATS)
2890 if (rl_visible_stats)
2891 extension_char = stat_char (s);
2892 else
2893#endif
2894 if (gdb_path_isdir (s))
2895 extension_char = '/';
2896 }
2897
2898 xfree (s);
2899 if (extension_char)
2900 {
2901 displayer->putch (displayer, extension_char);
2902 printed_len++;
2903 }
2904 }
2905
2906 return printed_len;
2907}
2908
2909/* GDB version of readline/complete.c:complete_get_screenwidth. */
2910
2911static int
2912gdb_complete_get_screenwidth (const struct match_list_displayer *displayer)
2913{
2914 /* Readline has other stuff here which it's not clear we need. */
2915 return displayer->width;
2916}
2917
0a4f5f8c 2918extern int _rl_completion_prefix_display_length;
56000a98
PA
2919extern int _rl_print_completions_horizontally;
2920
2921EXTERN_C int _rl_qsort_string_compare (const void *, const void *);
2922typedef int QSFUNC (const void *, const void *);
2923
82083d6d 2924/* GDB version of readline/complete.c:rl_display_match_list.
ef0b411a
GB
2925 See gdb_display_match_list for a description of MATCHES, LEN, MAX.
2926 Returns non-zero if all matches are displayed. */
82083d6d 2927
ef0b411a 2928static int
82083d6d
DE
2929gdb_display_match_list_1 (char **matches, int len, int max,
2930 const struct match_list_displayer *displayer)
2931{
2932 int count, limit, printed_len, lines, cols;
2933 int i, j, k, l, common_length, sind;
2934 char *temp, *t;
2935 int page_completions = displayer->height != INT_MAX && pagination_enabled;
82083d6d
DE
2936
2937 /* Find the length of the prefix common to all items: length as displayed
2938 characters (common_length) and as a byte index into the matches (sind) */
2939 common_length = sind = 0;
0a4f5f8c 2940 if (_rl_completion_prefix_display_length > 0)
82083d6d
DE
2941 {
2942 t = gdb_printable_part (matches[0]);
2943 temp = strrchr (t, '/');
2944 common_length = temp ? gdb_fnwidth (temp) : gdb_fnwidth (t);
2945 sind = temp ? strlen (temp) : strlen (t);
2946
0a4f5f8c 2947 if (common_length > _rl_completion_prefix_display_length && common_length > ELLIPSIS_LEN)
82083d6d 2948 max -= common_length - ELLIPSIS_LEN;
0a4f5f8c 2949 else
82083d6d
DE
2950 common_length = sind = 0;
2951 }
2952
2953 /* How many items of MAX length can we fit in the screen window? */
2954 cols = gdb_complete_get_screenwidth (displayer);
2955 max += 2;
2956 limit = cols / max;
2957 if (limit != 1 && (limit * max == cols))
2958 limit--;
2959
2960 /* If cols == 0, limit will end up -1 */
2961 if (cols < displayer->width && limit < 0)
2962 limit = 1;
2963
2964 /* Avoid a possible floating exception. If max > cols,
2965 limit will be 0 and a divide-by-zero fault will result. */
2966 if (limit == 0)
2967 limit = 1;
2968
2969 /* How many iterations of the printing loop? */
2970 count = (len + (limit - 1)) / limit;
2971
2972 /* Watch out for special case. If LEN is less than LIMIT, then
2973 just do the inner printing loop.
2974 0 < len <= limit implies count = 1. */
2975
2976 /* Sort the items if they are not already sorted. */
2977 if (rl_ignore_completion_duplicates == 0 && rl_sort_completion_matches)
2978 qsort (matches + 1, len, sizeof (char *), (QSFUNC *)_rl_qsort_string_compare);
2979
2980 displayer->crlf (displayer);
2981
2982 lines = 0;
2983 if (_rl_print_completions_horizontally == 0)
2984 {
2985 /* Print the sorted items, up-and-down alphabetically, like ls. */
2986 for (i = 1; i <= count; i++)
2987 {
2988 for (j = 0, l = i; j < limit; j++)
2989 {
2990 if (l > len || matches[l] == 0)
2991 break;
2992 else
2993 {
2994 temp = gdb_printable_part (matches[l]);
2995 printed_len = gdb_print_filename (temp, matches[l], sind,
2996 displayer);
2997
2998 if (j + 1 < limit)
2999 for (k = 0; k < max - printed_len; k++)
3000 displayer->putch (displayer, ' ');
3001 }
3002 l += count;
3003 }
3004 displayer->crlf (displayer);
3005 lines++;
3006 if (page_completions && lines >= (displayer->height - 1) && i < count)
3007 {
3008 lines = gdb_display_match_list_pager (lines, displayer);
3009 if (lines < 0)
ef0b411a 3010 return 0;
82083d6d
DE
3011 }
3012 }
3013 }
3014 else
3015 {
3016 /* Print the sorted items, across alphabetically, like ls -x. */
3017 for (i = 1; matches[i]; i++)
3018 {
3019 temp = gdb_printable_part (matches[i]);
3020 printed_len = gdb_print_filename (temp, matches[i], sind, displayer);
3021 /* Have we reached the end of this line? */
3022 if (matches[i+1])
3023 {
3024 if (i && (limit > 1) && (i % limit) == 0)
3025 {
3026 displayer->crlf (displayer);
3027 lines++;
3028 if (page_completions && lines >= displayer->height - 1)
3029 {
3030 lines = gdb_display_match_list_pager (lines, displayer);
3031 if (lines < 0)
ef0b411a 3032 return 0;
82083d6d
DE
3033 }
3034 }
3035 else
3036 for (k = 0; k < max - printed_len; k++)
3037 displayer->putch (displayer, ' ');
3038 }
3039 }
3040 displayer->crlf (displayer);
3041 }
ef0b411a
GB
3042
3043 return 1;
82083d6d
DE
3044}
3045
3046/* Utility for displaying completion list matches, used by both CLI and TUI.
3047
3048 MATCHES is the list of strings, in argv format, LEN is the number of
05cdcf3d
DE
3049 strings in MATCHES, and MAX is the length of the longest string in
3050 MATCHES. */
82083d6d
DE
3051
3052void
3053gdb_display_match_list (char **matches, int len, int max,
3054 const struct match_list_displayer *displayer)
3055{
ef0b411a
GB
3056 /* Readline will never call this if complete_line returned NULL. */
3057 gdb_assert (max_completions != 0);
3058
3059 /* complete_line will never return more than this. */
3060 if (max_completions > 0)
3061 gdb_assert (len <= max_completions);
3062
82083d6d
DE
3063 if (rl_completion_query_items > 0 && len >= rl_completion_query_items)
3064 {
3065 char msg[100];
3066
3067 /* We can't use *query here because they wait for <RET> which is
3068 wrong here. This follows the readline version as closely as possible
3069 for compatibility's sake. See readline/complete.c. */
3070
3071 displayer->crlf (displayer);
3072
3073 xsnprintf (msg, sizeof (msg),
3074 "Display all %d possibilities? (y or n)", len);
3075 displayer->puts (displayer, msg);
3076 displayer->flush (displayer);
3077
3078 if (gdb_get_y_or_n (0, displayer) == 0)
3079 {
3080 displayer->crlf (displayer);
3081 return;
3082 }
3083 }
3084
ef0b411a
GB
3085 if (gdb_display_match_list_1 (matches, len, max, displayer))
3086 {
3087 /* Note: MAX_COMPLETIONS may be -1 or zero, but LEN is always > 0. */
3088 if (len == max_completions)
3089 {
3090 /* The maximum number of completions has been reached. Warn the user
3091 that there may be more. */
3092 const char *message = get_max_completions_reached_message ();
3093
3094 displayer->puts (displayer, message);
3095 displayer->crlf (displayer);
3096 }
3097 }
3098}
ef0b411a 3099
6c265988 3100void _initialize_completer ();
ef0b411a 3101void
6c265988 3102_initialize_completer ()
ef0b411a
GB
3103{
3104 add_setshow_zuinteger_unlimited_cmd ("max-completions", no_class,
3105 &max_completions, _("\
3106Set maximum number of completion candidates."), _("\
3107Show maximum number of completion candidates."), _("\
3108Use this to limit the number of candidates considered\n\
3109during completion. Specifying \"unlimited\" or -1\n\
3110disables limiting. Note that setting either no limit or\n\
3111a very large limit can make completion slow."),
3112 NULL, NULL, &setlist, &showlist);
82083d6d 3113}
This page took 1.471149 seconds and 4 git commands to generate.