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