* python/py-cmd.c (gdbpy_string_to_argv): Decrement reference
[platform/upstream/binutils.git] / gdb / python / py-type.c
1 /* Python interface to types.
2
3    Copyright (C) 2008, 2009, 2010, 2011 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 "value.h"
22 #include "exceptions.h"
23 #include "python-internal.h"
24 #include "charset.h"
25 #include "gdbtypes.h"
26 #include "cp-support.h"
27 #include "demangle.h"
28 #include "objfiles.h"
29 #include "language.h"
30 #include "vec.h"
31 #include "bcache.h"
32
33 typedef struct pyty_type_object
34 {
35   PyObject_HEAD
36   struct type *type;
37
38   /* If a Type object is associated with an objfile, it is kept on a
39      doubly-linked list, rooted in the objfile.  This lets us copy the
40      underlying struct type when the objfile is deleted.  */
41   struct pyty_type_object *prev;
42   struct pyty_type_object *next;
43 } type_object;
44
45 static PyTypeObject type_object_type;
46
47 /* A Field object.  */
48 typedef struct pyty_field_object
49 {
50   PyObject_HEAD
51
52   /* Dictionary holding our attributes.  */
53   PyObject *dict;
54 } field_object;
55
56 static PyTypeObject field_object_type;
57
58 /* This is used to initialize various gdb.TYPE_ constants.  */
59 struct pyty_code
60 {
61   /* The code.  */
62   enum type_code code;
63   /* The name.  */
64   const char *name;
65 };
66
67 #define ENTRY(X) { X, #X }
68
69 static struct pyty_code pyty_codes[] =
70 {
71   ENTRY (TYPE_CODE_PTR),
72   ENTRY (TYPE_CODE_ARRAY),
73   ENTRY (TYPE_CODE_STRUCT),
74   ENTRY (TYPE_CODE_UNION),
75   ENTRY (TYPE_CODE_ENUM),
76   ENTRY (TYPE_CODE_FLAGS),
77   ENTRY (TYPE_CODE_FUNC),
78   ENTRY (TYPE_CODE_INT),
79   ENTRY (TYPE_CODE_FLT),
80   ENTRY (TYPE_CODE_VOID),
81   ENTRY (TYPE_CODE_SET),
82   ENTRY (TYPE_CODE_RANGE),
83   ENTRY (TYPE_CODE_STRING),
84   ENTRY (TYPE_CODE_BITSTRING),
85   ENTRY (TYPE_CODE_ERROR),
86   ENTRY (TYPE_CODE_METHOD),
87   ENTRY (TYPE_CODE_METHODPTR),
88   ENTRY (TYPE_CODE_MEMBERPTR),
89   ENTRY (TYPE_CODE_REF),
90   ENTRY (TYPE_CODE_CHAR),
91   ENTRY (TYPE_CODE_BOOL),
92   ENTRY (TYPE_CODE_COMPLEX),
93   ENTRY (TYPE_CODE_TYPEDEF),
94   ENTRY (TYPE_CODE_NAMESPACE),
95   ENTRY (TYPE_CODE_DECFLOAT),
96   ENTRY (TYPE_CODE_INTERNAL_FUNCTION),
97   { TYPE_CODE_UNDEF, NULL }
98 };
99
100 \f
101
102 static void
103 field_dealloc (PyObject *obj)
104 {
105   field_object *f = (field_object *) obj;
106
107   Py_XDECREF (f->dict);
108   f->ob_type->tp_free (obj);
109 }
110
111 static PyObject *
112 field_new (void)
113 {
114   field_object *result = PyObject_New (field_object, &field_object_type);
115
116   if (result)
117     {
118       result->dict = PyDict_New ();
119       if (!result->dict)
120         {
121           Py_DECREF (result);
122           result = NULL;
123         }
124     }
125   return (PyObject *) result;
126 }
127
128 \f
129
130 /* Return the code for this type.  */
131 static PyObject *
132 typy_get_code (PyObject *self, void *closure)
133 {
134   struct type *type = ((type_object *) self)->type;
135
136   return PyInt_FromLong (TYPE_CODE (type));
137 }
138
139 /* Helper function for typy_fields which converts a single field to a
140    dictionary.  Returns NULL on error.  */
141 static PyObject *
142 convert_field (struct type *type, int field)
143 {
144   PyObject *result = field_new ();
145   PyObject *arg;
146
147   if (!result)
148     return NULL;
149
150   if (!field_is_static (&TYPE_FIELD (type, field)))
151     {
152       arg = PyLong_FromLong (TYPE_FIELD_BITPOS (type, field));
153       if (!arg)
154         goto fail;
155
156       if (PyObject_SetAttrString (result, "bitpos", arg) < 0)
157         goto failarg;
158     }
159
160   if (TYPE_FIELD_NAME (type, field))
161     arg = PyString_FromString (TYPE_FIELD_NAME (type, field));
162   else
163     {
164       arg = Py_None;
165       Py_INCREF (arg);
166     }
167   if (!arg)
168     goto fail;
169   if (PyObject_SetAttrString (result, "name", arg) < 0)
170     goto failarg;
171
172   arg = TYPE_FIELD_ARTIFICIAL (type, field) ? Py_True : Py_False;
173   Py_INCREF (arg);
174   if (PyObject_SetAttrString (result, "artificial", arg) < 0)
175     goto failarg;
176
177   if (TYPE_CODE (type) == TYPE_CODE_CLASS)
178     arg = field < TYPE_N_BASECLASSES (type) ? Py_True : Py_False;
179   else
180     arg = Py_False;
181   Py_INCREF (arg);
182   if (PyObject_SetAttrString (result, "is_base_class", arg) < 0)
183     goto failarg;
184
185   arg = PyLong_FromLong (TYPE_FIELD_BITSIZE (type, field));
186   if (!arg)
187     goto fail;
188   if (PyObject_SetAttrString (result, "bitsize", arg) < 0)
189     goto failarg;
190
191   /* A field can have a NULL type in some situations.  */
192   if (TYPE_FIELD_TYPE (type, field) == NULL)
193     {
194       arg = Py_None;
195       Py_INCREF (arg);
196     }
197   else
198     arg = type_to_type_object (TYPE_FIELD_TYPE (type, field));
199   if (!arg)
200     goto fail;
201   if (PyObject_SetAttrString (result, "type", arg) < 0)
202     goto failarg;
203
204   return result;
205
206  failarg:
207   Py_DECREF (arg);
208  fail:
209   Py_DECREF (result);
210   return NULL;
211 }
212
213 /* Return a sequence of all fields.  Each field is a dictionary with
214    some pre-defined keys.  */
215 static PyObject *
216 typy_fields (PyObject *self, PyObject *args)
217 {
218   PyObject *result;
219   int i;
220   struct type *type = ((type_object *) self)->type;
221   volatile struct gdb_exception except;
222
223   TRY_CATCH (except, RETURN_MASK_ALL)
224     {
225       CHECK_TYPEDEF (type);
226     }
227   GDB_PY_HANDLE_EXCEPTION (except);
228
229   /* We would like to make a tuple here, make fields immutable, and
230      then memoize the result (and perhaps make Field.type() lazy).
231      However, that can lead to cycles.  */
232   result = PyList_New (0);
233
234   for (i = 0; i < TYPE_NFIELDS (type); ++i)
235     {
236       PyObject *dict = convert_field (type, i);
237
238       if (!dict)
239         {
240           Py_DECREF (result);
241           return NULL;
242         }
243       if (PyList_Append (result, dict))
244         {
245           Py_DECREF (dict);
246           Py_DECREF (result);
247           return NULL;
248         }
249       Py_DECREF (dict);
250     }
251
252   return result;
253 }
254
255 /* Return the type's tag, or None.  */
256 static PyObject *
257 typy_get_tag (PyObject *self, void *closure)
258 {
259   struct type *type = ((type_object *) self)->type;
260
261   if (!TYPE_TAG_NAME (type))
262     Py_RETURN_NONE;
263   return PyString_FromString (TYPE_TAG_NAME (type));
264 }
265
266 /* Return the type, stripped of typedefs. */
267 static PyObject *
268 typy_strip_typedefs (PyObject *self, PyObject *args)
269 {
270   struct type *type = ((type_object *) self)->type;
271
272   return type_to_type_object (check_typedef (type));
273 }
274
275 /* Return an array type.  */
276
277 static PyObject *
278 typy_array (PyObject *self, PyObject *args)
279 {
280   long n1, n2;
281   PyObject *n2_obj = NULL;
282   struct type *array = NULL;
283   struct type *type = ((type_object *) self)->type;
284   volatile struct gdb_exception except;
285
286   if (! PyArg_ParseTuple (args, "l|O", &n1, &n2_obj))
287     return NULL;
288
289   if (n2_obj)
290     {
291       if (!PyInt_Check (n2_obj))
292         {
293           PyErr_SetString (PyExc_RuntimeError,
294                            _("Array bound must be an integer"));
295           return NULL;
296         }
297
298       if (! gdb_py_int_as_long (n2_obj, &n2))
299         return NULL;
300     }
301   else
302     {
303       n2 = n1;
304       n1 = 0;
305     }
306
307   if (n2 < n1)
308     {
309       PyErr_SetString (PyExc_ValueError,
310                        _("Array length must not be negative"));
311       return NULL;
312     }
313
314   TRY_CATCH (except, RETURN_MASK_ALL)
315     {
316       array = lookup_array_range_type (type, n1, n2);
317     }
318   GDB_PY_HANDLE_EXCEPTION (except);
319
320   return type_to_type_object (array);
321 }
322
323 /* Return a Type object which represents a pointer to SELF.  */
324 static PyObject *
325 typy_pointer (PyObject *self, PyObject *args)
326 {
327   struct type *type = ((type_object *) self)->type;
328   volatile struct gdb_exception except;
329
330   TRY_CATCH (except, RETURN_MASK_ALL)
331     {
332       type = lookup_pointer_type (type);
333     }
334   GDB_PY_HANDLE_EXCEPTION (except);
335
336   return type_to_type_object (type);
337 }
338
339 /* Return the range of a type represented by SELF.  The return type is
340    a tuple.  The first element of the tuple contains the low bound,
341    while the second element of the tuple contains the high bound.  */
342 static PyObject *
343 typy_range (PyObject *self, PyObject *args)
344 {
345   struct type *type = ((type_object *) self)->type;
346   PyObject *result;
347   PyObject *low_bound = NULL, *high_bound = NULL;
348   /* Initialize these to appease GCC warnings.  */
349   LONGEST low = 0, high = 0;
350
351   if (TYPE_CODE (type) != TYPE_CODE_ARRAY
352       && TYPE_CODE (type) != TYPE_CODE_STRING
353       && TYPE_CODE (type) != TYPE_CODE_RANGE)
354     {
355       PyErr_SetString (PyExc_RuntimeError,
356                        _("This type does not have a range."));
357       return NULL;
358     }
359
360   switch (TYPE_CODE (type))
361     {
362     case TYPE_CODE_ARRAY:
363     case TYPE_CODE_STRING:
364       low = TYPE_LOW_BOUND (TYPE_INDEX_TYPE (type));
365       high = TYPE_HIGH_BOUND (TYPE_INDEX_TYPE (type));
366       break;
367     case TYPE_CODE_RANGE:
368       low = TYPE_LOW_BOUND (type);
369       high = TYPE_HIGH_BOUND (type);
370       break;
371     }
372
373   low_bound = PyLong_FromLong (low);
374   if (!low_bound)
375     goto failarg;
376
377   high_bound = PyLong_FromLong (high);
378   if (!high_bound)
379     goto failarg;
380
381   result = PyTuple_New (2);
382   if (!result)
383     goto failarg;
384
385   if (PyTuple_SetItem (result, 0, low_bound) != 0)
386     {
387       Py_DECREF (result);
388       goto failarg;
389     }
390   if (PyTuple_SetItem (result, 1, high_bound) != 0)
391     {
392       Py_DECREF (high_bound);
393       Py_DECREF (result);
394       return NULL;
395     }
396   return result;
397   
398  failarg:
399   Py_XDECREF (high_bound);
400   Py_XDECREF (low_bound);
401   return NULL;
402 }
403
404 /* Return a Type object which represents a reference to SELF.  */
405 static PyObject *
406 typy_reference (PyObject *self, PyObject *args)
407 {
408   struct type *type = ((type_object *) self)->type;
409   volatile struct gdb_exception except;
410
411   TRY_CATCH (except, RETURN_MASK_ALL)
412     {
413       type = lookup_reference_type (type);
414     }
415   GDB_PY_HANDLE_EXCEPTION (except);
416
417   return type_to_type_object (type);
418 }
419
420 /* Return a Type object which represents the target type of SELF.  */
421 static PyObject *
422 typy_target (PyObject *self, PyObject *args)
423 {
424   struct type *type = ((type_object *) self)->type;
425
426   if (!TYPE_TARGET_TYPE (type))
427     {
428       PyErr_SetString (PyExc_RuntimeError, 
429                        _("Type does not have a target."));
430       return NULL;
431     }
432
433   return type_to_type_object (TYPE_TARGET_TYPE (type));
434 }
435
436 /* Return a const-qualified type variant.  */
437 static PyObject *
438 typy_const (PyObject *self, PyObject *args)
439 {
440   struct type *type = ((type_object *) self)->type;
441   volatile struct gdb_exception except;
442
443   TRY_CATCH (except, RETURN_MASK_ALL)
444     {
445       type = make_cv_type (1, 0, type, NULL);
446     }
447   GDB_PY_HANDLE_EXCEPTION (except);
448
449   return type_to_type_object (type);
450 }
451
452 /* Return a volatile-qualified type variant.  */
453 static PyObject *
454 typy_volatile (PyObject *self, PyObject *args)
455 {
456   struct type *type = ((type_object *) self)->type;
457   volatile struct gdb_exception except;
458
459   TRY_CATCH (except, RETURN_MASK_ALL)
460     {
461       type = make_cv_type (0, 1, type, NULL);
462     }
463   GDB_PY_HANDLE_EXCEPTION (except);
464
465   return type_to_type_object (type);
466 }
467
468 /* Return an unqualified type variant.  */
469 static PyObject *
470 typy_unqualified (PyObject *self, PyObject *args)
471 {
472   struct type *type = ((type_object *) self)->type;
473   volatile struct gdb_exception except;
474
475   TRY_CATCH (except, RETURN_MASK_ALL)
476     {
477       type = make_cv_type (0, 0, type, NULL);
478     }
479   GDB_PY_HANDLE_EXCEPTION (except);
480
481   return type_to_type_object (type);
482 }
483
484 /* Return the size of the type represented by SELF, in bytes.  */
485 static PyObject *
486 typy_get_sizeof (PyObject *self, void *closure)
487 {
488   struct type *type = ((type_object *) self)->type;
489   volatile struct gdb_exception except;
490
491   TRY_CATCH (except, RETURN_MASK_ALL)
492     {
493       check_typedef (type);
494     }
495   /* Ignore exceptions.  */
496
497   return PyLong_FromLong (TYPE_LENGTH (type));
498 }
499
500 static struct type *
501 typy_lookup_typename (const char *type_name, struct block *block)
502 {
503   struct type *type = NULL;
504   volatile struct gdb_exception except;
505
506   TRY_CATCH (except, RETURN_MASK_ALL)
507     {
508       if (!strncmp (type_name, "struct ", 7))
509         type = lookup_struct (type_name + 7, NULL);
510       else if (!strncmp (type_name, "union ", 6))
511         type = lookup_union (type_name + 6, NULL);
512       else if (!strncmp (type_name, "enum ", 5))
513         type = lookup_enum (type_name + 5, NULL);
514       else
515         type = lookup_typename (python_language, python_gdbarch,
516                                 type_name, block, 0);
517     }
518   if (except.reason < 0)
519     {
520       PyErr_Format (except.reason == RETURN_QUIT
521                     ? PyExc_KeyboardInterrupt : PyExc_RuntimeError,
522                     "%s", except.message);
523       return NULL;
524     }
525
526   return type;
527 }
528
529 static struct type *
530 typy_lookup_type (struct demangle_component *demangled,
531                   struct block *block)
532 {
533   struct type *type;
534   char *type_name;
535   enum demangle_component_type demangled_type;
536
537   /* Save the type: typy_lookup_type() may (indirectly) overwrite
538      memory pointed by demangled.  */
539   demangled_type = demangled->type;
540
541   if (demangled_type == DEMANGLE_COMPONENT_POINTER
542       || demangled_type == DEMANGLE_COMPONENT_REFERENCE
543       || demangled_type == DEMANGLE_COMPONENT_CONST
544       || demangled_type == DEMANGLE_COMPONENT_VOLATILE)
545     {
546       type = typy_lookup_type (demangled->u.s_binary.left, block);
547       if (! type)
548         return NULL;
549
550       switch (demangled_type)
551         {
552         case DEMANGLE_COMPONENT_REFERENCE:
553           return lookup_reference_type (type);
554         case DEMANGLE_COMPONENT_POINTER:
555           return lookup_pointer_type (type);
556         case DEMANGLE_COMPONENT_CONST:
557           return make_cv_type (1, 0, type, NULL);
558         case DEMANGLE_COMPONENT_VOLATILE:
559           return make_cv_type (0, 1, type, NULL);
560         }
561     }
562
563   type_name = cp_comp_to_string (demangled, 10);
564   type = typy_lookup_typename (type_name, block);
565   xfree (type_name);
566
567   return type;
568 }
569
570 /* This is a helper function for typy_template_argument that is used
571    when the type does not have template symbols attached.  It works by
572    parsing the type name.  This happens with compilers, like older
573    versions of GCC, that do not emit DW_TAG_template_*.  */
574
575 static PyObject *
576 typy_legacy_template_argument (struct type *type, struct block *block,
577                                int argno)
578 {
579   int i;
580   struct demangle_component *demangled;
581   struct demangle_parse_info *info;
582   const char *err;
583   struct type *argtype;
584   struct cleanup *cleanup;
585
586   if (TYPE_NAME (type) == NULL)
587     {
588       PyErr_SetString (PyExc_RuntimeError, _("Null type name."));
589       return NULL;
590     }
591
592   /* Note -- this is not thread-safe.  */
593   info = cp_demangled_name_to_comp (TYPE_NAME (type), &err);
594   if (! info)
595     {
596       PyErr_SetString (PyExc_RuntimeError, err);
597       return NULL;
598     }
599   demangled = info->tree;
600   cleanup = make_cleanup_cp_demangled_name_parse_free (info);
601
602   /* Strip off component names.  */
603   while (demangled->type == DEMANGLE_COMPONENT_QUAL_NAME
604          || demangled->type == DEMANGLE_COMPONENT_LOCAL_NAME)
605     demangled = demangled->u.s_binary.right;
606
607   if (demangled->type != DEMANGLE_COMPONENT_TEMPLATE)
608     {
609       do_cleanups (cleanup);
610       PyErr_SetString (PyExc_RuntimeError, _("Type is not a template."));
611       return NULL;
612     }
613
614   /* Skip from the template to the arguments.  */
615   demangled = demangled->u.s_binary.right;
616
617   for (i = 0; demangled && i < argno; ++i)
618     demangled = demangled->u.s_binary.right;
619
620   if (! demangled)
621     {
622       do_cleanups (cleanup);
623       PyErr_Format (PyExc_RuntimeError, _("No argument %d in template."),
624                     argno);
625       return NULL;
626     }
627
628   argtype = typy_lookup_type (demangled->u.s_binary.left, block);
629   do_cleanups (cleanup);
630   if (! argtype)
631     return NULL;
632
633   return type_to_type_object (argtype);
634 }
635
636 static PyObject *
637 typy_template_argument (PyObject *self, PyObject *args)
638 {
639   int argno;
640   struct type *type = ((type_object *) self)->type;
641   struct block *block = NULL;
642   PyObject *block_obj = NULL;
643   struct symbol *sym;
644   struct value *val = NULL;
645   volatile struct gdb_exception except;
646
647   if (! PyArg_ParseTuple (args, "i|O", &argno, &block_obj))
648     return NULL;
649
650   if (block_obj)
651     {
652       block = block_object_to_block (block_obj);
653       if (! block)
654         {
655           PyErr_SetString (PyExc_RuntimeError,
656                            _("Second argument must be block."));
657           return NULL;
658         }
659     }
660
661   TRY_CATCH (except, RETURN_MASK_ALL)
662     {
663       type = check_typedef (type);
664       if (TYPE_CODE (type) == TYPE_CODE_REF)
665         type = check_typedef (TYPE_TARGET_TYPE (type));
666     }
667   GDB_PY_HANDLE_EXCEPTION (except);
668
669   /* We might not have DW_TAG_template_*, so try to parse the type's
670      name.  This is inefficient if we do not have a template type --
671      but that is going to wind up as an error anyhow.  */
672   if (! TYPE_N_TEMPLATE_ARGUMENTS (type))
673     return typy_legacy_template_argument (type, block, argno);
674
675   if (argno >= TYPE_N_TEMPLATE_ARGUMENTS (type))
676     {
677       PyErr_Format (PyExc_RuntimeError, _("No argument %d in template."),
678                     argno);
679       return NULL;
680     }
681
682   sym = TYPE_TEMPLATE_ARGUMENT (type, argno);
683   if (SYMBOL_CLASS (sym) == LOC_TYPEDEF)
684     return type_to_type_object (SYMBOL_TYPE (sym));
685   else if (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT)
686     {
687       PyErr_Format (PyExc_RuntimeError,
688                     _("Template argument is optimized out"));
689       return NULL;
690     }
691
692   TRY_CATCH (except, RETURN_MASK_ALL)
693     {
694       val = value_of_variable (sym, block);
695     }
696   GDB_PY_HANDLE_EXCEPTION (except);
697
698   return value_to_value_object (val);
699 }
700
701 static PyObject *
702 typy_str (PyObject *self)
703 {
704   volatile struct gdb_exception except;
705   char *thetype = NULL;
706   long length = 0;
707   PyObject *result;
708
709   TRY_CATCH (except, RETURN_MASK_ALL)
710     {
711       struct cleanup *old_chain;
712       struct ui_file *stb;
713
714       stb = mem_fileopen ();
715       old_chain = make_cleanup_ui_file_delete (stb);
716
717       type_print (type_object_to_type (self), "", stb, -1);
718
719       thetype = ui_file_xstrdup (stb, &length);
720       do_cleanups (old_chain);
721     }
722   if (except.reason < 0)
723     {
724       xfree (thetype);
725       GDB_PY_HANDLE_EXCEPTION (except);
726     }
727
728   result = PyUnicode_Decode (thetype, length, host_charset (), NULL);
729   xfree (thetype);
730
731   return result;
732 }
733
734 /* An entry in the type-equality bcache.  */
735
736 typedef struct type_equality_entry
737 {
738   struct type *type1, *type2;
739 } type_equality_entry_d;
740
741 DEF_VEC_O (type_equality_entry_d);
742
743 /* A helper function to compare two strings.  Returns 1 if they are
744    the same, 0 otherwise.  Handles NULLs properly.  */
745
746 static int
747 compare_strings (const char *s, const char *t)
748 {
749   if (s == NULL && t != NULL)
750     return 0;
751   else if (s != NULL && t == NULL)
752     return 0;
753   else if (s == NULL && t== NULL)
754     return 1;
755   return strcmp (s, t) == 0;
756 }
757
758 /* A helper function for typy_richcompare that checks two types for
759    "deep" equality.  Returns Py_EQ if the types are considered the
760    same, Py_NE otherwise.  */
761
762 static int
763 check_types_equal (struct type *type1, struct type *type2,
764                    VEC (type_equality_entry_d) **worklist)
765 {
766   CHECK_TYPEDEF (type1);
767   CHECK_TYPEDEF (type2);
768
769   if (type1 == type2)
770     return Py_EQ;
771
772   if (TYPE_CODE (type1) != TYPE_CODE (type2)
773       || TYPE_LENGTH (type1) != TYPE_LENGTH (type2)
774       || TYPE_UNSIGNED (type1) != TYPE_UNSIGNED (type2)
775       || TYPE_NOSIGN (type1) != TYPE_NOSIGN (type2)
776       || TYPE_VARARGS (type1) != TYPE_VARARGS (type2)
777       || TYPE_VECTOR (type1) != TYPE_VECTOR (type2)
778       || TYPE_NOTTEXT (type1) != TYPE_NOTTEXT (type2)
779       || TYPE_INSTANCE_FLAGS (type1) != TYPE_INSTANCE_FLAGS (type2)
780       || TYPE_NFIELDS (type1) != TYPE_NFIELDS (type2))
781     return Py_NE;
782
783   if (!compare_strings (TYPE_TAG_NAME (type1), TYPE_TAG_NAME (type2)))
784     return Py_NE;
785   if (!compare_strings (TYPE_NAME (type1), TYPE_NAME (type2)))
786     return Py_NE;
787
788   if (TYPE_CODE (type1) == TYPE_CODE_RANGE)
789     {
790       if (memcmp (TYPE_RANGE_DATA (type1), TYPE_RANGE_DATA (type2),
791                   sizeof (*TYPE_RANGE_DATA (type1))) != 0)
792         return Py_NE;
793     }
794   else
795     {
796       int i;
797
798       for (i = 0; i < TYPE_NFIELDS (type1); ++i)
799         {
800           const struct field *field1 = &TYPE_FIELD (type1, i);
801           const struct field *field2 = &TYPE_FIELD (type2, i);
802           struct type_equality_entry entry;
803
804           if (FIELD_ARTIFICIAL (*field1) != FIELD_ARTIFICIAL (*field2)
805               || FIELD_BITSIZE (*field1) != FIELD_BITSIZE (*field2)
806               || FIELD_LOC_KIND (*field1) != FIELD_LOC_KIND (*field2))
807             return Py_NE;
808           if (!compare_strings (FIELD_NAME (*field1), FIELD_NAME (*field2)))
809             return Py_NE;
810           switch (FIELD_LOC_KIND (*field1))
811             {
812             case FIELD_LOC_KIND_BITPOS:
813               if (FIELD_BITPOS (*field1) != FIELD_BITPOS (*field2))
814                 return Py_NE;
815               break;
816             case FIELD_LOC_KIND_PHYSADDR:
817               if (FIELD_STATIC_PHYSADDR (*field1)
818                   != FIELD_STATIC_PHYSADDR (*field2))
819                 return Py_NE;
820               break;
821             case FIELD_LOC_KIND_PHYSNAME:
822               if (!compare_strings (FIELD_STATIC_PHYSNAME (*field1),
823                                     FIELD_STATIC_PHYSNAME (*field2)))
824                 return Py_NE;
825               break;
826             }
827
828           entry.type1 = FIELD_TYPE (*field1);
829           entry.type2 = FIELD_TYPE (*field2);
830           VEC_safe_push (type_equality_entry_d, *worklist, &entry);
831         }
832     }
833
834   if (TYPE_TARGET_TYPE (type1) != NULL)
835     {
836       struct type_equality_entry entry;
837       int added;
838
839       if (TYPE_TARGET_TYPE (type2) == NULL)
840         return Py_NE;
841
842       entry.type1 = TYPE_TARGET_TYPE (type1);
843       entry.type2 = TYPE_TARGET_TYPE (type2);
844       VEC_safe_push (type_equality_entry_d, *worklist, &entry);
845     }
846   else if (TYPE_TARGET_TYPE (type2) != NULL)
847     return Py_NE;
848
849   return Py_EQ;
850 }
851
852 /* Check types on a worklist for equality.  Returns Py_NE if any pair
853    is not equal, Py_EQ if they are all considered equal.  */
854
855 static int
856 check_types_worklist (VEC (type_equality_entry_d) **worklist,
857                       struct bcache *cache)
858 {
859   while (!VEC_empty (type_equality_entry_d, *worklist))
860     {
861       struct type_equality_entry entry;
862       int added;
863
864       entry = *VEC_last (type_equality_entry_d, *worklist);
865       VEC_pop (type_equality_entry_d, *worklist);
866
867       /* If the type pair has already been visited, we know it is
868          ok.  */
869       bcache_full (&entry, sizeof (entry), cache, &added);
870       if (!added)
871         continue;
872
873       if (check_types_equal (entry.type1, entry.type2, worklist) == Py_NE)
874         return Py_NE;
875     }
876
877   return Py_EQ;
878 }
879
880 /* Implement the richcompare method.  */
881
882 static PyObject *
883 typy_richcompare (PyObject *self, PyObject *other, int op)
884 {
885   int result = Py_NE;
886   struct type *type1 = type_object_to_type (self);
887   struct type *type2 = type_object_to_type (other);
888   volatile struct gdb_exception except;
889
890   /* We can only compare ourselves to another Type object, and only
891      for equality or inequality.  */
892   if (type2 == NULL || (op != Py_EQ && op != Py_NE))
893     {
894       Py_INCREF (Py_NotImplemented);
895       return Py_NotImplemented;
896     }
897
898   if (type1 == type2)
899     result = Py_EQ;
900   else
901     {
902       struct bcache *cache;
903       VEC (type_equality_entry_d) *worklist = NULL;
904       struct type_equality_entry entry;
905
906       cache = bcache_xmalloc (NULL, NULL);
907
908       entry.type1 = type1;
909       entry.type2 = type2;
910       VEC_safe_push (type_equality_entry_d, worklist, &entry);
911
912       TRY_CATCH (except, RETURN_MASK_ALL)
913         {
914           result = check_types_worklist (&worklist, cache);
915         }
916       if (except.reason < 0)
917         result = Py_NE;
918
919       bcache_xfree (cache);
920       VEC_free (type_equality_entry_d, worklist);
921     }
922
923   if (op == result)
924     Py_RETURN_TRUE;
925   Py_RETURN_FALSE;
926 }
927
928 \f
929
930 static const struct objfile_data *typy_objfile_data_key;
931
932 static void
933 save_objfile_types (struct objfile *objfile, void *datum)
934 {
935   type_object *obj = datum;
936   htab_t copied_types;
937   struct cleanup *cleanup;
938
939   /* This prevents another thread from freeing the objects we're
940      operating on.  */
941   cleanup = ensure_python_env (get_objfile_arch (objfile), current_language);
942
943   copied_types = create_copied_types_hash (objfile);
944
945   while (obj)
946     {
947       type_object *next = obj->next;
948
949       htab_empty (copied_types);
950
951       obj->type = copy_type_recursive (objfile, obj->type, copied_types);
952
953       obj->next = NULL;
954       obj->prev = NULL;
955
956       obj = next;
957     }
958
959   htab_delete (copied_types);
960
961   do_cleanups (cleanup);
962 }
963
964 static void
965 set_type (type_object *obj, struct type *type)
966 {
967   obj->type = type;
968   obj->prev = NULL;
969   if (type && TYPE_OBJFILE (type))
970     {
971       struct objfile *objfile = TYPE_OBJFILE (type);
972
973       obj->next = objfile_data (objfile, typy_objfile_data_key);
974       if (obj->next)
975         obj->next->prev = obj;
976       set_objfile_data (objfile, typy_objfile_data_key, obj);
977     }
978   else
979     obj->next = NULL;
980 }
981
982 static void
983 typy_dealloc (PyObject *obj)
984 {
985   type_object *type = (type_object *) obj;
986
987   if (type->prev)
988     type->prev->next = type->next;
989   else if (type->type && TYPE_OBJFILE (type->type))
990     {
991       /* Must reset head of list.  */
992       struct objfile *objfile = TYPE_OBJFILE (type->type);
993
994       if (objfile)
995         set_objfile_data (objfile, typy_objfile_data_key, type->next);
996     }
997   if (type->next)
998     type->next->prev = type->prev;
999
1000   type->ob_type->tp_free (type);
1001 }
1002
1003 /* Create a new Type referring to TYPE.  */
1004 PyObject *
1005 type_to_type_object (struct type *type)
1006 {
1007   type_object *type_obj;
1008
1009   type_obj = PyObject_New (type_object, &type_object_type);
1010   if (type_obj)
1011     set_type (type_obj, type);
1012
1013   return (PyObject *) type_obj;
1014 }
1015
1016 struct type *
1017 type_object_to_type (PyObject *obj)
1018 {
1019   if (! PyObject_TypeCheck (obj, &type_object_type))
1020     return NULL;
1021   return ((type_object *) obj)->type;
1022 }
1023
1024 \f
1025
1026 /* Implementation of gdb.lookup_type.  */
1027 PyObject *
1028 gdbpy_lookup_type (PyObject *self, PyObject *args, PyObject *kw)
1029 {
1030   static char *keywords[] = { "name", "block", NULL };
1031   const char *type_name = NULL;
1032   struct type *type = NULL;
1033   PyObject *block_obj = NULL;
1034   struct block *block = NULL;
1035
1036   if (! PyArg_ParseTupleAndKeywords (args, kw, "s|O", keywords,
1037                                      &type_name, &block_obj))
1038     return NULL;
1039
1040   if (block_obj)
1041     {
1042       block = block_object_to_block (block_obj);
1043       if (! block)
1044         {
1045           PyErr_SetString (PyExc_RuntimeError,
1046                            _("'block' argument must be a Block."));
1047           return NULL;
1048         }
1049     }
1050
1051   type = typy_lookup_typename (type_name, block);
1052   if (! type)
1053     return NULL;
1054
1055   return (PyObject *) type_to_type_object (type);
1056 }
1057
1058 void
1059 gdbpy_initialize_types (void)
1060 {
1061   int i;
1062
1063   typy_objfile_data_key
1064     = register_objfile_data_with_cleanup (save_objfile_types, NULL);
1065
1066   if (PyType_Ready (&type_object_type) < 0)
1067     return;
1068   if (PyType_Ready (&field_object_type) < 0)
1069     return;
1070
1071   for (i = 0; pyty_codes[i].name; ++i)
1072     {
1073       if (PyModule_AddIntConstant (gdb_module,
1074                                    /* Cast needed for Python 2.4.  */
1075                                    (char *) pyty_codes[i].name,
1076                                    pyty_codes[i].code) < 0)
1077         return;
1078     }
1079
1080   Py_INCREF (&type_object_type);
1081   PyModule_AddObject (gdb_module, "Type", (PyObject *) &type_object_type);
1082
1083   Py_INCREF (&field_object_type);
1084   PyModule_AddObject (gdb_module, "Field", (PyObject *) &field_object_type);
1085 }
1086
1087 \f
1088
1089 static PyGetSetDef type_object_getset[] =
1090 {
1091   { "code", typy_get_code, NULL,
1092     "The code for this type.", NULL },
1093   { "sizeof", typy_get_sizeof, NULL,
1094     "The size of this type, in bytes.", NULL },
1095   { "tag", typy_get_tag, NULL,
1096     "The tag name for this type, or None.", NULL },
1097   { NULL }
1098 };
1099
1100 static PyMethodDef type_object_methods[] =
1101 {
1102   { "array", typy_array, METH_VARARGS,
1103     "array (N) -> Type\n\
1104 Return a type which represents an array of N objects of this type." },
1105   { "const", typy_const, METH_NOARGS,
1106     "const () -> Type\n\
1107 Return a const variant of this type." },
1108   { "fields", typy_fields, METH_NOARGS,
1109     "field () -> list\n\
1110 Return a sequence holding all the fields of this type.\n\
1111 Each field is a dictionary." },
1112   { "pointer", typy_pointer, METH_NOARGS,
1113     "pointer () -> Type\n\
1114 Return a type of pointer to this type." },
1115   { "range", typy_range, METH_NOARGS,
1116     "range () -> tuple\n\
1117 Return a tuple containing the lower and upper range for this type."},
1118   { "reference", typy_reference, METH_NOARGS,
1119     "reference () -> Type\n\
1120 Return a type of reference to this type." },
1121   { "strip_typedefs", typy_strip_typedefs, METH_NOARGS,
1122     "strip_typedefs () -> Type\n\
1123 Return a type formed by stripping this type of all typedefs."},
1124   { "target", typy_target, METH_NOARGS,
1125     "target () -> Type\n\
1126 Return the target type of this type." },
1127   { "template_argument", typy_template_argument, METH_VARARGS,
1128     "template_argument (arg, [block]) -> Type\n\
1129 Return the type of a template argument." },
1130   { "unqualified", typy_unqualified, METH_NOARGS,
1131     "unqualified () -> Type\n\
1132 Return a variant of this type without const or volatile attributes." },
1133   { "volatile", typy_volatile, METH_NOARGS,
1134     "volatile () -> Type\n\
1135 Return a volatile variant of this type" },
1136   { NULL }
1137 };
1138
1139 static PyTypeObject type_object_type =
1140 {
1141   PyObject_HEAD_INIT (NULL)
1142   0,                              /*ob_size*/
1143   "gdb.Type",                     /*tp_name*/
1144   sizeof (type_object),           /*tp_basicsize*/
1145   0,                              /*tp_itemsize*/
1146   typy_dealloc,                   /*tp_dealloc*/
1147   0,                              /*tp_print*/
1148   0,                              /*tp_getattr*/
1149   0,                              /*tp_setattr*/
1150   0,                              /*tp_compare*/
1151   0,                              /*tp_repr*/
1152   0,                              /*tp_as_number*/
1153   0,                              /*tp_as_sequence*/
1154   0,                              /*tp_as_mapping*/
1155   0,                              /*tp_hash */
1156   0,                              /*tp_call*/
1157   typy_str,                       /*tp_str*/
1158   0,                              /*tp_getattro*/
1159   0,                              /*tp_setattro*/
1160   0,                              /*tp_as_buffer*/
1161   Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_ITER,  /*tp_flags*/
1162   "GDB type object",              /* tp_doc */
1163   0,                              /* tp_traverse */
1164   0,                              /* tp_clear */
1165   typy_richcompare,               /* tp_richcompare */
1166   0,                              /* tp_weaklistoffset */
1167   0,                              /* tp_iter */
1168   0,                              /* tp_iternext */
1169   type_object_methods,            /* tp_methods */
1170   0,                              /* tp_members */
1171   type_object_getset,             /* tp_getset */
1172   0,                              /* tp_base */
1173   0,                              /* tp_dict */
1174   0,                              /* tp_descr_get */
1175   0,                              /* tp_descr_set */
1176   0,                              /* tp_dictoffset */
1177   0,                              /* tp_init */
1178   0,                              /* tp_alloc */
1179   0,                              /* tp_new */
1180 };
1181
1182 static PyTypeObject field_object_type =
1183 {
1184   PyObject_HEAD_INIT (NULL)
1185   0,                              /*ob_size*/
1186   "gdb.Field",                    /*tp_name*/
1187   sizeof (field_object),          /*tp_basicsize*/
1188   0,                              /*tp_itemsize*/
1189   field_dealloc,                  /*tp_dealloc*/
1190   0,                              /*tp_print*/
1191   0,                              /*tp_getattr*/
1192   0,                              /*tp_setattr*/
1193   0,                              /*tp_compare*/
1194   0,                              /*tp_repr*/
1195   0,                              /*tp_as_number*/
1196   0,                              /*tp_as_sequence*/
1197   0,                              /*tp_as_mapping*/
1198   0,                              /*tp_hash */
1199   0,                              /*tp_call*/
1200   0,                              /*tp_str*/
1201   0,                              /*tp_getattro*/
1202   0,                              /*tp_setattro*/
1203   0,                              /*tp_as_buffer*/
1204   Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_ITER,  /*tp_flags*/
1205   "GDB field object",             /* tp_doc */
1206   0,                              /* tp_traverse */
1207   0,                              /* tp_clear */
1208   0,                              /* tp_richcompare */
1209   0,                              /* tp_weaklistoffset */
1210   0,                              /* tp_iter */
1211   0,                              /* tp_iternext */
1212   0,                              /* tp_methods */
1213   0,                              /* tp_members */
1214   0,                              /* tp_getset */
1215   0,                              /* tp_base */
1216   0,                              /* tp_dict */
1217   0,                              /* tp_descr_get */
1218   0,                              /* tp_descr_set */
1219   offsetof (field_object, dict),  /* tp_dictoffset */
1220   0,                              /* tp_init */
1221   0,                              /* tp_alloc */
1222   0,                              /* tp_new */
1223 };