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