blob: 2e2c8be4fa1eec4047424019dcca13b530721963 [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
Johnny Chenf6ce70a2011-07-03 19:55:50 +000013# '#endif', the '#ifdef SWIG', the c comment marker, the trailing blank (SPC's)
14# line, and the doxygen comment start marker.
Johnny Chen09e0a422011-07-01 22:14:07 +000015#
Johnny Chen37811372011-07-06 21:55:45 +000016# In addition to the 'residues' removal during the cleanup step, it also
17# transforms the 'char' data type (which was actually 'char *' but the 'autodoc'
18# feature of swig removes ' *' from it into 'str' (as a Python str type).
19#
Johnny Chen14097802011-04-28 21:31:18 +000020# It also calls SBDebugger.Initialize() to initialize the lldb debugger
21# subsystem.
22#
23
24import sys, re, StringIO
25
26if len (sys.argv) != 2:
27 output_name = "./lldb.py"
28else:
29 output_name = sys.argv[1] + "/lldb.py"
30
31# print "output_name is '" + output_name + "'"
32
Johnny Chen37811372011-07-06 21:55:45 +000033#
Johnny Chen09e0a422011-07-01 22:14:07 +000034# Residues to be removed.
Johnny Chen37811372011-07-06 21:55:45 +000035#
Johnny Chen09e0a422011-07-01 22:14:07 +000036c_endif_swig = "#endif"
37c_ifdef_swig = "#ifdef SWIG"
Johnny Chen2c77fa42011-07-02 20:01:09 +000038c_comment_marker = "//------------"
Johnny Chenf451e302011-07-03 01:43:29 +000039trailing_blank_line = ' '
Johnny Chen2c77fa42011-07-02 20:01:09 +000040# The pattern for recognizing the doxygen comment block line.
41doxygen_comment_start = re.compile("^\s*( /// ?)")
Johnny Chenf6ce70a2011-07-03 19:55:50 +000042# The demarcation point for turning on/off residue removal state.
43# When bracketed by the lines, the CLEANUP_DOCSTRING state (see below) is ON.
44toggle_docstring_cleanup_line = ' """'
Johnny Chen09e0a422011-07-01 22:14:07 +000045
Johnny Chen37811372011-07-06 21:55:45 +000046def char_to_str_xform(line):
47 """This transforms the 'char', i.e, 'char *' to 'str', Python string."""
48 line = line.replace(' char', ' str')
49 line = line.replace('char ', 'str ')
50 return line
51
52#
53# The one-liner docstring also needs char_to_str transformation, btw.
54#
55one_liner_docstring_pattern = re.compile('^ """.*"""$')
56
Johnny Chen14097802011-04-28 21:31:18 +000057#
Johnny Chenec5e0a22011-06-01 18:40:11 +000058# lldb_iter() should appear before our first SB* class definition.
Johnny Chen14097802011-04-28 21:31:18 +000059#
60lldb_iter_def = '''
61# ===================================
62# Iterator for lldb container objects
63# ===================================
64def lldb_iter(obj, getsize, getelem):
65 """A generator adaptor to support iteration for lldb container objects."""
66 size = getattr(obj, getsize)
67 elem = getattr(obj, getelem)
68 for i in range(size()):
69 yield elem(i)
70
Johnny Chen81422202011-06-01 19:21:08 +000071# ==============================================================================
72# The modify-python-lldb.py script is responsible for post-processing this SWIG-
73# generated lldb.py module. It is responsible for adding the above lldb_iter()
74# function definition as well as the supports, in the following, for iteration
75# protocol: __iter__, rich comparison methods: __eq__ and __ne__, truth value
76# testing (and built-in operation bool()): __nonzero__, and built-in function
77# len(): __len__.
78# ==============================================================================
Johnny Chen14097802011-04-28 21:31:18 +000079'''
80
Johnny Chen14097802011-04-28 21:31:18 +000081# This supports the iteration protocol.
Johnny Chen14097802011-04-28 21:31:18 +000082iter_def = " def __iter__(self): return lldb_iter(self, '%s', '%s')"
83module_iter = " def module_iter(self): return lldb_iter(self, '%s', '%s')"
84breakpoint_iter = " def breakpoint_iter(self): return lldb_iter(self, '%s', '%s')"
Johnny Chen2077f0d2011-05-17 22:14:39 +000085
Johnny Chena79a21c2011-05-16 20:31:18 +000086# Called to implement the built-in function len().
87# Eligible objects are those containers with unambiguous iteration support.
Johnny Chena79a21c2011-05-16 20:31:18 +000088len_def = " def __len__(self): return self.%s()"
Johnny Chen2077f0d2011-05-17 22:14:39 +000089
Johnny Chen3a3d6592011-04-29 19:03:02 +000090# This supports the rich comparison methods of __eq__ and __ne__.
Johnny Chen7616cb92011-05-02 19:05:52 +000091eq_def = " def __eq__(self, other): return isinstance(other, %s) and %s"
Johnny Chen3a3d6592011-04-29 19:03:02 +000092ne_def = " def __ne__(self, other): return not self.__eq__(other)"
Johnny Chen14097802011-04-28 21:31:18 +000093
Johnny Chen2077f0d2011-05-17 22:14:39 +000094# Called to implement truth value testing and the built-in operation bool();
95# should return False or True, or their integer equivalents 0 or 1.
96# Delegate to self.IsValid() if it is defined for the current lldb object.
97nonzero_def = " def __nonzero__(self): return self.IsValid()"
98
Johnny Chen14097802011-04-28 21:31:18 +000099#
Johnny Chena6303ef2011-05-24 22:53:03 +0000100# This dictionary defines a mapping from classname to (getsize, getelem) tuple.
Johnny Chen14097802011-04-28 21:31:18 +0000101#
102d = { 'SBBreakpoint': ('GetNumLocations', 'GetLocationAtIndex'),
103 'SBCompileUnit': ('GetNumLineEntries', 'GetLineEntryAtIndex'),
104 'SBDebugger': ('GetNumTargets', 'GetTargetAtIndex'),
105 'SBModule': ('GetNumSymbols', 'GetSymbolAtIndex'),
106 'SBProcess': ('GetNumThreads', 'GetThreadAtIndex'),
107 'SBThread': ('GetNumFrames', 'GetFrameAtIndex'),
108
109 'SBInstructionList': ('GetSize', 'GetInstructionAtIndex'),
110 'SBStringList': ('GetSize', 'GetStringAtIndex',),
111 'SBSymbolContextList': ('GetSize', 'GetContextAtIndex'),
112 'SBValueList': ('GetSize', 'GetValueAtIndex'),
113
114 'SBType': ('GetNumberChildren', 'GetChildAtIndex'),
115 'SBValue': ('GetNumChildren', 'GetChildAtIndex'),
116
Johnny Chen08477f52011-05-24 22:57:42 +0000117 # SBTarget needs special processing, see below.
Johnny Chen14097802011-04-28 21:31:18 +0000118 'SBTarget': {'module': ('GetNumModules', 'GetModuleAtIndex'),
119 'breakpoint': ('GetNumBreakpoints', 'GetBreakpointAtIndex')
120 }
121 }
122
Johnny Chen3a3d6592011-04-29 19:03:02 +0000123#
Johnny Chen7616cb92011-05-02 19:05:52 +0000124# This dictionary defines a mapping from classname to equality method name(s).
Johnny Chen3a3d6592011-04-29 19:03:02 +0000125#
Johnny Chen694cfd02011-06-09 22:04:56 +0000126e = { 'SBAddress': ['GetFileAddress', 'GetModule'],
127 'SBBreakpoint': ['GetID'],
Johnny Chen7616cb92011-05-02 19:05:52 +0000128 'SBFileSpec': ['GetFilename', 'GetDirectory'],
129 'SBModule': ['GetFileSpec', 'GetUUIDString']
130 }
131
132def list_to_frag(list):
133 """Transform a list to equality program fragment.
134
135 For example, ['GetID'] is transformed to 'self.GetID() == other.GetID()',
136 and ['GetFilename', 'GetDirectory'] to 'self.GetFilename() == other.GetFilename()
137 and self.GetDirectory() == other.GetDirectory()'.
138 """
139 if not list:
140 raise Exception("list should be non-empty")
141 frag = StringIO.StringIO()
142 for i in range(len(list)):
143 if i > 0:
144 frag.write(" and ")
145 frag.write("self.{0}() == other.{0}()".format(list[i]))
146 return frag.getvalue()
Johnny Chen3a3d6592011-04-29 19:03:02 +0000147
Johnny Chen14097802011-04-28 21:31:18 +0000148# The new content will have the iteration protocol defined for our lldb objects.
149new_content = StringIO.StringIO()
150
151with open(output_name, 'r') as f_in:
152 content = f_in.read()
153
154# The pattern for recognizing the beginning of an SB class definition.
155class_pattern = re.compile("^class (SB.*)\(_object\):$")
156
157# The pattern for recognizing the beginning of the __init__ method definition.
158init_pattern = re.compile("^ def __init__\(self, \*args\):")
159
Johnny Chen2077f0d2011-05-17 22:14:39 +0000160# The pattern for recognizing the beginning of the IsValid method definition.
Peter Collingbournef2084532011-06-14 03:55:41 +0000161isvalid_pattern = re.compile("^ def IsValid\(")
Johnny Chen2077f0d2011-05-17 22:14:39 +0000162
Johnny Chena79a21c2011-05-16 20:31:18 +0000163# These define the states of our finite state machine.
Johnny Chen14097802011-04-28 21:31:18 +0000164NORMAL = 0
165DEFINING_ITERATOR = 1
Johnny Chen3a3d6592011-04-29 19:03:02 +0000166DEFINING_EQUALITY = 2
Johnny Chenf6ce70a2011-07-03 19:55:50 +0000167CLEANUP_DOCSTRING = 4
Johnny Chen14097802011-04-28 21:31:18 +0000168
169# The lldb_iter_def only needs to be inserted once.
170lldb_iter_defined = False;
171
Johnny Chen2077f0d2011-05-17 22:14:39 +0000172# Our FSM begins its life in the NORMAL state, and transitions to the
173# DEFINING_ITERATOR and/or DEFINING_EQUALITY state whenever it encounters the
174# beginning of certain class definitions, see dictionaries 'd' and 'e' above.
175#
176# Note that the two states DEFINING_ITERATOR and DEFINING_EQUALITY are
177# orthogonal in that our FSM can be in one, the other, or both states at the
178# same time. During such time, the FSM is eagerly searching for the __init__
179# method definition in order to insert the appropriate method(s) into the lldb
180# module.
181#
Johnny Chenf6ce70a2011-07-03 19:55:50 +0000182# The state CLEANUP_DOCSTRING can be entered from either the NORMAL or the
183# DEFINING_ITERATOR/EQUALITY states. While in this state, the FSM is fixing/
184# cleaning the Python docstrings generated by the swig docstring features.
185#
Johnny Chenb72d1772011-05-24 22:29:49 +0000186# The FSM, in all possible states, also checks the current input for IsValid()
187# definition, and inserts a __nonzero__() method definition to implement truth
188# value testing and the built-in operation bool().
Johnny Chen14097802011-04-28 21:31:18 +0000189state = NORMAL
190for line in content.splitlines():
Johnny Chenf6ce70a2011-07-03 19:55:50 +0000191 # Handle the state transition into CLEANUP_DOCSTRING state as it is possible
192 # to enter this state from either NORMAL or DEFINING_ITERATOR/EQUALITY.
193 #
194 # If ' """' is the sole line, prepare to transition to the
195 # CLEANUP_DOCSTRING state or out of it.
196 if line == toggle_docstring_cleanup_line:
197 if state & CLEANUP_DOCSTRING:
198 state ^= CLEANUP_DOCSTRING
199 else:
200 state |= CLEANUP_DOCSTRING
Johnny Chen09e0a422011-07-01 22:14:07 +0000201
Johnny Chen14097802011-04-28 21:31:18 +0000202 if state == NORMAL:
203 match = class_pattern.search(line)
Johnny Chen2077f0d2011-05-17 22:14:39 +0000204 # Inserts the lldb_iter() definition before the first class definition.
Johnny Chen14097802011-04-28 21:31:18 +0000205 if not lldb_iter_defined and match:
206 print >> new_content, lldb_iter_def
207 lldb_iter_defined = True
Johnny Chen2077f0d2011-05-17 22:14:39 +0000208
209 # If we are at the beginning of the class definitions, prepare to
210 # transition to the DEFINING_ITERATOR/DEFINING_EQUALITY state for the
211 # right class names.
Johnny Chen3a3d6592011-04-29 19:03:02 +0000212 if match:
Johnny Chen14097802011-04-28 21:31:18 +0000213 cls = match.group(1)
Johnny Chen3a3d6592011-04-29 19:03:02 +0000214 if cls in d:
215 # Adding support for iteration for the matched SB class.
Johnny Chenf6ce70a2011-07-03 19:55:50 +0000216 state |= DEFINING_ITERATOR
Johnny Chen3a3d6592011-04-29 19:03:02 +0000217 if cls in e:
218 # Adding support for eq and ne for the matched SB class.
Johnny Chenf6ce70a2011-07-03 19:55:50 +0000219 state |= DEFINING_EQUALITY
220
221 elif (state & DEFINING_ITERATOR) or (state & DEFINING_EQUALITY):
Johnny Chen14097802011-04-28 21:31:18 +0000222 match = init_pattern.search(line)
223 if match:
224 # We found the beginning of the __init__ method definition.
Johnny Chen3a3d6592011-04-29 19:03:02 +0000225 # This is a good spot to insert the iter and/or eq-ne support.
Johnny Chen14097802011-04-28 21:31:18 +0000226 #
227 # But note that SBTarget has two types of iterations.
228 if cls == "SBTarget":
229 print >> new_content, module_iter % (d[cls]['module'])
230 print >> new_content, breakpoint_iter % (d[cls]['breakpoint'])
231 else:
Johnny Chen3a3d6592011-04-29 19:03:02 +0000232 if (state & DEFINING_ITERATOR):
233 print >> new_content, iter_def % d[cls]
Johnny Chena79a21c2011-05-16 20:31:18 +0000234 print >> new_content, len_def % d[cls][0]
Johnny Chen3a3d6592011-04-29 19:03:02 +0000235 if (state & DEFINING_EQUALITY):
Johnny Chen7616cb92011-05-02 19:05:52 +0000236 print >> new_content, eq_def % (cls, list_to_frag(e[cls]))
Johnny Chen3a3d6592011-04-29 19:03:02 +0000237 print >> new_content, ne_def
Johnny Chena2f86e82011-04-29 19:19:13 +0000238
239 # Next state will be NORMAL.
240 state = NORMAL
Johnny Chen14097802011-04-28 21:31:18 +0000241
Johnny Chenf6ce70a2011-07-03 19:55:50 +0000242 elif (state & CLEANUP_DOCSTRING):
243 # Cleanse the lldb.py of the autodoc'ed residues.
244 if c_ifdef_swig in line or c_endif_swig in line:
245 continue
246 # As well as the comment marker line and trailing blank line.
247 if c_comment_marker in line or line == trailing_blank_line:
248 continue
249 # Also remove the '\a ' substrings.
250 line = line.replace('\a ', '')
251 # And the leading '///' substring.
252 doxygen_comment_match = doxygen_comment_start.match(line)
253 if doxygen_comment_match:
254 line = line.replace(doxygen_comment_match.group(1), '', 1)
255
Johnny Chen37811372011-07-06 21:55:45 +0000256 line = char_to_str_xform(line)
257
Johnny Chenf6ce70a2011-07-03 19:55:50 +0000258 # Note that the transition out of CLEANUP_DOCSTRING is handled at the
259 # beginning of this function already.
260
Johnny Chen37811372011-07-06 21:55:45 +0000261 # This deals with one-liner docstring, for example, SBThread.GetName:
262 # """GetName(self) -> char""".
263 if one_liner_docstring_pattern.match(line):
264 line = char_to_str_xform(line)
265
Johnny Chenb72d1772011-05-24 22:29:49 +0000266 # Look for 'def IsValid(*args):', and once located, add implementation
267 # of truth value testing for this object by delegation.
268 if isvalid_pattern.search(line):
269 print >> new_content, nonzero_def
270
Johnny Chen6ea16c72011-05-02 17:53:04 +0000271 # Pass the original line of content to new_content.
Johnny Chen14097802011-04-28 21:31:18 +0000272 print >> new_content, line
273
274with open(output_name, 'w') as f_out:
275 f_out.write(new_content.getvalue())
276 f_out.write("debugger_unique_id = 0\n")
277 f_out.write("SBDebugger.Initialize()\n")