blob: 93d0bd446bdd4121a3713c9183ea3663a21203c3 [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
11# advantage of the already existing C++-style headerdoc and make it the Python
12# 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"
31
Johnny Chen14097802011-04-28 21:31:18 +000032#
Johnny Chenec5e0a22011-06-01 18:40:11 +000033# lldb_iter() should appear before our first SB* class definition.
Johnny Chen14097802011-04-28 21:31:18 +000034#
35lldb_iter_def = '''
36# ===================================
37# Iterator for lldb container objects
38# ===================================
39def lldb_iter(obj, getsize, getelem):
40 """A generator adaptor to support iteration for lldb container objects."""
41 size = getattr(obj, getsize)
42 elem = getattr(obj, getelem)
43 for i in range(size()):
44 yield elem(i)
45
Johnny Chen81422202011-06-01 19:21:08 +000046# ==============================================================================
47# The modify-python-lldb.py script is responsible for post-processing this SWIG-
48# generated lldb.py module. It is responsible for adding the above lldb_iter()
49# function definition as well as the supports, in the following, for iteration
50# protocol: __iter__, rich comparison methods: __eq__ and __ne__, truth value
51# testing (and built-in operation bool()): __nonzero__, and built-in function
52# len(): __len__.
53# ==============================================================================
Johnny Chen14097802011-04-28 21:31:18 +000054'''
55
Johnny Chen14097802011-04-28 21:31:18 +000056# This supports the iteration protocol.
Johnny Chen14097802011-04-28 21:31:18 +000057iter_def = " def __iter__(self): return lldb_iter(self, '%s', '%s')"
58module_iter = " def module_iter(self): return lldb_iter(self, '%s', '%s')"
59breakpoint_iter = " def breakpoint_iter(self): return lldb_iter(self, '%s', '%s')"
Johnny Chen2077f0d2011-05-17 22:14:39 +000060
Johnny Chena79a21c2011-05-16 20:31:18 +000061# Called to implement the built-in function len().
62# Eligible objects are those containers with unambiguous iteration support.
Johnny Chena79a21c2011-05-16 20:31:18 +000063len_def = " def __len__(self): return self.%s()"
Johnny Chen2077f0d2011-05-17 22:14:39 +000064
Johnny Chen3a3d6592011-04-29 19:03:02 +000065# This supports the rich comparison methods of __eq__ and __ne__.
Johnny Chen7616cb92011-05-02 19:05:52 +000066eq_def = " def __eq__(self, other): return isinstance(other, %s) and %s"
Johnny Chen3a3d6592011-04-29 19:03:02 +000067ne_def = " def __ne__(self, other): return not self.__eq__(other)"
Johnny Chen14097802011-04-28 21:31:18 +000068
Johnny Chen2077f0d2011-05-17 22:14:39 +000069# Called to implement truth value testing and the built-in operation bool();
70# should return False or True, or their integer equivalents 0 or 1.
71# Delegate to self.IsValid() if it is defined for the current lldb object.
72nonzero_def = " def __nonzero__(self): return self.IsValid()"
73
Johnny Chen14097802011-04-28 21:31:18 +000074#
Johnny Chena6303ef2011-05-24 22:53:03 +000075# This dictionary defines a mapping from classname to (getsize, getelem) tuple.
Johnny Chen14097802011-04-28 21:31:18 +000076#
77d = { 'SBBreakpoint': ('GetNumLocations', 'GetLocationAtIndex'),
78 'SBCompileUnit': ('GetNumLineEntries', 'GetLineEntryAtIndex'),
79 'SBDebugger': ('GetNumTargets', 'GetTargetAtIndex'),
80 'SBModule': ('GetNumSymbols', 'GetSymbolAtIndex'),
81 'SBProcess': ('GetNumThreads', 'GetThreadAtIndex'),
82 'SBThread': ('GetNumFrames', 'GetFrameAtIndex'),
83
84 'SBInstructionList': ('GetSize', 'GetInstructionAtIndex'),
85 'SBStringList': ('GetSize', 'GetStringAtIndex',),
86 'SBSymbolContextList': ('GetSize', 'GetContextAtIndex'),
87 'SBValueList': ('GetSize', 'GetValueAtIndex'),
88
89 'SBType': ('GetNumberChildren', 'GetChildAtIndex'),
90 'SBValue': ('GetNumChildren', 'GetChildAtIndex'),
91
Johnny Chen08477f52011-05-24 22:57:42 +000092 # SBTarget needs special processing, see below.
Johnny Chen14097802011-04-28 21:31:18 +000093 'SBTarget': {'module': ('GetNumModules', 'GetModuleAtIndex'),
94 'breakpoint': ('GetNumBreakpoints', 'GetBreakpointAtIndex')
95 }
96 }
97
Johnny Chen3a3d6592011-04-29 19:03:02 +000098#
Johnny Chen7616cb92011-05-02 19:05:52 +000099# This dictionary defines a mapping from classname to equality method name(s).
Johnny Chen3a3d6592011-04-29 19:03:02 +0000100#
Johnny Chen694cfd02011-06-09 22:04:56 +0000101e = { 'SBAddress': ['GetFileAddress', 'GetModule'],
102 'SBBreakpoint': ['GetID'],
Johnny Chen7616cb92011-05-02 19:05:52 +0000103 'SBFileSpec': ['GetFilename', 'GetDirectory'],
104 'SBModule': ['GetFileSpec', 'GetUUIDString']
105 }
106
107def list_to_frag(list):
108 """Transform a list to equality program fragment.
109
110 For example, ['GetID'] is transformed to 'self.GetID() == other.GetID()',
111 and ['GetFilename', 'GetDirectory'] to 'self.GetFilename() == other.GetFilename()
112 and self.GetDirectory() == other.GetDirectory()'.
113 """
114 if not list:
115 raise Exception("list should be non-empty")
116 frag = StringIO.StringIO()
117 for i in range(len(list)):
118 if i > 0:
119 frag.write(" and ")
120 frag.write("self.{0}() == other.{0}()".format(list[i]))
121 return frag.getvalue()
Johnny Chen3a3d6592011-04-29 19:03:02 +0000122
Johnny Chen14097802011-04-28 21:31:18 +0000123# The new content will have the iteration protocol defined for our lldb objects.
124new_content = StringIO.StringIO()
125
126with open(output_name, 'r') as f_in:
127 content = f_in.read()
128
129# The pattern for recognizing the beginning of an SB class definition.
130class_pattern = re.compile("^class (SB.*)\(_object\):$")
131
132# The pattern for recognizing the beginning of the __init__ method definition.
133init_pattern = re.compile("^ def __init__\(self, \*args\):")
134
Johnny Chen2077f0d2011-05-17 22:14:39 +0000135# The pattern for recognizing the beginning of the IsValid method definition.
Peter Collingbournef2084532011-06-14 03:55:41 +0000136isvalid_pattern = re.compile("^ def IsValid\(")
Johnny Chen2077f0d2011-05-17 22:14:39 +0000137
Johnny Chena79a21c2011-05-16 20:31:18 +0000138# These define the states of our finite state machine.
Johnny Chen14097802011-04-28 21:31:18 +0000139NORMAL = 0
140DEFINING_ITERATOR = 1
Johnny Chen3a3d6592011-04-29 19:03:02 +0000141DEFINING_EQUALITY = 2
Johnny Chen14097802011-04-28 21:31:18 +0000142
143# The lldb_iter_def only needs to be inserted once.
144lldb_iter_defined = False;
145
Johnny Chen2077f0d2011-05-17 22:14:39 +0000146# Our FSM begins its life in the NORMAL state, and transitions to the
147# DEFINING_ITERATOR and/or DEFINING_EQUALITY state whenever it encounters the
148# beginning of certain class definitions, see dictionaries 'd' and 'e' above.
149#
150# Note that the two states DEFINING_ITERATOR and DEFINING_EQUALITY are
151# orthogonal in that our FSM can be in one, the other, or both states at the
152# same time. During such time, the FSM is eagerly searching for the __init__
153# method definition in order to insert the appropriate method(s) into the lldb
154# module.
155#
Johnny Chenb72d1772011-05-24 22:29:49 +0000156# The FSM, in all possible states, also checks the current input for IsValid()
157# definition, and inserts a __nonzero__() method definition to implement truth
158# value testing and the built-in operation bool().
Johnny Chen14097802011-04-28 21:31:18 +0000159state = NORMAL
160for line in content.splitlines():
Johnny Chen09e0a422011-07-01 22:14:07 +0000161 # Cleanse the lldb.py of the autodoc'ed residues.
162 if c_ifdef_swig in line or c_endif_swig in line:
163 continue
164 # Also remove the '\a ' substrings.
165 line = line.replace('\a ', '')
166
Johnny Chen14097802011-04-28 21:31:18 +0000167 if state == NORMAL:
168 match = class_pattern.search(line)
Johnny Chen2077f0d2011-05-17 22:14:39 +0000169 # Inserts the lldb_iter() definition before the first class definition.
Johnny Chen14097802011-04-28 21:31:18 +0000170 if not lldb_iter_defined and match:
171 print >> new_content, lldb_iter_def
172 lldb_iter_defined = True
Johnny Chen2077f0d2011-05-17 22:14:39 +0000173
174 # If we are at the beginning of the class definitions, prepare to
175 # transition to the DEFINING_ITERATOR/DEFINING_EQUALITY state for the
176 # right class names.
Johnny Chen3a3d6592011-04-29 19:03:02 +0000177 if match:
Johnny Chen14097802011-04-28 21:31:18 +0000178 cls = match.group(1)
Johnny Chen3a3d6592011-04-29 19:03:02 +0000179 if cls in d:
180 # Adding support for iteration for the matched SB class.
181 state = (state | DEFINING_ITERATOR)
182 if cls in e:
183 # Adding support for eq and ne for the matched SB class.
184 state = (state | DEFINING_EQUALITY)
185 elif state > NORMAL:
Johnny Chen14097802011-04-28 21:31:18 +0000186 match = init_pattern.search(line)
187 if match:
188 # We found the beginning of the __init__ method definition.
Johnny Chen3a3d6592011-04-29 19:03:02 +0000189 # This is a good spot to insert the iter and/or eq-ne support.
Johnny Chen14097802011-04-28 21:31:18 +0000190 #
191 # But note that SBTarget has two types of iterations.
192 if cls == "SBTarget":
193 print >> new_content, module_iter % (d[cls]['module'])
194 print >> new_content, breakpoint_iter % (d[cls]['breakpoint'])
195 else:
Johnny Chen3a3d6592011-04-29 19:03:02 +0000196 if (state & DEFINING_ITERATOR):
197 print >> new_content, iter_def % d[cls]
Johnny Chena79a21c2011-05-16 20:31:18 +0000198 print >> new_content, len_def % d[cls][0]
Johnny Chen3a3d6592011-04-29 19:03:02 +0000199 if (state & DEFINING_EQUALITY):
Johnny Chen7616cb92011-05-02 19:05:52 +0000200 print >> new_content, eq_def % (cls, list_to_frag(e[cls]))
Johnny Chen3a3d6592011-04-29 19:03:02 +0000201 print >> new_content, ne_def
Johnny Chena2f86e82011-04-29 19:19:13 +0000202
203 # Next state will be NORMAL.
204 state = NORMAL
Johnny Chen14097802011-04-28 21:31:18 +0000205
Johnny Chenb72d1772011-05-24 22:29:49 +0000206 # Look for 'def IsValid(*args):', and once located, add implementation
207 # of truth value testing for this object by delegation.
208 if isvalid_pattern.search(line):
209 print >> new_content, nonzero_def
210
Johnny Chen6ea16c72011-05-02 17:53:04 +0000211 # Pass the original line of content to new_content.
Johnny Chen14097802011-04-28 21:31:18 +0000212 print >> new_content, line
213
214with open(output_name, 'w') as f_out:
215 f_out.write(new_content.getvalue())
216 f_out.write("debugger_unique_id = 0\n")
217 f_out.write("SBDebugger.Initialize()\n")