blob: cae27b20a9705b834f2866b289f4e3588f8dce7c [file] [log] [blame]
Manuel Klimekde063382012-08-27 18:49:12 +00001#!/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
6import collections
7import re
8import urllib2
9
10MATCHERS_FILE = '../../include/clang/ASTMatchers/ASTMatchers.h'
11
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.
16TD_TEMPLATE="""
Manuel Klimek8bad9472012-09-07 13:10:32 +000017<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>
Manuel Klimekde063382012-08-27 18:49:12 +000018<tr><td colspan="4" class="doc" id="%(id)s"><pre>%(comment)s</pre></td></tr>
19"""
20
21# We categorize the matchers into these three categories in the reference:
22node_matchers = {}
23narrowing_matchers = {}
24traversal_matchers = {}
25
26# We output multiple rows per matcher if the matcher can be used on multiple
27# node types. Thus, we need a new id per row to control the documentation
28# pop-up. ids[name] keeps track of those ids.
29ids = collections.defaultdict(int)
30
31# Cache for doxygen urls we have already verified.
32doxygen_probes = {}
33
34def esc(text):
35 """Escape any html in the given text."""
36 text = re.sub(r'&', '&amp;', text)
37 text = re.sub(r'<', '&lt;', text)
38 text = re.sub(r'>', '&gt;', text)
39 def link_if_exists(m):
40 name = m.group(1)
Sylvestre Ledrubc5c3f52018-11-04 17:02:00 +000041 url = 'https://clang.llvm.org/doxygen/classclang_1_1%s.html' % name
Manuel Klimekde063382012-08-27 18:49:12 +000042 if url not in doxygen_probes:
43 try:
Serge Gueltonc0ebe772018-12-18 08:36:33 +000044 print('Probing %s...' % url)
Manuel Klimekde063382012-08-27 18:49:12 +000045 urllib2.urlopen(url)
46 doxygen_probes[url] = True
47 except:
48 doxygen_probes[url] = False
49 if doxygen_probes[url]:
Aaron Ballman672dde22016-01-22 23:15:00 +000050 return r'Matcher&lt;<a href="%s">%s</a>&gt;' % (url, name)
Manuel Klimekde063382012-08-27 18:49:12 +000051 else:
52 return m.group(0)
53 text = re.sub(
54 r'Matcher&lt;([^\*&]+)&gt;', link_if_exists, text)
55 return text
56
57def extract_result_types(comment):
58 """Extracts a list of result types from the given comment.
59
60 We allow annotations in the comment of the matcher to specify what
61 nodes a matcher can match on. Those comments have the form:
62 Usable as: Any Matcher | (Matcher<T1>[, Matcher<t2>[, ...]])
63
64 Returns ['*'] in case of 'Any Matcher', or ['T1', 'T2', ...].
65 Returns the empty list if no 'Usable as' specification could be
66 parsed.
67 """
68 result_types = []
69 m = re.search(r'Usable as: Any Matcher[\s\n]*$', comment, re.S)
70 if m:
71 return ['*']
72 while True:
73 m = re.match(r'^(.*)Matcher<([^>]+)>\s*,?[\s\n]*$', comment, re.S)
74 if not m:
75 if re.search(r'Usable as:\s*$', comment):
76 return result_types
77 else:
78 return None
79 result_types += [m.group(2)]
80 comment = m.group(1)
81
82def strip_doxygen(comment):
83 """Returns the given comment without \-escaped words."""
84 # If there is only a doxygen keyword in the line, delete the whole line.
85 comment = re.sub(r'^\\[^\s]+\n', r'', comment, flags=re.M)
Aaron Ballmanc35724c2016-01-21 15:18:25 +000086
87 # If there is a doxygen \see command, change the \see prefix into "See also:".
88 # FIXME: it would be better to turn this into a link to the target instead.
89 comment = re.sub(r'\\see', r'See also:', comment)
90
Manuel Klimekde063382012-08-27 18:49:12 +000091 # Delete the doxygen command and the following whitespace.
92 comment = re.sub(r'\\[^\s]+\s+', r'', comment)
93 return comment
94
95def unify_arguments(args):
96 """Gets rid of anything the user doesn't care about in the argument list."""
97 args = re.sub(r'internal::', r'', args)
Benjamin Kramerae7ff382018-01-17 16:50:14 +000098 args = re.sub(r'extern const\s+(.*)&', r'\1 ', args)
Manuel Klimekde063382012-08-27 18:49:12 +000099 args = re.sub(r'&', r' ', args)
100 args = re.sub(r'(^|\s)M\d?(\s)', r'\1Matcher<*>\2', args)
101 return args
102
103def add_matcher(result_type, name, args, comment, is_dyncast=False):
104 """Adds a matcher to one of our categories."""
105 if name == 'id':
106 # FIXME: Figure out whether we want to support the 'id' matcher.
107 return
108 matcher_id = '%s%d' % (name, ids[name])
109 ids[name] += 1
110 args = unify_arguments(args)
111 matcher_html = TD_TEMPLATE % {
112 'result': esc('Matcher<%s>' % result_type),
113 'name': name,
114 'args': esc(args),
115 'comment': esc(strip_doxygen(comment)),
116 'id': matcher_id,
117 }
118 if is_dyncast:
119 node_matchers[result_type + name] = matcher_html
120 # Use a heuristic to figure out whether a matcher is a narrowing or
121 # traversal matcher. By default, matchers that take other matchers as
122 # arguments (and are not node matchers) do traversal. We specifically
123 # exclude known narrowing matchers that also take other matchers as
124 # arguments.
125 elif ('Matcher<' not in args or
126 name in ['allOf', 'anyOf', 'anything', 'unless']):
Manuel Klimek03892692014-02-24 10:40:22 +0000127 narrowing_matchers[result_type + name + esc(args)] = matcher_html
Manuel Klimekde063382012-08-27 18:49:12 +0000128 else:
Manuel Klimek03892692014-02-24 10:40:22 +0000129 traversal_matchers[result_type + name + esc(args)] = matcher_html
Manuel Klimekde063382012-08-27 18:49:12 +0000130
131def act_on_decl(declaration, comment, allowed_types):
132 """Parse the matcher out of the given declaration and comment.
133
134 If 'allowed_types' is set, it contains a list of node types the matcher
135 can match on, as extracted from the static type asserts in the matcher
136 definition.
137 """
138 if declaration.strip():
139 # Node matchers are defined by writing:
140 # VariadicDynCastAllOfMatcher<ResultType, ArgumentType> name;
Manuel Klimekcdd5c232013-01-09 09:38:21 +0000141 m = re.match(r""".*Variadic(?:DynCast)?AllOfMatcher\s*<
142 \s*([^\s,]+)\s*(?:,
143 \s*([^\s>]+)\s*)?>
Manuel Klimekde063382012-08-27 18:49:12 +0000144 \s*([^\s;]+)\s*;\s*$""", declaration, flags=re.X)
145 if m:
146 result, inner, name = m.groups()
Manuel Klimekcdd5c232013-01-09 09:38:21 +0000147 if not inner:
148 inner = result
Manuel Klimekde063382012-08-27 18:49:12 +0000149 add_matcher(result, name, 'Matcher<%s>...' % inner,
150 comment, is_dyncast=True)
151 return
152
Benjamin Kramerae7ff382018-01-17 16:50:14 +0000153 # Special case of type matchers:
154 # AstTypeMatcher<ArgumentType> name
155 m = re.match(r""".*AstTypeMatcher\s*<
156 \s*([^\s>]+)\s*>
157 \s*([^\s;]+)\s*;\s*$""", declaration, flags=re.X)
Manuel Klimekcdd5c232013-01-09 09:38:21 +0000158 if m:
159 inner, name = m.groups()
160 add_matcher('Type', name, 'Matcher<%s>...' % inner,
161 comment, is_dyncast=True)
Manuel Klimekdba64f12013-07-25 06:05:50 +0000162 # FIXME: re-enable once we have implemented casting on the TypeLoc
163 # hierarchy.
164 # add_matcher('TypeLoc', '%sLoc' % name, 'Matcher<%sLoc>...' % inner,
165 # comment, is_dyncast=True)
Manuel Klimekcdd5c232013-01-09 09:38:21 +0000166 return
167
Benjamin Kramerae7ff382018-01-17 16:50:14 +0000168 # Parse the various matcher definition macros.
169 m = re.match(""".*AST_TYPE(LOC)?_TRAVERSE_MATCHER(?:_DECL)?\(
Manuel Klimekcdd5c232013-01-09 09:38:21 +0000170 \s*([^\s,]+\s*),
Samuel Benzaquen79656e12013-07-15 19:25:06 +0000171 \s*(?:[^\s,]+\s*),
Benjamin Kramer57dd9bd2015-03-07 20:38:15 +0000172 \s*AST_POLYMORPHIC_SUPPORTED_TYPES\(([^)]*)\)
Manuel Klimekcdd5c232013-01-09 09:38:21 +0000173 \)\s*;\s*$""", declaration, flags=re.X)
174 if m:
Manuel Klimek5d093282015-08-14 11:47:51 +0000175 loc, name, results = m.groups()[0:3]
Samuel Benzaquen79656e12013-07-15 19:25:06 +0000176 result_types = [r.strip() for r in results.split(',')]
177
178 comment_result_types = extract_result_types(comment)
179 if (comment_result_types and
180 sorted(result_types) != sorted(comment_result_types)):
181 raise Exception('Inconsistent documentation for: %s' % name)
Manuel Klimekcdd5c232013-01-09 09:38:21 +0000182 for result_type in result_types:
183 add_matcher(result_type, name, 'Matcher<Type>', comment)
Stephen Kelly7b79fb42018-10-09 08:24:18 +0000184 # if loc:
185 # add_matcher('%sLoc' % result_type, '%sLoc' % name, 'Matcher<TypeLoc>',
186 # comment)
Manuel Klimekcdd5c232013-01-09 09:38:21 +0000187 return
188
Samuel Benzaquenc6f2c9b2013-06-21 15:51:31 +0000189 m = re.match(r"""^\s*AST_POLYMORPHIC_MATCHER(_P)?(.?)(?:_OVERLOAD)?\(
190 \s*([^\s,]+)\s*,
Benjamin Kramer57dd9bd2015-03-07 20:38:15 +0000191 \s*AST_POLYMORPHIC_SUPPORTED_TYPES\(([^)]*)\)
Samuel Benzaquenc6f2c9b2013-06-21 15:51:31 +0000192 (?:,\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
199 if m:
Manuel Klimek5d093282015-08-14 11:47:51 +0000200 p, n, name, results = m.groups()[0:4]
201 args = m.groups()[4:]
Samuel Benzaquenc6f2c9b2013-06-21 15:51:31 +0000202 result_types = [r.strip() for r in results.split(',')]
203 if allowed_types and allowed_types != result_types:
204 raise Exception('Inconsistent documentation for: %s' % name)
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 for result_type in result_types:
210 add_matcher(result_type, name, args, comment)
211 return
212
Samuel Benzaquena0839352014-03-10 15:40:23 +0000213 m = re.match(r"""^\s*AST_MATCHER_FUNCTION(_P)?(.?)(?:_OVERLOAD)?\(
214 (?:\s*([^\s,]+)\s*,)?
215 \s*([^\s,]+)\s*
216 (?:,\s*([^\s,]+)\s*
217 ,\s*([^\s,]+)\s*)?
218 (?:,\s*([^\s,]+)\s*
219 ,\s*([^\s,]+)\s*)?
220 (?:,\s*\d+\s*)?
221 \)\s*{\s*$""", declaration, flags=re.X)
222 if m:
223 p, n, result, name = m.groups()[0:4]
224 args = m.groups()[4:]
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 add_matcher(result, name, args, comment)
230 return
231
Samuel Benzaquenc6f2c9b2013-06-21 15:51:31 +0000232 m = re.match(r"""^\s*AST_MATCHER(_P)?(.?)(?:_OVERLOAD)?\(
Manuel Klimekde063382012-08-27 18:49:12 +0000233 (?:\s*([^\s,]+)\s*,)?
234 \s*([^\s,]+)\s*
Samuel Benzaquena4076ea2016-05-04 20:45:00 +0000235 (?:,\s*([^,]+)\s*
Manuel Klimekde063382012-08-27 18:49:12 +0000236 ,\s*([^\s,]+)\s*)?
237 (?:,\s*([^\s,]+)\s*
238 ,\s*([^\s,]+)\s*)?
Manuel Klimek4feac282013-02-06 20:36:22 +0000239 (?:,\s*\d+\s*)?
Benjamin Kramer8bf200a2018-01-17 23:14:49 +0000240 \)\s*{""", declaration, flags=re.X)
Manuel Klimekde063382012-08-27 18:49:12 +0000241 if m:
Samuel Benzaquenc6f2c9b2013-06-21 15:51:31 +0000242 p, n, result, name = m.groups()[0:4]
243 args = m.groups()[4:]
Manuel Klimekde063382012-08-27 18:49:12 +0000244 if not result:
245 if not allowed_types:
246 raise Exception('Did not find allowed result types for: %s' % name)
247 result_types = allowed_types
248 else:
249 result_types = [result]
250 if n not in ['', '2']:
251 raise Exception('Cannot parse "%s"' % declaration)
252 args = ', '.join('%s %s' % (args[i], args[i+1])
253 for i in range(0, len(args), 2) if args[i])
254 for result_type in result_types:
255 add_matcher(result_type, name, args, comment)
256 return
257
Samuel Benzaquenbd7d8872013-08-16 16:19:42 +0000258 # Parse ArgumentAdapting matchers.
259 m = re.match(
Benjamin Kramerae7ff382018-01-17 16:50:14 +0000260 r"""^.*ArgumentAdaptingMatcherFunc<.*>\s*
261 ([a-zA-Z]*);$""",
Samuel Benzaquenbd7d8872013-08-16 16:19:42 +0000262 declaration, flags=re.X)
263 if m:
264 name = m.groups()[0]
265 add_matcher('*', name, 'Matcher<*>', comment)
266 return
267
Samuel Benzaquen922bef42016-02-22 21:13:02 +0000268 # Parse Variadic functions.
269 m = re.match(
Samuel Benzaquena4076ea2016-05-04 20:45:00 +0000270 r"""^.*internal::VariadicFunction\s*<\s*([^,]+),\s*([^,]+),\s*[^>]+>\s*
Benjamin Kramerae7ff382018-01-17 16:50:14 +0000271 ([a-zA-Z]*);$""",
Samuel Benzaquen922bef42016-02-22 21:13:02 +0000272 declaration, flags=re.X)
273 if m:
274 result, arg, name = m.groups()[:3]
275 add_matcher(result, name, '%s, ..., %s' % (arg, arg), comment)
276 return
277
Samuel Benzaquen85ec25d2013-08-27 15:11:16 +0000278 # Parse Variadic operator matchers.
279 m = re.match(
Benjamin Kramerae7ff382018-01-17 16:50:14 +0000280 r"""^.*VariadicOperatorMatcherFunc\s*<\s*([^,]+),\s*([^\s]+)\s*>\s*
281 ([a-zA-Z]*);$""",
Samuel Benzaquen85ec25d2013-08-27 15:11:16 +0000282 declaration, flags=re.X)
283 if m:
Manuel Klimek4f8f8902014-02-24 10:28:36 +0000284 min_args, max_args, name = m.groups()[:3]
285 if max_args == '1':
286 add_matcher('*', name, 'Matcher<*>', comment)
287 return
Benjamin Kramerae7ff382018-01-17 16:50:14 +0000288 elif max_args == 'std::numeric_limits<unsigned>::max()':
Manuel Klimek4f8f8902014-02-24 10:28:36 +0000289 add_matcher('*', name, 'Matcher<*>, ..., Matcher<*>', comment)
290 return
Samuel Benzaquen85ec25d2013-08-27 15:11:16 +0000291
Samuel Benzaquenbd7d8872013-08-16 16:19:42 +0000292
Manuel Klimekde063382012-08-27 18:49:12 +0000293 # Parse free standing matcher functions, like:
294 # Matcher<ResultType> Name(Matcher<ArgumentType> InnerMatcher) {
295 m = re.match(r"""^\s*(.*)\s+
296 ([^\s\(]+)\s*\(
297 (.*)
298 \)\s*{""", declaration, re.X)
299 if m:
300 result, name, args = m.groups()
301 args = ', '.join(p.strip() for p in args.split(','))
Manuel Klimekcdd5c232013-01-09 09:38:21 +0000302 m = re.match(r'.*\s+internal::(Bindable)?Matcher<([^>]+)>$', result)
Manuel Klimekde063382012-08-27 18:49:12 +0000303 if m:
Manuel Klimekcdd5c232013-01-09 09:38:21 +0000304 result_types = [m.group(2)]
Manuel Klimekde063382012-08-27 18:49:12 +0000305 else:
306 result_types = extract_result_types(comment)
307 if not result_types:
308 if not comment:
309 # Only overloads don't have their own doxygen comments; ignore those.
Serge Gueltonc0ebe772018-12-18 08:36:33 +0000310 print('Ignoring "%s"' % name)
Manuel Klimekde063382012-08-27 18:49:12 +0000311 else:
Serge Gueltonc0ebe772018-12-18 08:36:33 +0000312 print('Cannot determine result type for "%s"' % name)
Manuel Klimekde063382012-08-27 18:49:12 +0000313 else:
314 for result_type in result_types:
315 add_matcher(result_type, name, args, comment)
316 else:
Serge Gueltonc0ebe772018-12-18 08:36:33 +0000317 print('*** Unparsable: "' + declaration + '" ***')
Manuel Klimekde063382012-08-27 18:49:12 +0000318
319def sort_table(matcher_type, matcher_map):
320 """Returns the sorted html table for the given row map."""
321 table = ''
322 for key in sorted(matcher_map.keys()):
323 table += matcher_map[key] + '\n'
324 return ('<!-- START_%(type)s_MATCHERS -->\n' +
325 '%(table)s' +
326 '<!--END_%(type)s_MATCHERS -->') % {
327 'type': matcher_type,
328 'table': table,
329 }
330
331# Parse the ast matchers.
332# We alternate between two modes:
333# body = True: We parse the definition of a matcher. We need
334# to parse the full definition before adding a matcher, as the
335# definition might contain static asserts that specify the result
336# type.
337# body = False: We parse the comments and declaration of the matcher.
338comment = ''
339declaration = ''
340allowed_types = []
341body = False
342for line in open(MATCHERS_FILE).read().splitlines():
343 if body:
344 if line.strip() and line[0] == '}':
345 if declaration:
346 act_on_decl(declaration, comment, allowed_types)
347 comment = ''
348 declaration = ''
349 allowed_types = []
350 body = False
351 else:
352 m = re.search(r'is_base_of<([^,]+), NodeType>', line)
353 if m and m.group(1):
354 allowed_types += [m.group(1)]
355 continue
356 if line.strip() and line.lstrip()[0] == '/':
Aaron Ballman94f3e742018-12-11 19:30:49 +0000357 comment += re.sub(r'^/+\s?', '', line) + '\n'
Manuel Klimekde063382012-08-27 18:49:12 +0000358 else:
359 declaration += ' ' + line
360 if ((not line.strip()) or
361 line.rstrip()[-1] == ';' or
Samuel Benzaquen85ec25d2013-08-27 15:11:16 +0000362 (line.rstrip()[-1] == '{' and line.rstrip()[-3:] != '= {')):
Manuel Klimekde063382012-08-27 18:49:12 +0000363 if line.strip() and line.rstrip()[-1] == '{':
364 body = True
365 else:
366 act_on_decl(declaration, comment, allowed_types)
367 comment = ''
368 declaration = ''
369 allowed_types = []
370
371node_matcher_table = sort_table('DECL', node_matchers)
372narrowing_matcher_table = sort_table('NARROWING', narrowing_matchers)
373traversal_matcher_table = sort_table('TRAVERSAL', traversal_matchers)
374
375reference = open('../LibASTMatchersReference.html').read()
376reference = re.sub(r'<!-- START_DECL_MATCHERS.*END_DECL_MATCHERS -->',
Yury Gribov75118f52016-02-18 15:43:56 +0000377 node_matcher_table, reference, flags=re.S)
Manuel Klimekde063382012-08-27 18:49:12 +0000378reference = re.sub(r'<!-- START_NARROWING_MATCHERS.*END_NARROWING_MATCHERS -->',
Yury Gribov75118f52016-02-18 15:43:56 +0000379 narrowing_matcher_table, reference, flags=re.S)
Manuel Klimekde063382012-08-27 18:49:12 +0000380reference = re.sub(r'<!-- START_TRAVERSAL_MATCHERS.*END_TRAVERSAL_MATCHERS -->',
Yury Gribov75118f52016-02-18 15:43:56 +0000381 traversal_matcher_table, reference, flags=re.S)
Manuel Klimekde063382012-08-27 18:49:12 +0000382
Benjamin Kramer611d33a2015-11-20 07:46:19 +0000383with open('../LibASTMatchersReference.html', 'wb') as output:
Manuel Klimekde063382012-08-27 18:49:12 +0000384 output.write(reference)
385