forked from panda3d/panda3d
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReferrerSearch.py
More file actions
executable file
·329 lines (277 loc) · 10.5 KB
/
ReferrerSearch.py
File metadata and controls
executable file
·329 lines (277 loc) · 10.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
import inspect
import sys
import gc
from direct.showbase.PythonUtil import _getSafeReprNotify
from direct.showbase.Job import Job
class ReferrerSearch(Job):
def __init__(self, obj, maxRefs = 100):
Job.__init__(self, 'ReferrerSearch')
self.obj = obj
self.maxRefs = maxRefs
self.visited = set()
self.depth = 0
self.found = 0
self.shouldPrintStats = False
def __call__(self):
safeReprNotify = _getSafeReprNotify()
info = safeReprNotify.getInfo()
safeReprNotify.setInfo(0)
self.visited = set()
try:
self.step(0, [self.obj])
finally:
self.obj = None
pass
safeReprNotify.setInfo(info)
pass
def run(self):
safeReprNotify = _getSafeReprNotify()
self.info = safeReprNotify.getInfo()
safeReprNotify.setInfo(0)
print('RefPath(%s): Beginning ReferrerSearch for %s' %(self._id, fastRepr(self.obj)))
self.visited = set()
for x in self.stepGenerator(0, [self.obj]):
yield None
pass
yield Job.Done
pass
def finished(self):
print('RefPath(%s): Finished ReferrerSearch for %s' %(self._id, fastRepr(self.obj)))
self.obj = None
safeReprNotify = _getSafeReprNotify()
safeReprNotify.setInfo(self.info)
pass
def __del__(self):
print('ReferrerSearch garbage collected')
def truncateAtNewLine(self, s):
if s.find('\n') == -1:
return s
else:
return s[:s.find('\n')]
def printStatsWhenAble(self):
self.shouldPrintStats = True
pass
def myrepr(self, referrer, refersTo):
pre = ''
if (isinstance(referrer, dict)):
for k,v in referrer.items():
if v is refersTo:
pre = self.truncateAtNewLine(fastRepr(k)) + ']-> '
break
elif (isinstance(referrer, (list, tuple))):
for x, ref in enumerate(referrer):
if ref is refersTo:
pre = '%s]-> ' % (x)
break
if (isinstance(refersTo, dict)):
post = 'dict['
elif (isinstance(refersTo, list)):
post = 'list['
elif (isinstance(refersTo, tuple)):
post = 'tuple['
elif (isinstance(refersTo, set)):
post = 'set->'
else:
post = self.truncateAtNewLine(fastRepr(refersTo)) + "-> "
return '%s%s' % (pre, post)
def step(self, depth, path):
if self.shouldPrintStats:
self.printStats(path)
self.shouldPrintStats = False
at = path[-1]
if id(at) in self.visited:
# don't continue down this path
return
# check for success
if (self.isAtRoot(at, path)):
self.found += 1
return
# mark our progress after checking goal
self.visited.add(id(at))
referrers = [ref for ref in gc.get_referrers(at) \
if not (ref is path or \
inspect.isframe(ref) or \
(isinstance(ref, dict) and \
list(ref.keys()) == list(locals().keys())) or \
ref is self.__dict__ or \
id(ref) in self.visited) ]
# Check to see if this object has an unusually large
# ref-count. This usually indicates that it is some
# sort of global, singleton, or manager object
# and as such no further knowledge would be gained from
# traversing further up the ref tree.
if (self.isManyRef(at, path, referrers)):
return
while(referrers):
ref = referrers.pop()
self.depth+=1
for x in self.stepGenerator(depth + 1, path + [ref]):
pass
self.depth-=1
pass
pass
def stepGenerator(self, depth, path):
if self.shouldPrintStats:
self.printStats(path)
self.shouldPrintStats = False
at = path[-1]
# check for success
if (self.isAtRoot(at, path)):
self.found += 1
raise StopIteration
if id(at) in self.visited:
# don't continue down this path
raise StopIteration
# mark our progress after checking goal
self.visited.add(id(at))
# Look for all referrers, culling out the ones that
# we know to be red herrings.
referrers = [ref for ref in gc.get_referrers(at) \
if not (# we disregard the steps of our traversal
ref is path or \
# The referrer is this call frame
inspect.isframe(ref) or \
# The referrer is the locals() dictionary (closure)
(isinstance(ref, dict) and list(ref.keys()) == list(locals().keys())) or \
# We found the reference on self
ref is self.__dict__ or \
# We've already seen this referrer
id(ref) in self.visited) ]
# Check to see if this object has an unusually large
# ref-count. This usually indicates that it is some
# sort of global, singleton, or manager object
# and as such no further knowledge would be gained from
# traversing further up the ref tree.
if (self.isManyRef(at, path, referrers)):
raise StopIteration
while(referrers):
ref = referrers.pop()
self.depth+=1
for x in self.stepGenerator(depth + 1, path + [ref]):
yield None
pass
self.depth-=1
pass
yield None
pass
def printStats(self, path):
path = list(reversed(path))
path.insert(0,0)
print('RefPath(%s) - Stats - visited(%s) | found(%s) | depth(%s) | CurrentPath(%s)' % \
(self._id, len(self.visited), self.found, self.depth, ''.join(self.myrepr(path[x], path[x+1]) for x in range(len(path) - 1))))
pass
def isAtRoot(self, at, path):
# Now we define our 'roots', or places where we will
# end this particular thread of search
# We found a circular reference
if at in path:
sys.stdout.write("RefPath(%s): Circular: " % self._id)
path = list(reversed(path))
path.insert(0,0)
for x in range(len(path) - 1):
sys.stdout.write(self.myrepr(path[x], path[x+1]))
pass
print("")
return True
# __builtins__
if at is __builtins__:
sys.stdout.write("RefPath(%s): __builtins__-> " % self._id)
path = list(reversed(path))
path.insert(0,0)
for x in range(len(path) - 1):
sys.stdout.write(self.myrepr(path[x], path[x+1]))
pass
print("")
return True
# any module scope
if inspect.ismodule(at):
sys.stdout.write("RefPath(%s): Module(%s)-> " % (self._id, at.__name__))
path = list(reversed(path))
for x in range(len(path) - 1):
sys.stdout.write(self.myrepr(path[x], path[x+1]))
pass
print("")
return True
# any class scope
if inspect.isclass(at):
sys.stdout.write("RefPath(%s): Class(%s)-> " % (self._id, at.__name__))
path = list(reversed(path))
for x in range(len(path) - 1):
sys.stdout.write(self.myrepr(path[x], path[x+1]))
pass
print("")
return True
# simbase
if at is simbase:
sys.stdout.write("RefPath(%s): simbase-> " % self._id)
path = list(reversed(path))
for x in range(len(path) - 1):
sys.stdout.write(self.myrepr(path[x], path[x+1]))
pass
print("")
return True
# simbase.air
if at is simbase.air:
sys.stdout.write("RefPath(%s): simbase.air-> " % self._id)
path = list(reversed(path))
for x in range(len(path) - 1):
sys.stdout.write(self.myrepr(path[x], path[x+1]))
pass
print("")
return True
# messenger
if at is messenger:
sys.stdout.write("RefPath(%s): messenger-> " % self._id)
path = list(reversed(path))
for x in range(len(path) - 1):
sys.stdout.write(self.myrepr(path[x], path[x+1]))
pass
print("")
return True
# taskMgr
if at is taskMgr:
sys.stdout.write("RefPath(%s): taskMgr-> " % self._id)
path = list(reversed(path))
for x in range(len(path) - 1):
sys.stdout.write(self.myrepr(path[x], path[x+1]))
pass
print("")
return True
# world
if hasattr(simbase.air, 'mainWorld') and at is simbase.air.mainWorld:
sys.stdout.write("RefPath(%s): mainWorld-> " % self._id)
path = list(reversed(path))
for x in range(len(path) - 1):
sys.stdout.write(self.myrepr(path[x], path[x+1]))
pass
print("")
return True
pass
return False
def isManyRef(self, at, path, referrers):
if (len(referrers) > self.maxRefs and \
at is not self.obj):
if not isinstance(at, (list, tuple, dict, set)):
sys.stdout.write("RefPath(%s): ManyRefs(%s)[%s]-> " % (self._id, len(referrers), fastRepr(at)))
path = list(reversed(path))
path.insert(0,0)
for x in range(len(path) - 1):
sys.stdout.write(self.myrepr(path[x], path[x+1]))
pass
print("")
return True
else:
sys.stdout.write("RefPath(%s): ManyRefsAllowed(%s)[%s]-> " % (self._id, len(referrers), fastRepr(at, maxLen = 1, strFactor = 30)))
print("")
pass
pass
return False
pass
"""
from direct.showbase.ReferrerSearch import ReferrerSearch
door = simbase.air.doFind("DistributedBuildingDoorAI")
class A: pass
door = A()
ReferrerSearch()(door)
reload(ReferrerSearch); from direct.showbase.PythonUtil import ReferrerSearch
"""