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