generate_jsdoc.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  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. """Tool to insert JsDoc before a function.
  17. This script attempts to find the first function passed in to stdin, generate
  18. JSDoc for it (with argument names and possibly return value), and inject
  19. it in the string. This is intended to be used as a subprocess by editors
  20. such as emacs and vi.
  21. """
  22. import re
  23. import sys
  24. # Matches a typical Closure-style function definition.
  25. _FUNCTION_REGEX = re.compile(r"""
  26. # Start of line
  27. ^
  28. # Indentation
  29. (?P<indentation>[ ]*)
  30. # Identifier (handling split across line)
  31. (?P<identifier>\w+(\s*\.\s*\w+)*)
  32. # "= function"
  33. \s* = \s* function \s*
  34. # opening paren
  35. \(
  36. # Function arguments
  37. (?P<arguments>(?:\s|\w+|,)*)
  38. # closing paren
  39. \)
  40. # opening bracket
  41. \s* {
  42. """, re.MULTILINE | re.VERBOSE)
  43. def _MatchFirstFunction(script):
  44. """Match the first function seen in the script."""
  45. return _FUNCTION_REGEX.search(script)
  46. def _ParseArgString(arg_string):
  47. """Parse an argument string (inside parens) into parameter names."""
  48. for arg in arg_string.split(','):
  49. arg = arg.strip()
  50. if arg:
  51. yield arg
  52. def _ExtractFunctionBody(script, indentation=0):
  53. """Attempt to return the function body."""
  54. # Real extraction would require a token parser and state machines.
  55. # We look for first bracket at the same level of indentation.
  56. regex_str = r'{(.*?)^[ ]{%d}}' % indentation
  57. function_regex = re.compile(regex_str, re.MULTILINE | re.DOTALL)
  58. match = function_regex.search(script)
  59. if match:
  60. return match.group(1)
  61. def _ContainsReturnValue(function_body):
  62. """Attempt to determine if the function body returns a value."""
  63. return_regex = re.compile(r'\breturn\b[^;]')
  64. # If this matches, we assume they're returning something.
  65. return bool(return_regex.search(function_body))
  66. def _InsertString(original_string, inserted_string, index):
  67. """Insert a string into another string at a given index."""
  68. return original_string[0:index] + inserted_string + original_string[index:]
  69. def _GenerateJsDoc(args, return_val=False):
  70. """Generate JSDoc for a function.
  71. Args:
  72. args: A list of names of the argument.
  73. return_val: Whether the function has a return value.
  74. Returns:
  75. The JSDoc as a string.
  76. """
  77. lines = []
  78. lines.append('/**')
  79. lines += [' * @param {} %s' % arg for arg in args]
  80. if return_val:
  81. lines.append(' * @return')
  82. lines.append(' */')
  83. return '\n'.join(lines) + '\n'
  84. def _IndentString(source_string, indentation):
  85. """Indent string some number of characters."""
  86. lines = [(indentation * ' ') + line
  87. for line in source_string.splitlines(True)]
  88. return ''.join(lines)
  89. def InsertJsDoc(script):
  90. """Attempt to insert JSDoc for the first seen function in the script.
  91. Args:
  92. script: The script, as a string.
  93. Returns:
  94. Returns the new string if function was found and JSDoc inserted. Otherwise
  95. returns None.
  96. """
  97. match = _MatchFirstFunction(script)
  98. if not match:
  99. return
  100. # Add argument flags.
  101. args_string = match.group('arguments')
  102. args = _ParseArgString(args_string)
  103. start_index = match.start(0)
  104. function_to_end = script[start_index:]
  105. lvalue_indentation = len(match.group('indentation'))
  106. return_val = False
  107. function_body = _ExtractFunctionBody(function_to_end, lvalue_indentation)
  108. if function_body:
  109. return_val = _ContainsReturnValue(function_body)
  110. jsdoc = _GenerateJsDoc(args, return_val)
  111. if lvalue_indentation:
  112. jsdoc = _IndentString(jsdoc, lvalue_indentation)
  113. return _InsertString(script, jsdoc, start_index)
  114. if __name__ == '__main__':
  115. stdin_script = sys.stdin.read()
  116. result = InsertJsDoc(stdin_script)
  117. if result:
  118. sys.stdout.write(result)
  119. else:
  120. sys.stdout.write(stdin_script)