-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathecmacile.py
More file actions
2521 lines (2172 loc) · 104 KB
/
ecmacile.py
File metadata and controls
2521 lines (2172 loc) · 104 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
# ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1/GPL 2.0/LGPL 2.1
#
# The contents of this file are subject to the Mozilla Public License
# Version 1.1 (the "License"); you may not use this file except in
# compliance with the License. You may obtain a copy of the License at
# http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS IS"
# basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
# License for the specific language governing rights and limitations
# under the License.
#
# The Original Code is Komodo code.
#
# The Initial Developer of the Original Code is ActiveState Software Inc.
# Portions created by ActiveState Software Inc are Copyright (C) 2004-2006
# ActiveState Software Inc. All Rights Reserved.
#
# Portions created by German Mendez Bravo (Kronuz) are Copyright (C) 2017
# German Mendez Bravo (Kronuz). All Rights Reserved.
#
# Contributor(s):
# Trent Mick (TrentM@ActiveState.com)
# German Mendez Bravo (Kronuz) (german.mb@gmail.com)
#
# Alternatively, the contents of this file may be used under the terms of
# either the GNU General Public License Version 2 or later (the "GPL"), or
# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
# in which case the provisions of the GPL or the LGPL are applicable instead
# of those above. If you wish to allow use of your version of this file only
# under the terms of either the GPL or the LGPL, and not to allow others to
# use your version of this file under the terms of the MPL, indicate your
# decision by deleting the provisions above and replace them with the notice
# and other provisions required by the GPL or the LGPL. If you do not delete
# the provisions above, a recipient may use your version of this file under
# the terms of any one of the MPL, the GPL or the LGPL.
#
# ***** END LICENSE BLOCK *****
"""
ecmacile - a Code Intelligence Language Engine for the ECMAScript language
Module Usage:
from ecmacile import scan
mtime = os.stat("foo.js")[stat.ST_MTIME]
content = open("foo.js", "r").read()
scan(content, "foo.js", mtime=mtime)
Command-line Usage:
ecmacile.py [<options>...] [<ECMAScript 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 ECMAScript files can be specified as arguments or content can be
passed in on stdin. A directory can also be specified, in which case
all .js, .jsx and .es 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)
from __future__ import print_function
import os
import sys
if __name__ == "__main__":
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
import getopt
from hashlib import md5
import re
import logging
import pprint
import glob
import time
import stat
from six.moves import cStringIO as StringIO
try:
from io import BytesIO
except ImportError:
BytesIO = StringIO
import six
from collections import OrderedDict
# 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 esprima
from codeintel2.common import CILEError
from codeintel2.jsdoc import JSDoc as RealJSDoc, JSDocParameter
from codeintel2 import util
__LOCAL__ = "__local__"
__EXPORTED__ = "__exported__"
__INSTANCEVAR__ = "__instancevar__"
# ---- exceptions
class ESCILEError(CILEError):
pass
# ---- global data
_version_ = (0, 1, 0)
log = logging.getLogger("codeintel.ecmacile")
# 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
CITDL_MODULE = "module"
CITDL_CLASS = "class"
CITDL_OBJECT = "object"
CITDL_INTERFACE = "interface"
CITDL_FUNCTION = "function"
CITDL_VOID = "void"
CITDL_NULL = "null"
CITDL_UNDEFINED = "undefined"
CITDL_STRING = "string"
CITDL_NUMBER = "number"
CITDL_BOOLEAN = "boolean"
CITDL_ARRAY = "Array"
CITDL_INSTANCE = "Object"
CITDL_REGEXP = "RegExp"
CITDL_REQUIRE = "require(string)"
CITDL_EMPTY = (CITDL_UNDEFINED, CITDL_NULL, CITDL_VOID)
JSDocParameter.type_map = {
"void": CITDL_VOID,
"null": CITDL_NULL,
"undefined": CITDL_UNDEFINED,
"array": CITDL_ARRAY,
"function": CITDL_FUNCTION,
"object": CITDL_INSTANCE,
"string": CITDL_STRING,
"number": CITDL_NUMBER,
"boolean": CITDL_BOOLEAN,
"regex": CITDL_REGEXP,
}
def JSDocParameter____init__(self, paramname, paramtype=None, doc=None):
self.paramname = paramname
self.paramtype = paramtype
self.doc = doc
if paramname:
self.optional = paramname[0] == '[' and paramname[-1] == ']'
name = paramname[1:-1] if self.optional else paramname
name, _, default = name.partition('=')
self.name = name.strip()
self.default = default.strip()
else:
self.name = None
self.default = None
self.optional = None
if paramtype:
paramtype = paramtype.strip()
paramtype = paramtype.lstrip('{') # FIXME: Bug in JSDoc "{string|function}" gets "{string"
self.type = JSDocParameter.type_map.get(paramtype.lower(), paramtype)
else:
self.type = None
JSDocParameter.__init__ = JSDocParameter____init__
class JSDoc(RealJSDoc):
def __init__(self, comment=None, strip_html_tags=False):
RealJSDoc.__init__(self, comment=comment, strip_html_tags=strip_html_tags)
params_dict = {}
for param in self.params:
params_dict[param.paramname] = param
self.params_dict = params_dict
# ---- internal routines and classes
def _isobject(namespace):
return (len(namespace["types"]) == 1 and CITDL_OBJECT in namespace["types"] or (
CITDL_MODULE not in namespace["types"] and
CITDL_CLASS not in namespace["types"] and
CITDL_INTERFACE not in namespace["types"] and
CITDL_FUNCTION not in namespace["types"] and
CITDL_REQUIRE not in namespace["types"] and
namespace["symbols"]))
def _isclass(namespace):
return (len(namespace["types"]) == 1 and CITDL_CLASS in namespace["types"])
def _isinterface(namespace):
return (len(namespace["types"]) == 1 and CITDL_INTERFACE in namespace["types"])
def _isfunction(namespace):
return (len(namespace["types"]) == 1 and CITDL_FUNCTION in namespace["types"])
def _isrequire(namespace):
return (len(namespace["types"]) == 1 and CITDL_REQUIRE 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, six.string_types):
value = six.text_type(value).encode("utf-8")
elif isinstance(value, six.text_type):
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])')
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 ECMAScript 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, six.text_type):
s = s.encode("utf-8")
parts = s.split("]]>")
return "]]]]><![CDATA[>".join(parts)
def _unistr(x):
if isinstance(x, six.text_type):
return x
elif isinstance(x, six.binary_type):
return x.decode('utf8')
else:
return six.text_type(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, extra_attributes=[], **kw):
return dict(name=node["name"],
line=node.get("line"),
lineend=node.get("lineend"),
start=node.get("start"),
end=node.get("end"),
doc=node.get("doc"),
attributes=" ".join(node.get("attributes", []) + extra_attributes) or None,
**kw)
def _node_citdls(node):
# 'guesses' is a types dict: {<type guess>: <score>, ...}
guesses = node.get("types", {})
for item in sorted(reversed(list(guesses.items())), key=lambda x: -x[1]):
citdl = item[0]
if citdl:
ts = citdl.split(None, 1)
# Don't emit void types, it does not help us.
if ts[0] not in CITDL_EMPTY:
citdl = ts[0] # XXX Drop the <start-scope> part of CITDL for now.
yield citdl
def _node_citdl(node):
citdls = list(_node_citdls(node))
if citdls:
return citdls[0]
class AST2CIXVisitor(esprima.NodeVisitor):
"""Generate Code Intelligence XML (CIX) from walking a ECMAScript 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 ECMAScript 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.
ECMAScript AST docs at:
http://esprima.org
"""
DEBUG = 0
def __init__(self, moduleName=None, content=None, filename=None, lang='ECMAScript'):
self.lang = lang
if self.DEBUG is None:
self.DEBUG = log.isEnabledFor(logging.DEBUG)
self.moduleName = moduleName
self.content = content
self.filename = filename
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
self.uniques = {}
def _unique_id(self, name):
if name not in self.uniques:
self.uniques[name] = 0
unique_name = "____%s_%s" % (name, self.uniques[name])
self.uniques[name] += 1
return unique_name
def get_type(self, obj):
typ = type(obj.value)
return {
type(None): CITDL_NULL,
type(u''): CITDL_STRING,
type(b''): CITDL_STRING,
type(1): CITDL_NUMBER,
type(1.1): CITDL_NUMBER,
type(1 == 1): CITDL_BOOLEAN,
type(re.compile('')): CITDL_REGEXP,
}.get(typ, typ.__name__)
def get_repr(self, obj):
if obj.regex:
r = "/%s/%s" % (obj.regex.pattern, obj.regex.flags)
elif isinstance(obj.value, six.text_type):
r = repr(obj.value).lstrip('bur')
else:
r = repr(obj.value)
return r
def parse(self, **kwargs):
"""Parse text into a tree and walk the result"""
convertor = None
log.info('FILE: %s', self.filename)
self.tree = _getAST(convertor, self.content, self.filename, **kwargs)
# log.debug('TREE: %r', self.tree)
def generic_visit(self, node):
"""Called if no explicit visitor function exists for a node."""
# log.info("GENERIC visit_%s:%s: %r %r", node.__class__.__name__, node.loc.start.line, self.lines and node.loc.start.line and self.lines[node.loc.start.line - 1], node.keys())
return super(AST2CIXVisitor, self).generic_visit(node)
def generic_transform(self, node, metadata):
"""Called if no explicit visitor function exists for a node."""
# log.info("GENERIC transform_%s:%s: %r %r", node.__class__.__name__, metadata.start.line, self.lines and metadata.start.line and self.lines[metadata.start.line - 1], node.keys())
return super(AST2CIXVisitor, self).generic_transform(node, metadata)
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 CITDL_MODULE in node["types"]
attrs = _node_attrs(node, lang=self.lang, ilk="blob")
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=False):
# 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=False):
if _isclass(node):
self.cix_class(node)
elif _isinterface(node):
self.cix_interface(node)
elif _isfunction(node):
self.cix_function(node)
elif _isobject(node):
self.cix_object(node)
else:
self.cix_variable(node, parentIsClass)
def cix_variable(self, node, parentIsClass=False):
# log.debug("cix_variable(%s, level=%r, parentIsClass=%r)",
# '.'.join(node["nspath"]), level, parentIsClass)
extra_attributes = []
if parentIsClass and "is-class-var" not in node:
# Special CodeIntel <variable> attribute to distinguish from the
# usual class variables.
extra_attributes.append(__INSTANCEVAR__)
citdl = _node_citdl(node)
required_library_name = node.get("required_library_name")
attrs = _node_attrs(node,
citdl=citdl,
required_library_name=required_library_name,
extra_attributes=extra_attributes)
self.emit_start('variable', attrs)
self.cix_symbols(node["symbols"])
self.emit_end('variable')
def cix_class(self, node):
# log.debug("cix_class(%s, level=%r)", '.'.join(node["nspath"]), level)
if node.get("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
extra_attributes = []
attrs = _node_attrs(node,
extra_attributes=extra_attributes,
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=True)
self.emit_end('scope')
def cix_interface(self, node):
# log.debug("cix_interface(%s, level=%r)", '.'.join(node["nspath"]), level)
if node.get("interfacerefs"):
citdls = (t for t in (_node_citdl(n) for n in node["interfacerefs"])
if t is not None)
interfacerefs = " ".join(citdls)
else:
interfacerefs = None
extra_attributes = []
attrs = _node_attrs(node,
extra_attributes=extra_attributes,
signature=node.get("signature"),
ilk="interface",
interfacerefs=interfacerefs)
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_object(self, node):
# log.debug("cix_object(%s, level=%r)", '.'.join(node["nspath"]), level)
if node.get("objectrefs"):
citdls = (t for t in (_node_citdl(n) for n in node["objectrefs"])
if t is not None)
objectrefs = " ".join(citdls)
else:
objectrefs = None
extra_attributes = []
citdl = _node_citdl(node)
required_library_name = node.get("required_library_name")
attrs = _node_attrs(node,
extra_attributes=extra_attributes,
signature=node.get("signature"),
ilk="object",
citdl=citdl,
required_library_name=required_library_name,
objectrefs=objectrefs)
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_argument(self, node):
# log.debug("cix_argument(%s, level=%r)", '.'.join(node["nspath"]), level)
extra_attributes = []
citdl = _node_citdl(node)
required_library_name = node.get("required_library_name")
attrs = _node_attrs(node,
extra_attributes=extra_attributes,
citdl=citdl,
required_library_name=required_library_name,
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
extra_attributes = []
attrs = _node_attrs(node,
extra_attributes=extra_attributes,
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 _parseMemberExpression(self, expr, base):
object, _, property = expr.rpartition('.')
property = esprima.nodes.Identifier(property)
property.loc = base.loc
property.range = base.range
if object:
expression = esprima.nodes.StaticMemberExpression(self._parseMemberExpression(object, base), property)
expression.loc = base.loc
expression.range = base.range
return expression
return property
def visit_Module(self, node):
log.info("visit_%s:%s: %r %r", node.__class__.__name__, node.loc.start.line, self.lines and node.loc.start.line and self.lines[node.loc.start.line - 1], node.keys())
nspath = ()
namespace = {"name": self.moduleName,
"nspath": nspath,
"types": OrderedDict({CITDL_MODULE: 0}),
"symbols": {}}
doc = None
if node.body:
leadingComments = node.body[0].leadingComments
if leadingComments:
doc = "/*%s*/" % "\n".join(d.value for d in leadingComments if d.value.startswith('*'))
jsdoc = JSDoc(doc) if doc else None
if jsdoc:
if jsdoc.doc:
namespace["doc"] = jsdoc.doc
self.st[nspath] = namespace
self.nsstack.append(namespace)
self.generic_visit(node)
self.nsstack.pop()
def visit_ReturnStatement(self, node):
log.info("visit_%s:%s: %r %r", node.__class__.__name__, node.loc.start.line, self.lines and node.loc.start.line and self.lines[node.loc.start.line - 1], node.keys())
self.generic_visit(node)
# If there's already a variable assigned to the node, use it:
variable = node.argument and node.argument._variable
if variable:
if _isclass(variable) or _isinterface(variable) or _isfunction(variable) or _isobject(variable) or _isrequire(variable):
citdl_types = [".".join(variable["nspath"])]
else:
citdl_types = list(variable["types"].keys())
else:
citdl_types = self._guessTypes(node.argument)
for citdl in citdl_types:
if citdl:
ts = citdl.split(None, 1)
if ts[0] not in CITDL_EMPTY:
func_node = self.nsstack[-1]
if "returns" in func_node:
t = func_node["returns"]
citdl = ts[0] # XXX Drop the <start-scope> part of CITDL for now.
t[citdl] = t.get(citdl, 0) + 1
def _createObject(self, type, parent, node, extra_attributes):
nspath = parent["nspath"]
namespace = {
"types": OrderedDict({type: 0}),
"%srefs" % type: [],
"symbols": {},
}
bodies = node.body
if bodies and not isinstance(bodies, list):
bodies = bodies.body
if bodies and not isinstance(bodies, list):
bodies = [bodies]
doc = None
if node.body:
leadingComments = node.leadingComments
if leadingComments:
doc = "/*%s*/" % "\n".join(d.value for d in leadingComments if d.value.startswith('*'))
jsdoc = JSDoc(doc) if doc else None
if jsdoc:
if jsdoc.doc:
namespace["doc"] = jsdoc.doc
namespace["declaration"] = namespace
namespace["line"] = node.loc.start.line
namespace["start"] = node.range[0]
namespace["end"] = node.range[1]
if bodies:
lastNode = bodies[-1]
namespace["lineend"] = lastNode.loc.end.line
namespace["end"] = lastNode.range[1]
name = None
if node._member or node._field:
if node._member:
name = node._member.property.name
else: # if node._field:
name = node._field.name
if not name and node.id:
name = node.id.name
if not name and node.name:
name = node.name
if not name:
name = self._unique_id(type)
nspath = nspath + (name,)
namespace["nspath"] = nspath
namespace["name"] = name
# self.st[nspath] = namespace # Objects don't add to the scope's symbol table
parent["symbols"][name] = namespace
attributes = []
namespace["attributes"] = attributes
namespace["attributes"].extend(extra_attributes)
node._parent = parent
node._variable = namespace
return namespace
def visit_JSXElement(self, node):
log.info("visit_%s:%s: %r %r", node.__class__.__name__, node.loc.start.line, self.lines and node.loc.start.line and self.lines[node.loc.start.line - 1], node.keys())
self._visitJSXElement(node)
def _visitJSXElement(self, node, extra_attributes=[]):
parent = self.nsstack[-1]
node.name = self._unique_id(node.openingElement.name.name)
namespace = self._createObject(CITDL_OBJECT, parent, node, extra_attributes)
namespace["objectrefs"] = [{"name": "Object", "types": OrderedDict({CITDL_INSTANCE: 0})}]
# Guess JSX element type:
for citdl in self._guessTypes(node.openingElement.name.name):
# ts = citdl.split(None, 1)
# ts[0] += "()"
# citdl = " ".join(ts)
if citdl not in namespace["types"]:
namespace["types"][citdl] = 0
namespace["types"][citdl] += 1
namespace["attributes"].append("__jsx__")
self.nsstack.append(namespace)
node.openingElement.name = "props"
props = self._createObject(CITDL_OBJECT, namespace, node.openingElement, extra_attributes)
props["types"][CITDL_INSTANCE] = 0
props["objectrefs"] = [{"name": "Object", "types": OrderedDict({CITDL_INSTANCE: 0})}]
self.nsstack.append(props)
self.visit(node.openingElement)
self.nsstack.pop()
if node.children:
for child in node.children:
self.visit(child)
if node.closingElement:
self.visit(node.closingElement)
self.nsstack.pop()
if __EXPORTED__ in extra_attributes:
default = self._parseMemberExpression("exports." + namespace["name"], node)
name = self._parseMemberExpression(namespace["name"], node)
name._member = default
self._visitSimpleAssign(default, name, node.loc.start.line, node.range[0], node.range[1])
def visit_JSXAttribute(self, node):
log.info("visit_%s:%s: %r %r", node.__class__.__name__, node.loc.start.line, self.lines and node.loc.start.line and self.lines[node.loc.start.line - 1], node.keys())
self._visitAssign(node.name, node.value, node.loc.start.line, node.range[0], node.range[1])
def visit_ExportAllDeclaration(self, node):
log.info("visit_%s:%s: %r %r", node.__class__.__name__, node.loc.start.line, self.lines and node.loc.start.line and self.lines[node.loc.start.line - 1], node.keys())
exports, citdl = self._resolveObjectRef(u"exports")
exports["types"][CITDL_REQUIRE] = 0
exports["required_library_name"] = node.source.value
if "line" not in exports:
exports["line"] = node.loc.start.line
exports["start"] = node.range[0]
exports["end"] = node.range[1]
self.generic_visit(node)
def visit_ExportNamedDeclaration(self, node):
log.info("visit_%s:%s: %r %r", node.__class__.__name__, node.loc.start.line, self.lines and node.loc.start.line and self.lines[node.loc.start.line - 1], node.keys())
exports, citdl = self._resolveObjectRef(u"exports")
self.nsstack.append(exports)
if node.source:
self._addImports(node)
if node.specifiers:
for specifier in node.specifiers:
typ = specifier.type
if typ is esprima.Syntax.ExportDefaultSpecifier:
specifier.exported = specifier.local
declaration = specifier.exported if node.source else specifier.local
# Try resolving the variable for the declaration and use the line where it was declared
variable, citdl = self._resolveObjectRef(declaration)
if variable:
line = variable.get('line', node.loc.start.line)
start = variable.get('start', node.range[0])
end = variable.get('end', node.range[1])
else:
line = node.loc.start.line
start = node.range[0]
end = node.range[1]
self._visitAssign(specifier.exported, declaration, line, start, end, extra_attributes=["__no_defn__"])
self.nsstack.pop()
if node.declaration:
typ = node.declaration.type
if typ is esprima.Syntax.VariableDeclaration:
self._visitVariableDeclaration(node.declaration, extra_attributes=[__EXPORTED__])
elif typ is esprima.Syntax.AssignmentExpression:
self._visitAssignmentExpression(node.declaration, extra_attributes=[__EXPORTED__])
elif typ is esprima.Syntax.ObjectExpression:
self._visitObject(node.declaration, extra_attributes=[__EXPORTED__])
elif typ in (esprima.Syntax.ClassDeclaration, esprima.Syntax.ClassExpression):
self._visitClass(node.declaration, extra_attributes=[__EXPORTED__])
elif typ in (esprima.Syntax.FunctionDeclaration, esprima.Syntax.FunctionExpression):
self._visitFunction(node.declaration, extra_attributes=[__EXPORTED__])
else:
self.generic_visit(node)
def visit_ExportDefaultDeclaration(self, node):
log.info("visit_%s:%s: %r %r", node.__class__.__name__, node.loc.start.line, self.lines and node.loc.start.line and self.lines[node.loc.start.line - 1], node.keys())
exports, citdl = self._resolveObjectRef(u"exports")
self.nsstack.append(exports)
default = self._parseMemberExpression(u"default", node)
node.declaration._field = default
typ = node.declaration.type
if typ is esprima.Syntax.AssignmentExpression:
self._visitAssignmentExpression(node.declaration)
declaration = node.declaration.left
else:
self.visit(node.declaration)
declaration = node.declaration
# Try resolving the variable for the declaration and use the line where it was declared
variable, citdl = self._resolveObjectRef(declaration)
if variable:
line = variable.get('line', node.loc.start.line)
start = variable.get('start', node.range[0])
end = variable.get('end', node.range[1])
else:
line = node.loc.start.line
start = node.range[0]
end = node.range[1]
if typ in (esprima.Syntax.Identifier, esprima.JSXSyntax.JSXIdentifier, esprima.Syntax.MemberExpression):
extra_attributes = ["__no_defn__"]
else:
extra_attributes = []
self._visitSimpleAssign(default, declaration, line, start, end, extra_attributes=extra_attributes)
self.nsstack.pop()
def visit_ObjectExpression(self, node):
log.info("visit_%s:%s: %r %r", node.__class__.__name__, node.loc.start.line, self.lines and node.loc.start.line and self.lines[node.loc.start.line - 1], node.keys())
for prop in node.properties:
if prop.type is esprima.Syntax.Property and not prop.computed:
prop.value._member = esprima.nodes.StaticMemberExpression(prop.value, prop.key)
prop.value._member.loc = prop.value.loc
prop.value._member.range = prop.value.range
self._visitObject(node)
def _visitObject(self, node, extra_attributes=[]):
parent = self.nsstack[-1]
namespace = self._createObject(CITDL_OBJECT, parent, node, extra_attributes)
namespace["types"][CITDL_INSTANCE] = 0
namespace["objectrefs"] = [{"name": "Object", "types": OrderedDict({CITDL_INSTANCE: 0})}]
self.nsstack.append(namespace)
self.generic_visit(node)
self.nsstack.pop()
if __EXPORTED__ in extra_attributes:
default = self._parseMemberExpression("exports." + namespace["name"], node)
name = self._parseMemberExpression(namespace["name"], node)
name._member = default
self._visitSimpleAssign(default, name, node.loc.start.line, node.range[0], node.range[1])
def visit_Property(self, node):
log.info("visit_%s:%s: %r %r", node.__class__.__name__, node.loc.start.line, self.lines and node.loc.start.line and self.lines[node.loc.start.line - 1], node.keys())
# Propagate comments:
if not node.value.leadingComments and node.leadingComments:
node.value.leadingComments = node.leadingComments
self.generic_visit(node)
if not node.computed:
self._visitSimpleAssign(node.key, node.value, node.loc.start.line, node.range[0], node.range[1])
def visit_SpreadElement(self, node):
log.info("visit_%s:%s: %r %r", node.__class__.__name__, node.loc.start.line, self.lines and node.loc.start.line and self.lines[node.loc.start.line - 1], node.keys())
self.generic_visit(node)
namespace = self.nsstack[-1]
if "objectrefs" in namespace: