dump_ast_matchers.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. #!/usr/bin/env python
  2. # A tool to parse ASTMatchers.h and update the documentation in
  3. # ../LibASTMatchersReference.html automatically. Run from the
  4. # directory in which this file is located to update the docs.
  5. import collections
  6. import re
  7. import urllib2
  8. MATCHERS_FILE = '../../include/clang/ASTMatchers/ASTMatchers.h'
  9. # Each matcher is documented in one row of the form:
  10. # result | name | argA
  11. # The subsequent row contains the documentation and is hidden by default,
  12. # becoming visible via javascript when the user clicks the matcher name.
  13. TD_TEMPLATE="""
  14. <tr><td>%(result)s</td><td class="name" onclick="toggle('%(id)s')"><a name="%(id)sAnchor">%(name)s</a></td><td>%(args)s</td></tr>
  15. <tr><td colspan="4" class="doc" id="%(id)s"><pre>%(comment)s</pre></td></tr>
  16. """
  17. # We categorize the matchers into these three categories in the reference:
  18. node_matchers = {}
  19. narrowing_matchers = {}
  20. traversal_matchers = {}
  21. # We output multiple rows per matcher if the matcher can be used on multiple
  22. # node types. Thus, we need a new id per row to control the documentation
  23. # pop-up. ids[name] keeps track of those ids.
  24. ids = collections.defaultdict(int)
  25. # Cache for doxygen urls we have already verified.
  26. doxygen_probes = {}
  27. def esc(text):
  28. """Escape any html in the given text."""
  29. text = re.sub(r'&', '&amp;', text)
  30. text = re.sub(r'<', '&lt;', text)
  31. text = re.sub(r'>', '&gt;', text)
  32. def link_if_exists(m):
  33. name = m.group(1)
  34. url = 'http://clang.llvm.org/doxygen/classclang_1_1%s.html' % name
  35. if url not in doxygen_probes:
  36. try:
  37. print 'Probing %s...' % url
  38. urllib2.urlopen(url)
  39. doxygen_probes[url] = True
  40. except:
  41. doxygen_probes[url] = False
  42. if doxygen_probes[url]:
  43. return r'Matcher&lt;<a href="%s">%s</a>&gt;' % (url, name)
  44. else:
  45. return m.group(0)
  46. text = re.sub(
  47. r'Matcher&lt;([^\*&]+)&gt;', link_if_exists, text)
  48. return text
  49. def extract_result_types(comment):
  50. """Extracts a list of result types from the given comment.
  51. We allow annotations in the comment of the matcher to specify what
  52. nodes a matcher can match on. Those comments have the form:
  53. Usable as: Any Matcher | (Matcher<T1>[, Matcher<t2>[, ...]])
  54. Returns ['*'] in case of 'Any Matcher', or ['T1', 'T2', ...].
  55. Returns the empty list if no 'Usable as' specification could be
  56. parsed.
  57. """
  58. result_types = []
  59. m = re.search(r'Usable as: Any Matcher[\s\n]*$', comment, re.S)
  60. if m:
  61. return ['*']
  62. while True:
  63. m = re.match(r'^(.*)Matcher<([^>]+)>\s*,?[\s\n]*$', comment, re.S)
  64. if not m:
  65. if re.search(r'Usable as:\s*$', comment):
  66. return result_types
  67. else:
  68. return None
  69. result_types += [m.group(2)]
  70. comment = m.group(1)
  71. def strip_doxygen(comment):
  72. """Returns the given comment without \-escaped words."""
  73. # If there is only a doxygen keyword in the line, delete the whole line.
  74. comment = re.sub(r'^\\[^\s]+\n', r'', comment, flags=re.M)
  75. # If there is a doxygen \see command, change the \see prefix into "See also:".
  76. # FIXME: it would be better to turn this into a link to the target instead.
  77. comment = re.sub(r'\\see', r'See also:', comment)
  78. # Delete the doxygen command and the following whitespace.
  79. comment = re.sub(r'\\[^\s]+\s+', r'', comment)
  80. return comment
  81. def unify_arguments(args):
  82. """Gets rid of anything the user doesn't care about in the argument list."""
  83. args = re.sub(r'internal::', r'', args)
  84. args = re.sub(r'const\s+(.*)&', r'\1 ', args)
  85. args = re.sub(r'&', r' ', args)
  86. args = re.sub(r'(^|\s)M\d?(\s)', r'\1Matcher<*>\2', args)
  87. return args
  88. def add_matcher(result_type, name, args, comment, is_dyncast=False):
  89. """Adds a matcher to one of our categories."""
  90. if name == 'id':
  91. # FIXME: Figure out whether we want to support the 'id' matcher.
  92. return
  93. matcher_id = '%s%d' % (name, ids[name])
  94. ids[name] += 1
  95. args = unify_arguments(args)
  96. matcher_html = TD_TEMPLATE % {
  97. 'result': esc('Matcher<%s>' % result_type),
  98. 'name': name,
  99. 'args': esc(args),
  100. 'comment': esc(strip_doxygen(comment)),
  101. 'id': matcher_id,
  102. }
  103. if is_dyncast:
  104. node_matchers[result_type + name] = matcher_html
  105. # Use a heuristic to figure out whether a matcher is a narrowing or
  106. # traversal matcher. By default, matchers that take other matchers as
  107. # arguments (and are not node matchers) do traversal. We specifically
  108. # exclude known narrowing matchers that also take other matchers as
  109. # arguments.
  110. elif ('Matcher<' not in args or
  111. name in ['allOf', 'anyOf', 'anything', 'unless']):
  112. narrowing_matchers[result_type + name + esc(args)] = matcher_html
  113. else:
  114. traversal_matchers[result_type + name + esc(args)] = matcher_html
  115. def act_on_decl(declaration, comment, allowed_types):
  116. """Parse the matcher out of the given declaration and comment.
  117. If 'allowed_types' is set, it contains a list of node types the matcher
  118. can match on, as extracted from the static type asserts in the matcher
  119. definition.
  120. """
  121. if declaration.strip():
  122. # Node matchers are defined by writing:
  123. # VariadicDynCastAllOfMatcher<ResultType, ArgumentType> name;
  124. m = re.match(r""".*Variadic(?:DynCast)?AllOfMatcher\s*<
  125. \s*([^\s,]+)\s*(?:,
  126. \s*([^\s>]+)\s*)?>
  127. \s*([^\s;]+)\s*;\s*$""", declaration, flags=re.X)
  128. if m:
  129. result, inner, name = m.groups()
  130. if not inner:
  131. inner = result
  132. add_matcher(result, name, 'Matcher<%s>...' % inner,
  133. comment, is_dyncast=True)
  134. return
  135. # Parse the various matcher definition macros.
  136. m = re.match(""".*AST_TYPE_MATCHER\(
  137. \s*([^\s,]+\s*),
  138. \s*([^\s,]+\s*)
  139. \)\s*;\s*$""", declaration, flags=re.X)
  140. if m:
  141. inner, name = m.groups()
  142. add_matcher('Type', name, 'Matcher<%s>...' % inner,
  143. comment, is_dyncast=True)
  144. # FIXME: re-enable once we have implemented casting on the TypeLoc
  145. # hierarchy.
  146. # add_matcher('TypeLoc', '%sLoc' % name, 'Matcher<%sLoc>...' % inner,
  147. # comment, is_dyncast=True)
  148. return
  149. m = re.match(""".*AST_TYPE(LOC)?_TRAVERSE_MATCHER\(
  150. \s*([^\s,]+\s*),
  151. \s*(?:[^\s,]+\s*),
  152. \s*AST_POLYMORPHIC_SUPPORTED_TYPES\(([^)]*)\)
  153. \)\s*;\s*$""", declaration, flags=re.X)
  154. if m:
  155. loc, name, results = m.groups()[0:3]
  156. result_types = [r.strip() for r in results.split(',')]
  157. comment_result_types = extract_result_types(comment)
  158. if (comment_result_types and
  159. sorted(result_types) != sorted(comment_result_types)):
  160. raise Exception('Inconsistent documentation for: %s' % name)
  161. for result_type in result_types:
  162. add_matcher(result_type, name, 'Matcher<Type>', comment)
  163. if loc:
  164. add_matcher('%sLoc' % result_type, '%sLoc' % name, 'Matcher<TypeLoc>',
  165. comment)
  166. return
  167. m = re.match(r"""^\s*AST_POLYMORPHIC_MATCHER(_P)?(.?)(?:_OVERLOAD)?\(
  168. \s*([^\s,]+)\s*,
  169. \s*AST_POLYMORPHIC_SUPPORTED_TYPES\(([^)]*)\)
  170. (?:,\s*([^\s,]+)\s*
  171. ,\s*([^\s,]+)\s*)?
  172. (?:,\s*([^\s,]+)\s*
  173. ,\s*([^\s,]+)\s*)?
  174. (?:,\s*\d+\s*)?
  175. \)\s*{\s*$""", declaration, flags=re.X)
  176. if m:
  177. p, n, name, results = m.groups()[0:4]
  178. args = m.groups()[4:]
  179. result_types = [r.strip() for r in results.split(',')]
  180. if allowed_types and allowed_types != result_types:
  181. raise Exception('Inconsistent documentation for: %s' % name)
  182. if n not in ['', '2']:
  183. raise Exception('Cannot parse "%s"' % declaration)
  184. args = ', '.join('%s %s' % (args[i], args[i+1])
  185. for i in range(0, len(args), 2) if args[i])
  186. for result_type in result_types:
  187. add_matcher(result_type, name, args, comment)
  188. return
  189. m = re.match(r"""^\s*AST_MATCHER_FUNCTION(_P)?(.?)(?:_OVERLOAD)?\(
  190. (?:\s*([^\s,]+)\s*,)?
  191. \s*([^\s,]+)\s*
  192. (?:,\s*([^\s,]+)\s*
  193. ,\s*([^\s,]+)\s*)?
  194. (?:,\s*([^\s,]+)\s*
  195. ,\s*([^\s,]+)\s*)?
  196. (?:,\s*\d+\s*)?
  197. \)\s*{\s*$""", declaration, flags=re.X)
  198. if m:
  199. p, n, result, name = m.groups()[0:4]
  200. args = m.groups()[4:]
  201. if n not in ['', '2']:
  202. raise Exception('Cannot parse "%s"' % declaration)
  203. args = ', '.join('%s %s' % (args[i], args[i+1])
  204. for i in range(0, len(args), 2) if args[i])
  205. add_matcher(result, name, args, comment)
  206. return
  207. m = re.match(r"""^\s*AST_MATCHER(_P)?(.?)(?:_OVERLOAD)?\(
  208. (?:\s*([^\s,]+)\s*,)?
  209. \s*([^\s,]+)\s*
  210. (?:,\s*([^,]+)\s*
  211. ,\s*([^\s,]+)\s*)?
  212. (?:,\s*([^\s,]+)\s*
  213. ,\s*([^\s,]+)\s*)?
  214. (?:,\s*\d+\s*)?
  215. \)\s*{\s*$""", declaration, flags=re.X)
  216. if m:
  217. p, n, result, name = m.groups()[0:4]
  218. args = m.groups()[4:]
  219. if not result:
  220. if not allowed_types:
  221. raise Exception('Did not find allowed result types for: %s' % name)
  222. result_types = allowed_types
  223. else:
  224. result_types = [result]
  225. if n not in ['', '2']:
  226. raise Exception('Cannot parse "%s"' % declaration)
  227. args = ', '.join('%s %s' % (args[i], args[i+1])
  228. for i in range(0, len(args), 2) if args[i])
  229. for result_type in result_types:
  230. add_matcher(result_type, name, args, comment)
  231. return
  232. # Parse ArgumentAdapting matchers.
  233. m = re.match(
  234. r"""^.*ArgumentAdaptingMatcherFunc<.*>\s*(?:LLVM_ATTRIBUTE_UNUSED\s*)
  235. ([a-zA-Z]*)\s*=\s*{};$""",
  236. declaration, flags=re.X)
  237. if m:
  238. name = m.groups()[0]
  239. add_matcher('*', name, 'Matcher<*>', comment)
  240. return
  241. # Parse Variadic functions.
  242. m = re.match(
  243. r"""^.*internal::VariadicFunction\s*<\s*([^,]+),\s*([^,]+),\s*[^>]+>\s*
  244. ([a-zA-Z]*)\s*=\s*{.*};$""",
  245. declaration, flags=re.X)
  246. if m:
  247. result, arg, name = m.groups()[:3]
  248. add_matcher(result, name, '%s, ..., %s' % (arg, arg), comment)
  249. return
  250. # Parse Variadic operator matchers.
  251. m = re.match(
  252. r"""^.*VariadicOperatorMatcherFunc\s*<\s*([^,]+),\s*([^\s>]+)\s*>\s*
  253. ([a-zA-Z]*)\s*=\s*{.*};$""",
  254. declaration, flags=re.X)
  255. if m:
  256. min_args, max_args, name = m.groups()[:3]
  257. if max_args == '1':
  258. add_matcher('*', name, 'Matcher<*>', comment)
  259. return
  260. elif max_args == 'UINT_MAX':
  261. add_matcher('*', name, 'Matcher<*>, ..., Matcher<*>', comment)
  262. return
  263. # Parse free standing matcher functions, like:
  264. # Matcher<ResultType> Name(Matcher<ArgumentType> InnerMatcher) {
  265. m = re.match(r"""^\s*(.*)\s+
  266. ([^\s\(]+)\s*\(
  267. (.*)
  268. \)\s*{""", declaration, re.X)
  269. if m:
  270. result, name, args = m.groups()
  271. args = ', '.join(p.strip() for p in args.split(','))
  272. m = re.match(r'.*\s+internal::(Bindable)?Matcher<([^>]+)>$', result)
  273. if m:
  274. result_types = [m.group(2)]
  275. else:
  276. result_types = extract_result_types(comment)
  277. if not result_types:
  278. if not comment:
  279. # Only overloads don't have their own doxygen comments; ignore those.
  280. print 'Ignoring "%s"' % name
  281. else:
  282. print 'Cannot determine result type for "%s"' % name
  283. else:
  284. for result_type in result_types:
  285. add_matcher(result_type, name, args, comment)
  286. else:
  287. print '*** Unparsable: "' + declaration + '" ***'
  288. def sort_table(matcher_type, matcher_map):
  289. """Returns the sorted html table for the given row map."""
  290. table = ''
  291. for key in sorted(matcher_map.keys()):
  292. table += matcher_map[key] + '\n'
  293. return ('<!-- START_%(type)s_MATCHERS -->\n' +
  294. '%(table)s' +
  295. '<!--END_%(type)s_MATCHERS -->') % {
  296. 'type': matcher_type,
  297. 'table': table,
  298. }
  299. # Parse the ast matchers.
  300. # We alternate between two modes:
  301. # body = True: We parse the definition of a matcher. We need
  302. # to parse the full definition before adding a matcher, as the
  303. # definition might contain static asserts that specify the result
  304. # type.
  305. # body = False: We parse the comments and declaration of the matcher.
  306. comment = ''
  307. declaration = ''
  308. allowed_types = []
  309. body = False
  310. for line in open(MATCHERS_FILE).read().splitlines():
  311. if body:
  312. if line.strip() and line[0] == '}':
  313. if declaration:
  314. act_on_decl(declaration, comment, allowed_types)
  315. comment = ''
  316. declaration = ''
  317. allowed_types = []
  318. body = False
  319. else:
  320. m = re.search(r'is_base_of<([^,]+), NodeType>', line)
  321. if m and m.group(1):
  322. allowed_types += [m.group(1)]
  323. continue
  324. if line.strip() and line.lstrip()[0] == '/':
  325. comment += re.sub(r'/+\s?', '', line) + '\n'
  326. else:
  327. declaration += ' ' + line
  328. if ((not line.strip()) or
  329. line.rstrip()[-1] == ';' or
  330. (line.rstrip()[-1] == '{' and line.rstrip()[-3:] != '= {')):
  331. if line.strip() and line.rstrip()[-1] == '{':
  332. body = True
  333. else:
  334. act_on_decl(declaration, comment, allowed_types)
  335. comment = ''
  336. declaration = ''
  337. allowed_types = []
  338. node_matcher_table = sort_table('DECL', node_matchers)
  339. narrowing_matcher_table = sort_table('NARROWING', narrowing_matchers)
  340. traversal_matcher_table = sort_table('TRAVERSAL', traversal_matchers)
  341. reference = open('../LibASTMatchersReference.html').read()
  342. reference = re.sub(r'<!-- START_DECL_MATCHERS.*END_DECL_MATCHERS -->',
  343. node_matcher_table, reference, flags=re.S)
  344. reference = re.sub(r'<!-- START_NARROWING_MATCHERS.*END_NARROWING_MATCHERS -->',
  345. narrowing_matcher_table, reference, flags=re.S)
  346. reference = re.sub(r'<!-- START_TRAVERSAL_MATCHERS.*END_TRAVERSAL_MATCHERS -->',
  347. traversal_matcher_table, reference, flags=re.S)
  348. with open('../LibASTMatchersReference.html', 'wb') as output:
  349. output.write(reference)