Fix converting a remote PyStringObject to a local string
[cython.git] / Cython / Debugger / libcython.py
1 """
2 GDB extension that adds Cython support.
3 """
4
5 from __future__ import with_statement
6
7 import os
8 import sys
9 import textwrap
10 import operator
11 import traceback
12 import functools
13 import itertools
14 import collections
15
16 import gdb
17
18 try:
19   from lxml import etree
20   have_lxml = True
21 except ImportError:
22     have_lxml = False
23     try:
24         # Python 2.5
25         from xml.etree import cElementTree as etree
26     except ImportError:
27         try:
28             # Python 2.5
29             from xml.etree import ElementTree as etree
30         except ImportError:
31             try:
32                 # normal cElementTree install
33                 import cElementTree as etree
34             except ImportError:
35                 # normal ElementTree install
36                 import elementtree.ElementTree as etree
37
38 try:
39     import pygments.lexers
40     import pygments.formatters
41 except ImportError:
42     pygments = None
43     sys.stderr.write("Install pygments for colorized source code.\n")
44
45 if hasattr(gdb, 'string_to_argv'):
46     from gdb import string_to_argv
47 else:
48     from shlex import split as string_to_argv
49
50 from Cython.Debugger import libpython
51
52 # C or Python type
53 CObject = 'CObject'
54 PythonObject = 'PythonObject'
55
56 _data_types = dict(CObject=CObject, PythonObject=PythonObject)
57 _filesystemencoding = sys.getfilesystemencoding() or 'UTF-8'
58
59 # decorators
60
61 def dont_suppress_errors(function):
62     "*sigh*, readline"
63     @functools.wraps(function)
64     def wrapper(*args, **kwargs):
65         try:
66             return function(*args, **kwargs)
67         except Exception:
68             traceback.print_exc()
69             raise
70     
71     return wrapper
72
73 def default_selected_gdb_frame(err=True):
74     def decorator(function):
75         @functools.wraps(function)
76         def wrapper(self, frame=None, *args, **kwargs):
77             try:
78                 frame = frame or gdb.selected_frame()
79             except RuntimeError:
80                 raise gdb.GdbError("No frame is currently selected.")
81                 
82             if err and frame.name() is None:
83                 raise NoFunctionNameInFrameError()
84     
85             return function(self, frame, *args, **kwargs)
86         return wrapper
87     return decorator
88
89 def require_cython_frame(function):
90     @functools.wraps(function)
91     @require_running_program
92     def wrapper(self, *args, **kwargs):
93         frame = kwargs.get('frame') or gdb.selected_frame()
94         if not self.is_cython_function(frame):
95             raise gdb.GdbError('Selected frame does not correspond with a '
96                                'Cython function we know about.')
97         return function(self, *args, **kwargs)
98     return wrapper 
99
100 def dispatch_on_frame(c_command, python_command=None):
101     def decorator(function):
102         @functools.wraps(function)
103         def wrapper(self, *args, **kwargs):
104             is_cy = self.is_cython_function()
105             is_py = self.is_python_function()
106             
107             if is_cy or (is_py and not python_command):
108                 function(self, *args, **kwargs)
109             elif is_py:
110                 gdb.execute(python_command)
111             elif self.is_relevant_function():
112                 gdb.execute(c_command)
113             else:
114                 raise gdb.GdbError("Not a function cygdb knows about. "
115                                    "Use the normal GDB commands instead.")
116         
117         return wrapper
118     return decorator
119
120 def require_running_program(function):
121     @functools.wraps(function)
122     def wrapper(*args, **kwargs):
123         try:
124             gdb.selected_frame()
125         except RuntimeError:
126             raise gdb.GdbError("No frame is currently selected.")
127         
128         return function(*args, **kwargs)
129     return wrapper
130     
131
132 def gdb_function_value_to_unicode(function):
133     @functools.wraps(function)
134     def wrapper(self, string, *args, **kwargs):
135         if isinstance(string, gdb.Value):
136             string = string.string()
137
138         return function(self, string, *args, **kwargs)
139     return wrapper
140
141
142 # Classes that represent the debug information
143 # Don't rename the parameters of these classes, they come directly from the XML
144
145 class CythonModule(object):
146     def __init__(self, module_name, filename, c_filename):
147         self.name = module_name
148         self.filename = filename
149         self.c_filename = c_filename
150         self.globals = {}
151         # {cython_lineno: min(c_linenos)}
152         self.lineno_cy2c = {}
153         # {c_lineno: cython_lineno}
154         self.lineno_c2cy = {}
155         self.functions = {}
156         
157     def qualified_name(self, varname):
158         return '.'.join(self.name, varname)
159
160 class CythonVariable(object):
161
162     def __init__(self, name, cname, qualified_name, type):
163         self.name = name
164         self.cname = cname
165         self.qualified_name = qualified_name
166         self.type = type
167
168 class CythonFunction(CythonVariable):
169     def __init__(self, 
170                  module, 
171                  name, 
172                  cname, 
173                  pf_cname,
174                  qualified_name, 
175                  lineno, 
176                  type=CObject):
177         super(CythonFunction, self).__init__(name, 
178                                              cname, 
179                                              qualified_name, 
180                                              type)
181         self.module = module
182         self.pf_cname = pf_cname
183         self.lineno = int(lineno)
184         self.locals = {}
185         self.arguments = []
186         self.step_into_functions = set()
187
188
189 # General purpose classes
190
191 class CythonBase(object):
192     
193     @default_selected_gdb_frame(err=False)
194     def is_cython_function(self, frame):
195         return frame.name() in self.cy.functions_by_cname
196
197     @default_selected_gdb_frame(err=False)
198     def is_python_function(self, frame):
199         """
200         Tells if a frame is associated with a Python function.
201         If we can't read the Python frame information, don't regard it as such.
202         """
203         if frame.name() == 'PyEval_EvalFrameEx':
204             pyframe = libpython.Frame(frame).get_pyop()
205             return pyframe and not pyframe.is_optimized_out()
206         return False
207         
208     @default_selected_gdb_frame()
209     def get_c_function_name(self, frame):
210         return frame.name()
211
212     @default_selected_gdb_frame()
213     def get_c_lineno(self, frame):
214         return frame.find_sal().line
215     
216     @default_selected_gdb_frame()
217     def get_cython_function(self, frame):
218         result = self.cy.functions_by_cname.get(frame.name())
219         if result is None:
220             raise NoCythonFunctionInFrameError()
221             
222         return result
223     
224     @default_selected_gdb_frame()
225     def get_cython_lineno(self, frame):
226         """
227         Get the current Cython line number. Returns 0 if there is no 
228         correspondence between the C and Cython code.
229         """
230         cyfunc = self.get_cython_function(frame)
231         return cyfunc.module.lineno_c2cy.get(self.get_c_lineno(frame), 0)
232     
233     @default_selected_gdb_frame()
234     def get_source_desc(self, frame):
235         filename = lineno = lexer = None
236         if self.is_cython_function(frame):
237             filename = self.get_cython_function(frame).module.filename
238             lineno = self.get_cython_lineno(frame)
239             if pygments:
240                 lexer = pygments.lexers.CythonLexer(stripall=False)
241         elif self.is_python_function(frame):
242             pyframeobject = libpython.Frame(frame).get_pyop()
243
244             if not pyframeobject:
245                 raise gdb.GdbError('Unable to read information on python frame')
246
247             filename = pyframeobject.filename()
248             lineno = pyframeobject.current_line_num()
249             
250             if pygments:
251                 lexer = pygments.lexers.PythonLexer(stripall=False)
252         else:
253             symbol_and_line_obj = frame.find_sal()
254             if not symbol_and_line_obj or not symbol_and_line_obj.symtab:
255                 filename = None
256                 lineno = 0
257             else:
258                 filename = symbol_and_line_obj.symtab.filename
259                 lineno = symbol_and_line_obj.line
260                 if pygments:
261                     lexer = pygments.lexers.CLexer(stripall=False)
262             
263         return SourceFileDescriptor(filename, lexer), lineno
264
265     @default_selected_gdb_frame()
266     def get_source_line(self, frame):
267         source_desc, lineno = self.get_source_desc()
268         return source_desc.get_source(lineno)
269     
270     @default_selected_gdb_frame()
271     def is_relevant_function(self, frame):
272         """
273         returns whether we care about a frame on the user-level when debugging
274         Cython code
275         """
276         name = frame.name()
277         older_frame = frame.older()
278         if self.is_cython_function(frame) or self.is_python_function(frame):
279             return True
280         elif (parameters.step_into_c_code and 
281               older_frame and self.is_cython_function(older_frame)):
282             # direct C function call from a Cython function
283             cython_func = self.get_cython_function(older_frame)
284             return name in cython_func.step_into_functions
285
286         return False
287     
288     @default_selected_gdb_frame(err=False)
289     def print_stackframe(self, frame, index, is_c=False):
290         """
291         Print a C, Cython or Python stack frame and the line of source code
292         if available.
293         """
294         # do this to prevent the require_cython_frame decorator from
295         # raising GdbError when calling self.cy.cy_cvalue.invoke()
296         selected_frame = gdb.selected_frame()
297         frame.select()
298         
299         try:
300             source_desc, lineno = self.get_source_desc(frame)
301         except NoFunctionNameInFrameError:
302             print '#%-2d Unknown Frame (compile with -g)' % index
303             return
304
305         if not is_c and self.is_python_function(frame):
306             pyframe = libpython.Frame(frame).get_pyop()
307             if pyframe is None or pyframe.is_optimized_out():
308                 # print this python function as a C function
309                 return self.print_stackframe(frame, index, is_c=True)
310             
311             func_name = pyframe.co_name
312             func_cname = 'PyEval_EvalFrameEx'
313             func_args = []
314         elif self.is_cython_function(frame):
315             cyfunc = self.get_cython_function(frame)
316             f = lambda arg: self.cy.cy_cvalue.invoke(arg, frame=frame)
317             
318             func_name = cyfunc.name
319             func_cname = cyfunc.cname
320             func_args = [] # [(arg, f(arg)) for arg in cyfunc.arguments]
321         else:
322             source_desc, lineno = self.get_source_desc(frame)
323             func_name = frame.name()
324             func_cname = func_name
325             func_args = []
326         
327         try:
328             gdb_value = gdb.parse_and_eval(func_cname)
329         except RuntimeError:
330             func_address = 0
331         else:
332             # Seriously? Why is the address not an int?
333             func_address = int(str(gdb_value.address).split()[0], 0)
334         
335         a = ', '.join('%s=%s' % (name, val) for name, val in func_args)
336         print '#%-2d 0x%016x in %s(%s)' % (index, func_address, func_name, a),
337             
338         if source_desc.filename is not None:
339             print 'at %s:%s' % (source_desc.filename, lineno),
340         
341         print
342             
343         try:
344             print '    ' + source_desc.get_source(lineno)
345         except gdb.GdbError:
346             pass
347         
348         selected_frame.select()
349     
350     def get_cython_globals_dict(self):
351         """
352         Get the Cython globals dict where the remote names are turned into
353         local strings.
354         """
355         m = gdb.parse_and_eval('__pyx_m')
356         
357         try:
358             PyModuleObject = gdb.lookup_type('PyModuleObject')
359         except RuntimeError:
360             raise gdb.GdbError(textwrap.dedent("""\
361                 Unable to lookup type PyModuleObject, did you compile python 
362                 with debugging support (-g)?"""))
363             
364         m = m.cast(PyModuleObject.pointer())
365         pyobject_dict = libpython.PyObjectPtr.from_pyobject_ptr(m['md_dict'])
366         
367         result = {}
368         seen = set()
369         for k, v in pyobject_dict.iteritems():
370             result[k.proxyval(seen)] = v
371             
372         return result
373
374     def print_gdb_value(self, name, value, max_name_length=None, prefix=''):
375         if libpython.pretty_printer_lookup(value):
376             typename = ''
377         else:
378             typename = '(%s) ' % (value.type,)
379                 
380         if max_name_length is None:
381             print '%s%s = %s%s' % (prefix, name, typename, value)
382         else:
383             print '%s%-*s = %s%s' % (prefix, max_name_length, name, typename, 
384                                      value)
385
386
387 class SourceFileDescriptor(object):
388     def __init__(self, filename, lexer, formatter=None):
389         self.filename = filename
390         self.lexer = lexer
391         self.formatter = formatter
392
393     def valid(self):
394         return self.filename is not None
395
396     def lex(self, code):
397         if pygments and self.lexer and parameters.colorize_code:
398             bg = parameters.terminal_background.value
399             if self.formatter is None:
400                 formatter = pygments.formatters.TerminalFormatter(bg=bg)
401             else:
402                 formatter = self.formatter
403
404             return pygments.highlight(code, self.lexer, formatter)
405
406         return code
407
408     def _get_source(self, start, stop, lex_source, mark_line, lex_entire):
409         with open(self.filename) as f:
410             # to provide "correct" colouring, the entire code needs to be
411             # lexed. However, this makes a lot of things terribly slow, so
412             # we decide not to. Besides, it's unlikely to matter.
413             
414             if lex_source and lex_entire:
415                 f = self.lex(f.read()).splitlines()
416             
417             slice = itertools.islice(f, start - 1, stop - 1)
418             
419             for idx, line in enumerate(slice):
420                 if start + idx == mark_line:
421                     prefix = '>'
422                 else:
423                     prefix = ' '
424                 
425                 if lex_source and not lex_entire:
426                     line = self.lex(line)
427
428                 yield '%s %4d    %s' % (prefix, start + idx, line.rstrip())
429
430     def get_source(self, start, stop=None, lex_source=True, mark_line=0, 
431                    lex_entire=False):
432         exc = gdb.GdbError('Unable to retrieve source code')
433         
434         if not self.filename:
435             raise exc
436         
437         start = max(start, 1)
438         if stop is None:
439             stop = start + 1
440
441         try:
442             return '\n'.join(
443                 self._get_source(start, stop, lex_source, mark_line, lex_entire))
444         except IOError:
445             raise exc
446
447
448 # Errors
449
450 class CyGDBError(gdb.GdbError):
451     """
452     Base class for Cython-command related erorrs
453     """
454     
455     def __init__(self, *args):
456         args = args or (self.msg,)
457         super(CyGDBError, self).__init__(*args)
458     
459 class NoCythonFunctionInFrameError(CyGDBError):
460     """
461     raised when the user requests the current cython function, which is 
462     unavailable
463     """
464     msg = "Current function is a function cygdb doesn't know about"
465
466 class NoFunctionNameInFrameError(NoCythonFunctionInFrameError):
467     """
468     raised when the name of the C function could not be determined 
469     in the current C stack frame
470     """
471     msg = ('C function name could not be determined in the current C stack '
472            'frame')
473
474
475 # Parameters
476
477 class CythonParameter(gdb.Parameter):
478     """
479     Base class for cython parameters
480     """
481     
482     def __init__(self, name, command_class, parameter_class, default=None):
483         self.show_doc = self.set_doc = self.__class__.__doc__
484         super(CythonParameter, self).__init__(name, command_class, 
485                                               parameter_class)
486         if default is not None:
487             self.value = default
488    
489     def __nonzero__(self):
490         return bool(self.value)
491     
492     __bool__ = __nonzero__ # python 3
493
494 class CompleteUnqualifiedFunctionNames(CythonParameter):
495     """
496     Have 'cy break' complete unqualified function or method names.
497     """ 
498
499 class ColorizeSourceCode(CythonParameter):
500     """
501     Tell cygdb whether to colorize source code.
502     """
503
504 class TerminalBackground(CythonParameter):
505     """
506     Tell cygdb about the user's terminal background (light or dark).
507     """
508
509 class StepIntoCCode(CythonParameter):
510     """
511     Tells cygdb whether to step into C functions called directly from Cython
512     code.
513     """
514
515 class CythonParameters(object):
516     """
517     Simple container class that might get more functionality in the distant
518     future (mostly to remind us that we're dealing with parameters).
519     """
520     
521     def __init__(self):
522         self.complete_unqualified = CompleteUnqualifiedFunctionNames(
523             'cy_complete_unqualified',
524             gdb.COMMAND_BREAKPOINTS,
525             gdb.PARAM_BOOLEAN,
526             True)
527         self.colorize_code = ColorizeSourceCode(
528             'cy_colorize_code',
529             gdb.COMMAND_FILES,
530             gdb.PARAM_BOOLEAN,
531             True)
532         self.terminal_background = TerminalBackground(
533             'cy_terminal_background_color',
534             gdb.COMMAND_FILES,
535             gdb.PARAM_STRING,
536             "dark")
537         self.step_into_c_code = StepIntoCCode(
538             'cy_step_into_c_code',
539             gdb.COMMAND_RUNNING,
540             gdb.PARAM_BOOLEAN,
541             True)
542         
543 parameters = CythonParameters()
544
545
546 # Commands
547
548 class CythonCommand(gdb.Command, CythonBase):
549     """
550     Base class for Cython commands
551     """
552     
553     command_class = gdb.COMMAND_NONE
554     
555     @classmethod
556     def _register(cls, clsname, args, kwargs):
557         if not hasattr(cls, 'completer_class'):
558             return cls(clsname, cls.command_class, *args, **kwargs)
559         else:
560             return cls(clsname, cls.command_class, cls.completer_class, 
561                        *args, **kwargs)
562     
563     @classmethod
564     def register(cls, *args, **kwargs):
565         alias = getattr(cls, 'alias', None)
566         if alias:
567             cls._register(cls.alias, args, kwargs)
568             
569         return cls._register(cls.name, args, kwargs)
570
571
572 class CyCy(CythonCommand):
573     """
574     Invoke a Cython command. Available commands are:
575         
576         cy import
577         cy break
578         cy step
579         cy next
580         cy run
581         cy cont
582         cy up
583         cy down
584         cy bt / cy backtrace
585         cy print
586         cy list
587         cy locals
588         cy globals
589     """
590     
591     name = 'cy'
592     command_class = gdb.COMMAND_NONE
593     completer_class = gdb.COMPLETE_COMMAND
594     
595     def __init__(self, *args):
596         super(CythonCommand, self).__init__(*args, prefix=True)
597         
598         commands = dict(
599             import_ = CyImport.register(),
600             break_ = CyBreak.register(),
601             step = CyStep.register(),
602             next = CyNext.register(),
603             run = CyRun.register(),
604             cont = CyCont.register(),
605             up = CyUp.register(),
606             down = CyDown.register(),
607             bt = CyBacktrace.register(),
608             list = CyList.register(),
609             print_ = CyPrint.register(),
610             locals = CyLocals.register(),
611             globals = CyGlobals.register(),
612             cy_cname = CyCName('cy_cname'),
613             cy_cvalue = CyCValue('cy_cvalue'),
614             cy_lineno = CyLine('cy_lineno'),
615         )
616             
617         for command_name, command in commands.iteritems():
618             command.cy = self
619             setattr(self, command_name, command)
620         
621         self.cy = self
622         
623         # Cython module namespace
624         self.cython_namespace = {}
625         
626         # maps (unique) qualified function names (e.g. 
627         # cythonmodule.ClassName.method_name) to the CythonFunction object
628         self.functions_by_qualified_name = {}
629         
630         # unique cnames of Cython functions
631         self.functions_by_cname = {}
632         
633         # map function names like method_name to a list of all such 
634         # CythonFunction objects
635         self.functions_by_name = collections.defaultdict(list)
636
637
638 class CyImport(CythonCommand):
639     """
640     Import debug information outputted by the Cython compiler
641     Example: cy import FILE...
642     """
643     
644     name = 'cy import'
645     command_class = gdb.COMMAND_STATUS
646     completer_class = gdb.COMPLETE_FILENAME
647     
648     def invoke(self, args, from_tty):
649         args = args.encode(_filesystemencoding)
650         for arg in string_to_argv(args):
651             try:
652                 f = open(arg)
653             except OSError, e:
654                 raise gdb.GdbError('Unable to open file %r: %s' % 
655                                                 (args, e.args[1]))
656             
657             t = etree.parse(f)
658             
659             for module in t.getroot():
660                 cython_module = CythonModule(**module.attrib)
661                 self.cy.cython_namespace[cython_module.name] = cython_module
662                 
663                 for variable in module.find('Globals'):
664                     d = variable.attrib
665                     cython_module.globals[d['name']] = CythonVariable(**d)
666                 
667                 for function in module.find('Functions'):
668                     cython_function = CythonFunction(module=cython_module, 
669                                                      **function.attrib)
670
671                     # update the global function mappings
672                     name = cython_function.name
673                     qname = cython_function.qualified_name
674                     
675                     self.cy.functions_by_name[name].append(cython_function)
676                     self.cy.functions_by_qualified_name[
677                         cython_function.qualified_name] = cython_function
678                     self.cy.functions_by_cname[
679                         cython_function.cname] = cython_function
680                     
681                     d = cython_module.functions[qname] = cython_function
682                     
683                     for local in function.find('Locals'):
684                         d = local.attrib
685                         cython_function.locals[d['name']] = CythonVariable(**d)
686
687                     for step_into_func in function.find('StepIntoFunctions'):
688                         d = step_into_func.attrib
689                         cython_function.step_into_functions.add(d['name'])
690                     
691                     cython_function.arguments.extend(
692                         funcarg.tag for funcarg in function.find('Arguments'))
693
694                 for marker in module.find('LineNumberMapping'):
695                     cython_lineno = int(marker.attrib['cython_lineno'])
696                     c_linenos = map(int, marker.attrib['c_linenos'].split())
697                     cython_module.lineno_cy2c[cython_lineno] = min(c_linenos)
698                     for c_lineno in c_linenos:
699                         cython_module.lineno_c2cy[c_lineno] = cython_lineno
700
701         self.cy.step.init_breakpoints()
702
703
704 class CyBreak(CythonCommand):
705     """
706     Set a breakpoint for Cython code using Cython qualified name notation, e.g.:
707         
708         cy break cython_modulename.ClassName.method_name...
709     
710     or normal notation:
711         
712         cy break function_or_method_name...
713     
714     or for a line number:
715     
716         cy break cython_module:lineno...
717     
718     Set a Python breakpoint:
719         Break on any function or method named 'func' in module 'modname'
720             
721             cy break -p modname.func...
722         
723         Break on any function or method named 'func'
724             
725             cy break -p func...
726     """
727     
728     name = 'cy break'
729     command_class = gdb.COMMAND_BREAKPOINTS
730     
731     def _break_pyx(self, name):
732         modulename, _, lineno = name.partition(':')
733         lineno = int(lineno)
734         if modulename:
735             cython_module = self.cy.cython_namespace[modulename]
736         else:
737             cython_module = self.get_cython_function().module
738
739         if lineno in cython_module.lineno_cy2c:
740             c_lineno = cython_module.lineno_cy2c[lineno]
741             breakpoint = '%s:%s' % (cython_module.c_filename, c_lineno)
742             gdb.execute('break ' + breakpoint)
743         else:
744             raise GdbError("Not a valid line number. "
745                            "Does it contain actual code?")
746     
747     def _break_funcname(self, funcname):
748         func = self.cy.functions_by_qualified_name.get(funcname)
749         break_funcs = [func]
750         
751         if not func:
752             funcs = self.cy.functions_by_name.get(funcname)
753             if not funcs:
754                 gdb.execute('break ' + funcname)
755                 return
756                 
757             if len(funcs) > 1:
758                 # multiple functions, let the user pick one
759                 print 'There are multiple such functions:'
760                 for idx, func in enumerate(funcs):
761                     print '%3d) %s' % (idx, func.qualified_name)
762                 
763                 while True:
764                     try:
765                         result = raw_input(
766                             "Select a function, press 'a' for all "
767                             "functions or press 'q' or '^D' to quit: ")
768                     except EOFError:
769                         return
770                     else:
771                         if result.lower() == 'q':
772                             return
773                         elif result.lower() == 'a':
774                             break_funcs = funcs
775                             break
776                         elif (result.isdigit() and 
777                             0 <= int(result) < len(funcs)):
778                             break_funcs = [funcs[int(result)]]
779                             break
780                         else:
781                             print 'Not understood...'
782             else:
783                 break_funcs = [funcs[0]]
784         
785         for func in break_funcs:
786             gdb.execute('break %s' % func.cname)
787             if func.pf_cname:
788                 gdb.execute('break %s' % func.pf_cname)
789     
790     def invoke(self, function_names, from_tty):
791         argv = string_to_argv(function_names.encode('UTF-8'))
792         if function_names.startswith('-p'):
793             argv = argv[1:]
794             python_breakpoints = True
795         else:
796             python_breakpoints = False
797         
798         for funcname in argv:
799             if python_breakpoints:
800                 gdb.execute('py-break %s' % funcname)
801             elif ':' in funcname:
802                 self._break_pyx(funcname)
803             else:
804                 self._break_funcname(funcname)
805     
806     @dont_suppress_errors
807     def complete(self, text, word):
808         names = self.cy.functions_by_qualified_name
809         if parameters.complete_unqualified:
810             names = itertools.chain(names, self.cy.functions_by_name)
811
812         words = text.strip().split()
813         if words and '.' in words[-1]:
814             lastword = words[-1]
815             compl = [n for n in self.cy.functions_by_qualified_name 
816                            if n.startswith(lastword)]
817         else:
818             seen = set(text[:-len(word)].split())
819             return [n for n in names if n.startswith(word) and n not in seen]
820         
821         if len(lastword) > len(word):
822             # readline sees something (e.g. a '.') as a word boundary, so don't
823             # "recomplete" this prefix
824             strip_prefix_length = len(lastword) - len(word)
825             compl = [n[strip_prefix_length:] for n in compl]
826             
827         return compl
828
829
830 class CythonCodeStepper(CythonCommand, libpython.GenericCodeStepper):
831     """
832     Base class for CyStep and CyNext. It implements the interface dictated by
833     libpython.GenericCodeStepper.
834     """
835     
836     def lineno(self, frame):
837         # Take care of the Python and Cython levels. We need to care for both
838         # as we can't simply dispath to 'py-step', since that would work for
839         # stepping through Python code, but it would not step back into Cython-
840         # related code. The C level should be dispatched to the 'step' command.
841         if self.is_cython_function(frame):
842             return self.get_cython_lineno(frame)
843         else:
844             return libpython.py_step.lineno(frame)
845     
846     def get_source_line(self, frame):
847         try:
848             line = super(CythonCodeStepper, self).get_source_line(frame)
849         except gdb.GdbError:
850             return None
851         else:
852             return line.strip() or None
853
854     @classmethod
855     def register(cls):
856         return cls(cls.name, stepinto=getattr(cls, 'stepinto', False))
857
858     def runtime_break_functions(self):
859         if self.is_cython_function():
860             return self.get_cython_function().step_into_functions
861     
862     def static_break_functions(self):
863         result = ['PyEval_EvalFrameEx']
864         result.extend(self.cy.functions_by_cname)
865         return result
866
867     def invoke(self, args, from_tty):
868         if not self.is_cython_function() and not self.is_python_function():
869             if self.stepinto:
870                 command = 'step'
871             else:
872                 command = 'next'
873                 
874             self.finish_executing(gdb.execute(command, to_string=True))
875         else:
876             super(CythonCodeStepper, self).invoke(args, from_tty)
877
878
879 class CyStep(CythonCodeStepper):
880     "Step through Cython, Python or C code."
881     
882     name = 'cy step'
883     stepinto = True
884
885
886 class CyNext(CythonCodeStepper):
887     "Step-over Python code."
888
889     name = 'cy next'
890     stepinto = False
891
892
893 class CyRun(CythonCodeStepper):
894     """
895     Run a Cython program. This is like the 'run' command, except that it 
896     displays Cython or Python source lines as well
897     """
898     
899     name = 'cy run'
900     _command = 'run'
901     
902     def invoke(self, *args):
903         self.finish_executing(gdb.execute(self._command, to_string=True))
904
905
906 class CyCont(CyRun):
907     """
908     Continue a Cython program. This is like the 'run' command, except that it 
909     displays Cython or Python source lines as well.
910     """
911     
912     name = 'cy cont'
913     _command = 'cont'
914
915
916 class CyUp(CythonCommand):
917     """
918     Go up a Cython, Python or relevant C frame.
919     """
920     name = 'cy up'
921     _command = 'up'
922     
923     def invoke(self, *args):
924         try:
925             gdb.execute(self._command, to_string=True)
926             while not self.is_relevant_function(gdb.selected_frame()):
927                 gdb.execute(self._command, to_string=True)
928         except RuntimeError, e:
929             raise gdb.GdbError(*e.args)
930         
931         frame = gdb.selected_frame()
932         index = 0
933         while frame:
934             frame = frame.older()
935             index += 1
936             
937         self.print_stackframe(index=index - 1)
938
939
940 class CyDown(CyUp):
941     """
942     Go down a Cython, Python or relevant C frame.
943     """
944     
945     name = 'cy down'
946     _command = 'down'
947
948
949 class CyBacktrace(CythonCommand):
950     'Print the Cython stack'
951     
952     name = 'cy bt'
953     alias = 'cy backtrace'
954     command_class = gdb.COMMAND_STACK
955     completer_class = gdb.COMPLETE_NONE
956     
957     @require_running_program
958     def invoke(self, args, from_tty):
959         # get the first frame
960         selected_frame = frame = gdb.selected_frame()
961         while frame.older():
962             frame = frame.older()
963         
964         print_all = args == '-a'
965         
966         index = 0
967         while frame:
968             is_c = False
969             
970             is_relevant = False
971             try:
972                 is_relevant = self.is_relevant_function(frame)
973             except CyGDBError:
974                 pass
975                 
976             if print_all or is_relevant:
977                 self.print_stackframe(frame, index)
978             
979             index += 1
980             frame = frame.newer()
981         
982         selected_frame.select()
983
984
985 class CyList(CythonCommand):
986     """
987     List Cython source code. To disable to customize colouring see the cy_*
988     parameters.
989     """
990     
991     name = 'cy list'
992     command_class = gdb.COMMAND_FILES
993     completer_class = gdb.COMPLETE_NONE
994     
995     @dispatch_on_frame(c_command='list')
996     def invoke(self, _, from_tty):
997         sd, lineno = self.get_source_desc()
998         source = sd.get_source(lineno - 5, lineno + 5, mark_line=lineno, 
999                                lex_entire=True)
1000         print source
1001
1002
1003 class CyPrint(CythonCommand):
1004     """
1005     Print a Cython variable using 'cy-print x' or 'cy-print module.function.x'
1006     """
1007     
1008     name = 'cy print'
1009     command_class = gdb.COMMAND_DATA
1010     
1011     def invoke(self, name, from_tty, max_name_length=None):
1012         if self.is_python_function():
1013             return gdb.execute('py-print ' + name)
1014         elif self.is_cython_function():
1015             value = self.cy.cy_cvalue.invoke(name.lstrip('*'))
1016             for c in name:
1017                 if c == '*':
1018                     value = value.dereference()
1019                 else:
1020                     break
1021                 
1022             self.print_gdb_value(name, value, max_name_length)
1023         else:
1024             gdb.execute('print ' + name)
1025         
1026     def complete(self):
1027         if self.is_cython_function():
1028             f = self.get_cython_function()
1029             return list(itertools.chain(f.locals, f.globals))
1030         else:
1031             return []
1032
1033
1034 sortkey = lambda (name, value): name.lower()
1035
1036 class CyLocals(CythonCommand):
1037     """
1038     List the locals from the current Cython frame.
1039     """
1040     
1041     name = 'cy locals'
1042     command_class = gdb.COMMAND_STACK
1043     completer_class = gdb.COMPLETE_NONE
1044     
1045     def _print_if_initialized(self, cyvar, max_name_length, prefix=''):
1046         try:
1047             value = gdb.parse_and_eval(cyvar.cname)
1048         except RuntimeError:
1049             # variable not initialized yet
1050             pass
1051         else:
1052             self.print_gdb_value(cyvar.name, value, max_name_length, prefix)
1053     
1054     @dispatch_on_frame(c_command='info locals', python_command='py-locals')
1055     def invoke(self, args, from_tty):
1056         local_cython_vars = self.get_cython_function().locals
1057         max_name_length = len(max(local_cython_vars, key=len))
1058         for name, cyvar in sorted(local_cython_vars.iteritems(), key=sortkey):
1059             self._print_if_initialized(cyvar, max_name_length)
1060
1061
1062 class CyGlobals(CyLocals):
1063     """
1064     List the globals from the current Cython module.
1065     """
1066     
1067     name = 'cy globals'
1068     command_class = gdb.COMMAND_STACK
1069     completer_class = gdb.COMPLETE_NONE
1070     
1071     @dispatch_on_frame(c_command='info variables', python_command='py-globals')
1072     def invoke(self, args, from_tty):
1073         global_python_dict = self.get_cython_globals_dict()
1074         module_globals = self.get_cython_function().module.globals
1075         
1076         max_globals_len = 0
1077         max_globals_dict_len = 0
1078         if module_globals:
1079             max_globals_len = len(max(module_globals, key=len))
1080         if global_python_dict:
1081             max_globals_dict_len = len(max(global_python_dict))
1082             
1083         max_name_length = max(max_globals_len, max_globals_dict_len)
1084         
1085         seen = set()
1086         print 'Python globals:'
1087         for k, v in sorted(global_python_dict.iteritems(), key=sortkey):
1088             v = v.get_truncated_repr(libpython.MAX_OUTPUT_LEN)
1089             seen.add(k)
1090             print '    %-*s = %s' % (max_name_length, k, v)
1091         
1092         print 'C globals:'
1093         for name, cyvar in sorted(module_globals.iteritems(), key=sortkey):
1094             if name not in seen:
1095                 self._print_if_initialized(cyvar, max_name_length, 
1096                                            prefix='    ')
1097
1098
1099 # Functions
1100
1101 class CyCName(gdb.Function, CythonBase):
1102     """
1103     Get the C name of a Cython variable in the current context.
1104     Examples:
1105         
1106         print $cy_cname("function")
1107         print $cy_cname("Class.method")
1108         print $cy_cname("module.function")
1109     """
1110     
1111     @require_cython_frame
1112     @gdb_function_value_to_unicode
1113     def invoke(self, cyname, frame=None):
1114         frame = frame or gdb.selected_frame()
1115         cname = None
1116         
1117         if self.is_cython_function(frame):
1118             cython_function = self.get_cython_function(frame)
1119             if cyname in cython_function.locals:
1120                 cname = cython_function.locals[cyname].cname
1121             elif cyname in cython_function.module.globals:
1122                 cname = cython_function.module.globals[cyname].cname
1123             else:
1124                 qname = '%s.%s' % (cython_function.module.name, cyname)
1125                 if qname in cython_function.module.functions:
1126                     cname = cython_function.module.functions[qname].cname
1127             
1128         if not cname:
1129             cname = self.cy.functions_by_qualified_name.get(cyname)
1130             
1131         if not cname:
1132             raise gdb.GdbError('No such Cython variable: %s' % cyname)
1133         
1134         return cname
1135
1136
1137 class CyCValue(CyCName):
1138     """
1139     Get the value of a Cython variable.
1140     """
1141     
1142     @require_cython_frame
1143     @gdb_function_value_to_unicode
1144     def invoke(self, cyname, frame=None):
1145         try:
1146             cname = super(CyCValue, self).invoke(cyname, frame=frame)
1147             return gdb.parse_and_eval(cname)
1148         except (gdb.GdbError, RuntimeError):
1149             # variable exists but may not have been initialized yet, or may be
1150             # in the globals dict of the Cython module
1151             d = self.get_cython_globals_dict()
1152             if cyname in d:
1153                 return d[cyname]._gdbval
1154
1155             raise gdb.GdbError("Variable %s not initialized yet." % cyname)
1156
1157
1158 class CyLine(gdb.Function, CythonBase):
1159     """
1160     Get the current Cython line.
1161     """
1162     
1163     @require_cython_frame
1164     def invoke(self):
1165         return self.get_cython_lineno()
1166
1167
1168 cy = CyCy.register()