dump_ast_matchers.py 14 KB

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