typeprint.c (find_global_typedef): Fix comment.
[external/binutils.git] / gdb / typeprint.c
1 /* Language independent support for printing types for GDB, the GNU debugger.
2
3    Copyright (C) 1986-2014 Free Software Foundation, Inc.
4
5    This file is part of GDB.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20 #include "defs.h"
21 #include "gdb_obstack.h"
22 #include "bfd.h"                /* Binary File Description */
23 #include "symtab.h"
24 #include "gdbtypes.h"
25 #include "expression.h"
26 #include "value.h"
27 #include "gdbcore.h"
28 #include "command.h"
29 #include "gdbcmd.h"
30 #include "target.h"
31 #include "language.h"
32 #include "cp-abi.h"
33 #include "typeprint.h"
34 #include "exceptions.h"
35 #include "valprint.h"
36 #include <ctype.h>
37 #include "cli/cli-utils.h"
38 #include "extension.h"
39 #include "completer.h"
40
41 extern void _initialize_typeprint (void);
42
43 static void ptype_command (char *, int);
44
45 static void whatis_command (char *, int);
46
47 static void whatis_exp (char *, int);
48
49 const struct type_print_options type_print_raw_options =
50 {
51   1,                            /* raw */
52   1,                            /* print_methods */
53   1,                            /* print_typedefs */
54   NULL,                         /* local_typedefs */
55   NULL,                         /* global_table */
56   NULL                          /* global_printers */
57 };
58
59 /* The default flags for 'ptype' and 'whatis'.  */
60
61 static struct type_print_options default_ptype_flags =
62 {
63   0,                            /* raw */
64   1,                            /* print_methods */
65   1,                            /* print_typedefs */
66   NULL,                         /* local_typedefs */
67   NULL,                         /* global_table */
68   NULL                          /* global_printers */
69 };
70
71 \f
72
73 /* A hash table holding typedef_field objects.  This is more
74    complicated than an ordinary hash because it must also track the
75    lifetime of some -- but not all -- of the contained objects.  */
76
77 struct typedef_hash_table
78 {
79   /* The actual hash table.  */
80   htab_t table;
81
82   /* Storage for typedef_field objects that must be synthesized.  */
83   struct obstack storage;
84 };
85
86 /* A hash function for a typedef_field.  */
87
88 static hashval_t
89 hash_typedef_field (const void *p)
90 {
91   const struct typedef_field *tf = p;
92   struct type *t = check_typedef (tf->type);
93
94   return htab_hash_string (TYPE_SAFE_NAME (t));
95 }
96
97 /* An equality function for a typedef field.  */
98
99 static int
100 eq_typedef_field (const void *a, const void *b)
101 {
102   const struct typedef_field *tfa = a;
103   const struct typedef_field *tfb = b;
104
105   return types_equal (tfa->type, tfb->type);
106 }
107
108 /* Add typedefs from T to the hash table TABLE.  */
109
110 void
111 recursively_update_typedef_hash (struct typedef_hash_table *table,
112                                  struct type *t)
113 {
114   int i;
115
116   if (table == NULL)
117     return;
118
119   for (i = 0; i < TYPE_TYPEDEF_FIELD_COUNT (t); ++i)
120     {
121       struct typedef_field *tdef = &TYPE_TYPEDEF_FIELD (t, i);
122       void **slot;
123
124       slot = htab_find_slot (table->table, tdef, INSERT);
125       /* Only add a given typedef name once.  Really this shouldn't
126          happen; but it is safe enough to do the updates breadth-first
127          and thus use the most specific typedef.  */
128       if (*slot == NULL)
129         *slot = tdef;
130     }
131
132   /* Recurse into superclasses.  */
133   for (i = 0; i < TYPE_N_BASECLASSES (t); ++i)
134     recursively_update_typedef_hash (table, TYPE_BASECLASS (t, i));
135 }
136
137 /* Add template parameters from T to the typedef hash TABLE.  */
138
139 void
140 add_template_parameters (struct typedef_hash_table *table, struct type *t)
141 {
142   int i;
143
144   if (table == NULL)
145     return;
146
147   for (i = 0; i < TYPE_N_TEMPLATE_ARGUMENTS (t); ++i)
148     {
149       struct typedef_field *tf;
150       void **slot;
151
152       /* We only want type-valued template parameters in the hash.  */
153       if (SYMBOL_CLASS (TYPE_TEMPLATE_ARGUMENT (t, i)) != LOC_TYPEDEF)
154         continue;
155
156       tf = XOBNEW (&table->storage, struct typedef_field);
157       tf->name = SYMBOL_LINKAGE_NAME (TYPE_TEMPLATE_ARGUMENT (t, i));
158       tf->type = SYMBOL_TYPE (TYPE_TEMPLATE_ARGUMENT (t, i));
159
160       slot = htab_find_slot (table->table, tf, INSERT);
161       if (*slot == NULL)
162         *slot = tf;
163     }
164 }
165
166 /* Create a new typedef-lookup hash table.  */
167
168 struct typedef_hash_table *
169 create_typedef_hash (void)
170 {
171   struct typedef_hash_table *result;
172
173   result = XNEW (struct typedef_hash_table);
174   result->table = htab_create_alloc (10, hash_typedef_field, eq_typedef_field,
175                                      NULL, xcalloc, xfree);
176   obstack_init (&result->storage);
177
178   return result;
179 }
180
181 /* Free a typedef field table.  */
182
183 void
184 free_typedef_hash (struct typedef_hash_table *table)
185 {
186   if (table != NULL)
187     {
188       htab_delete (table->table);
189       obstack_free (&table->storage, NULL);
190       xfree (table);
191     }
192 }
193
194 /* A cleanup for freeing a typedef_hash_table.  */
195
196 static void
197 do_free_typedef_hash (void *arg)
198 {
199   free_typedef_hash (arg);
200 }
201
202 /* Return a new cleanup that frees TABLE.  */
203
204 struct cleanup *
205 make_cleanup_free_typedef_hash (struct typedef_hash_table *table)
206 {
207   return make_cleanup (do_free_typedef_hash, table);
208 }
209
210 /* Helper function for copy_typedef_hash.  */
211
212 static int
213 copy_typedef_hash_element (void **slot, void *nt)
214 {
215   htab_t new_table = nt;
216   void **new_slot;
217
218   new_slot = htab_find_slot (new_table, *slot, INSERT);
219   if (*new_slot == NULL)
220     *new_slot = *slot;
221
222   return 1;
223 }
224
225 /* Copy a typedef hash.  */
226
227 struct typedef_hash_table *
228 copy_typedef_hash (struct typedef_hash_table *table)
229 {
230   struct typedef_hash_table *result;
231
232   if (table == NULL)
233     return NULL;
234
235   result = create_typedef_hash ();
236   htab_traverse_noresize (table->table, copy_typedef_hash_element,
237                           result->table);
238   return result;
239 }
240
241 /* A cleanup to free the global typedef hash.  */
242
243 static void
244 do_free_global_table (void *arg)
245 {
246   struct type_print_options *flags = arg;
247
248   free_typedef_hash (flags->global_typedefs);
249   free_ext_lang_type_printers (flags->global_printers);
250 }
251
252 /* Create the global typedef hash.  */
253
254 static struct cleanup *
255 create_global_typedef_table (struct type_print_options *flags)
256 {
257   gdb_assert (flags->global_typedefs == NULL && flags->global_printers == NULL);
258   flags->global_typedefs = create_typedef_hash ();
259   flags->global_printers = start_ext_lang_type_printers ();
260   return make_cleanup (do_free_global_table, flags);
261 }
262
263 /* Look up the type T in the global typedef hash.  If it is found,
264    return the typedef name.  If it is not found, apply the
265    type-printers, if any, given by start_script_type_printers and return the
266    result.  A NULL return means that the name was not found.  */
267
268 static const char *
269 find_global_typedef (const struct type_print_options *flags,
270                      struct type *t)
271 {
272   char *applied;
273   void **slot;
274   struct typedef_field tf, *new_tf;
275
276   if (flags->global_typedefs == NULL)
277     return NULL;
278
279   tf.name = NULL;
280   tf.type = t;
281
282   slot = htab_find_slot (flags->global_typedefs->table, &tf, INSERT);
283   if (*slot != NULL)
284     {
285       new_tf = *slot;
286       return new_tf->name;
287     }
288
289   /* Put an entry into the hash table now, in case
290      apply_ext_lang_type_printers recurses.  */
291   new_tf = XOBNEW (&flags->global_typedefs->storage, struct typedef_field);
292   new_tf->name = NULL;
293   new_tf->type = t;
294
295   *slot = new_tf;
296
297   applied = apply_ext_lang_type_printers (flags->global_printers, t);
298
299   if (applied != NULL)
300     {
301       new_tf->name = obstack_copy0 (&flags->global_typedefs->storage, applied,
302                                     strlen (applied));
303       xfree (applied);
304     }
305
306   return new_tf->name;
307 }
308
309 /* Look up the type T in the typedef hash table in with FLAGS.  If T
310    is in the table, return its short (class-relative) typedef name.
311    Otherwise return NULL.  If the table is NULL, this always returns
312    NULL.  */
313
314 const char *
315 find_typedef_in_hash (const struct type_print_options *flags, struct type *t)
316 {
317   if (flags->local_typedefs != NULL)
318     {
319       struct typedef_field tf, *found;
320
321       tf.name = NULL;
322       tf.type = t;
323       found = htab_find (flags->local_typedefs->table, &tf);
324
325       if (found != NULL)
326         return found->name;
327     }
328
329   return find_global_typedef (flags, t);
330 }
331
332 \f
333
334 /* Print a description of a type in the format of a 
335    typedef for the current language.
336    NEW is the new name for a type TYPE.  */
337
338 void
339 typedef_print (struct type *type, struct symbol *new, struct ui_file *stream)
340 {
341   LA_PRINT_TYPEDEF (type, new, stream);
342 }
343
344 /* The default way to print a typedef.  */
345
346 void
347 default_print_typedef (struct type *type, struct symbol *new_symbol,
348                        struct ui_file *stream)
349 {
350   error (_("Language not supported."));
351 }
352
353 /* Print a description of a type TYPE in the form of a declaration of a
354    variable named VARSTRING.  (VARSTRING is demangled if necessary.)
355    Output goes to STREAM (via stdio).
356    If SHOW is positive, we show the contents of the outermost level
357    of structure even if there is a type name that could be used instead.
358    If SHOW is negative, we never show the details of elements' types.  */
359
360 void
361 type_print (struct type *type, const char *varstring, struct ui_file *stream,
362             int show)
363 {
364   LA_PRINT_TYPE (type, varstring, stream, show, 0, &default_ptype_flags);
365 }
366
367 /* Print TYPE to a string, returning it.  The caller is responsible for
368    freeing the string.  */
369
370 char *
371 type_to_string (struct type *type)
372 {
373   char *s = NULL;
374   struct ui_file *stb;
375   struct cleanup *old_chain;
376   volatile struct gdb_exception except;
377
378   stb = mem_fileopen ();
379   old_chain = make_cleanup_ui_file_delete (stb);
380
381   TRY_CATCH (except, RETURN_MASK_ALL)
382     {
383       type_print (type, "", stb, -1);
384       s = ui_file_xstrdup (stb, NULL);
385     }
386   if (except.reason < 0)
387     s = NULL;
388
389   do_cleanups (old_chain);
390
391   return s;
392 }
393
394 /* Print type of EXP, or last thing in value history if EXP == NULL.
395    show is passed to type_print.  */
396
397 static void
398 whatis_exp (char *exp, int show)
399 {
400   struct expression *expr;
401   struct value *val;
402   struct cleanup *old_chain;
403   struct type *real_type = NULL;
404   struct type *type;
405   int full = 0;
406   int top = -1;
407   int using_enc = 0;
408   struct value_print_options opts;
409   struct type_print_options flags = default_ptype_flags;
410
411   old_chain = make_cleanup (null_cleanup, NULL);
412
413   if (exp)
414     {
415       if (*exp == '/')
416         {
417           int seen_one = 0;
418
419           for (++exp; *exp && !isspace (*exp); ++exp)
420             {
421               switch (*exp)
422                 {
423                 case 'r':
424                   flags.raw = 1;
425                   break;
426                 case 'm':
427                   flags.print_methods = 0;
428                   break;
429                 case 'M':
430                   flags.print_methods = 1;
431                   break;
432                 case 't':
433                   flags.print_typedefs = 0;
434                   break;
435                 case 'T':
436                   flags.print_typedefs = 1;
437                   break;
438                 default:
439                   error (_("unrecognized flag '%c'"), *exp);
440                 }
441               seen_one = 1;
442             }
443
444           if (!*exp && !seen_one)
445             error (_("flag expected"));
446           if (!isspace (*exp))
447             error (_("expected space after format"));
448           exp = skip_spaces (exp);
449         }
450
451       expr = parse_expression (exp);
452       make_cleanup (free_current_contents, &expr);
453       val = evaluate_type (expr);
454     }
455   else
456     val = access_value_history (0);
457
458   type = value_type (val);
459
460   get_user_print_options (&opts);
461   if (opts.objectprint)
462     {
463       if (((TYPE_CODE (type) == TYPE_CODE_PTR)
464            || (TYPE_CODE (type) == TYPE_CODE_REF))
465           && (TYPE_CODE (TYPE_TARGET_TYPE (type)) == TYPE_CODE_CLASS))
466         real_type = value_rtti_indirect_type (val, &full, &top, &using_enc);
467       else if (TYPE_CODE (type) == TYPE_CODE_CLASS)
468         real_type = value_rtti_type (val, &full, &top, &using_enc);
469     }
470
471   printf_filtered ("type = ");
472
473   if (!flags.raw)
474     create_global_typedef_table (&flags);
475
476   if (real_type)
477     {
478       printf_filtered ("/* real type = ");
479       type_print (real_type, "", gdb_stdout, -1);
480       if (! full)
481         printf_filtered (" (incomplete object)");
482       printf_filtered (" */\n");    
483     }
484
485   LA_PRINT_TYPE (type, "", gdb_stdout, show, 0, &flags);
486   printf_filtered ("\n");
487
488   do_cleanups (old_chain);
489 }
490
491 static void
492 whatis_command (char *exp, int from_tty)
493 {
494   /* Most of the time users do not want to see all the fields
495      in a structure.  If they do they can use the "ptype" command.
496      Hence the "-1" below.  */
497   whatis_exp (exp, -1);
498 }
499
500 /* TYPENAME is either the name of a type, or an expression.  */
501
502 static void
503 ptype_command (char *typename, int from_tty)
504 {
505   whatis_exp (typename, 1);
506 }
507
508 /* Print integral scalar data VAL, of type TYPE, onto stdio stream STREAM.
509    Used to print data from type structures in a specified type.  For example,
510    array bounds may be characters or booleans in some languages, and this
511    allows the ranges to be printed in their "natural" form rather than as
512    decimal integer values.
513
514    FIXME:  This is here simply because only the type printing routines
515    currently use it, and it wasn't clear if it really belonged somewhere
516    else (like printcmd.c).  There are a lot of other gdb routines that do
517    something similar, but they are generally concerned with printing values
518    that come from the inferior in target byte order and target size.  */
519
520 void
521 print_type_scalar (struct type *type, LONGEST val, struct ui_file *stream)
522 {
523   unsigned int i;
524   unsigned len;
525
526   CHECK_TYPEDEF (type);
527
528   switch (TYPE_CODE (type))
529     {
530
531     case TYPE_CODE_ENUM:
532       len = TYPE_NFIELDS (type);
533       for (i = 0; i < len; i++)
534         {
535           if (TYPE_FIELD_ENUMVAL (type, i) == val)
536             {
537               break;
538             }
539         }
540       if (i < len)
541         {
542           fputs_filtered (TYPE_FIELD_NAME (type, i), stream);
543         }
544       else
545         {
546           print_longest (stream, 'd', 0, val);
547         }
548       break;
549
550     case TYPE_CODE_INT:
551       print_longest (stream, TYPE_UNSIGNED (type) ? 'u' : 'd', 0, val);
552       break;
553
554     case TYPE_CODE_CHAR:
555       LA_PRINT_CHAR ((unsigned char) val, type, stream);
556       break;
557
558     case TYPE_CODE_BOOL:
559       fprintf_filtered (stream, val ? "TRUE" : "FALSE");
560       break;
561
562     case TYPE_CODE_RANGE:
563       print_type_scalar (TYPE_TARGET_TYPE (type), val, stream);
564       return;
565
566     case TYPE_CODE_UNDEF:
567     case TYPE_CODE_PTR:
568     case TYPE_CODE_ARRAY:
569     case TYPE_CODE_STRUCT:
570     case TYPE_CODE_UNION:
571     case TYPE_CODE_FUNC:
572     case TYPE_CODE_FLT:
573     case TYPE_CODE_VOID:
574     case TYPE_CODE_SET:
575     case TYPE_CODE_STRING:
576     case TYPE_CODE_ERROR:
577     case TYPE_CODE_MEMBERPTR:
578     case TYPE_CODE_METHODPTR:
579     case TYPE_CODE_METHOD:
580     case TYPE_CODE_REF:
581     case TYPE_CODE_NAMESPACE:
582       error (_("internal error: unhandled type in print_type_scalar"));
583       break;
584
585     default:
586       error (_("Invalid type code in symbol table."));
587     }
588   gdb_flush (stream);
589 }
590
591 /* Dump details of a type specified either directly or indirectly.
592    Uses the same sort of type lookup mechanism as ptype_command()
593    and whatis_command().  */
594
595 void
596 maintenance_print_type (char *typename, int from_tty)
597 {
598   struct value *val;
599   struct type *type;
600   struct cleanup *old_chain;
601   struct expression *expr;
602
603   if (typename != NULL)
604     {
605       expr = parse_expression (typename);
606       old_chain = make_cleanup (free_current_contents, &expr);
607       if (expr->elts[0].opcode == OP_TYPE)
608         {
609           /* The user expression names a type directly, just use that type.  */
610           type = expr->elts[1].type;
611         }
612       else
613         {
614           /* The user expression may name a type indirectly by naming an
615              object of that type.  Find that indirectly named type.  */
616           val = evaluate_type (expr);
617           type = value_type (val);
618         }
619       if (type != NULL)
620         {
621           recursive_dump_type (type, 0);
622         }
623       do_cleanups (old_chain);
624     }
625 }
626 \f
627
628 struct cmd_list_element *setprinttypelist;
629
630 struct cmd_list_element *showprinttypelist;
631
632 static void
633 set_print_type (char *arg, int from_tty)
634 {
635   printf_unfiltered (
636      "\"set print type\" must be followed by the name of a subcommand.\n");
637   help_list (setprintlist, "set print type ", all_commands, gdb_stdout);
638 }
639
640 static void
641 show_print_type (char *args, int from_tty)
642 {
643   cmd_show_list (showprinttypelist, from_tty, "");
644 }
645
646 static int print_methods = 1;
647
648 static void
649 set_print_type_methods (char *args, int from_tty, struct cmd_list_element *c)
650 {
651   default_ptype_flags.print_methods = print_methods;
652 }
653
654 static void
655 show_print_type_methods (struct ui_file *file, int from_tty,
656                          struct cmd_list_element *c, const char *value)
657 {
658   fprintf_filtered (file, _("Printing of methods defined in a class in %s\n"),
659                     value);
660 }
661
662 static int print_typedefs = 1;
663
664 static void
665 set_print_type_typedefs (char *args, int from_tty, struct cmd_list_element *c)
666 {
667   default_ptype_flags.print_typedefs = print_typedefs;
668 }
669
670 static void
671 show_print_type_typedefs (struct ui_file *file, int from_tty,
672                          struct cmd_list_element *c, const char *value)
673 {
674   fprintf_filtered (file, _("Printing of typedefs defined in a class in %s\n"),
675                     value);
676 }
677
678 void
679 _initialize_typeprint (void)
680 {
681   struct cmd_list_element *c;
682
683   c = add_com ("ptype", class_vars, ptype_command, _("\
684 Print definition of type TYPE.\n\
685 Usage: ptype[/FLAGS] TYPE | EXPRESSION\n\
686 Argument may be any type (for example a type name defined by typedef,\n\
687 or \"struct STRUCT-TAG\" or \"class CLASS-NAME\" or \"union UNION-TAG\"\n\
688 or \"enum ENUM-TAG\") or an expression.\n\
689 The selected stack frame's lexical context is used to look up the name.\n\
690 Contrary to \"whatis\", \"ptype\" always unrolls any typedefs.\n\
691 \n\
692 Available FLAGS are:\n\
693   /r    print in \"raw\" form; do not substitute typedefs\n\
694   /m    do not print methods defined in a class\n\
695   /M    print methods defined in a class\n\
696   /t    do not print typedefs defined in a class\n\
697   /T    print typedefs defined in a class"));
698   set_cmd_completer (c, expression_completer);
699
700   c = add_com ("whatis", class_vars, whatis_command,
701                _("Print data type of expression EXP.\n\
702 Only one level of typedefs is unrolled.  See also \"ptype\"."));
703   set_cmd_completer (c, expression_completer);
704
705   add_prefix_cmd ("type", no_class, show_print_type,
706                   _("Generic command for showing type-printing settings."),
707                   &showprinttypelist, "show print type ", 0, &showprintlist);
708   add_prefix_cmd ("type", no_class, set_print_type,
709                   _("Generic command for setting how types print."),
710                   &setprinttypelist, "show print type ", 0, &setprintlist);
711
712   add_setshow_boolean_cmd ("methods", no_class, &print_methods,
713                            _("\
714 Set printing of methods defined in classes."), _("\
715 Show printing of methods defined in classes."), NULL,
716                            set_print_type_methods,
717                            show_print_type_methods,
718                            &setprinttypelist, &showprinttypelist);
719   add_setshow_boolean_cmd ("typedefs", no_class, &print_typedefs,
720                            _("\
721 Set printing of typedefs defined in classes."), _("\
722 Show printing of typedefs defined in classes."), NULL,
723                            set_print_type_typedefs,
724                            show_print_type_typedefs,
725                            &setprinttypelist, &showprinttypelist);
726 }