2009-05-28 Pierre Muller <muller@ics.u-strasbg.fr>
[external/binutils.git] / gdb / python / python-prettyprint.c
1 /* Python pretty-printing
2
3    Copyright (C) 2008, 2009 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 "exceptions.h"
22 #include "objfiles.h"
23 #include "symtab.h"
24 #include "language.h"
25 #include "valprint.h"
26
27 #include "python.h"
28
29 #ifdef HAVE_PYTHON
30 #include "python-internal.h"
31
32
33 /* Helper function for find_pretty_printer which iterates over a list,
34    calls each function and inspects output.  This will return a
35    printer object if one recognizes VALUE.  If no printer is found, it
36    will return None.  On error, it will set the Python error and
37    return NULL.  */
38 static PyObject *
39 search_pp_list (PyObject *list, PyObject *value)
40 {
41   Py_ssize_t pp_list_size, list_index;
42   PyObject *function, *printer = NULL;
43
44   pp_list_size = PyList_Size (list);
45   for (list_index = 0; list_index < pp_list_size; list_index++)
46     {
47       function = PyList_GetItem (list, list_index);
48       if (! function)
49         return NULL;
50
51       printer = PyObject_CallFunctionObjArgs (function, value, NULL);
52       if (! printer)
53         return NULL;
54       else if (printer != Py_None)
55         return printer;
56
57       Py_DECREF (printer);
58     }
59
60   Py_RETURN_NONE;
61 }
62
63 /* Find the pretty-printing constructor function for VALUE.  If no
64    pretty-printer exists, return None.  If one exists, return a new
65    reference.  On error, set the Python error and return NULL.  */
66 static PyObject *
67 find_pretty_printer (PyObject *value)
68 {
69   PyObject *pp_list = NULL;
70   PyObject *function = NULL;
71   struct objfile *obj;
72   volatile struct gdb_exception except;
73
74   /* Look at the pretty-printer dictionary for each objfile.  */
75   ALL_OBJFILES (obj)
76   {
77     PyObject *objf = objfile_to_objfile_object (obj);
78     if (!objf)
79       {
80         /* Ignore the error and continue.  */
81         PyErr_Clear ();
82         continue;
83       }
84
85     pp_list = objfpy_get_printers (objf, NULL);
86     function = search_pp_list (pp_list, value);
87
88     /* If there is an error in any objfile list, abort the search and
89        exit.  */
90     if (! function)
91       {
92         Py_XDECREF (pp_list);
93         return NULL;
94       }
95
96     if (function != Py_None)
97       goto done;
98     
99     Py_DECREF (function);
100     Py_XDECREF (pp_list);
101   }
102
103   pp_list = NULL;
104   /* Fetch the global pretty printer dictionary.  */
105   if (! PyObject_HasAttrString (gdb_module, "pretty_printers"))
106     {
107       function = Py_None;
108       Py_INCREF (function);
109       goto done;
110     }
111   pp_list = PyObject_GetAttrString (gdb_module, "pretty_printers");
112   if (! pp_list)
113     goto done;
114   if (! PyList_Check (pp_list))
115     goto done;
116
117   function = search_pp_list (pp_list, value);
118
119  done:
120   Py_XDECREF (pp_list);
121   
122   return function;
123 }
124
125 /* Pretty-print a single value, via the printer object PRINTER.  If
126    the function returns a string, an xmalloc()d copy is returned.
127    Otherwise, if the function returns a value, a *OUT_VALUE is set to
128    the value, and NULL is returned.  On error, *OUT_VALUE is set to
129    NULL and NULL is returned.  */
130 static char *
131 pretty_print_one_value (PyObject *printer, struct value **out_value)
132 {
133   char *output = NULL;
134   volatile struct gdb_exception except;
135
136   TRY_CATCH (except, RETURN_MASK_ALL)
137     {
138       PyObject *result;
139
140       result = PyObject_CallMethodObjArgs (printer, gdbpy_to_string_cst, NULL);
141       if (result)
142         {
143           if (gdbpy_is_string (result))
144             output = python_string_to_host_string (result);
145           else
146             *out_value = convert_value_from_python (result);
147           Py_DECREF (result);
148         }
149     }
150
151   return output;
152 }
153
154 /* Return the display hint for the object printer, PRINTER.  Return
155    NULL if there is no display_hint method, or if the method did not
156    return a string.  On error, print stack trace and return NULL.  On
157    success, return an xmalloc()d string.  */
158 char *
159 gdbpy_get_display_hint (PyObject *printer)
160 {
161   PyObject *hint;
162   char *result = NULL;
163
164   if (! PyObject_HasAttr (printer, gdbpy_display_hint_cst))
165     return NULL;
166
167   hint = PyObject_CallMethodObjArgs (printer, gdbpy_display_hint_cst, NULL);
168   if (gdbpy_is_string (hint))
169     result = python_string_to_host_string (hint);
170   if (hint)
171     Py_DECREF (hint);
172   else
173     gdbpy_print_stack ();
174
175   return result;
176 }
177
178 /* Helper for apply_val_pretty_printer which calls to_string and
179    formats the result.  */
180 static void
181 print_string_repr (PyObject *printer, const char *hint,
182                    struct ui_file *stream, int recurse,
183                    const struct value_print_options *options,
184                    const struct language_defn *language)
185 {
186   char *output;
187   struct value *replacement = NULL;
188
189   output = pretty_print_one_value (printer, &replacement);
190   if (output)
191     {
192       if (hint && !strcmp (hint, "string"))
193         LA_PRINT_STRING (stream, builtin_type (current_gdbarch)->builtin_char,
194                          (gdb_byte *) output, strlen (output),
195                          0, options);
196       else
197         fputs_filtered (output, stream);
198       xfree (output);
199     }
200   else if (replacement)
201     common_val_print (replacement, stream, recurse, options, language);
202   else
203     gdbpy_print_stack ();
204 }
205
206 static void
207 py_restore_tstate (void *p)
208 {
209   PyFrameObject *frame = p;
210   PyThreadState *tstate = PyThreadState_GET ();
211   tstate->frame = frame;
212 }
213
214 /* Create a dummy PyFrameObject, needed to work around
215    a Python-2.4 bug with generators.  */
216 static PyObject *
217 push_dummy_python_frame ()
218 {
219   PyObject *empty_string, *null_tuple, *globals;
220   PyCodeObject *code;
221   PyFrameObject *frame;
222   PyThreadState *tstate;
223
224   empty_string = PyString_FromString ("");
225   if (!empty_string)
226     return NULL;
227
228   null_tuple = PyTuple_New (0);
229   if (!null_tuple)
230     {
231       Py_DECREF (empty_string);
232       return NULL;
233     }
234
235   code = PyCode_New (0,                 /* argcount */
236                      0,                 /* nlocals */
237                      0,                 /* stacksize */
238                      0,                 /* flags */
239                      empty_string,      /* code */
240                      null_tuple,        /* consts */
241                      null_tuple,        /* names */
242                      null_tuple,        /* varnames */
243 #if PYTHON_API_VERSION >= 1010
244                      null_tuple,        /* freevars */
245                      null_tuple,        /* cellvars */
246 #endif
247                      empty_string,      /* filename */
248                      empty_string,      /* name */
249                      1,                 /* firstlineno */
250                      empty_string       /* lnotab */
251                     );
252
253   Py_DECREF (empty_string);
254   Py_DECREF (null_tuple);
255
256   if (!code)
257     return NULL;
258
259   globals = PyDict_New ();
260   if (!globals)
261     {
262       Py_DECREF (code);
263       return NULL;
264     }
265
266   tstate = PyThreadState_GET ();
267
268   frame = PyFrame_New (tstate, code, globals, NULL);
269
270   Py_DECREF (globals);
271   Py_DECREF (code);
272
273   if (!frame)
274     return NULL;
275
276   tstate->frame = frame;
277   make_cleanup (py_restore_tstate, frame->f_back);
278   return (PyObject *) frame;
279 }
280
281 /* Helper for apply_val_pretty_printer that formats children of the
282    printer, if any exist.  */
283 static void
284 print_children (PyObject *printer, const char *hint,
285                 struct ui_file *stream, int recurse,
286                 const struct value_print_options *options,
287                 const struct language_defn *language)
288 {
289   int is_map, is_array, done_flag, pretty;
290   unsigned int i;
291   PyObject *children, *iter, *frame;
292   struct cleanup *cleanups;
293
294   if (! PyObject_HasAttr (printer, gdbpy_children_cst))
295     return;
296
297   /* If we are printing a map or an array, we want some special
298      formatting.  */
299   is_map = hint && ! strcmp (hint, "map");
300   is_array = hint && ! strcmp (hint, "array");
301
302   children = PyObject_CallMethodObjArgs (printer, gdbpy_children_cst,
303                                          NULL);
304   if (! children)
305     {
306       gdbpy_print_stack ();
307       return;
308     }
309
310   cleanups = make_cleanup_py_decref (children);
311
312   iter = PyObject_GetIter (children);
313   if (!iter)
314     {
315       gdbpy_print_stack ();
316       goto done;
317     }
318   make_cleanup_py_decref (iter);
319
320   /* Use the prettyprint_arrays option if we are printing an array,
321      and the pretty option otherwise.  */
322   pretty = is_array ? options->prettyprint_arrays : options->pretty;
323
324   /* Manufacture a dummy Python frame to work around Python 2.4 bug,
325      where it insists on having a non-NULL tstate->frame when
326      a generator is called.  */
327   frame = push_dummy_python_frame ();
328   if (!frame)
329     {
330       gdbpy_print_stack ();
331       goto done;
332     }
333   make_cleanup_py_decref (frame);
334
335   done_flag = 0;
336   for (i = 0; i < options->print_max; ++i)
337     {
338       PyObject *py_v, *item = PyIter_Next (iter);
339       char *name;
340       struct cleanup *inner_cleanup;
341
342       if (! item)
343         {
344           if (PyErr_Occurred ())
345             gdbpy_print_stack ();
346           /* Set a flag so we can know whether we printed all the
347              available elements.  */
348           else    
349             done_flag = 1;
350           break;
351         }
352
353       if (! PyArg_ParseTuple (item, "sO", &name, &py_v))
354         {
355           gdbpy_print_stack ();
356           Py_DECREF (item);
357           continue;
358         }
359       inner_cleanup = make_cleanup_py_decref (item);
360
361       /* Print initial "{".  For other elements, there are three
362          cases:
363          1. Maps.  Print a "," after each value element.
364          2. Arrays.  Always print a ",".
365          3. Other.  Always print a ",".  */
366       if (i == 0)
367         fputs_filtered (" = {", stream);
368       else if (! is_map || i % 2 == 0)
369         fputs_filtered (pretty ? "," : ", ", stream);
370
371       /* In summary mode, we just want to print "= {...}" if there is
372          a value.  */
373       if (options->summary)
374         {
375           /* This increment tricks the post-loop logic to print what
376              we want.  */
377           ++i;
378           /* Likewise.  */
379           pretty = 0;
380           break;
381         }
382
383       if (! is_map || i % 2 == 0)
384         {
385           if (pretty)
386             {
387               fputs_filtered ("\n", stream);
388               print_spaces_filtered (2 + 2 * recurse, stream);
389             }
390           else
391             wrap_here (n_spaces (2 + 2 *recurse));
392         }
393
394       if (is_map && i % 2 == 0)
395         fputs_filtered ("[", stream);
396       else if (is_array)
397         {
398           /* We print the index, not whatever the child method
399              returned as the name.  */
400           if (options->print_array_indexes)
401             fprintf_filtered (stream, "[%d] = ", i);
402         }
403       else if (! is_map)
404         {
405           fputs_filtered (name, stream);
406           fputs_filtered (" = ", stream);
407         }
408
409       if (gdbpy_is_string (py_v))
410         {
411           char *text = python_string_to_host_string (py_v);
412           if (! text)
413             gdbpy_print_stack ();
414           else
415             {
416               fputs_filtered (text, stream);
417               xfree (text);
418             }
419         }
420       else
421         {
422           struct value *value = convert_value_from_python (py_v);
423
424           if (value == NULL)
425             {
426               gdbpy_print_stack ();
427               error (_("Error while executing Python code."));
428             }
429           else
430             common_val_print (value, stream, recurse + 1, options, language);
431         }
432
433       if (is_map && i % 2 == 0)
434         fputs_filtered ("] = ", stream);
435
436       do_cleanups (inner_cleanup);
437     }
438
439   if (i)
440     {
441       if (!done_flag)
442         {
443           if (pretty)
444             {
445               fputs_filtered ("\n", stream);
446               print_spaces_filtered (2 + 2 * recurse, stream);
447             }
448           fputs_filtered ("...", stream);
449         }
450       if (pretty)
451         {
452           fputs_filtered ("\n", stream);
453           print_spaces_filtered (2 * recurse, stream);
454         }
455       fputs_filtered ("}", stream);
456     }
457
458  done:
459   do_cleanups (cleanups);
460 }
461
462 int
463 apply_val_pretty_printer (struct type *type, const gdb_byte *valaddr,
464                           int embedded_offset, CORE_ADDR address,
465                           struct ui_file *stream, int recurse,
466                           const struct value_print_options *options,
467                           const struct language_defn *language)
468 {
469   PyObject *printer = NULL;
470   PyObject *val_obj = NULL;
471   struct value *value;
472   char *hint = NULL;
473   struct cleanup *cleanups;
474   int result = 0;
475   PyGILState_STATE state;
476
477   state = PyGILState_Ensure ();
478   cleanups = make_cleanup_py_restore_gil (&state);
479
480   /* Instantiate the printer.  */
481   if (valaddr)
482     valaddr += embedded_offset;
483   value = value_from_contents_and_address (type, valaddr, address);
484
485   val_obj = value_to_value_object (value);
486   if (! val_obj)
487     goto done;
488   
489   /* Find the constructor.  */
490   printer = find_pretty_printer (val_obj);
491   Py_DECREF (val_obj);
492   make_cleanup_py_decref (printer);
493   if (! printer || printer == Py_None)
494     goto done;
495
496   /* If we are printing a map, we want some special formatting.  */
497   hint = gdbpy_get_display_hint (printer);
498   make_cleanup (free_current_contents, &hint);
499
500   /* Print the section */
501   print_string_repr (printer, hint, stream, recurse, options, language);
502   print_children (printer, hint, stream, recurse, options, language);
503   result = 1;
504
505
506  done:
507   if (PyErr_Occurred ())
508     gdbpy_print_stack ();
509   do_cleanups (cleanups);
510   return result;
511 }
512
513 /* Apply a pretty-printer for the varobj code.  PRINTER_OBJ is the
514    print object.  It must have a 'to_string' method (but this is
515    checked by varobj, not here) which takes no arguments and
516    returns a string.  This function returns an xmalloc()d string if
517    the printer returns a string.  The printer may return a replacement
518    value instead; in this case *REPLACEMENT is set to the replacement
519    value, and this function returns NULL.  On error, *REPLACEMENT is
520    set to NULL and this function also returns NULL.  */
521 char *
522 apply_varobj_pretty_printer (PyObject *printer_obj,
523                              struct value **replacement)
524 {
525   char *result;
526   PyGILState_STATE state = PyGILState_Ensure ();
527
528   *replacement = NULL;
529   result = pretty_print_one_value (printer_obj, replacement);
530   if (result == NULL);
531     gdbpy_print_stack ();
532   PyGILState_Release (state);
533
534   return result;
535 }
536
537 /* Find a pretty-printer object for the varobj module.  Returns a new
538    reference to the object if successful; returns NULL if not.  VALUE
539    is the value for which a printer tests to determine if it 
540    can pretty-print the value.  */
541 PyObject *
542 gdbpy_get_varobj_pretty_printer (struct value *value)
543 {
544   PyObject *val_obj;
545   PyObject *pretty_printer = NULL;
546   volatile struct gdb_exception except;
547
548   TRY_CATCH (except, RETURN_MASK_ALL)
549     {
550       value = value_copy (value);
551     }
552   GDB_PY_HANDLE_EXCEPTION (except);
553   
554   val_obj = value_to_value_object (value);
555   if (! val_obj)
556     return NULL;
557
558   pretty_printer = find_pretty_printer (val_obj);
559   Py_DECREF (val_obj);
560   return pretty_printer;
561 }
562
563 /* A Python function which wraps find_pretty_printer and instantiates
564    the resulting class.  This accepts a Value argument and returns a
565    pretty printer instance, or None.  This function is useful as an
566    argument to the MI command -var-set-visualizer.  */
567 PyObject *
568 gdbpy_default_visualizer (PyObject *self, PyObject *args)
569 {
570   PyObject *val_obj;
571   PyObject *cons, *printer = NULL;
572   struct value *value;
573
574   if (! PyArg_ParseTuple (args, "O", &val_obj))
575     return NULL;
576   value = value_object_to_value (val_obj);
577   if (! value)
578     {
579       PyErr_SetString (PyExc_TypeError, "argument must be a gdb.Value");
580       return NULL;
581     }
582
583   cons = find_pretty_printer (val_obj);
584   return cons;
585 }
586
587 #else /* HAVE_PYTHON */
588
589 int
590 apply_val_pretty_printer (struct type *type, const gdb_byte *valaddr,
591                           int embedded_offset, CORE_ADDR address,
592                           struct ui_file *stream, int recurse,
593                           const struct value_print_options *options,
594                           const struct language_defn *language)
595 {
596   return 0;
597 }
598
599 #endif /* HAVE_PYTHON */