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