-
Notifications
You must be signed in to change notification settings - Fork 12
/
pyclasvi.py
executable file
·1811 lines (1518 loc) · 70.8 KB
/
pyclasvi.py
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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
"""
Python Clang AST Viewer
Clang AST Viewer shows the abstract syntax tree of a c/c++ file in a window.
Enter 'pyclasvi.py -h' to show the usage
PyClASVi is distributed under the MIT License, see LICENSE file.
"""
import sys
if sys.version_info.major == 2:
import ttk
import Tkinter as tk
import tkFont
import tkFileDialog
import tkMessageBox
else: # python3
import tkinter.ttk as ttk
import tkinter as tk
import tkinter.font as tkFont
import tkinter.filedialog as tkFileDialog
import tkinter.messagebox as tkMessageBox
import clang.cindex
import ctypes
import argparse
import inspect
import re
# Convert objects to a string.
# Some object have no suitable standard string conversation, so use this.
def toStr(data):
if isinstance(data, bytes): # Python3 clang binding sometimes return bytes instead of strings
return data.decode('ascii') # ASCII should be default in C/C++ but what about comments
elif ((data.__class__ == int) # int but not bool, show decimal and hex
or (sys.version_info.major) == 2 and isinstance(data, long)):
if data < 0: # no negative hex values
return str(data)
else:
return '{0} ({0:#010x})'.format(data)
elif isinstance(data, clang.cindex.Cursor): # default output for cursors
return '{0} ({1:#010x}) {2}'.format(data.kind.name,
data.hash,
data.displayname)
elif isinstance(data, clang.cindex.SourceLocation):
return 'file: {0}\nline: {1}\ncolumn: {2}\noffset: {3}'.format(
data.file, data.line, data.column, data.offset)
else:
return str(data)
# Just join strings.
def join(*args):
return ''.join(args)
# Join everything to a string
def xjoin(*args):
return ''.join((str(a) for a in args))
# check if m is an instance methode
def is_instance_methode(m):
return inspect.ismethod(m)
# has this instance methode only the self parameter?
def is_simple_instance_methode(m):
argSpec = inspect.getargspec(m)
return len(argSpec.args) == 1 # only self
# get methode definition like "(arg1, arg2)" as string
def get_methode_prototype(m):
argSpec = inspect.getargspec(m)
return inspect.formatargspec(*argSpec)
# check if obj is in list
def is_obj_in_stack(obj, objStack):
for o in objStack:
if o.__class__ == obj.__class__: # some compare function trow exception if types are not equal
if o == obj:
return True
return False
# Cursor objects have a hash property but no __hash__ method
# You can use this class to make Cursor object hashable
class HashableObj:
def __init__(self, obj):
self.obj = obj
def __eq__(self, other):
return self.obj == other.obj
def __hash__(self):
return self.obj.hash
# Make widget scrollable by adding scrollbars to the right and below it.
# Of course parent is the parent widget of widget.
# If there are more than one widget inside the parent use widgetRow and widgetColumn
# to specify witch widget should be scrollable.
def make_scrollable(parent, widget, widgetRow=0, widgetColumn=0):
vsb = ttk.Scrollbar(parent, orient='vertical',command=widget.yview)
widget.configure(yscrollcommand=vsb.set)
vsb.grid(row=widgetRow, column=widgetColumn+1, sticky='ns')
hsb = ttk.Scrollbar(parent, orient='horizontal',command=widget.xview)
widget.configure(xscrollcommand=hsb.set)
hsb.grid(row=widgetRow+1, column=widgetColumn, sticky='we')
# Widget to handle all inputs (file name and parameters).
# Contain [Parse] Button to start parsing and fill result in output frames
class InputFrame(ttk.Frame):
def __init__(self, master=None, parseCmd=None):
ttk.Frame.__init__(self, master)
self.grid(sticky='nswe')
self.parseCmd = parseCmd
self.filename = tk.StringVar(value='')
self.xValue = tk.StringVar(value=InputFrame._X_OPTIONS[0]) # Option starting with "-x"
self.stdValue = tk.StringVar(value=InputFrame._STD_OPTIONS[0]) # Option starting with "-std"
self._create_widgets()
_SOURCEFILETYPES = (
('All source files', '.h', 'TEXT'),
('All source files', '.c', 'TEXT'),
('All source files', '.hh', 'TEXT'),
('All source files', '.hpp', 'TEXT'),
('All source files', '.hxx', 'TEXT'),
('All source files', '.h++', 'TEXT'),
('All source files', '.C', 'TEXT'),
('All source files', '.cc', 'TEXT'),
('All source files', '.cpp', 'TEXT'),
('All source files', '.cxx', 'TEXT'),
('All source files', '.c++', 'TEXT'),
('All files', '*'),
)
_FILETYPES = (
('Text files', '.txt', 'TEXT'),
('All files', '*'),
)
_X_OPTIONS = (
'no -x',
'-xc',
'-xc++'
)
_STD_OPTIONS = (
'no -std',
'-std=c89',
'-std=c90',
'-std=iso9899:1990',
'-std=iso9899:199409',
'-std=gnu89',
'-std=gnu90',
'-std=c99',
'-std=iso9899:1999',
'-std=gnu99',
'-std=c11',
'-std=iso9899:2011',
'-std=gnu11',
'-std=c17',
'-std=iso9899:2017',
'-std=gnu17',
'-std=c++98',
'-std=c++03',
'-std=gnu++98',
'-std=gnu++03',
'-std=c++11',
'-std=gnu++11',
'-std=c++14',
'-std=gnu++14',
'-std=c++17',
'-std=gnu++17',
'-std=c++2a',
'-std=gnu++2a'
)
def _create_widgets(self):
self.rowconfigure(4, weight=1)
self.columnconfigure(0, weight=1)
ttk.Label(self, text='Input file:').grid(row=0, sticky='w')
fileFrame = ttk.Frame(self)
fileFrame.columnconfigure(0, weight=1)
fileFrame.grid(row=1, column=0, columnspan=2, sticky='we')
filenameEntry = ttk.Entry(fileFrame, textvariable=self.filename)
filenameEntry.grid(row=0, column=0, sticky='we')
button = ttk.Button(fileFrame, text='...', command=self._on_select_file)
button.grid(row=0, column=1)
ttk.Label(self, text='Arguments:').grid(row=2, sticky='w')
buttonFrame = ttk.Frame(self)
buttonFrame.grid(row=3, column=0, columnspan=2, sticky='we')
button = ttk.Button(buttonFrame, text='+ Include', command=self._on_include)
button.grid()
button = ttk.Button(buttonFrame, text='+ Define', command=self._on_define)
button.grid(row=0, column=1)
xCBox = ttk.Combobox(buttonFrame, textvariable=self.xValue,
values=InputFrame._X_OPTIONS)
xCBox.bind('<<ComboboxSelected>>', self._on_select_x)
xCBox.grid(row=0, column=2)
stdCBox = ttk.Combobox(buttonFrame, textvariable=self.stdValue,
values=InputFrame._STD_OPTIONS)
stdCBox.bind('<<ComboboxSelected>>', self._on_select_std)
stdCBox.grid(row=0, column=3)
self.argsText = tk.Text(self, wrap='none')
self.argsText.grid(row=4, sticky='nswe')
make_scrollable(self, self.argsText, widgetRow=4, widgetColumn=0)
buttonFrame = ttk.Frame(self)
buttonFrame.grid(row=6, column=0, columnspan=2, sticky='we')
buttonFrame.columnconfigure(2, weight=1)
button = ttk.Button(buttonFrame, text='Load', command=self._on_file_load)
button.grid(row=0, column=0)
button = ttk.Button(buttonFrame, text='Save', command=self._on_file_save)
button.grid(row=0, column=1)
button = ttk.Button(buttonFrame, text='Parse', command=self.parseCmd)
button.grid(row=0, column=2, sticky='we')
def load_filename(self, filename):
data = []
with open(filename, 'r') as f:
data = f.read()
if data:
lines = data.split('\n')
if len(lines) > 0:
self.set_filename(lines[0])
self.set_args(lines[1:])
def _on_file_load(self):
fn = tkFileDialog.askopenfilename(filetypes=InputFrame._FILETYPES)
if fn:
self.load_filename(fn)
def _on_file_save(self):
with tkFileDialog.asksaveasfile(defaultextension='.txt', filetypes=InputFrame._FILETYPES) as f:
f.write(join(self.get_filename(), '\n'))
for arg in self.get_args():
f.write(join(arg, '\n'))
def _on_select_file(self):
fn = tkFileDialog.askopenfilename(filetypes=self._SOURCEFILETYPES)
if fn:
self.set_filename(fn)
def _on_include(self):
dir = tkFileDialog.askdirectory()
if dir:
self.add_arg(join('-I', dir))
def _on_define(self):
self.add_arg('-D<name>=<value>')
def _on_select_x(self, e):
arg = self.xValue.get()
if arg == InputFrame._X_OPTIONS[0]:
arg = None
self.set_arg('-x', arg)
def _on_select_std(self, e):
arg = self.stdValue.get()
if arg == InputFrame._STD_OPTIONS[0]:
arg = None
self.set_arg('-std', arg)
def set_parse_cmd(self, parseCmd):
self.parseCmd = parseCmd
def set_filename(self, fn):
self.filename.set(fn)
def get_filename(self):
return self.filename.get()
# Set a single arg starting with name.
# Replace or erase the first arg if there is still one starting with name.
# total is full argument string starting with name for replacement or None or empty string for erase.
def set_arg(self, name, total):
args = self.get_args()
i = 0
for arg in args:
if arg[:len(name)] == name:
break;
i += 1
newArgs = args[:i]
if total:
newArgs.append(total)
if i < len(args):
newArgs.extend(args[i+1:])
self.set_args(newArgs)
# Set/replace all args
def set_args(self, args):
self.argsText.delete('1.0', 'end')
for arg in args:
self.add_arg(arg)
def add_arg(self, arg):
txt = self.argsText.get('1.0', 'end')
if len(txt) > 1: # looks like there is always a trailing newline
prefix = '\n'
else:
prefix = ''
self.argsText.insert('end', join(prefix, arg))
def get_args(self):
args = []
argStr = self.argsText.get('1.0', 'end')
argStrList = argStr.split('\n')
for arg in argStrList:
if len(arg) > 0:
args.append(arg)
return args
# Widget to show all parse warnings and errors.
# The upper part shows the list, the lower part the Source position of selected diagnostics.
class ErrorFrame(ttk.Frame):
def __init__(self, master=None):
ttk.Frame.__init__(self, master)
self.grid(sticky='nswe')
self.filterValue=tk.StringVar(value=ErrorFrame._DIAG_STR_TAB[0]) # filter by severity
self._create_widgets()
self.errors = [] # list of diagnostics (also warnings not only errors)
# _DIAG_LEVEL_TAB and _DIAG_STR_TAB must have the same size and order
_DIAG_LEVEL_TAB = (
clang.cindex.Diagnostic.Ignored,
clang.cindex.Diagnostic.Note,
clang.cindex.Diagnostic.Warning,
clang.cindex.Diagnostic.Error,
clang.cindex.Diagnostic.Fatal
)
_DIAG_STR_TAB = (
xjoin(clang.cindex.Diagnostic.Ignored, ' Ignored'),
xjoin(clang.cindex.Diagnostic.Note, ' Note'),
xjoin(clang.cindex.Diagnostic.Warning, ' Warning'),
xjoin(clang.cindex.Diagnostic.Error, ' Error'),
xjoin(clang.cindex.Diagnostic.Fatal, ' Fatal')
)
_DIAG_TAG_TAB = {clang.cindex.Diagnostic.Warning:('warning',),
clang.cindex.Diagnostic.Error:('error',),
clang.cindex.Diagnostic.Fatal:('fatal',)}
def _create_widgets(self):
self.rowconfigure(0, weight=1)
self.columnconfigure(0, weight=1)
charSize = tkFont.nametofont('TkHeadingFont').measure('#')
pw = tk.PanedWindow(self, orient='vertical')
pw.grid(row=0, column=0, sticky='nswe')
frame = ttk.Frame(pw)
frame.rowconfigure(1, weight=1)
frame.columnconfigure(0, weight=1)
buttonFrame = ttk.Frame(frame)
buttonFrame.grid(row=0, column=0, columnspan=2, sticky='we')
label = tk.Label(buttonFrame, text='Filter:')
label.grid(row=0, column=0)
filterCBox = ttk.Combobox(buttonFrame, textvariable=self.filterValue,
values=ErrorFrame._DIAG_STR_TAB)
filterCBox.bind('<<ComboboxSelected>>', self._filter)
filterCBox.grid(row=0, column=1)
self.errorTable = ttk.Treeview(frame, columns=('category', 'severity', 'spelling', 'location',
'option'))
self.errorTable.tag_configure('warning', background='light yellow')
self.errorTable.tag_configure('error', background='indian red')
self.errorTable.tag_configure('fatal', background='dark red', foreground='white')
self.errorTable.bind('<<TreeviewSelect>>', self._on_selection)
self.errorTable.grid(row=1, column=0, sticky='nswe')
make_scrollable(frame, self.errorTable, 1)
pw.add(frame, stretch='always')
self.errorTable.heading('#0', text='#')
self.errorTable.column('#0', width=4*charSize, anchor='e', stretch=False)
self.errorTable.heading('category', text='Category')
self.errorTable.column('category', width=20*charSize, stretch=False)
self.errorTable.heading('severity', text='Severity')
self.errorTable.column('severity', width=8*charSize, stretch=False)
self.errorTable.heading('spelling', text='Text')
self.errorTable.column('spelling', width=50*charSize, stretch=False)
self.errorTable.heading('location', text='Location')
self.errorTable.column('location', width=50*charSize, stretch=False)
self.errorTable.heading('option', text='Option')
self.errorTable.column('option', width=20*charSize, stretch=False)
self.fileOutputFrame = FileOutputFrame(pw)
pw.add(self.fileOutputFrame, stretch='always')
# Show selected diagnostic in source file
def _on_selection(self, event):
curItem = self.errorTable.focus()
err = self.errors[int(curItem)]
range1 = None
for r in err.ranges:
range1 = r
break
self.fileOutputFrame.set_location(range1, err.location)
# Filter by selected severity
def _filter(self, e=None):
for i in self.errorTable.get_children():
self.errorTable.delete(i)
i = ErrorFrame._DIAG_STR_TAB.index(self.filterValue.get())
diagLevel = ErrorFrame._DIAG_LEVEL_TAB[i]
cnt = 0
for err in self.errors:
cnt = cnt + 1
if err.severity < diagLevel:
continue
if err.severity in ErrorFrame._DIAG_LEVEL_TAB:
i = ErrorFrame._DIAG_LEVEL_TAB.index(err.severity)
serverity = ErrorFrame._DIAG_STR_TAB[i]
else:
serverity = str(err.severity)
if err.severity in ErrorFrame._DIAG_TAG_TAB:
tagsVal=ErrorFrame._DIAG_TAG_TAB[err.severity]
else:
tagsVal=()
if err.location.file:
location = '{} {}:{}'.format(err.location.file.name,
err.location.line,
err.location.offset)
else:
location = None
self.errorTable.insert('', 'end', text=str(cnt), values=[
join(str(err.category_number), ' ', toStr(err.category_name)),
serverity,
err.spelling,
location,
err.option
],
tags=tagsVal,
iid=str(cnt-1))
def clear(self):
self.errors = []
self.fileOutputFrame.clear()
for i in self.errorTable.get_children():
self.errorTable.delete(i)
def set_errors(self, errors):
self.clear()
for err in errors:
self.errors.append(err)
self._filter()
return len(self.errors)
# Widget to show the AST in a Treeview like folders in a file browser
# This widget is the master for current selected Cursor object.
# If you want to show an other Cursor call set_current_cursor(...)
class ASTOutputFrame(ttk.Frame):
def __init__(self, master=None, selectCmd=None):
ttk.Frame.__init__(self, master)
self.grid(sticky='nswe')
self._create_widgets()
self.translationunit = None
self.mapIIDtoCursor = {} # Treeview use IIDs (stings) to identify a note,
self.mapCursorToIID = {} # so we need to map between IID and Cursor in both direction.
# One Cursor may have a list of IIDs if several times found in AST.
self.selectCmd = selectCmd # Callback after selecting a Cursor
def _create_widgets(self):
self.rowconfigure(0, weight=1)
self.columnconfigure(0, weight=1)
charSize = tkFont.nametofont('TkFixedFont').measure('#')
self.astView = ttk.Treeview(self, selectmode='browse')
self.astView.tag_configure('default', font='TkFixedFont')
self.astView.bind('<<TreeviewSelect>>', self._on_selection)
make_scrollable(self, self.astView)
self.astView.heading('#0', text='Cursor')
self.astView.grid(row=0, column=0, sticky='nswe')
def _on_selection(self, event):
if self.selectCmd is not None:
self.selectCmd()
def set_select_cmd(self, cmd):
self.selectCmd = cmd
def get_current_iid(self):
return self.astView.focus()
# Return a single IID or a list of IIDs.
def get_current_iids(self):
cursor = self.get_current_cursor()
if cursor is not None:
return self.mapCursorToIID[HashableObj(cursor)]
else:
return None
def get_current_cursor(self):
curCursor = None
curItem = self.astView.focus()
if curItem:
curCursor = self.mapIIDtoCursor[curItem]
return curCursor
def set_current_iid(self, iid):
self.astView.focus(iid)
self.astView.selection_set(iid)
self.astView.see(iid)
def set_current_cursor(self, cursor):
iid = self.mapCursorToIID[HashableObj(cursor)]
if isinstance(iid, list): # partly multimap
iid = iid[0]
self.set_current_iid(iid)
def clear(self):
for i in self.astView.get_children():
self.astView.delete(i)
self.translationunit = None
self.mapIIDtoCursor = {}
self.mapCursorToIID = {}
def _insert_children(self, cursor, iid, deep=1):
cntChildren = 0
for childCursor in cursor.get_children():
cntChildren = cntChildren + 1
newIID = self.astView.insert(iid,
'end',
text=toStr(childCursor),
tags=['default'])
self.mapIIDtoCursor[newIID] = childCursor
hCursor = HashableObj(childCursor)
if hCursor in self.mapCursorToIID: # already in map, make a partly multimap
self.cntDouble = self.cntDouble + 1
data = self.mapCursorToIID[hCursor]
if isinstance(data, str):
data = [data]
self.mapCursorToIID[hCursor] = data
data.append(newIID)
if len(data) > self.cntMaxDoubles:
self.cntMaxDoubles = len(data)
else:
self.mapCursorToIID[hCursor] = newIID
self._insert_children(childCursor, newIID, deep+1)
self.cntCursors = self.cntCursors + 1
if cntChildren > 0:
if cntChildren > self.cntMaxChildren:
self.cntMaxChildren = cntChildren
if deep > self.cntMaxDeep:
self.cntMaxDeep = deep
def set_translationunit(self, tu):
self.cntCursors = 1
self.cntDouble = 0
self.cntMaxDoubles = 0
self.cntMaxChildren = 0
self.cntMaxDeep = 0
self.clear()
self.translationunit = tu
root = tu.cursor
iid = self.astView.insert('',
'end',
text=toStr(root),
tags=['default'])
self.mapIIDtoCursor[iid] = root
self.mapCursorToIID[HashableObj(root)] = iid
self._insert_children(root, iid)
# some statistics
print('AST has {0} cursors including {1} doubles.'.format(self.cntCursors, self.cntDouble))
print('max doubles: {0}, max children {1}, max deep {2}'.format(
self.cntMaxDoubles, self.cntMaxChildren, self.cntMaxDeep))
# Search for IIDs matching to Cursors matching to kwargs.
def search(self, **kwargs):
result = []
useCursorKind = kwargs['use_CursorKind']
cursorKind = kwargs['CursorKind']
spelling = kwargs['spelling']
caseInsensitive = kwargs['caseInsensitive']
useRegEx = kwargs['use_RexEx']
if useRegEx:
reFlags = 0
if caseInsensitive:
reFlags = re.IGNORECASE
try:
reObj = re.compile(spelling, reFlags)
except Exception as e:
tkMessageBox.showerror('Search RegEx', str(e))
return result
elif caseInsensitive:
spelling = spelling.lower()
for iid in self.mapIIDtoCursor:
cursor = self.mapIIDtoCursor[iid]
found = True
if useCursorKind:
found = cursorKind == cursor.kind.name
if found:
if useRegEx:
if not reObj.match(toStr(cursor.spelling)):
found = False
elif caseInsensitive:
found = spelling == toStr(cursor.spelling).lower()
else:
found = spelling == toStr(cursor.spelling)
if found:
result.append(iid)
result.sort()
return result
# Helper class to represent un-/folded sections in Text widget of CursorOutputFrame.
# One node is of type FoldSection.
# No Node will be removed even if a new selected cursor object have less section.
# Therefore if you open the next cursor with the same section hierarchy it this tree
# can remember witch section should be shown and witch not.
#
# Remark, this only works if always the same kind of object with the same attribute order is shown.
# An example:
# Obj A:Cursor B:Cursor C:WahtElse
# +- brief_comment = None +- brief_comment = "a function" +- brief_comment = None
# +- get_arguments:iterator => empty +- get_arguments:iterator |
# | | +- [0]:Cursor |
# | | +- [1]:Cursor |
# +- spelling:sting = "a" +- spelling:sting = "func" +- spelling:sting = "x"
#
# Object A and B are fine, B create more active nodes in FoldSectionTree
# but the attribute order is identical. Object C have some same called attributes but in wrong order.
# If first B is shown with get_arguments (2nd attribute) open but spelling (3rd attribute) closed
# and than C was shown spelling (here 2nd attribute) will be open.
# If A is show some of the nodes representing the two sub Cursor in object B will be inactive.
class FoldSectionTree:
def __init__(self):
self.root = FoldSection(True) # just a root node witch is always shown
self.marker = None # a singe section header (attribute name) can be highlighted
def get_root(self):
return self.root
def set_marker(self, marker):
self.marker = marker
def get_marker(self):
return self.marker
def set_all_show(self, show):
FoldSection.show_default = show
self.root.set_all_show(show)
# Deactivate all section but do not erase it, they still know if they should be shown or not.
def clear_lines(self):
self.root.clear_lines()
# Find section starting at startLine in Text widget.
def find_section(self, startLine):
return self._find_section(startLine, self.root.members)
def _find_section(self, startLine, sectionList):
if sectionList:
lastSec = None
for sec in sectionList:
if sec.startLine == 0:
break
elif sec.startLine == startLine:
return sec
elif sec.startLine < startLine:
lastSec = sec
else:
break
if lastSec is not None:
return self._find_section(startLine, lastSec.members)
else:
return None
else:
return None
# Node in FoldSectionTree
class FoldSection:
def __init__(self, show, deep=-1):
self.startLine = 0 # if 0 this section is not active
self.show = show # fold or not
self.members = None # children
self.parent = None
self.childNr = -1 # child index from parent view
self.deep = deep # current deep in tree, root is -1, first real sections 0
show_default = False # default section are closed
# Map this section to starting text line in Text widget.
# This also activate this section (startLine > 0).
def set_line(self, startLine):
self.startLine = startLine
def set_show(self, show):
self.show = show
# Open this an all children sections.
def set_all_show(self, show):
self.show = show
if self.members:
for m in self.members:
m.set_all_show(show)
# Get the n-th children.
# Remark, children (nodes) represent Cursor attributes in same order.
# num may convert to attribute name to support different kind of objects in CursorOutputFrame.
def get_child(self, num):
if self.members is None:
self.members = []
while (num+1) > len(self.members):
newFS = FoldSection(FoldSection.show_default, self.deep+1)
newFS.parent = self
newFS.childNr = num
self.members.append(newFS)
return self.members[num]
# Deactivate this section and all children.
def clear_lines(self):
self.startLine = 0
if self.members:
for m in self.members:
m.clear_lines()
# Widget to show nearly all attributes of a Cursor object
# Private member are ignored and other Cursors are just shown as link.
# If the attribute its self have attributes they are also up to a defined deep, so you have still a tree.
# So you have still a tree. This is not implemented by a Treewiew widget but just Text widget.
# The text widget gives you more layout possibilities but you have to implement the folding logic
# by your self. Therefore the classes FoldSectionTree and FoldSection are used which also
# implements some features missed in the Treeview widget.
class CursorOutputFrame(ttk.Frame):
def __init__(self, master=None, selectCmd=None):
ttk.Frame.__init__(self, master)
self.grid(sticky='nswe')
self._create_widgets()
self.cursor = None
self.selectCmd = selectCmd # will be called on clicking a cursor link
self.cursorList = [] # list of cursor in same order as links are shown in text
self.foldTree = FoldSectionTree() # contains infos about foldable section (a single member)
_MAX_DEEP = 8 # max deep of foldable sections / attributes
_MAX_ITER_OUT = 25 # is a member is an iterator show just the first x elements
_DATA_INDENT = ' ' # indentation for sub sections / attributes
# ignore member with this types
_IGNORE_TYPES = ('function',)
def _create_widgets(self):
self.rowconfigure(0, weight=1)
self.columnconfigure(0, weight=1)
defFont = tkFont.Font(font='TkFixedFont')
defFontProp = defFont.actual()
self.cursorText = tk.Text(self, wrap='none')
self.cursorText.grid(row=0, sticky='nswe')
self.cursorText.bind('<Button-3>', self._on_right_click)
make_scrollable(self, self.cursorText)
self.cursorText.tag_configure('attr_name', font=(defFontProp['family'], defFontProp['size'], 'bold'))
self.cursorText.tag_bind('attr_name', '<ButtonPress-1>', self._on_attr_click)
self.cursorText.tag_configure('attr_name_marked', background='lightblue')
self.cursorText.tag_configure('attr_type', foreground='green')
self.cursorText.tag_configure('attr_err', foreground='red')
self.cursorText.tag_configure('link', foreground='blue')
self.cursorText.tag_bind('link', '<ButtonPress-1>', self._on_cursor_click)
self.cursorText.tag_bind('link', '<Enter>', self._on_link_enter)
self.cursorText.tag_bind('link', '<Leave>', self._on_link_leave)
self.cursorText.tag_configure('special', font=(defFontProp['family'], defFontProp['size'], 'italic'))
for n in range(CursorOutputFrame._MAX_DEEP):
self.cursorText.tag_configure(xjoin('section_header_', n), foreground='gray')
self.cursorText.tag_bind(xjoin('section_header_', n), '<ButtonPress-1>', self._on_section_click)
self.cursorText.tag_bind(xjoin('section_header_', n), '<Enter>', self._on_section_enter)
self.cursorText.tag_bind(xjoin('section_header_', n), '<Leave>', self._on_section_leave)
self.cursorText.tag_configure(xjoin('section_hidden_', n), elide=True)
self.cursorText.tag_configure(xjoin('section_', n))
self.cursorText.config(state='disabled')
# Change mouse cursor over links.
def _on_link_enter(self, event):
self.cursorText.configure(cursor='hand1')
# Reset mouse cursor after leaving links.
def _on_link_leave(self, event):
self.cursorText.configure(cursor='xterm')
# Cursor link was clicked, run callback.
def _on_cursor_click(self, event):
if self.selectCmd is None:
return
curIdx = self.cursorText.index('@{0},{1}'.format(event.x, event.y))
linkIdxs = list(self.cursorText.tag_ranges('link'))
listIdx = 0
for start, end in zip(linkIdxs[0::2], linkIdxs[1::2]):
if (self.cursorText.compare(curIdx, '>=', start) and
self.cursorText.compare(curIdx, '<', end)):
cursor = self.cursorList[listIdx]
self.selectCmd(cursor)
break
listIdx += 1
# Mark clicked attribute name and store it in foldTree.
def _on_attr_click(self, event):
self.cursorText.tag_remove('attr_name_marked', '1.0', 'end')
curIdx = self.cursorText.index('@{0},{1}'.format(event.x, event.y))
curLine = curIdx.split('.')[0]
curSec = self.foldTree.find_section(int(curLine))
if curSec is not None:
self.foldTree.set_marker(curSec)
attr = self.cursorText.tag_nextrange('attr_name', join(curLine, '.0'))
self.cursorText.tag_add('attr_name_marked', attr[0], attr[1])
# Scroll text widget so marked attribute is shown.
def goto_marker(self):
curMarker = self.cursorText.tag_nextrange('attr_name_marked', '1.0')
if curMarker:
self.cursorText.see('end') # first jump to the end, so also the lines ...
self.cursorText.see(curMarker[0]) # ...after attribute name are shown
# Show context menu.
def _on_right_click(self, event):
menu = tk.Menu(None, tearoff=0)
menu.add_command(label='Expand all', command=self.expand_all)
menu.add_command(label='Collapse all', command=self.collapse_all)
menu.tk_popup(event.x_root, event.y_root)
# Change mouse cursor over clickable [+]/[-] of a node of a foldable section.
def _on_section_enter(self, event):
self.cursorText.configure(cursor='arrow')
# Reset mouse cursor.
def _on_section_leave(self, event):
self.cursorText.configure(cursor='xterm')
# There was a click on [+]/[-], so we need to fold or unfold a section.
def _on_section_click(self, event):
curIdx = self.cursorText.index('@{0},{1}'.format(event.x, event.y))
curLine = int(curIdx.split('.')[0])
curSec = self.foldTree.find_section(curLine) # find clicked section in foldTree
if curSec is None:
return # should never happen
# find the matching section tag
curLev = curSec.deep
next_section = self.cursorText.tag_nextrange(xjoin('section_', curLev), curIdx)
if next_section: # should always be true
self.cursorText.config(state='normal')
cur_header = self.cursorText.tag_prevrange(xjoin('section_header_', curLev), next_section[0])
next_hidden = self.cursorText.tag_nextrange(xjoin('section_hidden_', curLev), curIdx)
self.cursorText.delete(join(cur_header[0], ' +1c'), join(cur_header[0], ' +2c'))
newShow = next_hidden and (next_hidden == next_section)
if newShow:
self.cursorText.tag_remove(xjoin('section_hidden_', curLev), next_section[0], next_section[1])
self.cursorText.insert(join(cur_header[0], ' +1c'), '-')
else:
self.cursorText.tag_add(xjoin('section_hidden_', curLev), next_section[0], next_section[1])
self.cursorText.insert(join(cur_header[0], ' +1c'), '+')
curSec.set_show(newShow)
self.cursorText.config(state='disabled')
# Expand all section (via context menu).
def expand_all(self):
self.foldTree.set_all_show(True)
self.cursorText.config(state='normal')
for n in range(CursorOutputFrame._MAX_DEEP):
secs = self.cursorText.tag_ranges(xjoin('section_', n))
for start, end in zip(secs[0::2], secs[1::2]):
cur_header = self.cursorText.tag_prevrange(xjoin('section_header_', n), start)
self.cursorText.delete(join(cur_header[0], ' +1c'), join(cur_header[0], ' +2c'))
self.cursorText.tag_remove(xjoin('section_hidden_', n), start, end)
self.cursorText.insert(join(cur_header[0], ' +1c'), '-')
self.cursorText.config(state='disabled')
# Collapse all sections (via context menu).
def collapse_all(self):
self.foldTree.set_all_show(False)
self.cursorText.config(state='normal')
for n in range(CursorOutputFrame._MAX_DEEP):
secs = self.cursorText.tag_ranges(xjoin('section_', n))
for start, end in zip(secs[0::2], secs[1::2]):
cur_header = self.cursorText.tag_prevrange(xjoin('section_header_', n), start)
self.cursorText.delete(join(cur_header[0], ' +1c'), join(cur_header[0], ' +2c'))
self.cursorText.tag_add(xjoin('section_hidden_', n), start, end)
self.cursorText.insert(join(cur_header[0], ' +1c'), '+')
self.cursorText.config(state='disabled')
def clear(self):
self.cursorText.config(state='normal')
self.cursorText.delete('1.0', 'end')
self.cursorText.config(state='disabled')
self.cursor = None
self.cursorList = []
# Output cursor with link in text widget.
def _add_cursor(self, cursor):
# we got an exception if we compare a Cursor object with an other none Cursor object like None
# Therfore Cursor == None will not work so we use a try
if isinstance(cursor, clang.cindex.Cursor):
self.cursorText.insert('end',
toStr(cursor),
'link')
self.cursorList.append(cursor)
else:
self.cursorText.insert('end', str(cursor))
# Add a single attribute or a value of an iterable to the output.
# This output contains a header and the value that can be fold/unfold.
# if index is >= 0 a value of an iterable is outputted else an attribute.
# Some attributes are skipped, so this function may output nothing.
# The attributes name is attrName and it belongs to the last object in objStack.
# foldNode contains FoldSection matching to current object the attribute belongs to.
# For values of an iterable objStack also contains this value and foldeNode
# belongs to the value. attrName may same useful name e.g. "[0]".
def _add_attr(self, objStack, attrName, foldNode, index=-1):
obj = objStack[-1]
deep = len(objStack) - 1
prefix = '\t' * deep
isIterData = index >= 0
# set default values
attrData = None # attribute value for output
attrDataTag = None # special tag for special output format (None, attr_err, special)
attrTypeTag = 'attr_type' # tag for attribute name (attr_type, attr_err)
if not isIterData:
try:
attrData = getattr(obj, attrName)
attrType = attrData.__class__.__name__
if attrType in CursorOutputFrame._IGNORE_TYPES:
return False # no new section created
except BaseException as e:
attrType = join(e.__class__.__name__, ' => do not use this')
attrTypeTag = 'attr_err'
else:
attrData = obj
attrType = attrData.__class__.__name__
if (isinstance(obj, clang.cindex.Type)
and (obj.kind == clang.cindex.TypeKind.INVALID)
and (attrName in ('get_address_space', 'get_typedef_name'))):
attrData = 'Do not uses this if kind is TypeKind.INVALID!'
attrDataTag = 'attr_err'
elif is_instance_methode(attrData):
attrType = join(attrType, ' ', get_methode_prototype(attrData))
if is_simple_instance_methode(attrData):
try:
attrData = attrData()
attrType = join(attrType, ' => ', attrData.__class__.__name__)
except BaseException as e:
attrData = join(e.__class__.__name__, ' => do not use this')
attrDataTag = 'attr_err'
if attrName == 'get_children':
cnt = 0
for c in attrData:
cnt = cnt+1
attrData = xjoin(cnt, ' children, see tree on the left')
attrDataTag = 'special'
# start output, first line is always shown if parent section is also shown