blob: 1e43ffd9bdf319771223cde894dbfc8dc3f059b0 [file] [log] [blame]
Johnny Chen14097802011-04-28 21:31:18 +00001#
Johnny Chenc6220052011-04-28 23:53:16 +00002# modify-lldb-python.py
Johnny Chen14097802011-04-28 21:31:18 +00003#
4# This script modifies the lldb module (which was automatically generated via
Johnny Chen22e418a2011-04-29 19:22:24 +00005# running swig) to support iteration and/or equality operations for certain lldb
Johnny Chene5637d22011-05-24 21:05:16 +00006# objects, implements truth value testing for certain lldb objects, and adds a
7# global variable 'debugger_unique_id' which is initialized to 0.
Johnny Chen14097802011-04-28 21:31:18 +00008#
Johnny Chen09e0a422011-07-01 22:14:07 +00009# As a cleanup step, it also removes the 'residues' from the autodoc features of
10# swig. For an example, take a look at SBTarget.h header file, where we take
Johnny Chen2c77fa42011-07-02 20:01:09 +000011# advantage of the already existing doxygen C++-docblock and make it the Python
Johnny Chen09e0a422011-07-01 22:14:07 +000012# docstring for the same method. The 'residues' in this context include the
13# '#endif' and the '#ifdef SWIG' lines.
14#
Johnny Chen14097802011-04-28 21:31:18 +000015# It also calls SBDebugger.Initialize() to initialize the lldb debugger
16# subsystem.
17#
18
19import sys, re, StringIO
20
21if len (sys.argv) != 2:
22 output_name = "./lldb.py"
23else:
24 output_name = sys.argv[1] + "/lldb.py"
25
26# print "output_name is '" + output_name + "'"
27
Johnny Chen09e0a422011-07-01 22:14:07 +000028# Residues to be removed.
29c_endif_swig = "#endif"
30c_ifdef_swig = "#ifdef SWIG"
Johnny Chen2c77fa42011-07-02 20:01:09 +000031c_comment_marker = "//------------"
Johnny Chenf451e302011-07-03 01:43:29 +000032trailing_blank_line = ' '
Johnny Chen2c77fa42011-07-02 20:01:09 +000033# The pattern for recognizing the doxygen comment block line.
34doxygen_comment_start = re.compile("^\s*( /// ?)")
Johnny Chen09e0a422011-07-01 22:14:07 +000035
Johnny Chen14097802011-04-28 21:31:18 +000036#
Johnny Chenec5e0a22011-06-01 18:40:11 +000037# lldb_iter() should appear before our first SB* class definition.
Johnny Chen14097802011-04-28 21:31:18 +000038#
39lldb_iter_def = '''
40# ===================================
41# Iterator for lldb container objects
42# ===================================
43def lldb_iter(obj, getsize, getelem):
44 """A generator adaptor to support iteration for lldb container objects."""
45 size = getattr(obj, getsize)
46 elem = getattr(obj, getelem)
47 for i in range(size()):
48 yield elem(i)
49
Johnny Chen81422202011-06-01 19:21:08 +000050# ==============================================================================
51# The modify-python-lldb.py script is responsible for post-processing this SWIG-
52# generated lldb.py module. It is responsible for adding the above lldb_iter()
53# function definition as well as the supports, in the following, for iteration
54# protocol: __iter__, rich comparison methods: __eq__ and __ne__, truth value
55# testing (and built-in operation bool()): __nonzero__, and built-in function
56# len(): __len__.
57# ==============================================================================
Johnny Chen14097802011-04-28 21:31:18 +000058'''
59
Johnny Chen14097802011-04-28 21:31:18 +000060# This supports the iteration protocol.
Johnny Chen14097802011-04-28 21:31:18 +000061iter_def = " def __iter__(self): return lldb_iter(self, '%s', '%s')"
62module_iter = " def module_iter(self): return lldb_iter(self, '%s', '%s')"
63breakpoint_iter = " def breakpoint_iter(self): return lldb_iter(self, '%s', '%s')"
Johnny Chen2077f0d2011-05-17 22:14:39 +000064
Johnny Chena79a21c2011-05-16 20:31:18 +000065# Called to implement the built-in function len().
66# Eligible objects are those containers with unambiguous iteration support.
Johnny Chena79a21c2011-05-16 20:31:18 +000067len_def = " def __len__(self): return self.%s()"
Johnny Chen2077f0d2011-05-17 22:14:39 +000068
Johnny Chen3a3d6592011-04-29 19:03:02 +000069# This supports the rich comparison methods of __eq__ and __ne__.
Johnny Chen7616cb92011-05-02 19:05:52 +000070eq_def = " def __eq__(self, other): return isinstance(other, %s) and %s"
Johnny Chen3a3d6592011-04-29 19:03:02 +000071ne_def = " def __ne__(self, other): return not self.__eq__(other)"
Johnny Chen14097802011-04-28 21:31:18 +000072
Johnny Chen2077f0d2011-05-17 22:14:39 +000073# Called to implement truth value testing and the built-in operation bool();
74# should return False or True, or their integer equivalents 0 or 1.
75# Delegate to self.IsValid() if it is defined for the current lldb object.
76nonzero_def = " def __nonzero__(self): return self.IsValid()"
77
Johnny Chen14097802011-04-28 21:31:18 +000078#
Johnny Chena6303ef2011-05-24 22:53:03 +000079# This dictionary defines a mapping from classname to (getsize, getelem) tuple.
Johnny Chen14097802011-04-28 21:31:18 +000080#
81d = { 'SBBreakpoint': ('GetNumLocations', 'GetLocationAtIndex'),
82 'SBCompileUnit': ('GetNumLineEntries', 'GetLineEntryAtIndex'),
83 'SBDebugger': ('GetNumTargets', 'GetTargetAtIndex'),
84 'SBModule': ('GetNumSymbols', 'GetSymbolAtIndex'),
85 'SBProcess': ('GetNumThreads', 'GetThreadAtIndex'),
86 'SBThread': ('GetNumFrames', 'GetFrameAtIndex'),
87
88 'SBInstructionList': ('GetSize', 'GetInstructionAtIndex'),
89 'SBStringList': ('GetSize', 'GetStringAtIndex',),
90 'SBSymbolContextList': ('GetSize', 'GetContextAtIndex'),
91 'SBValueList': ('GetSize', 'GetValueAtIndex'),
92
93 'SBType': ('GetNumberChildren', 'GetChildAtIndex'),
94 'SBValue': ('GetNumChildren', 'GetChildAtIndex'),
95
Johnny Chen08477f52011-05-24 22:57:42 +000096 # SBTarget needs special processing, see below.
Johnny Chen14097802011-04-28 21:31:18 +000097 'SBTarget': {'module': ('GetNumModules', 'GetModuleAtIndex'),
98 'breakpoint': ('GetNumBreakpoints', 'GetBreakpointAtIndex')
99 }
100 }
101
Johnny Chen3a3d6592011-04-29 19:03:02 +0000102#
Johnny Chen7616cb92011-05-02 19:05:52 +0000103# This dictionary defines a mapping from classname to equality method name(s).
Johnny Chen3a3d6592011-04-29 19:03:02 +0000104#
Johnny Chen694cfd02011-06-09 22:04:56 +0000105e = { 'SBAddress': ['GetFileAddress', 'GetModule'],
106 'SBBreakpoint': ['GetID'],
Johnny Chen7616cb92011-05-02 19:05:52 +0000107 'SBFileSpec': ['GetFilename', 'GetDirectory'],
108 'SBModule': ['GetFileSpec', 'GetUUIDString']
109 }
110
111def list_to_frag(list):
112 """Transform a list to equality program fragment.
113
114 For example, ['GetID'] is transformed to 'self.GetID() == other.GetID()',
115 and ['GetFilename', 'GetDirectory'] to 'self.GetFilename() == other.GetFilename()
116 and self.GetDirectory() == other.GetDirectory()'.
117 """
118 if not list:
119 raise Exception("list should be non-empty")
120 frag = StringIO.StringIO()
121 for i in range(len(list)):
122 if i > 0:
123 frag.write(" and ")
124 frag.write("self.{0}() == other.{0}()".format(list[i]))
125 return frag.getvalue()
Johnny Chen3a3d6592011-04-29 19:03:02 +0000126
Johnny Chen14097802011-04-28 21:31:18 +0000127# The new content will have the iteration protocol defined for our lldb objects.
128new_content = StringIO.StringIO()
129
130with open(output_name, 'r') as f_in:
131 content = f_in.read()
132
133# The pattern for recognizing the beginning of an SB class definition.
134class_pattern = re.compile("^class (SB.*)\(_object\):$")
135
136# The pattern for recognizing the beginning of the __init__ method definition.
137init_pattern = re.compile("^ def __init__\(self, \*args\):")
138
Johnny Chen2077f0d2011-05-17 22:14:39 +0000139# The pattern for recognizing the beginning of the IsValid method definition.
Peter Collingbournef2084532011-06-14 03:55:41 +0000140isvalid_pattern = re.compile("^ def IsValid\(")
Johnny Chen2077f0d2011-05-17 22:14:39 +0000141
Johnny Chena79a21c2011-05-16 20:31:18 +0000142# These define the states of our finite state machine.
Johnny Chen14097802011-04-28 21:31:18 +0000143NORMAL = 0
144DEFINING_ITERATOR = 1
Johnny Chen3a3d6592011-04-29 19:03:02 +0000145DEFINING_EQUALITY = 2
Johnny Chen14097802011-04-28 21:31:18 +0000146
147# The lldb_iter_def only needs to be inserted once.
148lldb_iter_defined = False;
149
Johnny Chen2077f0d2011-05-17 22:14:39 +0000150# Our FSM begins its life in the NORMAL state, and transitions to the
151# DEFINING_ITERATOR and/or DEFINING_EQUALITY state whenever it encounters the
152# beginning of certain class definitions, see dictionaries 'd' and 'e' above.
153#
154# Note that the two states DEFINING_ITERATOR and DEFINING_EQUALITY are
155# orthogonal in that our FSM can be in one, the other, or both states at the
156# same time. During such time, the FSM is eagerly searching for the __init__
157# method definition in order to insert the appropriate method(s) into the lldb
158# module.
159#
Johnny Chenb72d1772011-05-24 22:29:49 +0000160# The FSM, in all possible states, also checks the current input for IsValid()
161# definition, and inserts a __nonzero__() method definition to implement truth
162# value testing and the built-in operation bool().
Johnny Chen14097802011-04-28 21:31:18 +0000163state = NORMAL
164for line in content.splitlines():
Johnny Chen09e0a422011-07-01 22:14:07 +0000165 # Cleanse the lldb.py of the autodoc'ed residues.
166 if c_ifdef_swig in line or c_endif_swig in line:
167 continue
Johnny Chenf451e302011-07-03 01:43:29 +0000168 # As well as the comment marker line and trailing blank line.
169 if c_comment_marker in line or line == trailing_blank_line:
Johnny Chen2c77fa42011-07-02 20:01:09 +0000170 continue
Johnny Chen09e0a422011-07-01 22:14:07 +0000171 # Also remove the '\a ' substrings.
172 line = line.replace('\a ', '')
Johnny Chen2c77fa42011-07-02 20:01:09 +0000173 # And the leading '///' substring.
174 doxygen_comment_match = doxygen_comment_start.match(line)
175 if doxygen_comment_match:
176 line = line.replace(doxygen_comment_match.group(1), '', 1)
Johnny Chen09e0a422011-07-01 22:14:07 +0000177
Johnny Chen14097802011-04-28 21:31:18 +0000178 if state == NORMAL:
179 match = class_pattern.search(line)
Johnny Chen2077f0d2011-05-17 22:14:39 +0000180 # Inserts the lldb_iter() definition before the first class definition.
Johnny Chen14097802011-04-28 21:31:18 +0000181 if not lldb_iter_defined and match:
182 print >> new_content, lldb_iter_def
183 lldb_iter_defined = True
Johnny Chen2077f0d2011-05-17 22:14:39 +0000184
185 # If we are at the beginning of the class definitions, prepare to
186 # transition to the DEFINING_ITERATOR/DEFINING_EQUALITY state for the
187 # right class names.
Johnny Chen3a3d6592011-04-29 19:03:02 +0000188 if match:
Johnny Chen14097802011-04-28 21:31:18 +0000189 cls = match.group(1)
Johnny Chen3a3d6592011-04-29 19:03:02 +0000190 if cls in d:
191 # Adding support for iteration for the matched SB class.
192 state = (state | DEFINING_ITERATOR)
193 if cls in e:
194 # Adding support for eq and ne for the matched SB class.
195 state = (state | DEFINING_EQUALITY)
196 elif state > NORMAL:
Johnny Chen14097802011-04-28 21:31:18 +0000197 match = init_pattern.search(line)
198 if match:
199 # We found the beginning of the __init__ method definition.
Johnny Chen3a3d6592011-04-29 19:03:02 +0000200 # This is a good spot to insert the iter and/or eq-ne support.
Johnny Chen14097802011-04-28 21:31:18 +0000201 #
202 # But note that SBTarget has two types of iterations.
203 if cls == "SBTarget":
204 print >> new_content, module_iter % (d[cls]['module'])
205 print >> new_content, breakpoint_iter % (d[cls]['breakpoint'])
206 else:
Johnny Chen3a3d6592011-04-29 19:03:02 +0000207 if (state & DEFINING_ITERATOR):
208 print >> new_content, iter_def % d[cls]
Johnny Chena79a21c2011-05-16 20:31:18 +0000209 print >> new_content, len_def % d[cls][0]
Johnny Chen3a3d6592011-04-29 19:03:02 +0000210 if (state & DEFINING_EQUALITY):
Johnny Chen7616cb92011-05-02 19:05:52 +0000211 print >> new_content, eq_def % (cls, list_to_frag(e[cls]))
Johnny Chen3a3d6592011-04-29 19:03:02 +0000212 print >> new_content, ne_def
Johnny Chena2f86e82011-04-29 19:19:13 +0000213
214 # Next state will be NORMAL.
215 state = NORMAL
Johnny Chen14097802011-04-28 21:31:18 +0000216
Johnny Chenb72d1772011-05-24 22:29:49 +0000217 # Look for 'def IsValid(*args):', and once located, add implementation
218 # of truth value testing for this object by delegation.
219 if isvalid_pattern.search(line):
220 print >> new_content, nonzero_def
221
Johnny Chen6ea16c72011-05-02 17:53:04 +0000222 # Pass the original line of content to new_content.
Johnny Chen14097802011-04-28 21:31:18 +0000223 print >> new_content, line
224
225with open(output_name, 'w') as f_out:
226 f_out.write(new_content.getvalue())
227 f_out.write("debugger_unique_id = 0\n")
228 f_out.write("SBDebugger.Initialize()\n")