forked from SublimeCodeIntel/SublimeCodeIntel
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpythoncile1.py
More file actions
1840 lines (1627 loc) · 71.6 KB
/
pythoncile1.py
File metadata and controls
1840 lines (1627 loc) · 71.6 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
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
# Copyright (c) 2004-2006 ActiveState Software Inc.
#
# Contributors:
# Trent Mick ([email protected])
"""
pythoncile - a Code Intelligence Language Engine for the Python language
Module Usage:
from pythoncile import scan
mtime = os.stat("foo.py")[stat.ST_MTIME]
content = open("foo.py", "r").read()
scan(content, "foo.py", mtime=mtime)
Command-line Usage:
pythoncile.py [<options>...] [<Python files>...]
Options:
-h, --help dump this help and exit
-V, --version dump this script's version and exit
-v, --verbose verbose output, use twice for more verbose output
-f, --filename <path> specify the filename of the file content
passed in on stdin, this is used for the "path"
attribute of the emitted <file> tag.
--md5=<string> md5 hash for the input
--mtime=<secs> modification time for output info, in #secs since
1/1/70.
-L, --language <name>
the language of the file being scanned
-c, --clock print timing info for scans (CIX is not printed)
One or more Python files can be specified as arguments or content can be
passed in on stdin. A directory can also be specified, in which case
all .py files in that directory are scanned.
This is a Language Engine for the Code Intelligence (codeintel) system.
Code Intelligence XML format. See:
http://specs.activestate.com/Komodo_3.0/func/code_intelligence.html
The command-line interface will return non-zero iff the scan failed.
"""
# Dev Notes:
# <none>
#
# TODO:
# - type inferencing: asserts
# - type inferencing: return statements
# - type inferencing: calls to isinstance
# - special handling for None may be required
# - Comments and doc strings. What format?
# - JavaDoc - type hard to parse and not reliable
# (http://java.sun.com/j2se/javadoc/writingdoccomments/).
# - PHPDoc? Possibly, but not that rigorous.
# - Grouch (http://www.mems-exchange.org/software/grouch/) -- dunno yet.
# - Don't like requirement for "Instance attributes:" landmark in doc
# strings.
# - This can't be a full solution because the requirement to repeat
# the argument name doesn't "fit" with having a near-by comment when
# variable is declared.
# - Two space indent is quite rigid
# - Only allowing attribute description on the next line is limiting.
# - Seems focussed just on class attributes rather than function
# arguments.
# - Perhaps what PerlCOM POD markup uses?
# - Home grown? My own style? Dunno
# - make type inferencing optional (because it will probably take a long
# time to generate), this is tricky though b/c should the CodeIntel system
# re-scan a file after "I want type inferencing now" is turned on? Hmmm.
# - [lower priority] handle staticmethod(methname) and
# classmethod(methname). This means having to delay emitting XML until
# end of class scope and adding .visitCallFunc().
# - [lower priority] look for associated comments for variable
# declarations (as per VS.NET's spec, c.f. "Supplying Code Comments" in
# the VS.NET user docs)
import os
import sys
import getopt
from hashlib import md5
import re
import logging
import pprint
import glob
import time
import stat
import types
import io
from functools import partial
# this particular ET is different from xml.etree and is expected
# to be returned from scan_et() by the clients of this module
import ciElementTree as ET
import ast
import parser
from codeintel2.common import CILEError
from codeintel2 import util
from codeintel2 import tdparser
#---- exceptions
class PythonCILEError(CILEError):
pass
#---- global data
_version_ = (0, 3, 0)
log = logging.getLogger("codeintel.pythoncile")
# log.setLevel(logging.DEBUG)
util.makePerformantLogger(log)
_gClockIt = 0 # if true then we are gathering timing data
_gClock = None # if gathering timing data this is set to time retrieval fn
_gStartTime = None # start time of current file being scanned
#---- internal routines and classes
def _isclass(namespace):
return (len(namespace["types"]) == 1
and "class" in namespace["types"])
def _isfunction(namespace):
return (len(namespace["types"]) == 1
and "function" in namespace["types"])
def getAttrStr(attrs):
"""Construct an XML-safe attribute string from the given attributes
"attrs" is a dictionary of attributes
The returned attribute string includes a leading space, if necessary,
so it is safe to use the string right after a tag name. Any Unicode
attributes will be encoded into UTF8 encoding as part of this process.
"""
from xml.sax.saxutils import quoteattr
s = ''
for attr, value in list(attrs.items()):
if not isinstance(value, str):
value = str(value)
elif isinstance(value, str):
value = value.encode("utf-8")
s += ' %s=%s' % (attr, quoteattr(value))
return s
# match 0x00-0x1f except TAB(0x09), LF(0x0A), and CR(0x0D)
_encre = re.compile('([\x00-\x08\x0b\x0c\x0e-\x1f])')
# XXX: this is not used anywhere, is it needed at all?
if sys.version_info >= (2, 3):
charrefreplace = 'xmlcharrefreplace'
else:
# Python 2.2 doesn't have 'xmlcharrefreplace'. Fallback to a
# literal '?' -- this is better than failing outright.
charrefreplace = 'replace'
def xmlencode(s):
"""Encode the given string for inclusion in a UTF-8 XML document.
Note: s must *not* be Unicode, it must be encoded before being passed in.
Specifically, illegal or unpresentable characters are encoded as
XML character entities.
"""
# As defined in the XML spec some of the character from 0x00 to 0x19
# are not allowed in well-formed XML. We replace those with entity
# references here.
# http://www.w3.org/TR/2000/REC-xml-20001006#charsets
#
# Dev Notes:
# - It would be nice if Python has a codec for this. Perhaps we
# should write one.
# - Eric, at one point, had this change to '_xmlencode' for rubycile:
# p4 diff2 -du \
# //depot/main/Apps/Komodo-devel/src/codeintel/ruby/rubycile.py#7 \
# //depot/main/Apps/Komodo-devel/src/codeintel/ruby/rubycile.py#8
# but:
# My guess is that there was a bug here, and explicitly
# utf-8-encoding non-ascii characters fixed it. This was a year
# ago, and I don't recall what I mean by "avoid shuffling the data
# around", but it must be related to something I observed without
# that code.
# replace with XML decimal char entity, e.g. ''
return _encre.sub(lambda m: '&#%d;' % ord(m.group(1)), s)
def cdataescape(s):
"""Return the string escaped for inclusion in an XML CDATA section.
Note: Any Unicode will be encoded to UTF8 encoding as part of this process.
A CDATA section is terminated with ']]>', therefore this token in the
content must be escaped. To my knowledge the XML spec does not define
how to do that. My chosen escape is (courteousy of EricP) is to split
that token into multiple CDATA sections, so that, for example:
blah...]]>...blah
becomes:
blah...]]]]><![CDATA[>...blah
and the resulting content should be copacetic:
<b><![CDATA[blah...]]]]><![CDATA[>...blah]]></b>
"""
if isinstance(s, str):
s = s.encode("utf-8")
parts = s.split("]]>")
return "]]]]><![CDATA[>".join(parts)
def _unistr(x):
if isinstance(x, str):
return x
elif isinstance(x, str):
return x.decode('utf8')
else:
return str(x)
def _et_attrs(attrs):
return dict((_unistr(k), xmlencode(_unistr(v))) for k, v in list(attrs.items())
if v is not None)
def _et_data(data):
return xmlencode(_unistr(data))
def _node_attrs(node, **kw):
return dict(name=node["name"],
line=node.get("line"),
doc=node.get("doc"),
attributes=node.get("attributes") or None,
**kw)
def _node_citdl(node):
max_type = None
max_score = -1
#'guesses' is a types dict: {<type guess>: <score>, ...}
guesses = node.get("types", {})
for type, score in list(guesses.items()):
if ' ' in type:
# XXX Drop the <start-scope> part of CITDL for now.
type = type.split(None, 1)[0]
# Don't emit None types, it does not help us. Fix for bug:
# http://bugs.activestate.com/show_bug.cgi?id=71989
if type != "None":
if score > max_score:
max_type = type
max_score = score
return max_type
class AST2CIXVisitor(ast.NodeVisitor):
"""Generate Code Intelligence XML (CIX) from walking a Python AST tree.
This just generates the CIX content _inside_ of the <file/> tag. The
prefix and suffix have to be added separately.
Note: All node text elements are encoded in UTF-8 format by the Python AST
tree processing, no matter what encoding is used for the file's
original content. The generated CIX XML will also be UTF-8 encoded.
"""
DEBUG = 0
def __init__(self, moduleName=None, content=None, lang="Python"):
self.lang = lang
if self.DEBUG is None:
self.DEBUG = log.isEnabledFor(logging.DEBUG)
self.moduleName = moduleName
self.content = content
if content and self.DEBUG:
self.lines = content.splitlines(0)
else:
self.lines = None
# Symbol Tables (dicts) are built up for each scope. The namespace
# stack to the global-level is maintain in self.nsstack.
self.st = { # the main module symbol table
# <scope name>: <namespace dict>
}
self.nsstack = []
self.cix = ET.TreeBuilder()
self.tree = None
def parse(self):
"""Parse text into a tree and walk the result"""
self.tree = ast.parse(self.content)
def walk(self):
return self.visit(self.tree)
def emit_start(self, s, attrs={}):
self.cix.start(s, _et_attrs(attrs))
def emit_data(self, data):
self.cix.data(_et_data(data))
def emit_end(self, s):
self.cix.end(s)
def emit_tag(self, s, attrs={}, data=None):
self.emit_start(s, _et_attrs(attrs))
if data is not None:
self.emit_data(data)
self.emit_end(s)
def cix_module(self, node):
"""Emit CIX for the given module namespace."""
# log.debug("cix_module(%s, level=%r)", '.'.join(node["nspath"]),
# level)
assert len(node["types"]) == 1 and "module" in node["types"]
attrs = _node_attrs(node, lang=self.lang, ilk="blob")
module = self.emit_start('scope', attrs)
for import_ in node.get("imports", []):
self.cix_import(import_)
self.cix_symbols(node["symbols"])
self.emit_end('scope')
def cix_import(self, node):
# log.debug("cix_import(%s, level=%r)", node["module"], level)
attrs = node
self.emit_tag('import', attrs)
def cix_symbols(self, node, parentIsClass=0):
# Sort variables by line order. This provide the most naturally
# readable comparison of document with its associate CIX content.
vars = sorted(list(node.values()), key=lambda v: v.get("line"))
for var in vars:
self.cix_symbol(var, parentIsClass)
def cix_symbol(self, node, parentIsClass=0):
if _isclass(node):
self.cix_class(node)
elif _isfunction(node):
self.cix_function(node)
else:
self.cix_variable(node, parentIsClass)
def cix_variable(self, node, parentIsClass=0):
# log.debug("cix_variable(%s, level=%r, parentIsClass=%r)",
# '.'.join(node["nspath"]), level, parentIsClass)
attrs = _node_attrs(node, citdl=_node_citdl(node))
if parentIsClass and "is-class-var" not in node:
# Special CodeIntel <variable> attribute to distinguish from the
# usual class variables.
if attrs["attributes"]:
attrs["attributes"] += " __instancevar__"
else:
attrs["attributes"] = "__instancevar__"
self.emit_tag('variable', attrs)
def cix_class(self, node):
# log.debug("cix_class(%s, level=%r)", '.'.join(node["nspath"]), level)
if node["classrefs"]:
citdls = (t for t in (_node_citdl(n) for n in node["classrefs"])
if t is not None)
classrefs = " ".join(citdls)
else:
classrefs = None
attrs = _node_attrs(node,
lineend=node.get("lineend"),
signature=node.get("signature"),
ilk="class",
classrefs=classrefs)
self.emit_start('scope', attrs)
for import_ in node.get("imports", []):
self.cix_import(import_)
self.cix_symbols(node["symbols"], parentIsClass=1)
self.emit_end('scope')
def cix_argument(self, node):
# log.debug("cix_argument(%s, level=%r)", '.'.join(node["nspath"]),
# level)
attrs = _node_attrs(node, citdl=_node_citdl(node), ilk="argument")
self.emit_tag('variable', attrs)
def cix_function(self, node):
# log.debug("cix_function(%s, level=%r)", '.'.join(node["nspath"]), level)
# Determine the best return type.
best_citdl = None
max_count = 0
for citdl, count in list(node["returns"].items()):
if count > max_count:
best_citdl = citdl
attrs = _node_attrs(node,
lineend=node.get("lineend"),
returns=best_citdl,
signature=node.get("signature"),
ilk="function")
self.emit_start("scope", attrs)
for import_ in node.get("imports", []):
self.cix_import(import_)
argNames = []
for arg in node["arguments"]:
argNames.append(arg["name"])
self.cix_argument(arg)
symbols = {} # don't re-emit the function arguments
for symbolName, symbol in list(node["symbols"].items()):
if symbolName not in argNames:
symbols[symbolName] = symbol
self.cix_symbols(symbols)
# XXX <returns/> if one is defined
self.emit_end('scope')
def getCIX(self, path):
"""Return CIX content for parsed data."""
log.debug("getCIX")
self.emit_start('file', dict(lang=self.lang, path=path))
if self.st:
moduleNS = self.st[()]
self.cix_module(moduleNS)
self.emit_end('file')
file = self.cix.close()
return file
# def generic_visit(self, node):
# method = 'visit_' + node.__class__.__name__
# if not hasattr(self, method):
# log.info("generic visit_%s:%s: %r %r", node.__class__.__name__, getattr(node, 'lineno', '?'), self.lines and hasattr(node, 'lineno') and self.lines[node.lineno - 1], node._fields)
# return super(AST2CIXVisitor, self).generic_visit(node)
def visit_Module(self, node):
log.info("visit_%s:%s: %r %r", node.__class__.__name__, getattr(node, 'lineno', '?'), self.lines and hasattr(node, 'lineno') and self.lines[node.lineno - 1], node._fields)
nspath = ()
namespace = {"name": self.moduleName,
"nspath": nspath,
"types": {"module": 1},
"symbols": {}}
doc = ast.get_docstring(node)
if doc:
summarylines = util.parseDocSummary(doc.splitlines(0))
namespace["doc"] = "\n".join(summarylines)
self.st[nspath] = namespace
self.nsstack.append(namespace)
self.generic_visit(node)
self.nsstack.pop()
def visit_Return(self, node):
log.info("visit_%s:%s: %r %r", node.__class__.__name__, getattr(node, 'lineno', '?'), self.lines and hasattr(node, 'lineno') and self.lines[node.lineno - 1], node._fields)
citdl_types = self._guessTypes(node.value)
for citdl in citdl_types:
if citdl:
citdl = citdl.split(None, 1)[0]
if citdl and citdl not in ("None", "NoneType"):
if citdl in ("False", "True"):
citdl = "bool"
func_node = self.nsstack[-1]
t = func_node["returns"]
t[citdl] = t.get(citdl, 0) + 1
def visit_ClassDef(self, node):
log.info("visit_%s:%s: %r %r", node.__class__.__name__, getattr(node, 'lineno', '?'), self.lines and hasattr(node, 'lineno') and self.lines[node.lineno - 1], node._fields)
locals = self.nsstack[-1]
name = node.name
nspath = locals["nspath"] + (name,)
namespace = {
"nspath": nspath,
"name": name,
"types": {"class": 1},
# XXX Example of a base class that might surprise: the
# __metaclass__ class in
# c:\python22\lib\site-packages\ctypes\com\automation.py
# Should this be self._getCITDLExprRepr()???
"classrefs": [],
"symbols": {},
}
namespace["declaration"] = namespace
if node.lineno:
namespace["line"] = node.lineno
namespace["lineend"] = node.lineno
lastNode = node
while True:
try:
lastNode = list(ast.iter_child_nodes(lastNode))[-1]
if hasattr(lastNode, 'lineno'):
namespace["lineend"] = lastNode.lineno
except IndexError:
break
attributes = []
if name.startswith("__") and name.endswith("__"):
pass
elif name.startswith("__"):
attributes.append("private")
elif name.startswith("_"):
attributes.append("protected")
namespace["attributes"] = ' '.join(attributes)
if node.bases:
for baseNode in node.bases:
baseName = self._getExprRepr(baseNode)
classref = {"name": baseName, "types": {}}
for t in self._guessTypes(baseNode):
if t not in classref["types"]:
classref["types"][t] = 0
classref["types"][t] += 1
namespace["classrefs"].append(classref)
doc = ast.get_docstring(node)
if doc:
siglines, desclines = util.parsePyFuncDoc(doc)
if siglines:
namespace["signature"] = "\n".join(siglines)
if desclines:
namespace["doc"] = "\n".join(desclines)
self.st[nspath] = locals["symbols"][name] = namespace
self.nsstack.append(namespace)
self.generic_visit(node)
self.nsstack.pop()
def visit_FunctionDef(self, node):
log.info("visit_%s:%s: %r %r", node.__class__.__name__, getattr(node, 'lineno', '?'), self.lines and hasattr(node, 'lineno') and self.lines[node.lineno - 1], node._fields)
parent = self.nsstack[-1]
parentIsClass = _isclass(parent)
namespace = {
"types": {"function": 1},
"returns": {},
"arguments": [],
"symbols": {},
}
namespace["declaration"] = namespace
if node.lineno:
namespace["line"] = node.lineno
namespace["lineend"] = node.lineno
lastNode = node
while True:
try:
lastNode = list(ast.iter_child_nodes(lastNode))[-1]
if hasattr(lastNode, 'lineno'):
namespace["lineend"] = lastNode.lineno
except IndexError:
break
name = node.name
# Determine attributes
attributes = []
if name.startswith("__") and name.endswith("__"):
pass
elif name.startswith("__"):
attributes.append("private")
elif name.startswith("_"):
attributes.append("protected")
if name == "__init__" and parentIsClass:
attributes.append("__ctor__")
# process decorators
prop_var = None
if node.decorator_list:
for deco in node.decorator_list:
deco_name = getattr(deco, 'id', None)
prop_mode = None
if deco_name == 'staticmethod':
attributes.append("__staticmethod__")
continue
if deco_name == 'classmethod':
attributes.append("__classmethod__")
continue
if deco_name == 'property':
prop_mode = 'getter'
elif hasattr(deco, 'attrname') and deco.attrname in ('getter',
'setter',
'deleter'):
prop_mode = deco.attrname
if prop_mode:
if prop_mode == 'getter':
# it's a getter, create a pseudo-var
prop_var = parent["symbols"].get(name, None)
if prop_var is None:
prop_var = dict(name=name,
nspath=parent["nspath"] + (name,),
doc=None,
types={},
symbols={})
var_attrs = ['property']
if name.startswith("__") and name.endswith("__"):
pass
elif name.startswith("__"):
var_attrs.append("private")
elif name.startswith("_"):
var_attrs.append("protected")
prop_var["attributes"] = ' '.join(var_attrs)
prop_var["declaration"] = prop_var
parent["symbols"][name] = prop_var
if not "is-class-var" in prop_var:
prop_var["is-class-var"] = 1
# hide the function
attributes += ['__hidden__']
name += " (property %s)" % prop_mode
# only one property decorator makes sense
break
namespace["attributes"] = ' '.join(attributes)
if parentIsClass and name == "__init__":
fallbackSig = parent["name"]
else:
fallbackSig = name
namespace["name"] = name
nspath = parent["nspath"] + (name,)
namespace["nspath"] = nspath
# Handle arguments. The format of the relevant Function attributes
# makes this a little bit of pain.
node_args = node.args
defaultArgsBaseIndex = len(node_args.args) - len(node_args.defaults)
if node_args.kwarg:
defaultArgsBaseIndex -= 1
if node_args.vararg:
defaultArgsBaseIndex -= 1
varargsIndex = len(node_args.args) - 2
else:
varargsIndex = None
kwargsIndex = len(node_args.args) - 1
elif node_args.vararg:
defaultArgsBaseIndex -= 1
varargsIndex = len(node_args.args) - 1
kwargsIndex = None
else:
varargsIndex = kwargsIndex = None
sigArgs = []
for i in range(len(node_args.args)):
argName = node_args.args[i].arg
argument = {"name": argName,
"nspath": nspath + (argName,),
"doc": None,
"types": {},
"line": node.lineno,
"symbols": {}}
if i == kwargsIndex:
argument["attributes"] = "kwargs"
sigArgs.append("**" + argName)
elif i == varargsIndex:
argument["attributes"] = "varargs"
sigArgs.append("*" + argName)
elif i >= defaultArgsBaseIndex:
defaultNode = node_args.defaults[i - defaultArgsBaseIndex]
try:
argument["default"] = self._getExprRepr(defaultNode)
except PythonCILEError as ex:
raise PythonCILEError("unexpected default argument node "
"type for Function '%s': %s"
% (node.name, ex))
sigArgs.append(argName + '=' + argument["default"])
for t in self._guessTypes(defaultNode):
log.info("guessed type: %s ::= %s", argName, t)
if t not in argument["types"]:
argument["types"][t] = 0
argument["types"][t] += 1
else:
sigArgs.append(argName)
if i == 0 and parentIsClass:
# If this is a class method, then the first arg is the class
# instance.
className = self.nsstack[-1]["nspath"][-1]
argument["types"][className] = 1
argument["declaration"] = self.nsstack[-1]
arguments = [argument]
for argument in arguments:
if "declaration" not in argument:
argument[
"declaration"] = argument # namespace dict of the declaration
namespace["arguments"].append(argument)
namespace["symbols"][argument["name"]] = argument
# Drop first "self" argument from class method signatures.
# - This is a little bit of a compromise as the "self" argument
# should *sometimes* be included in a method's call signature.
if _isclass(parent) and sigArgs and "__staticmethod__" not in attributes:
# Delete the first "self" argument.
del sigArgs[0]
fallbackSig += "(%s)" % (", ".join(sigArgs))
if "__staticmethod__" in attributes:
fallbackSig += " - staticmethod"
elif "__classmethod__" in attributes:
fallbackSig += " - classmethod"
doc = ast.get_docstring(node)
if doc:
siglines, desclines = util.parsePyFuncDoc(doc, [fallbackSig])
namespace["signature"] = "\n".join(siglines)
if desclines:
namespace["doc"] = "\n".join(desclines)
else:
namespace["signature"] = fallbackSig
self.st[nspath] = parent["symbols"][name] = namespace
self.nsstack.append(namespace)
self.generic_visit(node)
self.nsstack.pop()
if prop_var:
# this is a property getter function,
# copy its return types to the corresponding property variable...
var_types = prop_var["types"]
for t in namespace["returns"]:
if t not in var_types:
var_types[t] = 0
else:
var_types[t] += 1
# ... as well as its line number
if "line" in namespace:
prop_var["line"] = namespace["line"]
def visit_Import(self, node):
log.info("visit_%s:%s: %r %r", node.__class__.__name__, getattr(node, 'lineno', '?'), self.lines and hasattr(node, 'lineno') and self.lines[node.lineno - 1], node._fields)
imports = self.nsstack[-1].setdefault("imports", [])
for alias in node.names:
import_ = {"module": alias.name}
if node.lineno:
import_["line"] = node.lineno
if alias.asname:
import_["alias"] = alias.asname
imports.append(import_)
def visit_ImportFrom(self, node):
log.info("visit_%s:%s: %r %r", node.__class__.__name__, getattr(node, 'lineno', '?'), self.lines and hasattr(node, 'lineno') and self.lines[node.lineno - 1], node._fields)
imports = self.nsstack[-1].setdefault("imports", [])
module = node.module or ''
if node.level > 0:
module = ("." * node.level) + module
for alias in node.names:
import_ = {"module": module, "symbol": alias.name}
if node.lineno:
import_["line"] = node.lineno
if alias.asname:
import_["alias"] = alias.asname
imports.append(import_)
# XXX
# def visit_Return(self, node):
# # set __rettypes__ on Functions
# pass
# def visit_Global(self, node):
# # note for future visitAssign to control namespace
# pass
# def visit_Yield(self, node):
# # modify the Function into a generator??? what are the implications?
# pass
# def visit_Assert(self, node):
# # support the assert hints that Wing does
# pass
def _assignVariable(self, varName, namespace, rhsNode, line,
isClassVar=0):
"""Handle a simple variable name assignment.
"varName" is the variable name being assign to.
"namespace" is the namespace dict to which to assign the variable.
"rhsNode" is the ast.Node of the right-hand side of the
assignment.
"line" is the line number on which the variable is being assigned.
"isClassVar" (optional) is a boolean indicating if this var is
a class variable, as opposed to an instance variable
"""
log.debug("_assignVariable(varName=%r, namespace %s, rhsNode=%r, "
"line, isClassVar=%r)", varName,
'.'.join(namespace["nspath"]), rhsNode, isClassVar)
variable = namespace["symbols"].get(varName, None)
new_var = False
if variable is None:
new_var = True
variable = {"name": varName,
"nspath": namespace["nspath"]+(varName,),
# Could try to parse documentation from a near-by
# string.
"doc": None,
# 'types' is a dict mapping a type name to the number
# of times this was guessed as the variable type.
"types": {},
"symbols": {}}
# Determine attributes
attributes = []
if varName.startswith("__") and varName.endswith("__"):
pass
elif varName.startswith("__"):
attributes.append("private")
elif varName.startswith("_"):
attributes.append("protected")
variable["attributes"] = ' '.join(attributes)
variable["declaration"] = variable
if line:
variable["line"] = line
namespace["symbols"][varName] = variable
if isClassVar and not "is-class-var" in variable:
variable["is-class-var"] = 1
# line number of first class-level assignment wins
if line:
variable["line"] = line
if (not new_var and
_isfunction(variable) and
isinstance(rhsNode, ast.Call) and
rhsNode.args and
isinstance(rhsNode.args[0], ast.Name) and
variable["name"] == rhsNode.args[0].id
):
# a speial case for 2.4-styled decorators
return
varTypes = variable["types"]
for t in self._guessTypes(rhsNode, namespace):
log.info("guessed type: %s ::= %s", varName, t)
if t not in varTypes:
varTypes[t] = 0
varTypes[t] += 1
def _visitSimpleAssign(self, lhsNode, rhsNode, line):
"""Handle a simple assignment: assignment to a symbol name or to
an attribute of a symbol name. If the given left-hand side (lhsNode)
is not an node type that can be handled, it is dropped.
"""
log.debug("_visitSimpleAssign(lhsNode=%r, rhsNode=%r)", lhsNode,
rhsNode)
if isinstance(lhsNode, ast.Name):
# E.g.: foo = ...
# Assign this to the local namespace, unless there was a
# 'global' statement. (XXX Not handling 'global' yet.)
ns = self.nsstack[-1]
self._assignVariable(lhsNode.id, ns, rhsNode, line,
isClassVar=_isclass(ns))
elif isinstance(lhsNode, ast.Attribute):
# E.g.: foo.bar = ...
# If we can resolve "foo", then we update that namespace.
variable, citdl = self._resolveObjectRef(lhsNode.value)
if variable:
self._assignVariable(lhsNode.attr,
variable["declaration"], rhsNode, line)
else:
log.debug("could not handle simple assign (module '%s'): "
"lhsNode=%r, rhsNode=%r", self.moduleName, lhsNode,
rhsNode)
def visit_Assign(self, node):
log.info("visit_%s:%s: %r %r", node.__class__.__name__, getattr(node, 'lineno', '?'), self.lines and hasattr(node, 'lineno') and self.lines[node.lineno - 1], node._fields)
lhsNode = node.targets[0]
rhsNode = node.value
if isinstance(lhsNode, (ast.Name, ast.Attribute)):
# E.g.:
# foo = ... (Name)
# foo.bar = ... (Attribute)
self._visitSimpleAssign(lhsNode, rhsNode, node.lineno)
elif isinstance(lhsNode, (ast.Tuple, ast.List)):
# E.g.:
# foo, bar = ...
# [foo, bar] = ...
# If the RHS is a sequence with the same number of elements,
# then we update each assigned-to variable. Otherwise, bail.
if isinstance(rhsNode, (ast.Tuple, ast.List)):
if len(lhsNode.elts) == len(rhsNode.elts):
for i in range(len(lhsNode.elts)):
self._visitSimpleAssign(lhsNode.elts[i],
rhsNode.elts[i],
node.lineno)
elif isinstance(rhsNode, ast.Dict):
if len(lhsNode.elts) == len(rhsNode.keys):
for i in range(len(lhsNode.elts)):
self._visitSimpleAssign(lhsNode.elts[i],
rhsNode.keys[i],
node.lineno)
elif isinstance(rhsNode, ast.Call):
for i in range(len(lhsNode.elts)):
self._visitSimpleAssign(lhsNode.elts[i],
None, # we don't have a good type.
node.lineno)
else:
log.info(
"visitAssign:: skipping unknown rhsNode type: %r - %r",
type(rhsNode), rhsNode)
elif isinstance(lhsNode, ast.Slice):
# E.g.: bar[1:2] = "foo"
# We don't bother with these: too hard.
log.info("visitAssign:: skipping slice - too hard")
pass
elif isinstance(lhsNode, ast.Subscript):
# E.g.: bar[1] = "foo"
# We don't bother with these: too hard.
log.info("visitAssign:: skipping subscript - too hard")
pass
else:
raise PythonCILEError("unexpected type of LHS of assignment: %r"
% lhsNode)
def _handleUnknownAssignment(self, assignNode, lineno):
if isinstance(assignNode, ast.Name):
self._visitSimpleAssign(assignNode, None, lineno)
elif isinstance(assignNode, ast.Tuple):
for anode in assignNode.elts:
self._visitSimpleAssign(anode, None, lineno)
def visit_For(self, node):
log.info("visit_%s:%s: %r %r", node.__class__.__name__, getattr(node, 'lineno', '?'), self.lines and hasattr(node, 'lineno') and self.lines[node.lineno - 1], node._fields)
# E.g.:
# for foo in ...
# None: don't bother trying to resolve the type of the RHS
self._handleUnknownAssignment(node.target, node.lineno)
self.generic_visit(node)
def visit_With(self, node):
log.info("visit_%s:%s: %r %r", node.__class__.__name__, getattr(node, 'lineno', '?'), self.lines and hasattr(node, 'lineno') and self.lines[node.lineno - 1], node._fields)
for item in node.items:
self._handleUnknownAssignment(item.context_expr, node.lineno)
self.generic_visit(node)
def visit_Try(self, node):
log.info("visit_%s:%s: %r %r", node.__class__.__name__, getattr(node, 'lineno', '?'), self.lines and hasattr(node, 'lineno') and self.lines[node.lineno - 1], node._fields)
for body in node.body:
self.visit(body)
for handler in node.handlers:
try:
if handler.name:
lineno = handler.lineno
self._handleUnknownAssignment(handler.name, lineno)
for body in handler.body:
self.visit(body)
except IndexError:
pass
for orelse in node.orelse:
self.visit(orelse)
for finalbody in node.finalbody:
self.visit(finalbody)
def _resolveObjectRef(self, expr):
"""Try to resolve the given expression to a variable namespace.
"expr" is some kind of ast.Node instance.
Returns the following 2-tuple for the object:
(<variable dict>, <CITDL string>)
where,
<variable dict> is the defining dict for the variable, e.g.
{'name': 'classvar', 'types': {'int': 1}}.
This is None if the variable could not be resolved.
<CITDL string> is a string of CITDL code (see the spec) describing
how to resolve the variable later. This is None if the
variable could be resolved or if the expression is not
expressible in CITDL (CITDL does not attempt to be a panacea).
"""
log.debug("_resolveObjectRef(expr=%r)", expr)
if isinstance(expr, ast.Name):
name = expr.id
nspath = self.nsstack[-1]["nspath"]
for i in range(len(nspath), -1, -1):
ns = self.st[nspath[:i]]
if name in ns["symbols"]:
return (ns["symbols"][name], None)
else:
log.debug(
"_resolveObjectRef: %r not in namespace %r", name,
'.'.join(ns["nspath"]))
elif isinstance(expr, ast.Attribute):
obj, citdl = self._resolveObjectRef(expr.value)
decl = obj and obj["declaration"] or None # want the declaration
if (decl # and "symbols" in decl #XXX this "and"-part necessary?
and expr.attr in decl["symbols"]):
return (decl["symbols"][expr.attr], None)
elif isinstance(expr.value, ast.Num):
# Special case: specifically refer to type object for
# attribute access on constants, e.g.:
# ' '.join
citdl = "__builtins__.%s.%s"\
% ((type(expr.value.n).__name__), expr.attr)
return (None, citdl)
# XXX Could optimize here for common built-in attributes. E.g.,
# we *know* that str.join() returns a string.