Skip to content

Commit 7782bdd

Browse files
liuliukolinkrewinkel
authored andcommitted
Make chisel compatible with Python 3 (#266)
* Make chisel compatible with Python 3 Xcode 11 shipped with Python 3 now. Unfortunately, chisel was written in Python 2 style and will fail load for lldb. This PR fixed the Python 3 compatibility issues. * Addressed comment. Updated with file output. * Properly resolve the conflict. * Import from future on print. * Address @lsavino comment.
1 parent dcff372 commit 7782bdd

13 files changed

+113
-109
lines changed

commands/FBAccessibilityCommands.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -126,15 +126,15 @@ def printAccessibilityHierarchy(view, indent = 0):
126126

127127
#if we don't have any accessibility string - we should have some children
128128
if int(a11yLabel.GetValue(), 16) == 0:
129-
print indentString + ('{} {}'.format(classDesc, view))
129+
print(indentString + ('{} {}'.format(classDesc, view)))
130130
#We call private method that gives back all visible accessibility children for view
131131
a11yElements = accessibilityElements(view)
132132
accessibilityElementsCount = int(fb.evaluateExpression('(int)[%s count]' % a11yElements))
133133
for index in range(0, accessibilityElementsCount):
134134
subview = fb.evaluateObjectExpression('[%s objectAtIndex:%i]' % (a11yElements, index))
135135
printAccessibilityHierarchy(subview, indent + 1)
136136
else:
137-
print indentString + ('({} {}) {}'.format(classDesc, view, a11yLabel.GetObjectDescription()))
137+
print(indentString + ('({} {}) {}'.format(classDesc, view, a11yLabel.GetObjectDescription())))
138138

139139
def printAccessibilityIdentifiersHierarchy(view, indent = 0):
140140
a11yIdentifier = accessibilityIdentifier(view)
@@ -143,12 +143,12 @@ def printAccessibilityIdentifiersHierarchy(view, indent = 0):
143143

144144
#if we don't have any accessibility identifier - we should have some children
145145
if int(a11yIdentifier.GetValue(), 16) == 0:
146-
print indentString + ('{} {}'.format(classDesc, view))
146+
print(indentString + ('{} {}'.format(classDesc, view)))
147147
#We call private method that gives back all visible accessibility children for view
148148
a11yElements = accessibilityElements(view)
149149
accessibilityElementsCount = int(fb.evaluateExpression('(int)[%s count]' % a11yElements))
150150
for index in range(0, accessibilityElementsCount):
151151
subview = fb.evaluateObjectExpression('[%s objectAtIndex:%i]' % (a11yElements, index))
152152
printAccessibilityIdentifiersHierarchy(subview, indent + 1)
153153
else:
154-
print indentString + ('({} {}) {}'.format(classDesc, view, a11yIdentifier.GetObjectDescription()))
154+
print(indentString + ('({} {}) {}'.format(classDesc, view, a11yIdentifier.GetObjectDescription())))

commands/FBAutoLayoutCommands.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ def run(self, arguments, options):
3131
view = fb.evaluateInputExpression(arguments[0])
3232
opt = fb.evaluateBooleanExpression('[UIView instancesRespondToSelector:@selector(_autolayoutTraceRecursively:)]')
3333
traceCall = '_autolayoutTraceRecursively:1' if opt else '_autolayoutTrace'
34-
print fb.describeObject('[{} {}]'.format(view, traceCall))
34+
print(fb.describeObject('[{} {}]'.format(view, traceCall)))
3535

3636

3737
def setBorderOnAmbiguousViewRecursive(view, width, color):

commands/FBClassDump.py

+10-10
Original file line numberDiff line numberDiff line change
@@ -39,17 +39,17 @@ def run(self, arguments, options):
3939
cls = getClassFromArgument(arguments[0], options.clsname)
4040

4141
if options.clsmethod:
42-
print 'Class Methods:'
42+
print('Class Methods:')
4343
printClassMethods(cls, options.showaddr)
4444

4545
if options.insmethod:
46-
print '\nInstance Methods:'
46+
print('\nInstance Methods:')
4747
printInstanceMethods(cls, options.showaddr)
4848

4949
if not options.clsmethod and not options.insmethod:
50-
print 'Class Methods:'
50+
print('Class Methods:')
5151
printClassMethods(cls, options.showaddr)
52-
print '\nInstance Methods:'
52+
print('\nInstance Methods:')
5353
printInstanceMethods(cls, options.showaddr)
5454

5555

@@ -147,15 +147,15 @@ def run(self, arguments, options):
147147

148148
signature = json['signature']
149149
if not signature:
150-
print 'Imp: ' + hex(json['invoke'])
150+
print('Imp: ' + hex(json['invoke']))
151151
return
152152

153153
sigStr = '{} ^('.format(decode(signature[0]))
154154
# the block`s implementation always take the block as it`s first argument, so we ignore it
155155
sigStr += ', '.join([decode(m) for m in signature[2:]])
156156
sigStr += ');'
157157

158-
print 'Imp: ' + hex(json['invoke']) + ' Signature: ' + sigStr
158+
print('Imp: ' + hex(json['invoke']) + ' Signature: ' + sigStr)
159159

160160
# helpers
161161
def isClassObject(arg):
@@ -178,21 +178,21 @@ def getClassFromArgument(arg, is_classname):
178178
def printInstanceMethods(cls, showaddr=False, prefix='-'):
179179
methods = getMethods(cls)
180180
if not methods:
181-
print "No methods were found"
181+
print("No methods were found")
182182

183183
for m in methods:
184184
if showaddr:
185-
print prefix + ' ' + m.prettyPrintString() + ' ' + str(m.imp)
185+
print(prefix + ' ' + m.prettyPrintString() + ' ' + str(m.imp))
186186
else:
187-
print prefix + ' ' + m.prettyPrintString()
187+
print(prefix + ' ' + m.prettyPrintString())
188188

189189
def printClassMethods(cls, showaddr=False):
190190
printInstanceMethods(runtimeHelpers.object_getClass(cls), showaddr, '+')
191191

192192
def printProperties(cls, showvalue=False):
193193
props = getProperties(cls)
194194
for p in props:
195-
print p.prettyPrintString()
195+
print(p.prettyPrintString())
196196

197197
def decode(code):
198198
encodeMap = {

commands/FBComponentCommands.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -35,12 +35,12 @@ def options(self):
3535
def run(self, arguments, options):
3636
if options.set:
3737
fb.evaluateEffect('[CKComponentDebugController setDebugMode:YES]')
38-
print 'Debug mode for ComponentKit has been set.'
38+
print('Debug mode for ComponentKit has been set.')
3939
elif options.unset:
4040
fb.evaluateEffect('[CKComponentDebugController setDebugMode:NO]')
41-
print 'Debug mode for ComponentKit has been unset.'
41+
print('Debug mode for ComponentKit has been unset.')
4242
else:
43-
print 'No option for ComponentKit Debug mode specified.'
43+
print('No option for ComponentKit Debug mode specified.')
4444

4545
class FBComponentsPrintCommand(fb.FBCommand):
4646
def name(self):
@@ -67,7 +67,7 @@ def run(self, arguments, options):
6767
# assume it's a CKComponent
6868
view = fb.evaluateExpression('((CKComponent *)%s).viewContext.view' % view)
6969

70-
print fb.describeObject('[CKComponentHierarchyDebugHelper componentHierarchyDescriptionForView:(UIView *)' + view + ' searchUpwards:' + upwards + ' showViews:' + showViews + ']')
70+
print(fb.describeObject('[CKComponentHierarchyDebugHelper componentHierarchyDescriptionForView:(UIView *)' + view + ' searchUpwards:' + upwards + ' showViews:' + showViews + ']'))
7171

7272
class FBComponentsReflowCommand(fb.FBCommand):
7373
def name(self):

commands/FBDebugCommands.py

+25-22
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,9 @@
55
# This source code is licensed under the MIT license found in the
66
# LICENSE file in the root directory of this source tree.
77

8+
# Can be removed when Python 2 support is removed.
9+
from __future__ import print_function
10+
811
import lldb
912
import fblldbbase as fb
1013
import fblldbobjcruntimehelpers as objc
@@ -58,9 +61,9 @@ def run(self, arguments, options):
5861
watchpoint = lldb.debugger.GetSelectedTarget().WatchAddress(objectAddress + ivarOffset, ivarSize, False, True, error)
5962

6063
if error.Success():
61-
print 'Remember to delete the watchpoint using: watchpoint delete {}'.format(watchpoint.GetID())
64+
print('Remember to delete the watchpoint using: watchpoint delete {}'.format(watchpoint.GetID()))
6265
else:
63-
print 'Could not create the watchpoint: {}'.format(error.GetCString())
66+
print('Could not create the watchpoint: {}'.format(error.GetCString()))
6467

6568
class FBFrameworkAddressBreakpointCommand(fb.FBCommand):
6669
def name(self):
@@ -108,12 +111,12 @@ def run(self, arguments, options):
108111
match = methodPattern.match(expression)
109112

110113
if not match:
111-
print 'Failed to parse expression. Do you even Objective-C?!'
114+
print('Failed to parse expression. Do you even Objective-C?!')
112115
return
113116

114117
expressionForSelf = objc.functionPreambleExpressionForSelf()
115118
if not expressionForSelf:
116-
print 'Your architecture, {}, is truly fantastic. However, I don\'t currently support it.'.format(arch)
119+
print('Your architecture, {}, is truly fantastic. However, I don\'t currently support it.'.format(arch))
117120
return
118121

119122
methodTypeCharacter = match.group('scope')
@@ -139,7 +142,7 @@ def run(self, arguments, options):
139142
targetClass = fb.evaluateObjectExpression('[{} class]'.format(targetObject), False)
140143

141144
if not targetClass or int(targetClass, 0) == 0:
142-
print 'Couldn\'t find a class from the expression "{}". Did you typo?'.format(classNameOrExpression)
145+
print('Couldn\'t find a class from the expression "{}". Did you typo?'.format(classNameOrExpression))
143146
return
144147

145148
if methodIsClassMethod:
@@ -155,7 +158,7 @@ def run(self, arguments, options):
155158
nextClass = objc.class_getSuperclass(nextClass)
156159

157160
if not found:
158-
print 'There doesn\'t seem to be an implementation of {} in the class hierarchy. Made a boo boo with the selector name?'.format(selector)
161+
print('There doesn\'t seem to be an implementation of {} in the class hierarchy. Made a boo boo with the selector name?'.format(selector))
159162
return
160163

161164
breakpointClassName = objc.class_getName(nextClass)
@@ -167,7 +170,7 @@ def run(self, arguments, options):
167170
else:
168171
breakpointCondition = '(void*){} == {}'.format(expressionForSelf, targetObject)
169172

170-
print 'Setting a breakpoint at {} with condition {}'.format(breakpointFullName, breakpointCondition)
173+
print('Setting a breakpoint at {} with condition {}'.format(breakpointFullName, breakpointCondition))
171174

172175
if category:
173176
lldb.debugger.HandleCommand('breakpoint set --skip-prologue false --fullname "{}" --condition "{}"'.format(breakpointFullName, breakpointCondition))
@@ -205,11 +208,11 @@ def switchBreakpointState(expression,on):
205208
target = lldb.debugger.GetSelectedTarget()
206209
for breakpoint in target.breakpoint_iter():
207210
if breakpoint.IsEnabled() != on and (expression_pattern.search(str(breakpoint))):
208-
print str(breakpoint)
211+
print(str(breakpoint))
209212
breakpoint.SetEnabled(on)
210213
for location in breakpoint:
211214
if location.IsEnabled() != on and (expression_pattern.search(str(location)) or expression == hex(location.GetAddress()) ):
212-
print str(location)
215+
print(str(location))
213216
location.SetEnabled(on)
214217

215218
class FBMethodBreakpointEnableCommand(fb.FBCommand):
@@ -330,7 +333,7 @@ def run(self, arguments, options):
330333
return
331334

332335
if len(arguments) == 0 or not arguments[0].strip():
333-
print 'Usage: findinstances <classOrProtocol> [<predicate>]; Run `help findinstances`'
336+
print('Usage: findinstances <classOrProtocol> [<predicate>]; Run `help findinstances`')
334337
return
335338

336339
query = arguments[0]
@@ -348,7 +351,7 @@ def loadChiselIfNecessary(self):
348351

349352
path = self.chiselLibraryPath()
350353
if not os.path.exists(path):
351-
print 'Chisel library missing: ' + path
354+
print('Chisel library missing: ' + path)
352355
return False
353356

354357
module = fb.evaluateExpressionValue('(void*)dlopen("{}", 2)'.format(path))
@@ -361,17 +364,17 @@ def loadChiselIfNecessary(self):
361364
error = fb.evaluateExpressionValue('(char*)dlerror()')
362365
if errno == 50:
363366
# KERN_CODESIGN_ERROR from <mach/kern_return.h>
364-
print 'Error loading Chisel: Code signing failure; Must re-run codesign'
367+
print('Error loading Chisel: Code signing failure; Must re-run codesign')
365368
elif error.unsigned != 0:
366-
print 'Error loading Chisel: ' + error.summary
369+
print('Error loading Chisel: ' + error.summary)
367370
elif errno != 0:
368371
error = fb.evaluateExpressionValue('(char*)strerror({})'.format(errno))
369372
if error.unsigned != 0:
370-
print 'Error loading Chisel: ' + error.summary
373+
print('Error loading Chisel: ' + error.summary)
371374
else:
372-
print 'Error loading Chisel (errno {})'.format(errno)
375+
print('Error loading Chisel (errno {})'.format(errno))
373376
else:
374-
print 'Unknown error loading Chisel'
377+
print('Unknown error loading Chisel')
375378

376379
return False
377380

@@ -428,9 +431,9 @@ def isHeap(addr):
428431

429432
allocations = (addr for addr in pointers if isHeap(addr))
430433
for addr in allocations:
431-
print >>self.result, '0x{addr:x} {path}'.format(addr=addr, path=pointers[addr])
434+
print('0x{addr:x} {path}'.format(addr=addr, path=pointers[addr]), file=self.result)
432435
if not allocations:
433-
print >>self.result, "No heap addresses found"
436+
print("No heap addresses found", file=self.result)
434437

435438

436439
class FBSequenceCommand(fb.FBCommand):
@@ -453,17 +456,17 @@ def run(self, arguments, options):
453456

454457
# Complete one command before running the next one in the sequence. Disable
455458
# async to do this. Also, save the current async value to restore it later.
456-
async = lldb.debugger.GetAsync()
459+
asyncFlag = lldb.debugger.GetAsync()
457460
lldb.debugger.SetAsync(False)
458461

459462
for command in commands[:-1]:
460463
success = self.run_command(interpreter, command)
461464
if not success:
462-
lldb.debugger.SetAsync(async)
465+
lldb.debugger.SetAsync(asyncFlag)
463466
return
464467

465468
# Restore original async value.
466-
lldb.debugger.SetAsync(async)
469+
lldb.debugger.SetAsync(asyncFlag)
467470

468471
# If the last command is `continue`, call Continue() on the process
469472
# instead. This is done because HandleCommand('continue') has strange
@@ -478,7 +481,7 @@ def run_command(self, interpreter, command):
478481
ret = lldb.SBCommandReturnObject()
479482
interpreter.HandleCommand(command, ret)
480483
if ret.GetOutput():
481-
print >>self.result, ret.GetOutput().strip()
484+
print(ret.GetOutput().strip(), file=self.result)
482485

483486
if ret.Succeeded():
484487
return True

commands/FBFindCommands.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,6 @@ def run(self, arguments, options):
120120
@staticmethod
121121
def taplog_callback(frame, bp_loc, internal_dict):
122122
parameterExpr = objc.functionPreambleExpressionForObjectParameterAtIndex(0)
123-
print fb.describeObject('[[[%s allTouches] anyObject] view]' % (parameterExpr))
123+
print(fb.describeObject('[[[%s allTouches] anyObject] view]' % (parameterExpr)))
124124
# We don't want to proceed event (click on button for example), so we just skip it
125125
lldb.debugger.HandleCommand('thread return')

commands/FBFlickerCommands.py

+9-9
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ def args(self):
5151
return [ fb.FBCommandArgument(arg='view', type='UIView*', help='The view to border.') ]
5252

5353
def run(self, arguments, options):
54-
print '\nUse the following and (q) to quit.\n(w) move to superview\n(s) move to first subview\n(a) move to previous sibling\n(d) move to next sibling\n(p) print the hierarchy\n'
54+
print('\nUse the following and (q) to quit.\n(w) move to superview\n(s) move to first subview\n(a) move to previous sibling\n(d) move to next sibling\n(p) print the hierarchy\n')
5555

5656
object = fb.evaluateInputExpression(arguments[0])
5757
walker = FlickerWalker(object)
@@ -78,29 +78,29 @@ def inputCallback(self, input):
7878
cmd = 'echo %s | tr -d "\n" | pbcopy' % oldView
7979
os.system(cmd)
8080

81-
print '\nI hope ' + oldView + ' was what you were looking for. I put it on your clipboard.'
81+
print('\nI hope ' + oldView + ' was what you were looking for. I put it on your clipboard.')
8282
viewHelpers.unmaskView(oldView)
8383
self.keepRunning = False
8484

8585
elif input == 'w':
8686
v = superviewOfView(self.currentView)
8787
if not v:
88-
print 'There is no superview. Where are you trying to go?!'
88+
print('There is no superview. Where are you trying to go?!')
8989
self.setCurrentView(v, oldView)
9090
elif input == 's':
9191
v = firstSubviewOfView(self.currentView)
9292
if not v:
93-
print '\nThe view has no subviews.\n'
93+
print('\nThe view has no subviews.\n')
9494
self.setCurrentView(v, oldView)
9595
elif input == 'd':
9696
v = nthSiblingOfView(self.currentView, -1)
9797
if v == oldView:
98-
print '\nThere are no sibling views to this view.\n'
98+
print('\nThere are no sibling views to this view.\n')
9999
self.setCurrentView(v, oldView)
100100
elif input == 'a':
101101
v = nthSiblingOfView(self.currentView, 1)
102102
if v == oldView:
103-
print '\nThere are no sibling views to this view.\n'
103+
print('\nThere are no sibling views to this view.\n')
104104
self.setCurrentView(v, oldView)
105105
elif input == 'p':
106106
recursionName = 'recursiveDescription'
@@ -109,17 +109,17 @@ def inputCallback(self, input):
109109
if isMac:
110110
recursionName = '_subtreeDescription'
111111

112-
print fb.describeObject('[(id){} {}]'.format(oldView, recursionName))
112+
print(fb.describeObject('[(id){} {}]'.format(oldView, recursionName)))
113113
else:
114-
print '\nI really have no idea what you meant by \'' + input + '\'... =\\\n'
114+
print('\nI really have no idea what you meant by \'' + input + '\'... =\\\n')
115115

116116
def setCurrentView(self, view, oldView=None):
117117
if view:
118118
self.currentView = view
119119
if oldView:
120120
viewHelpers.unmaskView(oldView)
121121
viewHelpers.maskView(self.currentView, 'red', '0.4')
122-
print fb.describeObject(view)
122+
print(fb.describeObject(view))
123123

124124
def superviewOfView(view):
125125
superview = fb.evaluateObjectExpression('[' + view + ' superview]')

0 commit comments

Comments
 (0)