forked from spadgos/sublime-jsdocs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jsdocs.py
1607 lines (1326 loc) · 54.8 KB
/
jsdocs.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
DocBlockr v2.14.1
by Nick Fisher, and all the great people listed in CONTRIBUTORS.md
https://github.com/spadgos/sublime-jsdocs
*** Please read CONTIBUTING.md before sending pull requests. Thanks! ***
"""
import sublime
import sublime_plugin
import re
import datetime
import time
import imp
from functools import reduce
def read_line(view, point):
if (point >= view.size()):
return
next_line = view.line(point)
return view.substr(next_line)
def write(view, str):
view.run_command(
'insert_snippet', {
'contents': str
}
)
def counter():
count = 0
while True:
count += 1
yield(count)
def escape(str):
return str.replace('$', '\$').replace('{', '\{').replace('}', '\}')
def is_numeric(val):
try:
float(val)
return True
except ValueError:
return False
def getParser(view):
scope = view.scope_name(view.sel()[0].end())
res = re.search('\\bsource\\.([a-z+\-]+)', scope)
sourceLang = res.group(1) if res else 'js'
viewSettings = view.settings()
if sourceLang == "php":
return JsdocsPHP(viewSettings)
elif sourceLang == "coffee":
return JsdocsCoffee(viewSettings)
elif sourceLang == "actionscript" or sourceLang == 'haxe':
return JsdocsActionscript(viewSettings)
elif sourceLang == "c++" or sourceLang == 'c' or sourceLang == 'cuda-c++':
return JsdocsCPP(viewSettings)
elif sourceLang == 'objc' or sourceLang == 'objc++':
return JsdocsObjC(viewSettings)
elif sourceLang == 'java' or sourceLang == 'groovy' or sourceLang == 'apex':
return JsdocsJava(viewSettings)
elif sourceLang == 'rust':
return JsdocsRust(viewSettings)
elif sourceLang == 'ts':
return JsdocsTypescript(viewSettings)
return JsdocsJavascript(viewSettings)
def splitByCommas(str):
"""
Split a string by unenclosed commas: that is, commas which are not inside of quotes or brackets.
splitByCommas('foo, bar(baz, quux), fwip = "hey, hi"')
==> ['foo', 'bar(baz, quux)', 'fwip = "hey, hi"']
"""
out = []
if not str:
return out
# the current token
current = ''
# characters which open a section inside which commas are not separators between different arguments
openQuotes = '"\'<({'
# characters which close the section. The position of the character here should match the opening
# indicator in `openQuotes`
closeQuotes = '"\'>)}'
matchingQuote = ''
insideQuotes = False
nextIsLiteral = False
for char in str:
if nextIsLiteral: # previous char was a \
current += char
nextIsLiteral = False
elif insideQuotes:
if char == '\\':
nextIsLiteral = True
else:
current += char
if char == matchingQuote:
insideQuotes = False
else:
if char == ',':
out.append(current.strip())
current = ''
else:
current += char
quoteIndex = openQuotes.find(char)
if quoteIndex > -1:
matchingQuote = closeQuotes[quoteIndex]
insideQuotes = True
out.append(current.strip())
return out
def flatten(theList):
"""
Flatten a shallow list. Only works when all items are lists.
[[(1,1)], [(2,2), (3, 3)]] --> [(1,1), (2,2), (3,3)]
"""
return [item for sublist in theList for item in sublist]
def getDocBlockRegion(view, point):
"""
Given a starting point inside a DocBlock, return a Region which encompasses the entire block.
This is similar to `run_command('expand_selection', { to: 'scope' })`, however it is resilient to bugs which occur
due to language files adding scopes inside the DocBlock (eg: to highlight tags)
"""
start = end = point
while start > 0 and view.scope_name(start - 1).find('comment.block') > -1:
start = start - 1
while end < view.size() and view.scope_name(end).find('comment.block') > -1:
end = end + 1
return sublime.Region(start, end)
class JsdocsCommand(sublime_plugin.TextCommand):
def run(self, edit, inline=False):
self.initialize(self.view, inline)
if self.parser.isExistingComment(self.line):
write(self.view, "\n *" + self.indentSpaces)
return
# erase characters in the view (will be added to the output later)
self.view.erase(edit, self.trailingRgn)
# match against a function declaration.
out = self.parser.parse(self.line)
snippet = self.generateSnippet(out, inline)
write(self.view, snippet)
def initialize(self, v, inline=False):
point = v.sel()[0].end()
self.settings = v.settings()
# trailing characters are put inside the body of the comment
self.trailingRgn = sublime.Region(point, v.line(point).end())
self.trailingString = v.substr(self.trailingRgn).strip()
# drop trailing '*/'
self.trailingString = escape(re.sub('\\s*\\*\\/\\s*$', '', self.trailingString))
self.indentSpaces = " " * max(0, self.settings.get("jsdocs_indentation_spaces", 1))
self.prefix = "*"
settingsAlignTags = self.settings.get("jsdocs_align_tags", 'deep')
self.deepAlignTags = settingsAlignTags == 'deep'
self.shallowAlignTags = settingsAlignTags in ('shallow', True)
self.parser = parser = getParser(v)
parser.inline = inline
# use trailing string as a description of the function
if self.trailingString:
parser.setNameOverride(self.trailingString)
# read the next line
self.line = parser.getDefinition(v, v.line(point).end() + 1)
def generateSnippet(self, out, inline=False):
# substitute any variables in the tags
if out:
out = self.substituteVariables(out)
# align the tags
if out and (self.shallowAlignTags or self.deepAlignTags) and not inline:
out = self.alignTags(out)
# fix all the tab stops so they're consecutive
if out:
out = self.fixTabStops(out)
if inline:
if out:
return " " + out[0] + " */"
else:
return " $0 */"
else:
return self.createSnippet(out) + ('\n' if self.settings.get('jsdocs_newline_after_block') else '')
def alignTags(self, out):
def outputWidth(str):
# get the length of a string, after it is output as a snippet,
# "${1:foo}" --> 3
return len(re.sub("[$][{]\\d+:([^}]+)[}]", "\\1", str).replace('\$', '$'))
# count how many columns we have
maxCols = 0
# this is a 2d list of the widths per column per line
widths = []
# Grab the return tag if required.
if self.settings.get('jsdocs_per_section_indent'):
returnTag = self.settings.get('jsdocs_return_tag') or '@return'
else:
returnTag = False
for line in out:
if line.startswith('@'):
# Ignore the return tag if we're doing per-section indenting.
if returnTag and line.startswith(returnTag):
continue
# ignore all the words after `@author`
columns = line.split(" ") if not line.startswith('@author') else ['@author']
widths.append(list(map(outputWidth, columns)))
maxCols = max(maxCols, len(widths[-1]))
# initialise a list to 0
maxWidths = [0] * maxCols
if (self.shallowAlignTags):
maxCols = 1
for i in range(0, maxCols):
for width in widths:
if (i < len(width)):
maxWidths[i] = max(maxWidths[i], width[i])
# Convert to a dict so we can use .get()
maxWidths = dict(enumerate(maxWidths))
# Minimum spaces between line columns
minColSpaces = self.settings.get('jsdocs_min_spaces_between_columns', 1)
for index, line in enumerate(out):
# format the spacing of columns, but ignore the author tag. (See #197)
if line.startswith('@') and not line.startswith('@author'):
newOut = []
for partIndex, part in enumerate(line.split(" ")):
newOut.append(part)
newOut.append(" " * minColSpaces + (" " * (maxWidths.get(partIndex, 0) - outputWidth(part))))
out[index] = "".join(newOut).strip()
return out
def substituteVariables(self, out):
def getVar(match):
varName = match.group(1)
if varName == 'datetime':
date = datetime.datetime.now().replace(microsecond=0)
offset = time.timezone / -3600.0
return "%s%s%02d%02d" % (
date.isoformat(),
'+' if offset >= 0 else "-",
abs(offset),
(offset % 1) * 60
)
elif varName == 'date':
return datetime.date.today().isoformat()
else:
return match.group(0)
def subLine(line):
return re.sub(r'\{\{([^}]+)\}\}', getVar, line)
return list(map(subLine, out))
def fixTabStops(self, out):
tabIndex = counter()
def swapTabs(m):
return "%s%d%s" % (m.group(1), next(tabIndex), m.group(2))
for index, outputLine in enumerate(out):
out[index] = re.sub("(\\$\\{)\\d+(:[^}]+\\})", swapTabs, outputLine)
return out
def createSnippet(self, out):
snippet = ""
closer = self.parser.settings['commentCloser']
if out:
if self.settings.get('jsdocs_spacer_between_sections') == True:
lastTag = None
for idx, line in enumerate(out):
res = re.match("^\\s*@([a-zA-Z]+)", line)
if res and (lastTag != res.group(1)):
if self.settings.get('jsdocs_function_description') == False:
if lastTag != None:
out.insert(idx, "")
else:
out.insert(idx, "")
lastTag = res.group(1)
elif self.settings.get('jsdocs_spacer_between_sections') == 'after_description' and self.settings.get('jsdocs_function_description'):
lastLineIsTag = False
for idx, line in enumerate(out):
res = re.match("^\\s*@([a-zA-Z]+)", line)
if res:
if not lastLineIsTag:
out.insert(idx, "")
lastLineIsTag = True
for line in out:
snippet += "\n " + self.prefix + (self.indentSpaces + line if line else "")
else:
snippet += "\n " + self.prefix + self.indentSpaces + "${0:" + self.trailingString + '}'
snippet += "\n" + closer
return snippet
class JsdocsParser(object):
def __init__(self, viewSettings):
self.viewSettings = viewSettings
self.setupSettings()
self.nameOverride = None
def isExistingComment(self, line):
return re.search('^\\s*\\*', line)
def setNameOverride(self, name):
""" overrides the description of the function - used instead of parsed description """
self.nameOverride = name
def getNameOverride(self):
return self.nameOverride
def parse(self, line):
if self.viewSettings.get('jsdocs_simple_mode'):
return None
try:
out = self.parseFunction(line) # (name, args, retval, options)
if (out):
return self.formatFunction(*out)
out = self.parseVar(line)
if out:
return self.formatVar(*out)
except:
# TODO show exception if dev\debug mode
return None
return None
def formatVar(self, name, val, valType=None):
out = []
if not valType:
if not val or val == '': # quick short circuit
valType = "[type]"
else:
valType = self.guessTypeFromValue(val) or self.guessTypeFromName(name) or "[type]"
if self.inline:
out.append("@%s %s${1:%s}%s ${1:[description]}" % (
self.settings['typeTag'],
"{" if self.settings['curlyTypes'] else "",
valType,
"}" if self.settings['curlyTypes'] else ""
))
else:
out.append("${1:[%s description]}" % (escape(name)))
out.append("@%s %s${1:%s}%s" % (
self.settings['typeTag'],
"{" if self.settings['curlyTypes'] else "",
valType,
"}" if self.settings['curlyTypes'] else ""
))
return out
def getTypeInfo(self, argType, argName):
typeInfo = ''
if self.settings['typeInfo']:
typeInfo = '%s${1:%s}%s ' % (
"{" if self.settings['curlyTypes'] else "",
escape(argType or self.guessTypeFromName(argName) or "[type]"),
"}" if self.settings['curlyTypes'] else "",
)
return typeInfo
def formatFunction(self, name, args, retval, options={}):
out = []
if 'as_setter' in options:
out.append('@private')
return out
extraTagAfter = self.viewSettings.get("jsdocs_extra_tags_go_after") or False
description = self.getNameOverride() or ('[%s%sdescription]' % (escape(name), ' ' if name else ''))
if self.viewSettings.get('jsdocs_function_description'):
out.append("${1:%s}" % description)
if (self.viewSettings.get("jsdocs_autoadd_method_tag") is True):
out.append("@%s %s" % (
"method",
escape(name)
))
if not extraTagAfter:
self.addExtraTags(out)
# if there are arguments, add a @param for each
if (args):
# remove comments inside the argument list.
args = re.sub(r'/\*.*?\*/', '', args)
for argType, argName in self.parseArgs(args):
typeInfo = self.getTypeInfo(argType, argName)
format_str = "@param %s%s"
if (self.viewSettings.get('jsdocs_param_description')):
format_str += " ${1:[description]}"
out.append(format_str % (
typeInfo,
escape(argName) if self.viewSettings.get('jsdocs_param_name') else ''
))
# return value type might be already available in some languages but
# even then ask language specific parser if it wants it listed
retType = self.getFunctionReturnType(name, retval)
if retType is not None:
typeInfo = ''
if self.settings['typeInfo']:
typeInfo = ' %s${1:%s}%s' % (
"{" if self.settings['curlyTypes'] else "",
retType or "[type]",
"}" if self.settings['curlyTypes'] else ""
)
format_args = [
self.viewSettings.get('jsdocs_return_tag') or '@return',
typeInfo
]
if (self.viewSettings.get('jsdocs_return_description')):
format_str = "%s%s %s${1:[description]}"
third_arg = ""
# the extra space here is so that the description will align with the param description
if args and self.viewSettings.get('jsdocs_align_tags') == 'deep':
if not self.viewSettings.get('jsdocs_per_section_indent'):
third_arg = " "
format_args.append(third_arg)
else:
format_str = "%s%s"
out.append(format_str % tuple(format_args))
for notation in self.getMatchingNotations(name):
if 'tags' in notation:
out.extend(notation['tags'])
if extraTagAfter:
self.addExtraTags(out)
return out
def getFunctionReturnType(self, name, retval):
""" returns None for no return type. False meaning unknown, or a string """
if re.match("[A-Z]", name):
# no return, but should add a class
return None
if re.match('[$_]?(?:set|add)($|[A-Z_])', name):
# setter/mutator, no return
return None
if re.match('[$_]?(?:is|has)($|[A-Z_])', name): # functions starting with 'is' or 'has'
return self.settings['bool']
return self.guessTypeFromName(name) or False
def parseArgs(self, args):
"""
a list of tuples, the first being the best guess at the type, the second being the name
"""
blocks = splitByCommas(args)
out = []
for arg in blocks:
out.append(self.getArgInfo(arg))
return flatten(out)
def getArgInfo(self, arg):
"""
Return a list of tuples, one for each argument derived from the arg param.
"""
return [(self.getArgType(arg), self.getArgName(arg))]
def getArgType(self, arg):
return None
def getArgName(self, arg):
return arg
def addExtraTags(self, out):
extraTags = self.viewSettings.get('jsdocs_extra_tags', [])
if (len(extraTags) > 0):
out.extend(extraTags)
def guessTypeFromName(self, name):
matches = self.getMatchingNotations(name)
if len(matches):
rule = matches[0]
if ('type' in rule):
return self.settings[rule['type']] if rule['type'] in self.settings else rule['type']
if (re.match("(?:is|has)[A-Z_]", name)):
return self.settings['bool']
if (re.match("^(?:cb|callback|done|next|fn)$", name)):
return self.settings['function']
return False
def getMatchingNotations(self, name):
def checkMatch(rule):
if 'prefix' in rule:
regex = re.escape(rule['prefix'])
if re.match('.*[a-z]', rule['prefix']):
regex += '(?:[A-Z_]|$)'
return re.match(regex, name)
elif 'regex' in rule:
return re.search(rule['regex'], name)
return list(filter(checkMatch, self.viewSettings.get('jsdocs_notation_map', [])))
def getDefinition(self, view, pos):
"""
get a relevant definition starting at the given point
returns string
"""
maxLines = 25 # don't go further than this
openBrackets = 0
definition = ''
# count the number of open parentheses
def countBrackets(total, bracket):
return total + (1 if bracket == '(' else -1)
for i in range(0, maxLines):
line = read_line(view, pos)
if line is None:
break
pos += len(line) + 1
# strip comments
line = re.sub(r"//.*", "", line)
line = re.sub(r"/\*.*\*/", "", line)
searchForBrackets = line
# on the first line, only start looking from *after* the actual function starts. This is
# needed for cases like this:
# (function (foo, bar) { ... })
if definition == '':
opener = re.search(self.settings['fnOpener'], line) if self.settings['fnOpener'] else False
if opener:
# ignore everything before the function opener
searchForBrackets = line[opener.start():]
openBrackets = reduce(countBrackets, re.findall('[()]', searchForBrackets), openBrackets)
definition += line
if openBrackets == 0:
break
return definition
class JsdocsJavascript(JsdocsParser):
def setupSettings(self):
identifier = '[a-zA-Z_$][a-zA-Z_$0-9]*'
self.settings = {
# curly brackets around the type information
"curlyTypes": True,
'typeInfo': True,
"typeTag": self.viewSettings.get('jsdocs_override_js_var') or "type",
# technically, they can contain all sorts of unicode, but w/e
"varIdentifier": identifier,
"fnIdentifier": identifier,
"fnOpener": '(?:'
+ r'function[\s*]*(?:' + identifier + r')?\s*\('
+ '|'
+ '(?:' + identifier + r'|\(.*\)\s*=>)'
+ '|'
+ '(?:' + identifier + r'\s*\(.*\)\s*\{)'
+ ')',
"commentCloser": " */",
"bool": "Boolean",
"function": "Function"
}
def parseFunction(self, line):
res = re.search(
# Normal functions...
# fnName = function, fnName : function
r'(?:(?P<name1>' + self.settings['varIdentifier'] + r')\s*[:=]\s*)?'
+ 'function'
# function fnName, function* fnName
+ r'(?P<generator>[\s*]+)?(?P<name2>' + self.settings['fnIdentifier'] + ')?'
# (arg1, arg2)
+ r'\s*\(\s*(?P<args>.*)\)',
line
) or re.search(
# ES6 arrow functions
# () => y, x => y, (x, y) => y, (x = 4) => y
r'(?:(?P<args>' + self.settings['varIdentifier'] + r')|\(\s*(?P<args2>.*)\))\s*=>',
line
) or re.search(
# ES6 method initializer shorthand
# var person = { getName() { return this.name; } }
r'(?P<name1>' + self.settings['varIdentifier'] + ')\s*\((?P<args>.*)\)\s*\{',
line
)
if not res:
return None
groups = {
'name1': '',
'name2': '',
'generator': '',
'args': '',
'args2': ''
}
groups.update(res.groupdict())
# grab the name out of "name1 = function name2(foo)" preferring name1
generatorSymbol = '*' if (groups['generator'] or '').find('*') > -1 else ''
name = generatorSymbol + (groups['name1'] or groups['name2'] or '')
args = groups['args'] or groups['args2'] or ''
return (name, args, None)
def parseVar(self, line):
res = re.search(
# var foo = blah,
# foo = blah;
# baz.foo = blah;
# baz = {
# foo : blah
# }
'(?P<name>' + self.settings['varIdentifier'] + ')\s*[=:]\s*(?P<val>.*?)(?:[;,]|$)',
line
)
if not res:
return None
return (res.group('name'), res.group('val').strip())
def getArgInfo(self, arg):
if (re.search('^\{.*\}$', arg)):
subItems = splitByCommas(arg[1:-1])
prefix = 'options.'
else:
subItems = [arg]
prefix = ''
out = []
for subItem in subItems:
out.append((self.getArgType(subItem), prefix + self.getArgName(subItem)))
return out
def getArgType(self, arg):
parts = re.split(r'\s*=\s*', arg, 1)
# rest parameters
if parts[0].find('...') == 0:
return '...[type]'
elif len(parts) > 1:
return self.guessTypeFromValue(parts[1])
def getArgName(self, arg):
namePart = re.split(r'\s*=\s*', arg, 1)[0]
# check for rest parameters, eg: function (foo, ...rest) {}
if namePart.find('...') == 0:
return namePart[3:]
return namePart
def getFunctionReturnType(self, name, retval):
if name and name[0] == '*':
return None
return super(JsdocsJavascript, self).getFunctionReturnType(name, retval)
def getMatchingNotations(self, name):
out = super(JsdocsJavascript, self).getMatchingNotations(name)
if name and name[0] == '*':
# if '@returns' is preferred, then also use '@yields'. Otherwise, '@return' and '@yield'
yieldTag = '@yield' + ('s' if self.viewSettings.get('jsdocs_return_tag', '_')[-1] == 's' else '')
description = ' ${1:[description]}' if self.viewSettings.get('jsdocs_return_description', True) else ''
out.append({ 'tags': [
'%s {${1:[type]}}%s' % (yieldTag, description)
]})
return out
def guessTypeFromValue(self, val):
lowerPrimitives = self.viewSettings.get('jsdocs_lower_case_primitives') or False
shortPrimitives = self.viewSettings.get('jsdocs_short_primitives') or False
if is_numeric(val):
return "number" if lowerPrimitives else "Number"
if val[0] == '"' or val[0] == "'":
return "string" if lowerPrimitives else "String"
if val[0] == '[':
return "Array"
if val[0] == '{':
return "Object"
if val == 'true' or val == 'false':
returnVal = 'Bool' if shortPrimitives else 'Boolean'
return returnVal.lower() if lowerPrimitives else returnVal
if re.match('RegExp\\b|\\/[^\\/]', val):
return 'RegExp'
if val.find('=>') > -1:
return 'function' if lowerPrimitives else 'Function'
if val[:4] == 'new ':
res = re.search('new (' + self.settings['fnIdentifier'] + ')', val)
return res and res.group(1) or None
return None
class JsdocsPHP(JsdocsParser):
def setupSettings(self):
shortPrimitives = self.viewSettings.get('jsdocs_short_primitives') or False
nameToken = '[a-zA-Z_\\x7f-\\xff][a-zA-Z0-9_\\x7f-\\xff]*'
self.settings = {
# curly brackets around the type information
'curlyTypes': False,
'typeInfo': True,
'typeTag': "var",
'varIdentifier': '&?[$]' + nameToken + '(?:->' + nameToken + ')*',
'fnIdentifier': nameToken,
'typeIdentifier': '\\\\?' + nameToken + '(\\\\' + nameToken + ')*',
'fnOpener': 'function(?:\\s+' + nameToken + ')?\\s*\\(',
'commentCloser': ' */',
'bool': 'bool' if shortPrimitives else 'boolean',
'function': "function"
}
def parseFunction(self, line):
res = re.search(
'function\\s+&?\\s*'
+ '(?P<name>' + self.settings['fnIdentifier'] + ')'
# function fnName
# (arg1, arg2)
+ '\\s*\\(\\s*(?P<args>.*)\\)',
line
)
if not res:
return None
return (res.group('name'), res.group('args'), None)
def getArgType(self, arg):
res = re.search(
'(?P<type>' + self.settings['typeIdentifier'] + ')?'
+ '\\s*(?P<name>' + self.settings['varIdentifier'] + ')'
+ '(\\s*=\\s*(?P<val>.*))?',
arg
);
if (res):
argType = res.group("type")
argName = res.group("name")
argVal = res.group("val")
# function fnc_name(type $name = val)
if (argType and argVal):
# function fnc_name(array $x = array())
# function fnc_name(array $x = [])
argValType = self.guessTypeFromValue(argVal)
if argType == argValType:
return argType
# function fnc_name(type $name = null)
return argType + "|" + argValType
# function fnc_name(type $name)
if (argType):
return argType
# function fnc_name($name = value)
if (argVal):
guessedType = self.guessTypeFromValue(argVal)
return guessedType if guessedType != 'null' else None
# function fnc_name()
return None
def getArgName(self, arg):
return re.search("(" + self.settings['varIdentifier'] + ")(?:\\s*=.*)?$", arg).group(1)
def parseVar(self, line):
res = re.search(
# var $foo = blah,
# $foo = blah;
# $baz->foo = blah;
# $baz = array(
# 'foo' => blah
# )
'(?P<name>' + self.settings['varIdentifier'] + ')\\s*=>?\\s*(?P<val>.*?)(?:[;,]|$)',
line
)
if res:
return (res.group('name'), res.group('val').strip())
res = re.search(
'\\b(?:var|public|private|protected|static)\\s+(?P<name>' + self.settings['varIdentifier'] + ')',
line
)
if res:
return (res.group('name'), None)
return None
def guessTypeFromValue(self, val):
shortPrimitives = self.viewSettings.get('jsdocs_short_primitives') or False
if is_numeric(val):
return "float" if '.' in val else 'int' if shortPrimitives else 'integer'
if val[0] == '"' or val[0] == "'":
return "string"
if val[:5] == 'array' or (val[0] == '[' and val[-1] == ']'):
return "array"
if val.lower() in ('true', 'false', 'filenotfound'):
return 'bool' if shortPrimitives else 'boolean'
if val[:4] == 'new ':
res = re.search('new (' + self.settings['fnIdentifier'] + ')', val)
return res and res.group(1) or None
if val.lower() in ('null'):
return 'null'
return None
def getFunctionReturnType(self, name, retval):
shortPrimitives = self.viewSettings.get('jsdocs_short_primitives') or False
if (name[:2] == '__'):
if name in ('__construct', '__destruct', '__set', '__unset', '__wakeup'):
return None
if name == '__sleep':
return 'array'
if name == '__toString':
return 'string'
if name == '__isset':
return 'bool' if shortPrimitives else 'boolean'
return JsdocsParser.getFunctionReturnType(self, name, retval)
class JsdocsCPP(JsdocsParser):
def setupSettings(self):
nameToken = '[a-zA-Z_][a-zA-Z0-9_]*'
identifier = '(%s)(::%s)?' % (nameToken, nameToken)
self.settings = {
'typeInfo': False,
'curlyTypes': False,
'typeTag': 'param',
'commentCloser': ' */',
'fnIdentifier': identifier,
'varIdentifier': '(' + identifier + ')\\s*(?:\\[(?:' + identifier + r')?\]|\((?:(?:\s*,\s*)?[a-z]+)+\s*\))*',
'fnOpener': identifier + '\\s+' + identifier + '\\s*\\(',
'bool': 'bool',
'function': 'function'
}
def parseFunction(self, line):
res = re.search(
'(?P<retval>' + self.settings['varIdentifier'] + ')[&*\\s]+'
+ '(?P<name>' + self.settings['varIdentifier'] + ');?'
# void fnName
# (arg1, arg2)
+ '\\s*\\(\\s*(?P<args>.*)\)',
line
)
if not res:
return None
return (res.group('name'), res.group('args'), res.group('retval'))
def parseArgs(self, args):
if args.strip() == 'void':
return []
return super(JsdocsCPP, self).parseArgs(args)
def getArgType(self, arg):
return None
def getArgName(self, arg):
return re.search(self.settings['varIdentifier'] + r"(?:\s*=.*)?$", arg).group(1)
def parseVar(self, line):
return None
def guessTypeFromValue(self, val):
return None
def getFunctionReturnType(self, name, retval):
return retval if retval != 'void' else None
class JsdocsCoffee(JsdocsParser):
def setupSettings(self):
identifier = '[a-zA-Z_$][a-zA-Z_$0-9]*'
self.settings = {
# curly brackets around the type information
'curlyTypes': True,
'typeTag': self.viewSettings.get('jsdocs_override_js_var') or "type",
'typeInfo': True,
# technically, they can contain all sorts of unicode, but w/e
'varIdentifier': identifier,
'fnIdentifier': identifier,
'fnOpener': None, # no multi-line function definitions for you, hipsters!
'commentCloser': '###',
'bool': 'Boolean',
'function': 'Function'
}
def parseFunction(self, line):
res = re.search(
# fnName = function, fnName : function
'(?:(?P<name>' + self.settings['varIdentifier'] + ')\s*[:=]\s*)?'
+ '(?:\\((?P<args>[^()]*?)\\))?\\s*([=-]>)',
line
)
if not res:
return None
# grab the name out of "name1 = function name2(foo)" preferring name1
name = res.group('name') or ''
args = res.group('args')
return (name, args, None)
def parseVar(self, line):
res = re.search(
# var foo = blah,
# foo = blah;
# baz.foo = blah;
# baz = {
# foo : blah
# }
'(?P<name>' + self.settings['varIdentifier'] + ')\s*[=:]\s*(?P<val>.*?)(?:[;,]|$)',
line
)
if not res:
return None
return (res.group('name'), res.group('val').strip())
def guessTypeFromValue(self, val):
lowerPrimitives = self.viewSettings.get('jsdocs_lower_case_primitives') or False
if is_numeric(val):
return "number" if lowerPrimitives else "Number"
if val[0] == '"' or val[0] == "'":
return "string" if lowerPrimitives else "String"
if val[0] == '[':
return "Array"
if val[0] == '{':
return "Object"
if val == 'true' or val == 'false':
return "boolean" if lowerPrimitives else "Boolean"
if re.match('RegExp\\b|\\/[^\\/]', val):
return 'RegExp'
if val[:4] == 'new ':
res = re.search('new (' + self.settings['fnIdentifier'] + ')', val)
return res and res.group(1) or None
return None
class JsdocsActionscript(JsdocsParser):