Debian Codegraph @

closure-library/closure/bin/labs/code/generate_jsdoc.py

raw
1 #!/usr/bin/env python
2 #
3 # Copyright 2013 The Closure Library Authors. All Rights Reserved.
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS-IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17 """Tool to insert JsDoc before a function.
18
19 This script attempts to find the first function passed in to stdin, generate
20 JSDoc for it (with argument names and possibly return value), and inject
21 it in the string. This is intended to be used as a subprocess by editors
22 such as emacs and vi.
23 """
24
25 import re
26 import sys
27
28
29 # Matches a typical Closure-style function definition.
30 _FUNCTION_REGEX = re.compile(r"""
31 # Start of line
32 ^
33
34 # Indentation
35 (?P<indentation>[ ]*)
36
37 # Identifier (handling split across line)
38 (?P<identifier>\w+(\s*\.\s*\w+)*)
39
40 # "= function"
41 \s* = \s* function \s*
42
43 # opening paren
44 \(
45
46 # Function arguments
47 (?P<arguments>(?:\s|\w+|,)*)
48
49 # closing paren
50 \)
51
52 # opening bracket
53 \s* {
54
55 """, re.MULTILINE | re.VERBOSE)
56
57
58 def _MatchFirstFunction(script):
59 """Match the first function seen in the script."""
60 return _FUNCTION_REGEX.search(script)
61
62
63 def _ParseArgString(arg_string):
64 """Parse an argument string (inside parens) into parameter names."""
65 for arg in arg_string.split(','):
66 arg = arg.strip()
67 if arg:
68 yield arg
69
70
71 def _ExtractFunctionBody(script, indentation=0):
72 """Attempt to return the function body."""
73
74 # Real extraction would require a token parser and state machines.
75 # We look for first bracket at the same level of indentation.
76 regex_str = r'{(.*?)^[ ]{%d}}' % indentation
77
78 function_regex = re.compile(regex_str, re.MULTILINE | re.DOTALL)
79 match = function_regex.search(script)
80 if match:
81 return match.group(1)
82
83
84 def _ContainsReturnValue(function_body):
85 """Attempt to determine if the function body returns a value."""
86 return_regex = re.compile(r'\breturn\b[^;]')
87
88 # If this matches, we assume they're returning something.
89 return bool(return_regex.search(function_body))
90
91
92 def _InsertString(original_string, inserted_string, index):
93 """Insert a string into another string at a given index."""
94 return original_string[0:index] + inserted_string + original_string[index:]
95
96
97 def _GenerateJsDoc(args, return_val=False):
98 """Generate JSDoc for a function.
99
100 Args:
101 args: A list of names of the argument.
102 return_val: Whether the function has a return value.
103
104 Returns:
105 The JSDoc as a string.
106 """
107
108 lines = []
109 lines.append('/**')
110
111 lines += [' * @param {} %s' % arg for arg in args]
112
113 if return_val:
114 lines.append(' * @return')
115
116 lines.append(' */')
117
118 return '\n'.join(lines) + '\n'
119
120
121 def _IndentString(source_string, indentation):
122 """Indent string some number of characters."""
123 lines = [(indentation * ' ') + line
124 for line in source_string.splitlines(True)]
125 return ''.join(lines)
126
127
128 def InsertJsDoc(script):
129 """Attempt to insert JSDoc for the first seen function in the script.
130
131 Args:
132 script: The script, as a string.
133
134 Returns:
135 Returns the new string if function was found and JSDoc inserted. Otherwise
136 returns None.
137 """
138
139 match = _MatchFirstFunction(script)
140 if not match:
141 return
142
143 # Add argument flags.
144 args_string = match.group('arguments')
145 args = _ParseArgString(args_string)
146
147 start_index = match.start(0)
148 function_to_end = script[start_index:]
149
150 lvalue_indentation = len(match.group('indentation'))
151
152 return_val = False
153 function_body = _ExtractFunctionBody(function_to_end, lvalue_indentation)
154 if function_body:
155 return_val = _ContainsReturnValue(function_body)
156
157 jsdoc = _GenerateJsDoc(args, return_val)
158 if lvalue_indentation:
159 jsdoc = _IndentString(jsdoc, lvalue_indentation)
160
161 return _InsertString(script, jsdoc, start_index)
162
163
164 if __name__ == '__main__':
165 stdin_script = sys.stdin.read()
166 result = InsertJsDoc(stdin_script)
167
168 if result:
169 sys.stdout.write(result)
170 else:
171 sys.stdout.write(stdin_script)