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