FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
pythonVSCode/pythonFiles/preview/jedi/parser/tree.py at master · pan76/pythonVSCode · GitHub
pan76
/
pythonVSCode
Public
forked from
DonJayamanne/pythonVSCode
Notifications
You must be signed in to change notification settings
Fork
0
Star
0
Code
Pull requests
0
Actions
Projects
Wiki
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Wiki
Security and quality
Insights
Expand file tree
Breadcrumbs
pythonVSCode
/
pythonFiles
/
preview
/
jedi
/
parser
/
tree.py
Copy path
More file actions
More file actions
Latest commit
History
History
History
1658 lines (1358 loc) · 49.5 KB
Breadcrumbs
pythonVSCode
/
pythonFiles
/
preview
/
jedi
/
parser
/
tree.py
Copy path
File metadata and controls
1658 lines (1358 loc) · 49.5 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
"""
If you know what an abstract syntax tree (AST) is, you'll see that this module
is pretty much that. The classes represent syntax elements like functions and
imports.
This is the "business logic" part of the parser. There's a lot of logic here
that makes it easier for Jedi (and other libraries to deal with a Python syntax
tree.
By using `get_code` on a module, you can get back the 1-to-1 representation of
the input given to the parser. This is important if you are using refactoring.
The easiest way to play with this module is to use :class:`parsing.Parser`.
:attr:`parsing.Parser.module` holds an instance of :class:`Module`:
>>> from jedi._compatibility import u
>>> from jedi.parser import ParserWithRecovery, load_grammar
>>> parser = ParserWithRecovery(load_grammar(), u('import os'), 'example.py')
>>> submodule = parser.module
>>> submodule
<Module: example.py@1-1>
Any subclasses of :class:`Scope`, including :class:`Module` has an attribute
:attr:`imports <Scope.imports>`:
>>> submodule.imports
[<ImportName: import os@1,0>]
See also :attr:`Scope.subscopes` and :attr:`Scope.statements`.
For static analysis purposes there exists a method called
``nodes_to_execute`` on all nodes and leaves. It's documented in the static
anaylsis documentation.
"""
import
os
import
re
from
inspect
import
cleandoc
from
itertools
import
chain
import
textwrap
import
abc
from
jedi
.
_compatibility
import
(
Python3Method
,
encoding
,
is_py3
,
utf8_repr
,
literal_eval
,
use_metaclass
,
unicode
)
from
jedi
.
parser
import
token
from
jedi
.
parser
.
utils
import
underscore_memoization
def
is_node
(
node
,
*
symbol_names
):
try
:
type
=
node
.
type
except
AttributeError
:
return
False
else
:
return
type
in
symbol_names
class
PositionModifier
(
object
):
"""A start_pos modifier for the fast parser."""
def
__init__
(
self
):
self
.
line
=
0
zero_position_modifier
=
PositionModifier
()
class
DocstringMixin
(
object
):
__slots__
=
()
@
property
def
raw_doc
(
self
):
""" Returns a cleaned version of the docstring token. """
if
isinstance
(
self
,
Module
):
node
=
self
.
children
[
0
]
elif
isinstance
(
self
,
ClassOrFunc
):
node
=
self
.
children
[
self
.
children
.
index
(
':'
)
+
1
]
if
is_node
(
node
,
'suite'
):
# Normally a suite
node
=
node
.
children
[
2
]
# -> NEWLINE INDENT stmt
else
:
# ExprStmt
simple_stmt
=
self
.
parent
c
=
simple_stmt
.
parent
.
children
index
=
c
.
index
(
simple_stmt
)
if
not
index
:
return
''
node
=
c
[
index
-
1
]
if
is_node
(
node
,
'simple_stmt'
):
node
=
node
.
children
[
0
]
if
node
.
type
==
'string'
:
# TODO We have to check next leaves until there are no new
# leaves anymore that might be part of the docstring. A
# docstring can also look like this: ``'foo' 'bar'
# Returns a literal cleaned version of the ``Token``.
cleaned
=
cleandoc
(
literal_eval
(
node
.
value
))
# Since we want the docstr output to be always unicode, just
# force it.
if
is_py3
or
isinstance
(
cleaned
,
unicode
):
return
cleaned
else
:
return
unicode
(
cleaned
,
'UTF-8'
,
'replace'
)
return
''
class
Base
(
object
):
"""
This is just here to have an isinstance check, which is also used on
evaluate classes. But since they have sometimes a special type of
delegation, it is important for those classes to override this method.
I know that there is a chance to do such things with __instancecheck__, but
since Python 2.5 doesn't support it, I decided to do it this way.
"""
__slots__
=
()
def
isinstance
(
self
,
*
cls
):
return
isinstance
(
self
,
cls
)
@
Python3Method
def
get_parent_until
(
self
,
classes
=
(),
reverse
=
False
,
include_current
=
True
):
"""
Searches the parent "chain" until the object is an instance of
classes. If classes is empty return the last parent in the chain
(is without a parent).
"""
if
type
(
classes
)
not
in
(
tuple
,
list
):
classes
=
(
classes
,)
scope
=
self
if
include_current
else
self
.
parent
while
scope
.
parent
is
not
None
:
# TODO why if classes?
if
classes
and
reverse
!=
scope
.
isinstance
(
*
classes
):
break
scope
=
scope
.
parent
return
scope
def
get_parent_scope
(
self
,
include_flows
=
False
):
"""
Returns the underlying scope.
"""
scope
=
self
.
parent
while
scope
is
not
None
:
if
include_flows
and
isinstance
(
scope
,
Flow
):
return
scope
if
scope
.
is_scope
():
break
scope
=
scope
.
parent
return
scope
def
get_definition
(
self
):
if
self
.
type
in
(
'newline'
,
'dedent'
,
'indent'
,
'endmarker'
):
raise
ValueError
(
'Cannot get the indentation of whitespace or indentation.'
)
scope
=
self
while
scope
.
parent
is
not
None
:
parent
=
scope
.
parent
if
scope
.
isinstance
(
Node
,
Leaf
)
and
parent
.
type
!=
'simple_stmt'
:
if
scope
.
type
==
'testlist_comp'
:
try
:
if
isinstance
(
scope
.
children
[
1
],
CompFor
):
return
scope
.
children
[
1
]
except
IndexError
:
pass
scope
=
parent
else
:
break
return
scope
def
assignment_indexes
(
self
):
"""
Returns an array of tuple(int, node) of the indexes that are used in
tuple assignments.
For example if the name is ``y`` in the following code::
x, (y, z) = 2, ''
would result in ``[(1, xyz_node), (0, yz_node)]``.
"""
indexes
=
[]
node
=
self
.
parent
compare
=
self
while
node
is
not
None
:
if
is_node
(
node
,
'testlist_comp'
,
'testlist_star_expr'
,
'exprlist'
):
for
i
,
child
in
enumerate
(
node
.
children
):
if
child
==
compare
:
indexes
.
insert
(
0
, (
int
(
i
/
2
),
node
))
break
else
:
raise
LookupError
(
"Couldn't find the assignment."
)
elif
isinstance
(
node
, (
ExprStmt
,
CompFor
)):
break
compare
=
node
node
=
node
.
parent
return
indexes
def
is_scope
(
self
):
# Default is not being a scope. Just inherit from Scope.
return
False
@
abc
.
abstractmethod
def
nodes_to_execute
(
self
,
last_added
=
False
):
raise
NotImplementedError
()
def
get_next_sibling
(
self
):
"""
The node immediately following the invocant in their parent's children
list. If the invocant does not have a next sibling, it is None
"""
# Can't use index(); we need to test by identity
for
i
,
child
in
enumerate
(
self
.
parent
.
children
):
if
child
is
self
:
try
:
return
self
.
parent
.
children
[
i
+
1
]
except
IndexError
:
return
None
def
get_previous_sibling
(
self
):
"""
The node/leaf immediately preceding the invocant in their parent's
children list. If the invocant does not have a previous sibling, it is
None.
"""
# Can't use index(); we need to test by identity
for
i
,
child
in
enumerate
(
self
.
parent
.
children
):
if
child
is
self
:
if
i
==
0
:
return
None
return
self
.
parent
.
children
[
i
-
1
]
def
get_previous_leaf
(
self
):
"""
Returns the previous leaf in the parser tree.
Raises an IndexError if it's the first element.
"""
node
=
self
while
True
:
c
=
node
.
parent
.
children
i
=
c
.
index
(
node
)
if
i
==
0
:
node
=
node
.
parent
if
node
.
parent
is
None
:
raise
IndexError
(
'Cannot access the previous element of the first one.'
)
else
:
node
=
c
[
i
-
1
]
break
while
True
:
try
:
node
=
node
.
children
[
-
1
]
except
AttributeError
:
# A Leaf doesn't have children.
return
node
def
get_next_leaf
(
self
):
"""
Returns the previous leaf in the parser tree.
Raises an IndexError if it's the last element.
"""
node
=
self
while
True
:
c
=
node
.
parent
.
children
i
=
c
.
index
(
node
)
if
i
==
len
(
c
)
-
1
:
node
=
node
.
parent
if
node
.
parent
is
None
:
raise
IndexError
(
'Cannot access the next element of the last one.'
)
else
:
node
=
c
[
i
+
1
]
break
while
True
:
try
:
node
=
node
.
children
[
0
]
except
AttributeError
:
# A Leaf doesn't have children.
return
node
class
Leaf
(
Base
):
__slots__
=
(
'position_modifier'
,
'value'
,
'parent'
,
'_start_pos'
,
'prefix'
)
def
__init__
(
self
,
position_modifier
,
value
,
start_pos
,
prefix
=
''
):
self
.
position_modifier
=
position_modifier
self
.
value
=
value
self
.
_start_pos
=
start_pos
self
.
prefix
=
prefix
self
.
parent
=
None
@
property
def
start_pos
(
self
):
return
self
.
_start_pos
[
0
]
+
self
.
position_modifier
.
line
,
self
.
_start_pos
[
1
]
@
start_pos
.
setter
def
start_pos
(
self
,
value
):
self
.
_start_pos
=
value
[
0
]
-
self
.
position_modifier
.
line
,
value
[
1
]
def
get_start_pos_of_prefix
(
self
):
try
:
previous_leaf
=
self
while
True
:
previous_leaf
=
previous_leaf
.
get_previous_leaf
()
if
previous_leaf
.
type
not
in
(
'indent'
,
'dedent'
):
return
previous_leaf
.
end_pos
except
IndexError
:
return
1
,
0
# It's the first leaf.
@
property
def
end_pos
(
self
):
return
(
self
.
_start_pos
[
0
]
+
self
.
position_modifier
.
line
,
self
.
_start_pos
[
1
]
+
len
(
self
.
value
))
def
move
(
self
,
line_offset
,
column_offset
):
self
.
_start_pos
=
(
self
.
_start_pos
[
0
]
+
line_offset
,
self
.
_start_pos
[
1
]
+
column_offset
)
def
first_leaf
(
self
):
return
self
def
get_code
(
self
,
normalized
=
False
,
include_prefix
=
True
):
if
normalized
:
return
self
.
value
if
include_prefix
:
return
self
.
prefix
+
self
.
value
else
:
return
self
.
value
def
nodes_to_execute
(
self
,
last_added
=
False
):
return
[]
@
utf8_repr
def
__repr__
(
self
):
return
"<%s: %s>"
%
(
type
(
self
).
__name__
,
self
.
value
)
class
LeafWithNewLines
(
Leaf
):
__slots__
=
()
@
property
def
end_pos
(
self
):
"""
Literals and whitespace end_pos are more complicated than normal
end_pos, because the containing newlines may change the indexes.
"""
end_pos_line
,
end_pos_col
=
self
.
start_pos
lines
=
self
.
value
.
split
(
'
\n
'
)
end_pos_line
+=
len
(
lines
)
-
1
# Check for multiline token
if
self
.
start_pos
[
0
]
==
end_pos_line
:
end_pos_col
+=
len
(
lines
[
-
1
])
else
:
end_pos_col
=
len
(
lines
[
-
1
])
return
end_pos_line
,
end_pos_col
@
utf8_repr
def
__repr__
(
self
):
return
"<%s: %r>"
%
(
type
(
self
).
__name__
,
self
.
value
)
class
EndMarker
(
Leaf
):
__slots__
=
()
type
=
'endmarker'
class
Newline
(
LeafWithNewLines
):
"""Contains NEWLINE and ENDMARKER tokens."""
__slots__
=
()
type
=
'newline'
@
utf8_repr
def
__repr__
(
self
):
return
"<%s: %s>"
%
(
type
(
self
).
__name__
,
repr
(
self
.
value
))
class
Name
(
Leaf
):
"""
A string. Sometimes it is important to know if the string belongs to a name
or not.
"""
type
=
'name'
__slots__
=
()
def
__str__
(
self
):
return
self
.
value
def
__unicode__
(
self
):
return
self
.
value
def
__repr__
(
self
):
return
"<%s: %s@%s,%s>"
%
(
type
(
self
).
__name__
,
self
.
value
,
self
.
start_pos
[
0
],
self
.
start_pos
[
1
])
def
is_definition
(
self
):
if
self
.
parent
.
type
in
(
'power'
,
'atom_expr'
):
# In `self.x = 3` self is not a definition, but x is.
return
False
stmt
=
self
.
get_definition
()
if
stmt
.
type
in
(
'funcdef'
,
'classdef'
,
'file_input'
,
'param'
):
return
self
==
stmt
.
name
elif
stmt
.
type
==
'for_stmt'
:
return
self
.
start_pos
<
stmt
.
children
[
2
].
start_pos
elif
stmt
.
type
==
'try_stmt'
:
return
self
.
get_previous_sibling
()
==
'as'
else
:
return
stmt
.
type
in
(
'expr_stmt'
,
'import_name'
,
'import_from'
,
'comp_for'
,
'with_stmt'
) \
and
self
in
stmt
.
get_defined_names
()
def
nodes_to_execute
(
self
,
last_added
=
False
):
if
last_added
is
False
:
yield
self
class
Literal
(
LeafWithNewLines
):
__slots__
=
()
def
eval
(
self
):
return
literal_eval
(
self
.
value
)
class
Number
(
Literal
):
type
=
'number'
__slots__
=
()
class
String
(
Literal
):
type
=
'string'
__slots__
=
()
class
Indent
(
Leaf
):
type
=
'indent'
__slots__
=
()
class
Dedent
(
Leaf
):
type
=
'dedent'
__slots__
=
()
class
Operator
(
Leaf
):
type
=
'operator'
__slots__
=
()
def
__str__
(
self
):
return
self
.
value
def
__eq__
(
self
,
other
):
"""
Make comparisons with strings easy.
Improves the readability of the parser.
"""
if
isinstance
(
other
,
Operator
):
return
self
is
other
else
:
return
self
.
value
==
other
def
__ne__
(
self
,
other
):
"""Python 2 compatibility."""
return
self
.
value
!=
other
def
__hash__
(
self
):
return
hash
(
self
.
value
)
class
Keyword
(
Leaf
):
type
=
'keyword'
__slots__
=
()
def
__eq__
(
self
,
other
):
"""
Make comparisons with strings easy.
Improves the readability of the parser.
"""
if
isinstance
(
other
,
Keyword
):
return
self
is
other
return
self
.
value
==
other
def
__ne__
(
self
,
other
):
"""Python 2 compatibility."""
return
not
self
.
__eq__
(
other
)
def
__hash__
(
self
):
return
hash
(
self
.
value
)
class
BaseNode
(
Base
):
"""
The super class for Scope, Import, Name and Statement. Every object in
the parser tree inherits from this class.
"""
__slots__
=
(
'children'
,
'parent'
)
type
=
None
def
__init__
(
self
,
children
):
"""
Initialize :class:`BaseNode`.
:param children: The module in which this Python object locates.
"""
for
c
in
children
:
c
.
parent
=
self
self
.
children
=
children
self
.
parent
=
None
def
move
(
self
,
line_offset
,
column_offset
):
"""
Move the Node's start_pos.
"""
for
c
in
self
.
children
:
c
.
move
(
line_offset
,
column_offset
)
@
property
def
start_pos
(
self
):
return
self
.
children
[
0
].
start_pos
def
get_start_pos_of_prefix
(
self
):
return
self
.
children
[
0
].
get_start_pos_of_prefix
()
@
property
def
end_pos
(
self
):
return
self
.
children
[
-
1
].
end_pos
def
get_code
(
self
,
normalized
=
False
,
include_prefix
=
True
):
# TODO implement normalized (depending on context).
if
include_prefix
:
return
""
.
join
(
c
.
get_code
(
normalized
)
for
c
in
self
.
children
)
else
:
first
=
self
.
children
[
0
].
get_code
(
include_prefix
=
False
)
return
first
+
""
.
join
(
c
.
get_code
(
normalized
)
for
c
in
self
.
children
[
1
:])
@
Python3Method
def
name_for_position
(
self
,
position
):
for
c
in
self
.
children
:
if
isinstance
(
c
,
Leaf
):
if
isinstance
(
c
,
Name
)
and
c
.
start_pos
<=
position
<=
c
.
end_pos
:
return
c
else
:
result
=
c
.
name_for_position
(
position
)
if
result
is
not
None
:
return
result
return
None
def
get_leaf_for_position
(
self
,
position
,
include_prefixes
=
False
):
for
c
in
self
.
children
:
if
include_prefixes
:
start_pos
=
c
.
get_start_pos_of_prefix
()
else
:
start_pos
=
c
.
start_pos
if
start_pos
<=
position
<=
c
.
end_pos
:
try
:
return
c
.
get_leaf_for_position
(
position
,
include_prefixes
)
except
AttributeError
:
while
c
.
type
in
(
'indent'
,
'dedent'
):
# We'd rather not have indents and dedents as a leaf,
# because they don't contain indentation information.
c
=
c
.
get_next_leaf
()
return
c
return
None
@
Python3Method
def
get_statement_for_position
(
self
,
pos
):
for
c
in
self
.
children
:
if
c
.
start_pos
<=
pos
<=
c
.
end_pos
:
if
c
.
type
not
in
(
'decorated'
,
'simple_stmt'
,
'suite'
) \
and
not
isinstance
(
c
, (
Flow
,
ClassOrFunc
)):
return
c
else
:
try
:
return
c
.
get_statement_for_position
(
pos
)
except
AttributeError
:
pass
# Must be a non-scope
return
None
def
first_leaf
(
self
):
try
:
return
self
.
children
[
0
].
first_leaf
()
except
AttributeError
:
return
self
.
children
[
0
]
def
get_next_leaf
(
self
):
"""
Raises an IndexError if it's the last node. (Would be the module)
"""
c
=
self
.
parent
.
children
index
=
c
.
index
(
self
)
if
index
==
len
(
c
)
-
1
:
# TODO WTF? recursion?
return
self
.
get_next_leaf
()
else
:
return
c
[
index
+
1
]
def
last_leaf
(
self
):
try
:
return
self
.
children
[
-
1
].
last_leaf
()
except
AttributeError
:
return
self
.
children
[
-
1
]
def
get_following_comment_same_line
(
self
):
"""
returns (as string) any comment that appears on the same line,
after the node, including the #
"""
try
:
if
self
.
isinstance
(
ForStmt
):
whitespace
=
self
.
children
[
5
].
first_leaf
().
prefix
elif
self
.
isinstance
(
WithStmt
):
whitespace
=
self
.
children
[
3
].
first_leaf
().
prefix
else
:
whitespace
=
self
.
last_leaf
().
get_next_leaf
().
prefix
except
AttributeError
:
return
None
except
ValueError
:
# TODO in some particular cases, the tree doesn't seem to be linked
# correctly
return
None
if
"#"
not
in
whitespace
:
return
None
comment
=
whitespace
[
whitespace
.
index
(
"#"
):]
if
"
\r
"
in
comment
:
comment
=
comment
[:
comment
.
index
(
"
\r
"
)]
if
"
\n
"
in
comment
:
comment
=
comment
[:
comment
.
index
(
"
\n
"
)]
return
comment
@
utf8_repr
def
__repr__
(
self
):
code
=
self
.
get_code
().
replace
(
'
\n
'
,
' '
).
strip
()
if
not
is_py3
:
code
=
code
.
encode
(
encoding
,
'replace'
)
return
"<%s: %s@%s,%s>"
%
\
(
type
(
self
).
__name__
,
code
,
self
.
start_pos
[
0
],
self
.
start_pos
[
1
])
class
Node
(
BaseNode
):
"""Concrete implementation for interior nodes."""
__slots__
=
(
'type'
,)
_IGNORE_EXECUTE_NODES
=
set
([
'suite'
,
'subscriptlist'
,
'subscript'
,
'simple_stmt'
,
'sliceop'
,
'testlist_comp'
,
'dictorsetmaker'
,
'trailer'
,
'decorators'
,
'decorated'
,
'arglist'
,
'argument'
,
'exprlist'
,
'testlist'
,
'testlist_safe'
,
'testlist1'
])
def
__init__
(
self
,
type
,
children
):
"""
Initializer.
Takes a type constant (a symbol number >= 256), a sequence of
child nodes, and an optional context keyword argument.
As a side effect, the parent pointers of the children are updated.
"""
super
(
Node
,
self
).
__init__
(
children
)
self
.
type
=
type
def
nodes_to_execute
(
self
,
last_added
=
False
):
"""
For static analysis.
"""
result
=
[]
if
self
.
type
not
in
Node
.
_IGNORE_EXECUTE_NODES
and
not
last_added
:
result
.
append
(
self
)
last_added
=
True
for
child
in
self
.
children
:
result
+=
child
.
nodes_to_execute
(
last_added
)
return
result
def
__repr__
(
self
):
return
"%s(%s, %r)"
%
(
self
.
__class__
.
__name__
,
self
.
type
,
self
.
children
)
class
ErrorNode
(
BaseNode
):
"""
TODO doc
"""
__slots__
=
()
type
=
'error_node'
def
nodes_to_execute
(
self
,
last_added
=
False
):
return
[]
class
ErrorLeaf
(
LeafWithNewLines
):
"""
TODO doc
"""
__slots__
=
(
'original_type'
)
type
=
'error_leaf'
def
__init__
(
self
,
position_modifier
,
original_type
,
value
,
start_pos
,
prefix
=
''
):
super
(
ErrorLeaf
,
self
).
__init__
(
position_modifier
,
value
,
start_pos
,
prefix
)
self
.
original_type
=
original_type
def
__repr__
(
self
):
token_type
=
token
.
tok_name
[
self
.
original_type
]
return
"<%s: %s, %s)>"
%
(
type
(
self
).
__name__
,
token_type
,
self
.
start_pos
)
class
IsScopeMeta
(
type
):
def
__instancecheck__
(
self
,
other
):
return
other
.
is_scope
()
class
IsScope
(
use_metaclass
(
IsScopeMeta
)):
pass
class
Scope
(
BaseNode
,
DocstringMixin
):
"""
Super class for the parser tree, which represents the state of a python
text file.
A Scope manages and owns its subscopes, which are classes and functions, as
well as variables and imports. It is used to access the structure of python
files.
:param start_pos: The position (line and column) of the scope.
:type start_pos: tuple(int, int)
"""
__slots__
=
(
'names_dict'
,)
def
__init__
(
self
,
children
):
super
(
Scope
,
self
).
__init__
(
children
)
@
property
def
returns
(
self
):
# Needed here for fast_parser, because the fast_parser splits and
# returns will be in "normal" modules.
return
self
.
_search_in_scope
(
ReturnStmt
)
@
property
def
subscopes
(
self
):
return
self
.
_search_in_scope
(
Scope
)
@
property
def
flows
(
self
):
return
self
.
_search_in_scope
(
Flow
)
@
property
def
imports
(
self
):
return
self
.
_search_in_scope
(
Import
)
@
Python3Method
def
_search_in_scope
(
self
,
typ
):
def
scan
(
children
):
elements
=
[]
for
element
in
children
:
if
isinstance
(
element
,
typ
):
elements
.
append
(
element
)
if
is_node
(
element
,
'suite'
,
'simple_stmt'
,
'decorated'
) \
or
isinstance
(
element
,
Flow
):
elements
+=
scan
(
element
.
children
)
return
elements
return
scan
(
self
.
children
)
@
property
def
statements
(
self
):
return
self
.
_search_in_scope
((
ExprStmt
,
KeywordStatement
))
def
is_scope
(
self
):
return
True
def
__repr__
(
self
):
try
:
name
=
self
.
path
except
AttributeError
:
try
:
name
=
self
.
name
except
AttributeError
:
name
=
self
.
command
return
"<%s: %s@%s-%s>"
%
(
type
(
self
).
__name__
,
name
,
self
.
start_pos
[
0
],
self
.
end_pos
[
0
])
def
walk
(
self
):
yield
self
for
s
in
self
.
subscopes
:
for
scope
in
s
.
walk
():
yield
scope
for
r
in
self
.
statements
:
while
isinstance
(
r
,
Flow
):
for
scope
in
r
.
walk
():
yield
scope
r
=
r
.
next
class
Module
(
Scope
):
"""
The top scope, which is always a module.
Depending on the underlying parser this may be a full module or just a part
of a module.
"""
__slots__
=
(
'path'
,
'global_names'
,
'used_names'
,
'_name'
)
type
=
'file_input'
def
__init__
(
self
,
children
):
"""
Initialize :class:`Module`.
:type path: str
:arg path: File path to this module.
.. todo:: Document `top_module`.
"""
super
(
Module
,
self
).
__init__
(
children
)
self
.
path
=
None
# Set later.
@
property
@
underscore_memoization
def
name
(
self
):
""" This is used for the goto functions. """
if
self
.
path
is
None
:
string
=
''
# no path -> empty name
else
:
sep
=
(
re
.
escape
(
os
.
path
.
sep
),)
*
2
r
=
re
.
search
(
r'([^%s]*?)(%s__init__)?(\.py|\.so)?$'
%
sep
,
self
.
path
)
# Remove PEP 3149 names
string
=
re
.
sub
(
'\.[a-z]+-\d{2}[mud]{0,3}$'
,
''
,
r
.
group
(
1
))
# Positions are not real, but a module starts at (1, 0)
p
=
(
1
,
0
)
name
=
Name
(
zero_position_modifier
,
string
,
p
)
name
.
parent
=
self
return
name
@
property
def
has_explicit_absolute_import
(
self
):
"""
Checks if imports in this module are explicitly absolute, i.e. there
is a ``__future__`` import.
"""
# TODO this is a strange scan and not fully correct. I think Python's
# parser does it in a different way and scans for the first
# statement/import with a tokenizer (to check for syntax changes like
# the future print statement).
for
imp
in
self
.
imports
:
if
imp
.
type
==
'import_from'
and
imp
.
level
==
0
:
for
path
in
imp
.
paths
():
if
[
str
(
name
)
for
name
in
path
]
==
[
'__future__'
,
'absolute_import'
]:
return
True
return
False
def
nodes_to_execute
(
self
,
last_added
=
False
):
# Yield itself, class needs to be executed for decorator checks.
result
=
[]
for
child
in
self
.
children
:
result
+=
child
.
nodes_to_execute
()
return
result
class
Decorator
(
BaseNode
):
type
=
'decorator'
__slots__
=
()
def
nodes_to_execute
(
self
,
last_added
=
False
):
if
self
.
children
[
-
2
]
==
')'
:
node
=
self
.
children
[
-
3
]
if
node
!=
'('
:
return
node
.
nodes_to_execute
()
return
[]
class
ClassOrFunc
(
Scope
):
__slots__
=
()
@
property
def
name
(
self
):
return
self
.
children
[
1
]
def
get_decorators
(
self
):
decorated
=
self
.
parent
if
is_node
(
decorated
,
'decorated'
):
if
is_node
(
decorated
.
children
[
0
],
'decorators'
):
return
decorated
.
children
[
0
].
children
else
:
return
decorated
.
children
[:
1
]
else
:
return
[]
class
Class
(
ClassOrFunc
):
"""
Used to store the parsed contents of a python class.
:param name: The Class name.
:type name: str
:param supers: The super classes of a Class.
:type supers: list
:param start_pos: The start position (line, column) of the class.
:type start_pos: tuple(int, int)
"""
type
=
'classdef'
__slots__
=
()
def
__init__
(
self
,
children
):
super
(
Class
,
self
).
__init__
(
children
)
def
get_super_arglist
(
self
):
if
self
.
children
[
2
]
!=
'('
:
# Has no parentheses
return
None
else
:
if
self
.
children
[
3
]
==
')'
:
# Empty parentheses
return
None
else
:
return
self
.
children
[
3
]
@
property
def
doc
(
self
):
"""
Return a document string including call signature of __init__.
"""
docstr
=
self
.
raw_doc
for
sub
in
self
.
subscopes
:
if
str
(
sub
.
name
)
==
'__init__'
:
return
'%s
\n
\n
%s'
%
(
sub
.
get_call_signature
(
func_name
=
self
.
name
),
docstr
)
return
docstr
def
nodes_to_execute
(
self
,
last_added
=
False
):
# Yield itself, class needs to be executed for decorator checks.
yield
self
# Super arguments.
arglist
=
self
.
get_super_arglist
()
try
:
children
=
arglist
.
children
except
AttributeError
:
if
arglist
is
not
None
:
for
node_to_execute
in
arglist
.
nodes_to_execute
():
yield
node_to_execute
else
:
for
argument
in
children
:
if
argument
.
type
==
'argument'
:
# metaclass= or list comprehension or */**
raise
NotImplementedError
(
'Metaclasses not implemented'
)
else
:
for
node_to_execute
in
argument
.
nodes_to_execute
():
yield
node_to_execute
# care for the class suite:
for
node
in
self
.
children
[
self
.
children
.
index
(
':'
):]:
# This could be easier without the fast parser. But we need to find
# the position of the colon, because everything after it can be a
# part of the class, not just its suite.
for
node_to_execute
in
node
.
nodes_to_execute
():
yield
node_to_execute
def
_create_params
(
parent
,
argslist_list
):
"""
`argslist_list` is a list that can contain an argslist as a first item, but
most not. It's basically the items between the parameter brackets (which is
at most one item).
This function modifies the parser structure. It generates `Param` objects
from the normal ast. Those param objects do not exist in a normal ast, but
make the evaluation of the ast tree so much easier.
You could also say that this function replaces the argslist node with a
list of Param objects.
"""
def
check_python2_nested_param
(
node
):
"""
Python 2 allows params to look like ``def x(a, (b, c))``, which is
basically a way of unpacking tuples in params. Python 3 has ditched
this behavior. Jedi currently just ignores those constructs.
"""
return
node
.
type
==
'tfpdef'
and
node
.
children
[
0
]
==
'('
try
:
first
=
argslist_list
[
0
]
except
IndexError
:
return
[]
if
first
.
type
in
(
'name'
,
'tfpdef'
):
if
check_python2_nested_param
(
first
):
return
[
first
]
else
:
return
[
Param
([
first
],
parent
)]
elif
first
==
'*'
:
return
[
first
]
else
:
# argslist is a `typedargslist` or a `varargslist`.
children
=
first
.
children
new_children
=
[]
start
=
0
# Start with offset 1, because the end is higher.
for
end
,
child
in
enumerate
(
children
+
[
None
],
1
):
if
child
is
None
or
child
==
','
:
param_children
=
children
[
start
:
end
]
if
param_children
:
# Could as well be comma and then end.
if
check_python2_nested_param
(
param_children
[
0
]):
new_children
+=
param_children
elif
param_children
[
0
]
==
'*'
and
param_children
[
1
]
==
','
:
new_children
+=
param_children
else
:
new_children
.
append
(
Param
(
param_children
,
parent
))
start
=
end
return
new_children
View remainder of file in raw view
Back
|
FazBrowse Home
|
New Git URL