cmake.py 12 KB

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