docstring.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. # -*- Mode: Python; py-indent-offset: 4 -*-
  2. # vim: tabstop=4 shiftwidth=4 expandtab
  3. #
  4. # Copyright (C) 2013 Simon Feltman <sfeltman@gnome.org>
  5. #
  6. # docstring.py: documentation string generator for gi.
  7. #
  8. # This library is free software; you can redistribute it and/or
  9. # modify it under the terms of the GNU Lesser General Public
  10. # License as published by the Free Software Foundation; either
  11. # version 2.1 of the License, or (at your option) any later version.
  12. #
  13. # This library is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  16. # Lesser General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU Lesser General Public
  19. # License along with this library; if not, write to the Free Software
  20. # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
  21. # USA
  22. from ._gi import \
  23. VFuncInfo, \
  24. FunctionInfo, \
  25. CallableInfo, \
  26. ObjectInfo, \
  27. StructInfo, \
  28. Direction, \
  29. TypeTag
  30. #: Module storage for currently registered doc string generator function.
  31. _generate_doc_string_func = None
  32. def set_doc_string_generator(func):
  33. """Set doc string generator function
  34. :param callable func:
  35. Callable which takes a GIInfoStruct and returns documentation for it.
  36. """
  37. global _generate_doc_string_func
  38. _generate_doc_string_func = func
  39. def get_doc_string_generator():
  40. """Returns the currently registered doc string generator."""
  41. return _generate_doc_string_func
  42. def generate_doc_string(info):
  43. """Generate a doc string given a GIInfoStruct.
  44. :param gi.types.BaseInfo info:
  45. GI info instance to generate documentation for.
  46. :returns:
  47. Generated documentation as a string.
  48. :rtype: str
  49. This passes the info struct to the currently registered doc string
  50. generator and returns the result.
  51. """
  52. return _generate_doc_string_func(info)
  53. _type_tag_to_py_type = {TypeTag.BOOLEAN: bool,
  54. TypeTag.INT8: int,
  55. TypeTag.UINT8: int,
  56. TypeTag.INT16: int,
  57. TypeTag.UINT16: int,
  58. TypeTag.INT32: int,
  59. TypeTag.UINT32: int,
  60. TypeTag.INT64: int,
  61. TypeTag.UINT64: int,
  62. TypeTag.FLOAT: float,
  63. TypeTag.DOUBLE: float,
  64. TypeTag.GLIST: list,
  65. TypeTag.GSLIST: list,
  66. TypeTag.ARRAY: list,
  67. TypeTag.GHASH: dict,
  68. TypeTag.UTF8: str,
  69. TypeTag.FILENAME: str,
  70. TypeTag.UNICHAR: str,
  71. TypeTag.INTERFACE: None,
  72. TypeTag.GTYPE: None,
  73. TypeTag.ERROR: None,
  74. TypeTag.VOID: None,
  75. }
  76. def _get_pytype_hint(gi_type):
  77. type_tag = gi_type.get_tag()
  78. py_type = _type_tag_to_py_type.get(type_tag, None)
  79. if py_type and hasattr(py_type, '__name__'):
  80. return py_type.__name__
  81. elif type_tag == TypeTag.INTERFACE:
  82. iface = gi_type.get_interface()
  83. info_name = iface.get_name()
  84. if not info_name:
  85. return gi_type.get_tag_as_string()
  86. return '%s.%s' % (iface.get_namespace(), info_name)
  87. return gi_type.get_tag_as_string()
  88. def _generate_callable_info_doc(info):
  89. in_args_strs = []
  90. if isinstance(info, VFuncInfo):
  91. in_args_strs = ['self']
  92. elif isinstance(info, FunctionInfo):
  93. if info.is_method():
  94. in_args_strs = ['self']
  95. args = info.get_arguments()
  96. hint_blacklist = ('void',)
  97. # Build lists of indices prior to adding the docs because it is possible
  98. # the index retrieved comes before input arguments being used.
  99. ignore_indices = set()
  100. user_data_indices = set()
  101. for arg in args:
  102. ignore_indices.add(arg.get_destroy())
  103. ignore_indices.add(arg.get_type().get_array_length())
  104. user_data_indices.add(arg.get_closure())
  105. # Build input argument strings
  106. for i, arg in enumerate(args):
  107. if arg.get_direction() == Direction.OUT:
  108. continue # skip exclusively output args
  109. if i in ignore_indices:
  110. continue
  111. argstr = arg.get_name()
  112. hint = _get_pytype_hint(arg.get_type())
  113. if hint not in hint_blacklist:
  114. argstr += ':' + hint
  115. if arg.may_be_null() or i in user_data_indices:
  116. # allow-none or user_data from a closure
  117. argstr += '=None'
  118. elif arg.is_optional():
  119. argstr += '=<optional>'
  120. in_args_strs.append(argstr)
  121. in_args_str = ', '.join(in_args_strs)
  122. # Build return + output argument strings
  123. out_args_strs = []
  124. return_hint = _get_pytype_hint(info.get_return_type())
  125. if not info.skip_return() and return_hint and return_hint not in hint_blacklist:
  126. argstr = return_hint
  127. if info.may_return_null():
  128. argstr += ' or None'
  129. out_args_strs.append(argstr)
  130. for i, arg in enumerate(args):
  131. if arg.get_direction() == Direction.IN:
  132. continue # skip exclusively input args
  133. if i in ignore_indices:
  134. continue
  135. argstr = arg.get_name()
  136. hint = _get_pytype_hint(arg.get_type())
  137. if hint not in hint_blacklist:
  138. argstr += ':' + hint
  139. out_args_strs.append(argstr)
  140. if out_args_strs:
  141. return '%s(%s) -> %s' % (info.__name__, in_args_str, ', '.join(out_args_strs))
  142. else:
  143. return '%s(%s)' % (info.__name__, in_args_str)
  144. def _generate_class_info_doc(info):
  145. header = '\n:Constructors:\n\n::\n\n' # start with \n to avoid auto indent of other lines
  146. doc = ''
  147. if isinstance(info, StructInfo):
  148. # Don't show default constructor for disguised (0 length) structs
  149. if info.get_size() > 0:
  150. doc += ' ' + info.get_name() + '()\n'
  151. else:
  152. doc += ' ' + info.get_name() + '(**properties)\n'
  153. for method_info in info.get_methods():
  154. if method_info.is_constructor():
  155. doc += ' ' + _generate_callable_info_doc(method_info) + '\n'
  156. if doc:
  157. return header + doc
  158. else:
  159. return ''
  160. def _generate_doc_dispatch(info):
  161. if isinstance(info, (ObjectInfo, StructInfo)):
  162. return _generate_class_info_doc(info)
  163. elif isinstance(info, CallableInfo):
  164. return _generate_callable_info_doc(info)
  165. return ''
  166. set_doc_string_generator(_generate_doc_dispatch)