cmake.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. #=============================================================================
  2. # CMake - Cross Platform Makefile Generator
  3. # Copyright 2000-2013 Kitware, Inc., Insight Software Consortium
  4. #
  5. # Distributed under the OSI-approved BSD License (the "License");
  6. # see accompanying file Copyright.txt for details.
  7. #
  8. # This software is distributed WITHOUT ANY WARRANTY; without even the
  9. # implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  10. # See the License for more information.
  11. #=============================================================================
  12. import os
  13. import re
  14. from docutils.parsers.rst import Directive, directives
  15. from docutils.transforms import Transform
  16. from docutils.utils.error_reporting import SafeString, ErrorString
  17. from docutils import io, nodes
  18. from sphinx.directives import ObjectDescription
  19. from sphinx.domains import Domain, ObjType
  20. from sphinx.roles import XRefRole
  21. from sphinx.util.nodes import make_refnode
  22. from sphinx import addnodes
  23. class CMakeModule(Directive):
  24. required_arguments = 1
  25. optional_arguments = 0
  26. final_argument_whitespace = True
  27. option_spec = {'encoding': directives.encoding}
  28. def __init__(self, *args, **keys):
  29. self.re_start = re.compile(r'^#\[(?P<eq>=*)\[\.rst:$')
  30. Directive.__init__(self, *args, **keys)
  31. def run(self):
  32. settings = self.state.document.settings
  33. if not settings.file_insertion_enabled:
  34. raise self.warning('"%s" directive disabled.' % self.name)
  35. env = self.state.document.settings.env
  36. rel_path, path = env.relfn2path(self.arguments[0])
  37. path = os.path.normpath(path)
  38. encoding = self.options.get('encoding', settings.input_encoding)
  39. e_handler = settings.input_encoding_error_handler
  40. try:
  41. settings.record_dependencies.add(path)
  42. f = io.FileInput(source_path=path, encoding=encoding,
  43. error_handler=e_handler)
  44. except UnicodeEncodeError, error:
  45. raise self.severe('Problems with "%s" directive path:\n'
  46. 'Cannot encode input file path "%s" '
  47. '(wrong locale?).' %
  48. (self.name, SafeString(path)))
  49. except IOError, error:
  50. raise self.severe('Problems with "%s" directive path:\n%s.' %
  51. (self.name, ErrorString(error)))
  52. raw_lines = f.read().splitlines()
  53. f.close()
  54. rst = None
  55. lines = []
  56. for line in raw_lines:
  57. if rst is not None and rst != '#':
  58. # Bracket mode: check for end bracket
  59. pos = line.find(rst)
  60. if pos >= 0:
  61. if line[0] == '#':
  62. line = ''
  63. else:
  64. line = line[0:pos]
  65. rst = None
  66. else:
  67. # Line mode: check for .rst start (bracket or line)
  68. m = self.re_start.match(line)
  69. if m:
  70. rst = ']%s]' % m.group('eq')
  71. line = ''
  72. elif line == '#.rst:':
  73. rst = '#'
  74. line = ''
  75. elif rst == '#':
  76. if line == '#' or line[:2] == '# ':
  77. line = line[2:]
  78. else:
  79. rst = None
  80. line = ''
  81. elif rst is None:
  82. line = ''
  83. lines.append(line)
  84. if rst is not None and rst != '#':
  85. raise self.warning('"%s" found unclosed bracket "#[%s[.rst:" in %s' %
  86. (self.name, rst[1:-1], path))
  87. self.state_machine.insert_input(lines, path)
  88. return []
  89. class _cmake_index_entry:
  90. def __init__(self, desc):
  91. self.desc = desc
  92. def __call__(self, title, targetid):
  93. return ('pair', u'%s ; %s' % (self.desc, title), targetid, 'main')
  94. _cmake_index_objs = {
  95. 'command': _cmake_index_entry('command'),
  96. 'generator': _cmake_index_entry('generator'),
  97. 'manual': _cmake_index_entry('manual'),
  98. 'module': _cmake_index_entry('module'),
  99. 'policy': _cmake_index_entry('policy'),
  100. 'prop_cache': _cmake_index_entry('cache property'),
  101. 'prop_dir': _cmake_index_entry('directory property'),
  102. 'prop_gbl': _cmake_index_entry('global property'),
  103. 'prop_sf': _cmake_index_entry('source file property'),
  104. 'prop_test': _cmake_index_entry('test property'),
  105. 'prop_tgt': _cmake_index_entry('target property'),
  106. 'variable': _cmake_index_entry('variable'),
  107. }
  108. def _cmake_object_inventory(env, document, line, objtype, targetid):
  109. inv = env.domaindata['cmake']['objects']
  110. if targetid in inv:
  111. document.reporter.warning(
  112. 'CMake object "%s" also described in "%s".' %
  113. (targetid, env.doc2path(inv[targetid][0])), line=line)
  114. inv[targetid] = (env.docname, objtype)
  115. class CMakeTransform(Transform):
  116. # Run this transform early since we insert nodes we want
  117. # treated as if they were written in the documents.
  118. default_priority = 210
  119. def __init__(self, document, startnode):
  120. Transform.__init__(self, document, startnode)
  121. self.titles = {}
  122. def parse_title(self, docname):
  123. """Parse a document title as the first line starting in [A-Za-z0-9<]
  124. or fall back to the document basename if no such line exists.
  125. The cmake --help-*-list commands also depend on this convention.
  126. Return the title or False if the document file does not exist.
  127. """
  128. env = self.document.settings.env
  129. title = self.titles.get(docname)
  130. if title is None:
  131. fname = os.path.join(env.srcdir, docname+'.rst')
  132. try:
  133. f = open(fname, 'r')
  134. except IOError:
  135. title = False
  136. else:
  137. for line in f:
  138. if len(line) > 0 and (line[0].isalnum() or line[0] == '<'):
  139. title = line.rstrip()
  140. break
  141. f.close()
  142. if title is None:
  143. title = os.path.basename(docname)
  144. self.titles[docname] = title
  145. return title
  146. def apply(self):
  147. env = self.document.settings.env
  148. # Treat some documents as cmake domain objects.
  149. objtype, sep, tail = env.docname.rpartition('/')
  150. make_index_entry = _cmake_index_objs.get(objtype)
  151. if make_index_entry:
  152. title = self.parse_title(env.docname)
  153. # Insert the object link target.
  154. targetid = '%s:%s' % (objtype, title)
  155. targetnode = nodes.target('', '', ids=[targetid])
  156. self.document.insert(0, targetnode)
  157. # Insert the object index entry.
  158. indexnode = addnodes.index()
  159. indexnode['entries'] = [make_index_entry(title, targetid)]
  160. self.document.insert(0, indexnode)
  161. # Add to cmake domain object inventory
  162. _cmake_object_inventory(env, self.document, 1, objtype, targetid)
  163. class CMakeObject(ObjectDescription):
  164. def handle_signature(self, sig, signode):
  165. # called from sphinx.directives.ObjectDescription.run()
  166. signode += addnodes.desc_name(sig, sig)
  167. return sig
  168. def add_target_and_index(self, name, sig, signode):
  169. targetid = '%s:%s' % (self.objtype, name)
  170. if targetid not in self.state.document.ids:
  171. signode['names'].append(targetid)
  172. signode['ids'].append(targetid)
  173. signode['first'] = (not self.names)
  174. self.state.document.note_explicit_target(signode)
  175. _cmake_object_inventory(self.env, self.state.document,
  176. self.lineno, self.objtype, targetid)
  177. make_index_entry = _cmake_index_objs.get(self.objtype)
  178. if make_index_entry:
  179. self.indexnode['entries'].append(make_index_entry(name, targetid))
  180. class CMakeXRefRole(XRefRole):
  181. # See sphinx.util.nodes.explicit_title_re; \x00 escapes '<'.
  182. _re = re.compile(r'^(.+?)(\s*)(?<!\x00)<(.*?)>$', re.DOTALL)
  183. _re_sub = re.compile(r'^([^()\s]+)\s*\(([^()]*)\)$', re.DOTALL)
  184. def __call__(self, typ, rawtext, text, *args, **keys):
  185. # Translate CMake command cross-references of the form:
  186. # `command_name(SUB_COMMAND)`
  187. # to have an explicit target:
  188. # `command_name(SUB_COMMAND) <command_name>`
  189. if typ == 'cmake:command':
  190. m = CMakeXRefRole._re_sub.match(text)
  191. if m:
  192. text = '%s <%s>' % (text, m.group(1))
  193. # CMake cross-reference targets frequently contain '<' so escape
  194. # any explicit `<target>` with '<' not preceded by whitespace.
  195. while True:
  196. m = CMakeXRefRole._re.match(text)
  197. if m and len(m.group(2)) == 0:
  198. text = '%s\x00<%s>' % (m.group(1), m.group(3))
  199. else:
  200. break
  201. return XRefRole.__call__(self, typ, rawtext, text, *args, **keys)
  202. class CMakeDomain(Domain):
  203. """CMake domain."""
  204. name = 'cmake'
  205. label = 'CMake'
  206. object_types = {
  207. 'command': ObjType('command', 'command'),
  208. 'generator': ObjType('generator', 'generator'),
  209. 'variable': ObjType('variable', 'variable'),
  210. 'module': ObjType('module', 'module'),
  211. 'policy': ObjType('policy', 'policy'),
  212. 'prop_cache': ObjType('prop_cache', 'prop_cache'),
  213. 'prop_dir': ObjType('prop_dir', 'prop_dir'),
  214. 'prop_gbl': ObjType('prop_gbl', 'prop_gbl'),
  215. 'prop_sf': ObjType('prop_sf', 'prop_sf'),
  216. 'prop_test': ObjType('prop_test', 'prop_test'),
  217. 'prop_tgt': ObjType('prop_tgt', 'prop_tgt'),
  218. 'manual': ObjType('manual', 'manual'),
  219. }
  220. directives = {
  221. 'command': CMakeObject,
  222. 'variable': CMakeObject,
  223. # Other object types cannot be created except by the CMakeTransform
  224. # 'generator': CMakeObject,
  225. # 'module': CMakeObject,
  226. # 'policy': CMakeObject,
  227. # 'prop_cache': CMakeObject,
  228. # 'prop_dir': CMakeObject,
  229. # 'prop_gbl': CMakeObject,
  230. # 'prop_sf': CMakeObject,
  231. # 'prop_test': CMakeObject,
  232. # 'prop_tgt': CMakeObject,
  233. # 'manual': CMakeObject,
  234. }
  235. roles = {
  236. 'command': CMakeXRefRole(fix_parens = True, lowercase = True),
  237. 'generator': CMakeXRefRole(),
  238. 'variable': CMakeXRefRole(),
  239. 'module': CMakeXRefRole(),
  240. 'policy': CMakeXRefRole(),
  241. 'prop_cache': CMakeXRefRole(),
  242. 'prop_dir': CMakeXRefRole(),
  243. 'prop_gbl': CMakeXRefRole(),
  244. 'prop_sf': CMakeXRefRole(),
  245. 'prop_test': CMakeXRefRole(),
  246. 'prop_tgt': CMakeXRefRole(),
  247. 'manual': CMakeXRefRole(),
  248. }
  249. initial_data = {
  250. 'objects': {}, # fullname -> docname, objtype
  251. }
  252. def clear_doc(self, docname):
  253. for fullname, (fn, _) in self.data['objects'].items():
  254. if fn == docname:
  255. del self.data['objects'][fullname]
  256. def resolve_xref(self, env, fromdocname, builder,
  257. typ, target, node, contnode):
  258. targetid = '%s:%s' % (typ, target)
  259. obj = self.data['objects'].get(targetid)
  260. if obj is None:
  261. # TODO: warn somehow?
  262. return None
  263. return make_refnode(builder, fromdocname, obj[0], targetid,
  264. contnode, target)
  265. def get_objects(self):
  266. for refname, (docname, type) in self.data['objects'].iteritems():
  267. yield (refname, refname, type, docname, refname, 1)
  268. def setup(app):
  269. app.add_directive('cmake-module', CMakeModule)
  270. app.add_transform(CMakeTransform)
  271. app.add_domain(CMakeDomain)