Remove path name from test case
[binutils-gdb.git] / gdb / completer.h
1 /* Header for GDB line completion.
2 Copyright (C) 2000-2023 Free Software Foundation, Inc.
3
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 3 of the License, or
7 (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>. */
16
17 #if !defined (COMPLETER_H)
18 #define COMPLETER_H 1
19
20 #include "gdbsupport/gdb-hashtab.h"
21 #include "gdbsupport/gdb_vecs.h"
22 #include "command.h"
23
24 /* Types of functions in struct match_list_displayer. */
25
26 struct match_list_displayer;
27
28 typedef void mld_crlf_ftype (const struct match_list_displayer *);
29 typedef void mld_putch_ftype (const struct match_list_displayer *, int);
30 typedef void mld_puts_ftype (const struct match_list_displayer *,
31 const char *);
32 typedef void mld_flush_ftype (const struct match_list_displayer *);
33 typedef void mld_erase_entire_line_ftype (const struct match_list_displayer *);
34 typedef void mld_beep_ftype (const struct match_list_displayer *);
35 typedef int mld_read_key_ftype (const struct match_list_displayer *);
36
37 /* Interface between CLI/TUI and gdb_match_list_displayer. */
38
39 struct match_list_displayer
40 {
41 /* The screen dimensions to work with when displaying matches. */
42 int height, width;
43
44 /* Print cr,lf. */
45 mld_crlf_ftype *crlf;
46
47 /* Not "putc" to avoid issues where it is a stdio macro. Sigh. */
48 mld_putch_ftype *putch;
49
50 /* Print a string. */
51 mld_puts_ftype *puts;
52
53 /* Flush all accumulated output. */
54 mld_flush_ftype *flush;
55
56 /* Erase the currently line on the terminal (but don't discard any text the
57 user has entered, readline may shortly re-print it). */
58 mld_erase_entire_line_ftype *erase_entire_line;
59
60 /* Ring the bell. */
61 mld_beep_ftype *beep;
62
63 /* Read one key. */
64 mld_read_key_ftype *read_key;
65 };
66
67 /* A list of completion candidates. Each element is a malloc string,
68 because ownership of the strings is transferred to readline, which
69 calls free on each element. */
70 typedef std::vector<gdb::unique_xmalloc_ptr<char>> completion_list;
71
72 /* The result of a successful completion match. When doing symbol
73 comparison, we use the symbol search name for the symbol name match
74 check, but the matched name that is shown to the user may be
75 different. For example, Ada uses encoded names for lookup, but
76 then wants to decode the symbol name to show to the user, and also
77 in some cases wrap the matched name in "<sym>" (meaning we can't
78 always use the symbol's print name). */
79
80 class completion_match
81 {
82 public:
83 /* Get the completion match result. See m_match/m_storage's
84 descriptions. */
85 const char *match ()
86 { return m_match; }
87
88 /* Set the completion match result. See m_match/m_storage's
89 descriptions. */
90 void set_match (const char *match)
91 { m_match = match; }
92
93 /* Get temporary storage for generating a match result, dynamically.
94 The built string is only good until the next clear() call. I.e.,
95 good until the next symbol comparison. */
96 std::string &storage ()
97 { return m_storage; }
98
99 /* Prepare for another completion matching sequence. */
100 void clear ()
101 {
102 m_match = NULL;
103 m_storage.clear ();
104 }
105
106 private:
107 /* The completion match result. This can either be a pointer into
108 M_STORAGE string, or it can be a pointer into the some other
109 string that outlives the completion matching sequence (usually, a
110 pointer to a symbol's name). */
111 const char *m_match;
112
113 /* Storage a symbol comparison routine can use for generating a
114 match result, dynamically. The built string is only good until
115 the next clear() call. I.e., good until the next symbol
116 comparison. */
117 std::string m_storage;
118 };
119
120 /* The result of a successful completion match, but for least common
121 denominator (LCD) computation. Some completers provide matches
122 that don't start with the completion "word". E.g., completing on
123 "b push_ba" on a C++ program usually completes to
124 std::vector<...>::push_back, std::string::push_back etc. In such
125 case, the symbol comparison routine will set the LCD match to point
126 into the "push_back" substring within the symbol's name string.
127 Also, in some cases, the symbol comparison routine will want to
128 ignore parts of the symbol name for LCD purposes, such as for
129 example symbols with abi tags in C++. In such cases, the symbol
130 comparison routine will set MARK_IGNORED_RANGE to mark the ignored
131 substrings of the matched string. The resulting LCD string with
132 the ignored parts stripped out is computed at the end of a
133 completion match sequence iff we had a positive match. */
134
135 class completion_match_for_lcd
136 {
137 public:
138 /* Get the resulting LCD, after a successful match. */
139 const char *match ()
140 { return m_match; }
141
142 /* Set the match for LCD. See m_match's description. */
143 void set_match (const char *match)
144 { m_match = match; }
145
146 /* Mark the range between [BEGIN, END) as ignored. */
147 void mark_ignored_range (const char *begin, const char *end)
148 {
149 gdb_assert (begin < end);
150 gdb_assert (m_ignored_ranges.empty ()
151 || m_ignored_ranges.back ().second < begin);
152 m_ignored_ranges.emplace_back (begin, end);
153 }
154
155 /* Get the resulting LCD, after a successful match. If there are
156 ignored ranges, then this builds a new string with the ignored
157 parts removed (and stores it internally). As such, the result of
158 this call is only good for the current completion match
159 sequence. */
160 const char *finish ()
161 {
162 if (m_ignored_ranges.empty ())
163 return m_match;
164 else
165 {
166 m_finished_storage.clear ();
167
168 gdb_assert (m_ignored_ranges.back ().second
169 <= (m_match + strlen (m_match)));
170
171 const char *prev = m_match;
172 for (const auto &range : m_ignored_ranges)
173 {
174 gdb_assert (prev < range.first);
175 gdb_assert (range.second > range.first);
176 m_finished_storage.append (prev, range.first);
177 prev = range.second;
178 }
179 m_finished_storage.append (prev);
180
181 return m_finished_storage.c_str ();
182 }
183 }
184
185 /* Prepare for another completion matching sequence. */
186 void clear ()
187 {
188 m_match = NULL;
189 m_ignored_ranges.clear ();
190 }
191
192 /* Return true if this object has had no match data set since its
193 creation, or the last call to clear. */
194 bool empty () const
195 {
196 return m_match == nullptr && m_ignored_ranges.empty ();
197 }
198
199 private:
200 /* The completion match result for LCD. This is usually either a
201 pointer into to a substring within a symbol's name, or to the
202 storage of the pairing completion_match object. */
203 const char *m_match;
204
205 /* The ignored substring ranges within M_MATCH. E.g., if we were
206 looking for completion matches for C++ functions starting with
207 "functio"
208 and successfully match:
209 "function[abi:cxx11](int)"
210 the ignored ranges vector will contain an entry that delimits the
211 "[abi:cxx11]" substring, such that calling finish() results in:
212 "function(int)"
213 */
214 std::vector<std::pair<const char *, const char *>> m_ignored_ranges;
215
216 /* Storage used by the finish() method, if it has to compute a new
217 string. */
218 std::string m_finished_storage;
219 };
220
221 /* Convenience aggregate holding info returned by the symbol name
222 matching routines (see symbol_name_matcher_ftype). */
223 struct completion_match_result
224 {
225 /* The completion match candidate. */
226 completion_match match;
227
228 /* The completion match, for LCD computation purposes. */
229 completion_match_for_lcd match_for_lcd;
230
231 /* Convenience that sets both MATCH and MATCH_FOR_LCD. M_FOR_LCD is
232 optional. If not specified, defaults to M. */
233 void set_match (const char *m, const char *m_for_lcd = NULL)
234 {
235 match.set_match (m);
236 if (m_for_lcd == NULL)
237 match_for_lcd.set_match (m);
238 else
239 match_for_lcd.set_match (m_for_lcd);
240 }
241 };
242
243 /* The final result of a completion that is handed over to either
244 readline or the "completion" command (which pretends to be
245 readline). Mainly a wrapper for a readline-style match list array,
246 though other bits of info are included too. */
247
248 struct completion_result
249 {
250 /* Create an empty result. */
251 completion_result ();
252
253 /* Create a result. */
254 completion_result (char **match_list, size_t number_matches,
255 bool completion_suppress_append);
256
257 /* Destroy a result. */
258 ~completion_result ();
259
260 DISABLE_COPY_AND_ASSIGN (completion_result);
261
262 /* Move a result. */
263 completion_result (completion_result &&rhs) noexcept;
264
265 /* Release ownership of the match list array. */
266 char **release_match_list ();
267
268 /* Sort the match list. */
269 void sort_match_list ();
270
271 private:
272 /* Destroy the match list array and its contents. */
273 void reset_match_list ();
274
275 public:
276 /* (There's no point in making these fields private, since the whole
277 point of this wrapper is to build data in the layout expected by
278 readline. Making them private would require adding getters for
279 the "complete" command, which would expose the same
280 implementation details anyway.) */
281
282 /* The match list array, in the format that readline expects.
283 match_list[0] contains the common prefix. The real match list
284 starts at index 1. The list is NULL terminated. If there's only
285 one match, then match_list[1] is NULL. If there are no matches,
286 then this is NULL. */
287 char **match_list;
288 /* The number of matched completions in MATCH_LIST. Does not
289 include the NULL terminator or the common prefix. */
290 size_t number_matches;
291
292 /* Whether readline should suppress appending a whitespace, when
293 there's only one possible completion. */
294 bool completion_suppress_append;
295 };
296
297 /* Object used by completers to build a completion match list to hand
298 over to readline. It tracks:
299
300 - How many unique completions have been generated, to terminate
301 completion list generation early if the list has grown to a size
302 so large as to be useless. This helps avoid GDB seeming to lock
303 up in the event the user requests to complete on something vague
304 that necessitates the time consuming expansion of many symbol
305 tables.
306
307 - The completer's idea of least common denominator (aka the common
308 prefix) between all completion matches to hand over to readline.
309 Some completers provide matches that don't start with the
310 completion "word". E.g., completing on "b push_ba" on a C++
311 program usually completes to std::vector<...>::push_back,
312 std::string::push_back etc. If all matches happen to start with
313 "std::", then readline would figure out that the lowest common
314 denominator is "std::", and thus would do a partial completion
315 with that. I.e., it would replace "push_ba" in the input buffer
316 with "std::", losing the original "push_ba", which is obviously
317 undesirable. To avoid that, such completers pass the substring
318 of the match that matters for common denominator computation as
319 MATCH_FOR_LCD argument to add_completion. The end result is
320 passed to readline in gdb_rl_attempted_completion_function.
321
322 - The custom word point to hand over to readline, for completers
323 that parse the input string in order to dynamically adjust
324 themselves depending on exactly what they're completing. E.g.,
325 the linespec completer needs to bypass readline's too-simple word
326 breaking algorithm.
327 */
328 class completion_tracker
329 {
330 public:
331 completion_tracker ();
332 ~completion_tracker ();
333
334 DISABLE_COPY_AND_ASSIGN (completion_tracker);
335
336 /* Add the completion NAME to the list of generated completions if
337 it is not there already. If too many completions were already
338 found, this throws an error. */
339 void add_completion (gdb::unique_xmalloc_ptr<char> name,
340 completion_match_for_lcd *match_for_lcd = NULL,
341 const char *text = NULL, const char *word = NULL);
342
343 /* Add all completions matches in LIST. Elements are moved out of
344 LIST. */
345 void add_completions (completion_list &&list);
346
347 /* Remove completion matching NAME from the completion list, does nothing
348 if NAME is not already in the completion list. */
349 void remove_completion (const char *name);
350
351 /* Set the quote char to be appended after a unique completion is
352 added to the input line. Set to '\0' to clear. See
353 m_quote_char's description. */
354 void set_quote_char (int quote_char)
355 { m_quote_char = quote_char; }
356
357 /* The quote char to be appended after a unique completion is added
358 to the input line. Returns '\0' if no quote char has been set.
359 See m_quote_char's description. */
360 int quote_char () { return m_quote_char; }
361
362 /* Tell the tracker that the current completer wants to provide a
363 custom word point instead of a list of a break chars, in the
364 handle_brkchars phase. Such completers must also compute their
365 completions then. */
366 void set_use_custom_word_point (bool enable)
367 { m_use_custom_word_point = enable; }
368
369 /* Whether the current completer computes a custom word point. */
370 bool use_custom_word_point () const
371 { return m_use_custom_word_point; }
372
373 /* The custom word point. */
374 int custom_word_point () const
375 { return m_custom_word_point; }
376
377 /* Set the custom word point to POINT. */
378 void set_custom_word_point (int point)
379 { m_custom_word_point = point; }
380
381 /* Advance the custom word point by LEN. */
382 void advance_custom_word_point_by (int len);
383
384 /* Whether to tell readline to skip appending a whitespace after the
385 completion. See m_suppress_append_ws. */
386 bool suppress_append_ws () const
387 { return m_suppress_append_ws; }
388
389 /* Set whether to tell readline to skip appending a whitespace after
390 the completion. See m_suppress_append_ws. */
391 void set_suppress_append_ws (bool suppress)
392 { m_suppress_append_ws = suppress; }
393
394 /* Return true if we only have one completion, and it matches
395 exactly the completion word. I.e., completing results in what we
396 already have. */
397 bool completes_to_completion_word (const char *word);
398
399 /* Get a reference to the shared (between all the multiple symbol
400 name comparison calls) completion_match_result object, ready for
401 another symbol name match sequence. */
402 completion_match_result &reset_completion_match_result ()
403 {
404 completion_match_result &res = m_completion_match_result;
405
406 /* Clear any previous match. */
407 res.match.clear ();
408 res.match_for_lcd.clear ();
409 return m_completion_match_result;
410 }
411
412 /* True if we have any completion match recorded. */
413 bool have_completions () const
414 { return htab_elements (m_entries_hash.get ()) > 0; }
415
416 /* Discard the current completion match list and the current
417 LCD. */
418 void discard_completions ();
419
420 /* Build a completion_result containing the list of completion
421 matches to hand over to readline. The parameters are as in
422 rl_attempted_completion_function. */
423 completion_result build_completion_result (const char *text,
424 int start, int end);
425
426 private:
427
428 /* The type that we place into the m_entries_hash hash table. */
429 class completion_hash_entry;
430
431 /* Add the completion NAME to the list of generated completions if
432 it is not there already. If false is returned, too many
433 completions were found. */
434 bool maybe_add_completion (gdb::unique_xmalloc_ptr<char> name,
435 completion_match_for_lcd *match_for_lcd,
436 const char *text, const char *word);
437
438 /* Ensure that the lowest common denominator held in the member variable
439 M_LOWEST_COMMON_DENOMINATOR is valid. This method must be called if
440 there is any chance that new completions have been added to the
441 tracker before the lowest common denominator is read. */
442 void recompute_lowest_common_denominator ();
443
444 /* Callback used from recompute_lowest_common_denominator, called for
445 every entry in m_entries_hash. */
446 void recompute_lcd_visitor (completion_hash_entry *entry);
447
448 /* Completion match outputs returned by the symbol name matching
449 routines (see symbol_name_matcher_ftype). These results are only
450 valid for a single match call. This is here in order to be able
451 to conveniently share the same storage among all the calls to the
452 symbol name matching routines. */
453 completion_match_result m_completion_match_result;
454
455 /* The completion matches found so far, in a hash table, for
456 duplicate elimination as entries are added. Otherwise the user
457 is left scratching his/her head: readline and complete_command
458 will remove duplicates, and if removal of duplicates there brings
459 the total under max_completions the user may think gdb quit
460 searching too early. */
461 htab_up m_entries_hash;
462
463 /* If non-zero, then this is the quote char that needs to be
464 appended after completion (iff we have a unique completion). We
465 don't rely on readline appending the quote char as delimiter as
466 then readline wouldn't append the ' ' after the completion.
467 I.e., we want this:
468
469 before tab: "b 'function("
470 after tab: "b 'function()' "
471 */
472 int m_quote_char = '\0';
473
474 /* If true, the completer has its own idea of "word" point, and
475 doesn't want to rely on readline computing it based on brkchars.
476 Set in the handle_brkchars phase. */
477 bool m_use_custom_word_point = false;
478
479 /* The completer's idea of where the "word" we were looking at is
480 relative to RL_LINE_BUFFER. This is advanced in the
481 handle_brkchars phase as the completer discovers potential
482 completable words. */
483 int m_custom_word_point = 0;
484
485 /* If true, tell readline to skip appending a whitespace after the
486 completion. Automatically set if we have a unique completion
487 that already has a space at the end. A completer may also
488 explicitly set this. E.g., the linespec completer sets this when
489 the completion ends with the ":" separator between filename and
490 function name. */
491 bool m_suppress_append_ws = false;
492
493 /* Our idea of lowest common denominator to hand over to readline.
494 See intro. */
495 char *m_lowest_common_denominator = NULL;
496
497 /* If true, the LCD is unique. I.e., all completions had the same
498 MATCH_FOR_LCD substring, even if the completions were different.
499 For example, if "break function<tab>" found "a::function()" and
500 "b::function()", the LCD will be "function()" in both cases and
501 so we want to tell readline to complete the line with
502 "function()", instead of showing all the possible
503 completions. */
504 bool m_lowest_common_denominator_unique = false;
505
506 /* True if the value in M_LOWEST_COMMON_DENOMINATOR is correct. This is
507 set to true each time RECOMPUTE_LOWEST_COMMON_DENOMINATOR is called,
508 and reset to false whenever a new completion is added. */
509 bool m_lowest_common_denominator_valid = false;
510
511 /* To avoid calls to xrealloc in RECOMPUTE_LOWEST_COMMON_DENOMINATOR, we
512 track the maximum possible size of the lowest common denominator,
513 which we know as each completion is added. */
514 size_t m_lowest_common_denominator_max_length = 0;
515 };
516
517 /* Return a string to hand off to readline as a completion match
518 candidate, potentially composed of parts of MATCH_NAME and of
519 TEXT/WORD. For a description of TEXT/WORD see completer_ftype. */
520
521 extern gdb::unique_xmalloc_ptr<char>
522 make_completion_match_str (const char *match_name,
523 const char *text, const char *word);
524
525 /* Like above, but takes ownership of MATCH_NAME (i.e., can
526 reuse/return it). */
527
528 extern gdb::unique_xmalloc_ptr<char>
529 make_completion_match_str (gdb::unique_xmalloc_ptr<char> &&match_name,
530 const char *text, const char *word);
531
532 extern void gdb_display_match_list (char **matches, int len, int max,
533 const struct match_list_displayer *);
534
535 extern const char *get_max_completions_reached_message (void);
536
537 extern void complete_line (completion_tracker &tracker,
538 const char *text,
539 const char *line_buffer,
540 int point);
541
542 /* Complete LINE and return completion results. For completion purposes,
543 cursor position is assumed to be at the end of LINE. WORD is set to
544 the end of word to complete. QUOTE_CHAR is set to the opening quote
545 character if we found an unclosed quoted substring, '\0' otherwise. */
546 extern completion_result
547 complete (const char *line, char const **word, int *quote_char);
548
549 /* Find the bounds of the word in TEXT for completion purposes, and
550 return a pointer to the end of the word. Calls the completion
551 machinery for a handle_brkchars phase (using TRACKER) to figure out
552 the right work break characters for the command in TEXT.
553 QUOTE_CHAR, if non-null, is set to the opening quote character if
554 we found an unclosed quoted substring, '\0' otherwise. */
555 extern const char *completion_find_completion_word (completion_tracker &tracker,
556 const char *text,
557 int *quote_char);
558
559
560 /* Assuming TEXT is an expression in the current language, find the
561 completion word point for TEXT, emulating the algorithm readline
562 uses to find the word point, using the current language's word
563 break characters. */
564 const char *advance_to_expression_complete_word_point
565 (completion_tracker &tracker, const char *text);
566
567 /* Assuming TEXT is an filename, find the completion word point for
568 TEXT, emulating the algorithm readline uses to find the word
569 point. */
570 extern const char *advance_to_filename_complete_word_point
571 (completion_tracker &tracker, const char *text);
572
573 extern char **gdb_rl_attempted_completion_function (const char *text,
574 int start, int end);
575
576 extern void noop_completer (struct cmd_list_element *,
577 completion_tracker &tracker,
578 const char *, const char *);
579
580 extern void filename_completer (struct cmd_list_element *,
581 completion_tracker &tracker,
582 const char *, const char *);
583
584 extern void expression_completer (struct cmd_list_element *,
585 completion_tracker &tracker,
586 const char *, const char *);
587
588 extern void location_completer (struct cmd_list_element *,
589 completion_tracker &tracker,
590 const char *, const char *);
591
592 extern void symbol_completer (struct cmd_list_element *,
593 completion_tracker &tracker,
594 const char *, const char *);
595
596 extern void command_completer (struct cmd_list_element *,
597 completion_tracker &tracker,
598 const char *, const char *);
599
600 extern void signal_completer (struct cmd_list_element *,
601 completion_tracker &tracker,
602 const char *, const char *);
603
604 extern void reg_or_group_completer (struct cmd_list_element *,
605 completion_tracker &tracker,
606 const char *, const char *);
607
608 extern void reggroup_completer (struct cmd_list_element *,
609 completion_tracker &tracker,
610 const char *, const char *);
611
612 extern const char *get_gdb_completer_quote_characters (void);
613
614 extern char *gdb_completion_word_break_characters (void);
615
616 /* Set the word break characters array to BREAK_CHARS. This function
617 is useful as const-correct alternative to direct assignment to
618 rl_completer_word_break_characters, which is "char *",
619 not "const char *". */
620 extern void set_rl_completer_word_break_characters (const char *break_chars);
621
622 /* Get the matching completer_handle_brkchars_ftype function for FN.
623 FN is one of the core completer functions above (filename,
624 location, symbol, etc.). This function is useful for cases when
625 the completer doesn't know the type of the completion until some
626 calculation is done (e.g., for Python functions). */
627
628 extern completer_handle_brkchars_ftype *
629 completer_handle_brkchars_func_for_completer (completer_ftype *fn);
630
631 /* Exported to linespec.c */
632
633 /* Return a list of all source files whose names begin with matching
634 TEXT. */
635 extern completion_list complete_source_filenames (const char *text);
636
637 /* Complete on expressions. Often this means completing on symbol
638 names, but some language parsers also have support for completing
639 field names. */
640 extern void complete_expression (completion_tracker &tracker,
641 const char *text, const char *word);
642
643 /* Called by custom word point completers that want to recurse into
644 the completion machinery to complete a command. Used to complete
645 COMMAND in "thread apply all COMMAND", for example. Note that
646 unlike command_completer, this fully recurses into the proper
647 completer for COMMAND, so that e.g.,
648
649 (gdb) thread apply all print -[TAB]
650
651 does the right thing and show the print options. */
652 extern void complete_nested_command_line (completion_tracker &tracker,
653 const char *text);
654
655 extern const char *skip_quoted_chars (const char *, const char *,
656 const char *);
657
658 extern const char *skip_quoted (const char *);
659
660 /* Called from command completion function to skip over /FMT
661 specifications, allowing the rest of the line to be completed. Returns
662 true if the /FMT is at the end of the current line and there is nothing
663 left to complete, otherwise false is returned.
664
665 In either case *ARGS can be updated to point after any part of /FMT that
666 is present.
667
668 This function is designed so that trying to complete '/' will offer no
669 completions, the user needs to insert the format specification
670 themselves. Trying to complete '/FMT' (where FMT is any non-empty set
671 of alpha-numeric characters) will cause readline to insert a single
672 space, setting the user up to enter the expression. */
673
674 extern bool skip_over_slash_fmt (completion_tracker &tracker,
675 const char **args);
676
677 /* Maximum number of candidates to consider before the completer
678 bails by throwing MAX_COMPLETIONS_REACHED_ERROR. Negative values
679 disable limiting. */
680
681 extern int max_completions;
682
683 #endif /* defined (COMPLETER_H) */