xref: /openbsd-src/gnu/llvm/clang/docs/tools/dump_ast_matchers.py (revision 12c855180aad702bbcca06e0398d774beeafb155)
1*12c85518Srobert#!/usr/bin/env python3
2e5dd7070Spatrick# A tool to parse ASTMatchers.h and update the documentation in
3e5dd7070Spatrick# ../LibASTMatchersReference.html automatically. Run from the
4e5dd7070Spatrick# directory in which this file is located to update the docs.
5e5dd7070Spatrick
6e5dd7070Spatrickimport collections
7e5dd7070Spatrickimport re
8e5dd7070Spatricktry:
9e5dd7070Spatrick    from urllib.request import urlopen
10e5dd7070Spatrickexcept ImportError:
11e5dd7070Spatrick    from urllib2 import urlopen
12e5dd7070Spatrick
13*12c85518SrobertCLASS_INDEX_PAGE_URL = 'https://clang.llvm.org/doxygen/classes.html'
14*12c85518Sroberttry:
15*12c85518Srobert  CLASS_INDEX_PAGE = urlopen(CLASS_INDEX_PAGE_URL).read().decode('utf-8')
16*12c85518Srobertexcept Exception as e:
17*12c85518Srobert  raise Exception('Unable to get %s: %s' % (CLASS_INDEX_PAGE_URL, e))
18*12c85518Srobert
19e5dd7070SpatrickMATCHERS_FILE = '../../include/clang/ASTMatchers/ASTMatchers.h'
20e5dd7070Spatrick
21e5dd7070Spatrick# Each matcher is documented in one row of the form:
22e5dd7070Spatrick#   result | name | argA
23e5dd7070Spatrick# The subsequent row contains the documentation and is hidden by default,
24e5dd7070Spatrick# becoming visible via javascript when the user clicks the matcher name.
25e5dd7070SpatrickTD_TEMPLATE="""
26e5dd7070Spatrick<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>
27e5dd7070Spatrick<tr><td colspan="4" class="doc" id="%(id)s"><pre>%(comment)s</pre></td></tr>
28e5dd7070Spatrick"""
29e5dd7070Spatrick
30e5dd7070Spatrick# We categorize the matchers into these three categories in the reference:
31e5dd7070Spatricknode_matchers = {}
32e5dd7070Spatricknarrowing_matchers = {}
33e5dd7070Spatricktraversal_matchers = {}
34e5dd7070Spatrick
35e5dd7070Spatrick# We output multiple rows per matcher if the matcher can be used on multiple
36e5dd7070Spatrick# node types. Thus, we need a new id per row to control the documentation
37e5dd7070Spatrick# pop-up. ids[name] keeps track of those ids.
38e5dd7070Spatrickids = collections.defaultdict(int)
39e5dd7070Spatrick
40e5dd7070Spatrick# Cache for doxygen urls we have already verified.
41e5dd7070Spatrickdoxygen_probes = {}
42e5dd7070Spatrick
43e5dd7070Spatrickdef esc(text):
44e5dd7070Spatrick  """Escape any html in the given text."""
45e5dd7070Spatrick  text = re.sub(r'&', '&amp;', text)
46e5dd7070Spatrick  text = re.sub(r'<', '&lt;', text)
47e5dd7070Spatrick  text = re.sub(r'>', '&gt;', text)
48e5dd7070Spatrick  def link_if_exists(m):
49*12c85518Srobert    """Wrap a likely AST node name in a link to its clang docs.
50*12c85518Srobert
51*12c85518Srobert       We want to do this only if the page exists, in which case it will be
52*12c85518Srobert       referenced from the class index page.
53*12c85518Srobert    """
54e5dd7070Spatrick    name = m.group(1)
55e5dd7070Spatrick    url = 'https://clang.llvm.org/doxygen/classclang_1_1%s.html' % name
56e5dd7070Spatrick    if url not in doxygen_probes:
57*12c85518Srobert      search_str = 'href="classclang_1_1%s.html"' % name
58*12c85518Srobert      doxygen_probes[url] = search_str in CLASS_INDEX_PAGE
59*12c85518Srobert      if not doxygen_probes[url]:
60*12c85518Srobert        print('Did not find %s in class index page' % name)
61e5dd7070Spatrick    if doxygen_probes[url]:
62e5dd7070Spatrick      return r'Matcher&lt;<a href="%s">%s</a>&gt;' % (url, name)
63e5dd7070Spatrick    else:
64e5dd7070Spatrick      return m.group(0)
65e5dd7070Spatrick  text = re.sub(
66e5dd7070Spatrick    r'Matcher&lt;([^\*&]+)&gt;', link_if_exists, text)
67e5dd7070Spatrick  return text
68e5dd7070Spatrick
69e5dd7070Spatrickdef extract_result_types(comment):
70e5dd7070Spatrick  """Extracts a list of result types from the given comment.
71e5dd7070Spatrick
72e5dd7070Spatrick     We allow annotations in the comment of the matcher to specify what
73e5dd7070Spatrick     nodes a matcher can match on. Those comments have the form:
74e5dd7070Spatrick       Usable as: Any Matcher | (Matcher<T1>[, Matcher<t2>[, ...]])
75e5dd7070Spatrick
76e5dd7070Spatrick     Returns ['*'] in case of 'Any Matcher', or ['T1', 'T2', ...].
77e5dd7070Spatrick     Returns the empty list if no 'Usable as' specification could be
78e5dd7070Spatrick     parsed.
79e5dd7070Spatrick  """
80e5dd7070Spatrick  result_types = []
81e5dd7070Spatrick  m = re.search(r'Usable as: Any Matcher[\s\n]*$', comment, re.S)
82e5dd7070Spatrick  if m:
83e5dd7070Spatrick    return ['*']
84e5dd7070Spatrick  while True:
85e5dd7070Spatrick    m = re.match(r'^(.*)Matcher<([^>]+)>\s*,?[\s\n]*$', comment, re.S)
86e5dd7070Spatrick    if not m:
87e5dd7070Spatrick      if re.search(r'Usable as:\s*$', comment):
88e5dd7070Spatrick        return result_types
89e5dd7070Spatrick      else:
90e5dd7070Spatrick        return None
91e5dd7070Spatrick    result_types += [m.group(2)]
92e5dd7070Spatrick    comment = m.group(1)
93e5dd7070Spatrick
94e5dd7070Spatrickdef strip_doxygen(comment):
95e5dd7070Spatrick  """Returns the given comment without \-escaped words."""
96e5dd7070Spatrick  # If there is only a doxygen keyword in the line, delete the whole line.
97e5dd7070Spatrick  comment = re.sub(r'^\\[^\s]+\n', r'', comment, flags=re.M)
98e5dd7070Spatrick
99e5dd7070Spatrick  # If there is a doxygen \see command, change the \see prefix into "See also:".
100e5dd7070Spatrick  # FIXME: it would be better to turn this into a link to the target instead.
101e5dd7070Spatrick  comment = re.sub(r'\\see', r'See also:', comment)
102e5dd7070Spatrick
103e5dd7070Spatrick  # Delete the doxygen command and the following whitespace.
104e5dd7070Spatrick  comment = re.sub(r'\\[^\s]+\s+', r'', comment)
105e5dd7070Spatrick  return comment
106e5dd7070Spatrick
107e5dd7070Spatrickdef unify_arguments(args):
108e5dd7070Spatrick  """Gets rid of anything the user doesn't care about in the argument list."""
109e5dd7070Spatrick  args = re.sub(r'internal::', r'', args)
110e5dd7070Spatrick  args = re.sub(r'extern const\s+(.*)&', r'\1 ', args)
111e5dd7070Spatrick  args = re.sub(r'&', r' ', args)
112e5dd7070Spatrick  args = re.sub(r'(^|\s)M\d?(\s)', r'\1Matcher<*>\2', args)
113ec727ea7Spatrick  args = re.sub(r'BindableMatcher', r'Matcher', args)
114ec727ea7Spatrick  args = re.sub(r'const Matcher', r'Matcher', args)
115e5dd7070Spatrick  return args
116e5dd7070Spatrick
117ec727ea7Spatrickdef unify_type(result_type):
118ec727ea7Spatrick  """Gets rid of anything the user doesn't care about in the type name."""
119ec727ea7Spatrick  result_type = re.sub(r'^internal::(Bindable)?Matcher<([a-zA-Z_][a-zA-Z0-9_]*)>$', r'\2', result_type)
120ec727ea7Spatrick  return result_type
121ec727ea7Spatrick
122e5dd7070Spatrickdef add_matcher(result_type, name, args, comment, is_dyncast=False):
123e5dd7070Spatrick  """Adds a matcher to one of our categories."""
124e5dd7070Spatrick  if name == 'id':
125e5dd7070Spatrick     # FIXME: Figure out whether we want to support the 'id' matcher.
126e5dd7070Spatrick     return
127e5dd7070Spatrick  matcher_id = '%s%d' % (name, ids[name])
128e5dd7070Spatrick  ids[name] += 1
129e5dd7070Spatrick  args = unify_arguments(args)
130ec727ea7Spatrick  result_type = unify_type(result_type)
131a9ac8606Spatrick
132a9ac8606Spatrick  docs_result_type = esc('Matcher<%s>' % result_type);
133a9ac8606Spatrick
134a9ac8606Spatrick  if name == 'mapAnyOf':
135a9ac8606Spatrick    args = "nodeMatcherFunction..."
136a9ac8606Spatrick    docs_result_type = "<em>unspecified</em>"
137a9ac8606Spatrick
138e5dd7070Spatrick  matcher_html = TD_TEMPLATE % {
139a9ac8606Spatrick    'result': docs_result_type,
140e5dd7070Spatrick    'name': name,
141e5dd7070Spatrick    'args': esc(args),
142e5dd7070Spatrick    'comment': esc(strip_doxygen(comment)),
143e5dd7070Spatrick    'id': matcher_id,
144e5dd7070Spatrick  }
145e5dd7070Spatrick  if is_dyncast:
146ec727ea7Spatrick    dict = node_matchers
147ec727ea7Spatrick    lookup = result_type + name
148e5dd7070Spatrick  # Use a heuristic to figure out whether a matcher is a narrowing or
149e5dd7070Spatrick  # traversal matcher. By default, matchers that take other matchers as
150e5dd7070Spatrick  # arguments (and are not node matchers) do traversal. We specifically
151e5dd7070Spatrick  # exclude known narrowing matchers that also take other matchers as
152e5dd7070Spatrick  # arguments.
153e5dd7070Spatrick  elif ('Matcher<' not in args or
154a9ac8606Spatrick        name in ['allOf', 'anyOf', 'anything', 'unless', 'mapAnyOf']):
155ec727ea7Spatrick    dict = narrowing_matchers
156ec727ea7Spatrick    lookup = result_type + name + esc(args)
157e5dd7070Spatrick  else:
158ec727ea7Spatrick    dict = traversal_matchers
159ec727ea7Spatrick    lookup = result_type + name + esc(args)
160ec727ea7Spatrick
161ec727ea7Spatrick  if dict.get(lookup) is None or len(dict.get(lookup)) < len(matcher_html):
162ec727ea7Spatrick    dict[lookup] = matcher_html
163e5dd7070Spatrick
164e5dd7070Spatrickdef act_on_decl(declaration, comment, allowed_types):
165e5dd7070Spatrick  """Parse the matcher out of the given declaration and comment.
166e5dd7070Spatrick
167e5dd7070Spatrick     If 'allowed_types' is set, it contains a list of node types the matcher
168e5dd7070Spatrick     can match on, as extracted from the static type asserts in the matcher
169e5dd7070Spatrick     definition.
170e5dd7070Spatrick  """
171e5dd7070Spatrick  if declaration.strip():
172ec727ea7Spatrick
173ec727ea7Spatrick    if re.match(r'^\s?(#|namespace|using)', declaration): return
174ec727ea7Spatrick
175e5dd7070Spatrick    # Node matchers are defined by writing:
176e5dd7070Spatrick    #   VariadicDynCastAllOfMatcher<ResultType, ArgumentType> name;
177e5dd7070Spatrick    m = re.match(r""".*Variadic(?:DynCast)?AllOfMatcher\s*<
178e5dd7070Spatrick                       \s*([^\s,]+)\s*(?:,
179e5dd7070Spatrick                       \s*([^\s>]+)\s*)?>
180e5dd7070Spatrick                       \s*([^\s;]+)\s*;\s*$""", declaration, flags=re.X)
181e5dd7070Spatrick    if m:
182e5dd7070Spatrick      result, inner, name = m.groups()
183e5dd7070Spatrick      if not inner:
184e5dd7070Spatrick        inner = result
185e5dd7070Spatrick      add_matcher(result, name, 'Matcher<%s>...' % inner,
186e5dd7070Spatrick                  comment, is_dyncast=True)
187e5dd7070Spatrick      return
188e5dd7070Spatrick
189e5dd7070Spatrick    # Special case of type matchers:
190e5dd7070Spatrick    #   AstTypeMatcher<ArgumentType> name
191e5dd7070Spatrick    m = re.match(r""".*AstTypeMatcher\s*<
192e5dd7070Spatrick                       \s*([^\s>]+)\s*>
193e5dd7070Spatrick                       \s*([^\s;]+)\s*;\s*$""", declaration, flags=re.X)
194e5dd7070Spatrick    if m:
195e5dd7070Spatrick      inner, name = m.groups()
196e5dd7070Spatrick      add_matcher('Type', name, 'Matcher<%s>...' % inner,
197e5dd7070Spatrick                  comment, is_dyncast=True)
198e5dd7070Spatrick      # FIXME: re-enable once we have implemented casting on the TypeLoc
199e5dd7070Spatrick      # hierarchy.
200e5dd7070Spatrick      # add_matcher('TypeLoc', '%sLoc' % name, 'Matcher<%sLoc>...' % inner,
201e5dd7070Spatrick      #             comment, is_dyncast=True)
202e5dd7070Spatrick      return
203e5dd7070Spatrick
204e5dd7070Spatrick    # Parse the various matcher definition macros.
205e5dd7070Spatrick    m = re.match(""".*AST_TYPE(LOC)?_TRAVERSE_MATCHER(?:_DECL)?\(
206e5dd7070Spatrick                       \s*([^\s,]+\s*),
207e5dd7070Spatrick                       \s*(?:[^\s,]+\s*),
208e5dd7070Spatrick                       \s*AST_POLYMORPHIC_SUPPORTED_TYPES\(([^)]*)\)
209e5dd7070Spatrick                     \)\s*;\s*$""", declaration, flags=re.X)
210e5dd7070Spatrick    if m:
211e5dd7070Spatrick      loc, name, results = m.groups()[0:3]
212e5dd7070Spatrick      result_types = [r.strip() for r in results.split(',')]
213e5dd7070Spatrick
214e5dd7070Spatrick      comment_result_types = extract_result_types(comment)
215e5dd7070Spatrick      if (comment_result_types and
216e5dd7070Spatrick          sorted(result_types) != sorted(comment_result_types)):
217e5dd7070Spatrick        raise Exception('Inconsistent documentation for: %s' % name)
218e5dd7070Spatrick      for result_type in result_types:
219e5dd7070Spatrick        add_matcher(result_type, name, 'Matcher<Type>', comment)
220e5dd7070Spatrick        # if loc:
221e5dd7070Spatrick        #   add_matcher('%sLoc' % result_type, '%sLoc' % name, 'Matcher<TypeLoc>',
222e5dd7070Spatrick        #               comment)
223e5dd7070Spatrick      return
224e5dd7070Spatrick
225e5dd7070Spatrick    m = re.match(r"""^\s*AST_POLYMORPHIC_MATCHER(_P)?(.?)(?:_OVERLOAD)?\(
226e5dd7070Spatrick                          \s*([^\s,]+)\s*,
227e5dd7070Spatrick                          \s*AST_POLYMORPHIC_SUPPORTED_TYPES\(([^)]*)\)
228e5dd7070Spatrick                       (?:,\s*([^\s,]+)\s*
229e5dd7070Spatrick                          ,\s*([^\s,]+)\s*)?
230e5dd7070Spatrick                       (?:,\s*([^\s,]+)\s*
231e5dd7070Spatrick                          ,\s*([^\s,]+)\s*)?
232e5dd7070Spatrick                       (?:,\s*\d+\s*)?
233e5dd7070Spatrick                      \)\s*{\s*$""", declaration, flags=re.X)
234e5dd7070Spatrick
235e5dd7070Spatrick    if m:
236e5dd7070Spatrick      p, n, name, results = m.groups()[0:4]
237e5dd7070Spatrick      args = m.groups()[4:]
238e5dd7070Spatrick      result_types = [r.strip() for r in results.split(',')]
239e5dd7070Spatrick      if allowed_types and allowed_types != result_types:
240e5dd7070Spatrick        raise Exception('Inconsistent documentation for: %s' % name)
241e5dd7070Spatrick      if n not in ['', '2']:
242e5dd7070Spatrick        raise Exception('Cannot parse "%s"' % declaration)
243e5dd7070Spatrick      args = ', '.join('%s %s' % (args[i], args[i+1])
244e5dd7070Spatrick                       for i in range(0, len(args), 2) if args[i])
245e5dd7070Spatrick      for result_type in result_types:
246e5dd7070Spatrick        add_matcher(result_type, name, args, comment)
247e5dd7070Spatrick      return
248e5dd7070Spatrick
249ec727ea7Spatrick    m = re.match(r"""^\s*AST_POLYMORPHIC_MATCHER_REGEX(?:_OVERLOAD)?\(
250ec727ea7Spatrick                          \s*([^\s,]+)\s*,
251ec727ea7Spatrick                          \s*AST_POLYMORPHIC_SUPPORTED_TYPES\(([^)]*)\),
252ec727ea7Spatrick                          \s*([^\s,]+)\s*
253ec727ea7Spatrick                       (?:,\s*\d+\s*)?
254ec727ea7Spatrick                      \)\s*{\s*$""", declaration, flags=re.X)
255ec727ea7Spatrick
256ec727ea7Spatrick    if m:
257ec727ea7Spatrick      name, results, arg_name = m.groups()[0:3]
258ec727ea7Spatrick      result_types = [r.strip() for r in results.split(',')]
259ec727ea7Spatrick      if allowed_types and allowed_types != result_types:
260ec727ea7Spatrick        raise Exception('Inconsistent documentation for: %s' % name)
261ec727ea7Spatrick      arg = "StringRef %s, Regex::RegexFlags Flags = NoFlags" % arg_name
262ec727ea7Spatrick      comment += """
263ec727ea7SpatrickIf the matcher is used in clang-query, RegexFlags parameter
264ec727ea7Spatrickshould be passed as a quoted string. e.g: "NoFlags".
265ec727ea7SpatrickFlags can be combined with '|' example \"IgnoreCase | BasicRegex\"
266ec727ea7Spatrick"""
267ec727ea7Spatrick      for result_type in result_types:
268ec727ea7Spatrick        add_matcher(result_type, name, arg, comment)
269ec727ea7Spatrick      return
270ec727ea7Spatrick
271e5dd7070Spatrick    m = re.match(r"""^\s*AST_MATCHER_FUNCTION(_P)?(.?)(?:_OVERLOAD)?\(
272e5dd7070Spatrick                       (?:\s*([^\s,]+)\s*,)?
273e5dd7070Spatrick                          \s*([^\s,]+)\s*
274e5dd7070Spatrick                       (?:,\s*([^\s,]+)\s*
275e5dd7070Spatrick                          ,\s*([^\s,]+)\s*)?
276e5dd7070Spatrick                       (?:,\s*([^\s,]+)\s*
277e5dd7070Spatrick                          ,\s*([^\s,]+)\s*)?
278e5dd7070Spatrick                       (?:,\s*\d+\s*)?
279e5dd7070Spatrick                      \)\s*{\s*$""", declaration, flags=re.X)
280e5dd7070Spatrick    if m:
281e5dd7070Spatrick      p, n, result, name = m.groups()[0:4]
282e5dd7070Spatrick      args = m.groups()[4:]
283e5dd7070Spatrick      if n not in ['', '2']:
284e5dd7070Spatrick        raise Exception('Cannot parse "%s"' % declaration)
285e5dd7070Spatrick      args = ', '.join('%s %s' % (args[i], args[i+1])
286e5dd7070Spatrick                       for i in range(0, len(args), 2) if args[i])
287e5dd7070Spatrick      add_matcher(result, name, args, comment)
288e5dd7070Spatrick      return
289e5dd7070Spatrick
290e5dd7070Spatrick    m = re.match(r"""^\s*AST_MATCHER(_P)?(.?)(?:_OVERLOAD)?\(
291e5dd7070Spatrick                       (?:\s*([^\s,]+)\s*,)?
292e5dd7070Spatrick                          \s*([^\s,]+)\s*
293e5dd7070Spatrick                       (?:,\s*([^,]+)\s*
294e5dd7070Spatrick                          ,\s*([^\s,]+)\s*)?
295e5dd7070Spatrick                       (?:,\s*([^\s,]+)\s*
296e5dd7070Spatrick                          ,\s*([^\s,]+)\s*)?
297e5dd7070Spatrick                       (?:,\s*\d+\s*)?
298e5dd7070Spatrick                      \)\s*{""", declaration, flags=re.X)
299e5dd7070Spatrick    if m:
300e5dd7070Spatrick      p, n, result, name = m.groups()[0:4]
301e5dd7070Spatrick      args = m.groups()[4:]
302e5dd7070Spatrick      if not result:
303e5dd7070Spatrick        if not allowed_types:
304e5dd7070Spatrick          raise Exception('Did not find allowed result types for: %s' % name)
305e5dd7070Spatrick        result_types = allowed_types
306e5dd7070Spatrick      else:
307e5dd7070Spatrick        result_types = [result]
308e5dd7070Spatrick      if n not in ['', '2']:
309e5dd7070Spatrick        raise Exception('Cannot parse "%s"' % declaration)
310e5dd7070Spatrick      args = ', '.join('%s %s' % (args[i], args[i+1])
311e5dd7070Spatrick                       for i in range(0, len(args), 2) if args[i])
312e5dd7070Spatrick      for result_type in result_types:
313e5dd7070Spatrick        add_matcher(result_type, name, args, comment)
314e5dd7070Spatrick      return
315e5dd7070Spatrick
316ec727ea7Spatrick    m = re.match(r"""^\s*AST_MATCHER_REGEX(?:_OVERLOAD)?\(
317ec727ea7Spatrick                       \s*([^\s,]+)\s*,
318ec727ea7Spatrick                       \s*([^\s,]+)\s*,
319ec727ea7Spatrick                       \s*([^\s,]+)\s*
320ec727ea7Spatrick                       (?:,\s*\d+\s*)?
321ec727ea7Spatrick                      \)\s*{""", declaration, flags=re.X)
322ec727ea7Spatrick    if m:
323ec727ea7Spatrick      result, name, arg_name = m.groups()[0:3]
324ec727ea7Spatrick      if not result:
325ec727ea7Spatrick        if not allowed_types:
326ec727ea7Spatrick          raise Exception('Did not find allowed result types for: %s' % name)
327ec727ea7Spatrick        result_types = allowed_types
328ec727ea7Spatrick      else:
329ec727ea7Spatrick        result_types = [result]
330ec727ea7Spatrick      arg = "StringRef %s, Regex::RegexFlags Flags = NoFlags" % arg_name
331ec727ea7Spatrick      comment += """
332ec727ea7SpatrickIf the matcher is used in clang-query, RegexFlags parameter
333ec727ea7Spatrickshould be passed as a quoted string. e.g: "NoFlags".
334ec727ea7SpatrickFlags can be combined with '|' example \"IgnoreCase | BasicRegex\"
335ec727ea7Spatrick"""
336ec727ea7Spatrick
337ec727ea7Spatrick      for result_type in result_types:
338ec727ea7Spatrick        add_matcher(result_type, name, arg, comment)
339ec727ea7Spatrick      return
340ec727ea7Spatrick
341e5dd7070Spatrick    # Parse ArgumentAdapting matchers.
342e5dd7070Spatrick    m = re.match(
343e5dd7070Spatrick        r"""^.*ArgumentAdaptingMatcherFunc<.*>\s*
344e5dd7070Spatrick              ([a-zA-Z]*);$""",
345e5dd7070Spatrick        declaration, flags=re.X)
346e5dd7070Spatrick    if m:
347e5dd7070Spatrick      name = m.groups()[0]
348e5dd7070Spatrick      add_matcher('*', name, 'Matcher<*>', comment)
349e5dd7070Spatrick      return
350e5dd7070Spatrick
351e5dd7070Spatrick    # Parse Variadic functions.
352e5dd7070Spatrick    m = re.match(
353e5dd7070Spatrick        r"""^.*internal::VariadicFunction\s*<\s*([^,]+),\s*([^,]+),\s*[^>]+>\s*
354e5dd7070Spatrick              ([a-zA-Z]*);$""",
355e5dd7070Spatrick        declaration, flags=re.X)
356e5dd7070Spatrick    if m:
357e5dd7070Spatrick      result, arg, name = m.groups()[:3]
358e5dd7070Spatrick      add_matcher(result, name, '%s, ..., %s' % (arg, arg), comment)
359e5dd7070Spatrick      return
360e5dd7070Spatrick
361ec727ea7Spatrick    m = re.match(
362ec727ea7Spatrick        r"""^.*internal::VariadicFunction\s*<\s*
363a9ac8606Spatrick              internal::PolymorphicMatcher<[\S\s]+
364a9ac8606Spatrick              AST_POLYMORPHIC_SUPPORTED_TYPES\(([^)]*)\),\s*(.*);$""",
365ec727ea7Spatrick        declaration, flags=re.X)
366ec727ea7Spatrick
367ec727ea7Spatrick    if m:
368a9ac8606Spatrick      results, trailing = m.groups()
369a9ac8606Spatrick      trailing, name = trailing.rsplit(">", 1)
370a9ac8606Spatrick      name = name.strip()
371a9ac8606Spatrick      trailing, _ = trailing.rsplit(",", 1)
372a9ac8606Spatrick      _, arg = trailing.rsplit(",", 1)
373a9ac8606Spatrick      arg = arg.strip()
374ec727ea7Spatrick
375ec727ea7Spatrick      result_types = [r.strip() for r in results.split(',')]
376ec727ea7Spatrick      for result_type in result_types:
377ec727ea7Spatrick        add_matcher(result_type, name, '%s, ..., %s' % (arg, arg), comment)
378ec727ea7Spatrick      return
379ec727ea7Spatrick
380ec727ea7Spatrick
381e5dd7070Spatrick    # Parse Variadic operator matchers.
382e5dd7070Spatrick    m = re.match(
383e5dd7070Spatrick        r"""^.*VariadicOperatorMatcherFunc\s*<\s*([^,]+),\s*([^\s]+)\s*>\s*
384e5dd7070Spatrick              ([a-zA-Z]*);$""",
385e5dd7070Spatrick        declaration, flags=re.X)
386e5dd7070Spatrick    if m:
387e5dd7070Spatrick      min_args, max_args, name = m.groups()[:3]
388e5dd7070Spatrick      if max_args == '1':
389e5dd7070Spatrick        add_matcher('*', name, 'Matcher<*>', comment)
390e5dd7070Spatrick        return
391e5dd7070Spatrick      elif max_args == 'std::numeric_limits<unsigned>::max()':
392e5dd7070Spatrick        add_matcher('*', name, 'Matcher<*>, ..., Matcher<*>', comment)
393e5dd7070Spatrick        return
394e5dd7070Spatrick
395a9ac8606Spatrick    m = re.match(
396a9ac8606Spatrick        r"""^.*MapAnyOfMatcher<.*>\s*
397a9ac8606Spatrick              ([a-zA-Z]*);$""",
398a9ac8606Spatrick        declaration, flags=re.X)
399a9ac8606Spatrick    if m:
400a9ac8606Spatrick      name = m.groups()[0]
401a9ac8606Spatrick      add_matcher('*', name, 'Matcher<*>...Matcher<*>', comment)
402a9ac8606Spatrick      return
403e5dd7070Spatrick
404e5dd7070Spatrick    # Parse free standing matcher functions, like:
405e5dd7070Spatrick    #   Matcher<ResultType> Name(Matcher<ArgumentType> InnerMatcher) {
406ec727ea7Spatrick    m = re.match(r"""^\s*(?:template\s+<\s*(?:class|typename)\s+(.+)\s*>\s+)?
407ec727ea7Spatrick                     (.*)\s+
408e5dd7070Spatrick                     ([^\s\(]+)\s*\(
409e5dd7070Spatrick                     (.*)
410e5dd7070Spatrick                     \)\s*{""", declaration, re.X)
411e5dd7070Spatrick    if m:
412ec727ea7Spatrick      template_name, result, name, args = m.groups()
413ec727ea7Spatrick      if template_name:
414ec727ea7Spatrick        matcherTemplateArgs = re.findall(r'Matcher<\s*(%s)\s*>' % template_name, args)
415ec727ea7Spatrick        templateArgs = re.findall(r'(?:^|[\s,<])(%s)(?:$|[\s,>])' % template_name, args)
416ec727ea7Spatrick        if len(matcherTemplateArgs) < len(templateArgs):
417ec727ea7Spatrick          # The template name is used naked, so don't replace with `*`` later on
418ec727ea7Spatrick          template_name = None
419ec727ea7Spatrick        else :
420ec727ea7Spatrick          args = re.sub(r'(^|[\s,<])%s($|[\s,>])' % template_name, r'\1*\2', args)
421e5dd7070Spatrick      args = ', '.join(p.strip() for p in args.split(','))
422ec727ea7Spatrick      m = re.match(r'(?:^|.*\s+)internal::(?:Bindable)?Matcher<([^>]+)>$', result)
423e5dd7070Spatrick      if m:
424ec727ea7Spatrick        result_types = [m.group(1)]
425*12c85518Srobert        if template_name and len(result_types) == 1 and result_types[0] == template_name:
426ec727ea7Spatrick          result_types = ['*']
427e5dd7070Spatrick      else:
428e5dd7070Spatrick        result_types = extract_result_types(comment)
429e5dd7070Spatrick      if not result_types:
430e5dd7070Spatrick        if not comment:
431e5dd7070Spatrick          # Only overloads don't have their own doxygen comments; ignore those.
432e5dd7070Spatrick          print('Ignoring "%s"' % name)
433e5dd7070Spatrick        else:
434e5dd7070Spatrick          print('Cannot determine result type for "%s"' % name)
435e5dd7070Spatrick      else:
436e5dd7070Spatrick        for result_type in result_types:
437e5dd7070Spatrick          add_matcher(result_type, name, args, comment)
438e5dd7070Spatrick    else:
439e5dd7070Spatrick      print('*** Unparsable: "' + declaration + '" ***')
440e5dd7070Spatrick
441e5dd7070Spatrickdef sort_table(matcher_type, matcher_map):
442e5dd7070Spatrick  """Returns the sorted html table for the given row map."""
443e5dd7070Spatrick  table = ''
444e5dd7070Spatrick  for key in sorted(matcher_map.keys()):
445e5dd7070Spatrick    table += matcher_map[key] + '\n'
446e5dd7070Spatrick  return ('<!-- START_%(type)s_MATCHERS -->\n' +
447e5dd7070Spatrick          '%(table)s' +
448e5dd7070Spatrick          '<!--END_%(type)s_MATCHERS -->') % {
449e5dd7070Spatrick    'type': matcher_type,
450e5dd7070Spatrick    'table': table,
451e5dd7070Spatrick  }
452e5dd7070Spatrick
453e5dd7070Spatrick# Parse the ast matchers.
454e5dd7070Spatrick# We alternate between two modes:
455e5dd7070Spatrick# body = True: We parse the definition of a matcher. We need
456e5dd7070Spatrick#   to parse the full definition before adding a matcher, as the
457e5dd7070Spatrick#   definition might contain static asserts that specify the result
458e5dd7070Spatrick#   type.
459e5dd7070Spatrick# body = False: We parse the comments and declaration of the matcher.
460e5dd7070Spatrickcomment = ''
461e5dd7070Spatrickdeclaration = ''
462e5dd7070Spatrickallowed_types = []
463e5dd7070Spatrickbody = False
464e5dd7070Spatrickfor line in open(MATCHERS_FILE).read().splitlines():
465e5dd7070Spatrick  if body:
466e5dd7070Spatrick    if line.strip() and line[0] == '}':
467e5dd7070Spatrick      if declaration:
468e5dd7070Spatrick        act_on_decl(declaration, comment, allowed_types)
469e5dd7070Spatrick        comment = ''
470e5dd7070Spatrick        declaration = ''
471e5dd7070Spatrick        allowed_types = []
472e5dd7070Spatrick      body = False
473e5dd7070Spatrick    else:
474e5dd7070Spatrick      m = re.search(r'is_base_of<([^,]+), NodeType>', line)
475e5dd7070Spatrick      if m and m.group(1):
476e5dd7070Spatrick        allowed_types += [m.group(1)]
477e5dd7070Spatrick    continue
478e5dd7070Spatrick  if line.strip() and line.lstrip()[0] == '/':
479e5dd7070Spatrick    comment += re.sub(r'^/+\s?', '', line) + '\n'
480e5dd7070Spatrick  else:
481e5dd7070Spatrick    declaration += ' ' + line
482e5dd7070Spatrick    if ((not line.strip()) or
483e5dd7070Spatrick        line.rstrip()[-1] == ';' or
484e5dd7070Spatrick        (line.rstrip()[-1] == '{' and line.rstrip()[-3:] != '= {')):
485e5dd7070Spatrick      if line.strip() and line.rstrip()[-1] == '{':
486e5dd7070Spatrick        body = True
487e5dd7070Spatrick      else:
488e5dd7070Spatrick        act_on_decl(declaration, comment, allowed_types)
489e5dd7070Spatrick        comment = ''
490e5dd7070Spatrick        declaration = ''
491e5dd7070Spatrick        allowed_types = []
492e5dd7070Spatrick
493e5dd7070Spatricknode_matcher_table = sort_table('DECL', node_matchers)
494e5dd7070Spatricknarrowing_matcher_table = sort_table('NARROWING', narrowing_matchers)
495e5dd7070Spatricktraversal_matcher_table = sort_table('TRAVERSAL', traversal_matchers)
496e5dd7070Spatrick
497e5dd7070Spatrickreference = open('../LibASTMatchersReference.html').read()
498e5dd7070Spatrickreference = re.sub(r'<!-- START_DECL_MATCHERS.*END_DECL_MATCHERS -->',
499e5dd7070Spatrick                   node_matcher_table, reference, flags=re.S)
500e5dd7070Spatrickreference = re.sub(r'<!-- START_NARROWING_MATCHERS.*END_NARROWING_MATCHERS -->',
501e5dd7070Spatrick                   narrowing_matcher_table, reference, flags=re.S)
502e5dd7070Spatrickreference = re.sub(r'<!-- START_TRAVERSAL_MATCHERS.*END_TRAVERSAL_MATCHERS -->',
503e5dd7070Spatrick                   traversal_matcher_table, reference, flags=re.S)
504e5dd7070Spatrick
505*12c85518Srobertwith open('../LibASTMatchersReference.html', 'w', newline='\n') as output:
506e5dd7070Spatrick  output.write(reference)
507e5dd7070Spatrick
508