blob: 267cdb054c9f83daa63764c91316deb345f5f095 [file] [log] [blame]
Manuel Klimek95a58d22012-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 Klimek67619ff2012-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 Klimek95a58d22012-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)
41 url = 'http://clang.llvm.org/doxygen/classclang_1_1%s.html' % name
42 if url not in doxygen_probes:
43 try:
44 print 'Probing %s...' % url
45 urllib2.urlopen(url)
46 doxygen_probes[url] = True
47 except:
48 doxygen_probes[url] = False
49 if doxygen_probes[url]:
50 return r'Matcher&lt<a href="%s">%s</a>&gt;' % (url, name)
51 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)
86 # Delete the doxygen command and the following whitespace.
87 comment = re.sub(r'\\[^\s]+\s+', r'', comment)
88 return comment
89
90def unify_arguments(args):
91 """Gets rid of anything the user doesn't care about in the argument list."""
92 args = re.sub(r'internal::', r'', args)
93 args = re.sub(r'const\s+', r'', args)
94 args = re.sub(r'&', r' ', args)
95 args = re.sub(r'(^|\s)M\d?(\s)', r'\1Matcher<*>\2', args)
96 return args
97
98def add_matcher(result_type, name, args, comment, is_dyncast=False):
99 """Adds a matcher to one of our categories."""
100 if name == 'id':
101 # FIXME: Figure out whether we want to support the 'id' matcher.
102 return
103 matcher_id = '%s%d' % (name, ids[name])
104 ids[name] += 1
105 args = unify_arguments(args)
106 matcher_html = TD_TEMPLATE % {
107 'result': esc('Matcher<%s>' % result_type),
108 'name': name,
109 'args': esc(args),
110 'comment': esc(strip_doxygen(comment)),
111 'id': matcher_id,
112 }
113 if is_dyncast:
114 node_matchers[result_type + name] = matcher_html
115 # Use a heuristic to figure out whether a matcher is a narrowing or
116 # traversal matcher. By default, matchers that take other matchers as
117 # arguments (and are not node matchers) do traversal. We specifically
118 # exclude known narrowing matchers that also take other matchers as
119 # arguments.
120 elif ('Matcher<' not in args or
121 name in ['allOf', 'anyOf', 'anything', 'unless']):
122 narrowing_matchers[result_type + name] = matcher_html
123 else:
124 traversal_matchers[result_type + name] = matcher_html
125
126def act_on_decl(declaration, comment, allowed_types):
127 """Parse the matcher out of the given declaration and comment.
128
129 If 'allowed_types' is set, it contains a list of node types the matcher
130 can match on, as extracted from the static type asserts in the matcher
131 definition.
132 """
133 if declaration.strip():
134 # Node matchers are defined by writing:
135 # VariadicDynCastAllOfMatcher<ResultType, ArgumentType> name;
Manuel Klimek41df16e2013-01-09 09:38:21 +0000136 m = re.match(r""".*Variadic(?:DynCast)?AllOfMatcher\s*<
137 \s*([^\s,]+)\s*(?:,
138 \s*([^\s>]+)\s*)?>
Manuel Klimek95a58d22012-08-27 18:49:12 +0000139 \s*([^\s;]+)\s*;\s*$""", declaration, flags=re.X)
140 if m:
141 result, inner, name = m.groups()
Manuel Klimek41df16e2013-01-09 09:38:21 +0000142 if not inner:
143 inner = result
Manuel Klimek95a58d22012-08-27 18:49:12 +0000144 add_matcher(result, name, 'Matcher<%s>...' % inner,
145 comment, is_dyncast=True)
146 return
147
148 # Parse the various matcher definition macros.
Manuel Klimek41df16e2013-01-09 09:38:21 +0000149 m = re.match(""".*AST_TYPE_MATCHER\(
150 \s*([^\s,]+\s*),
151 \s*([^\s,]+\s*)
152 \)\s*;\s*$""", declaration, flags=re.X)
153 if m:
154 inner, name = m.groups()
155 add_matcher('Type', name, 'Matcher<%s>...' % inner,
156 comment, is_dyncast=True)
157 add_matcher('TypeLoc', '%sLoc' % name, 'Matcher<%sLoc>...' % inner,
158 comment, is_dyncast=True)
159 return
160
161 m = re.match(""".*AST_TYPE(LOC)?_TRAVERSE_MATCHER\(
162 \s*([^\s,]+\s*),
163 \s*(?:[^\s,]+\s*)
164 \)\s*;\s*$""", declaration, flags=re.X)
165 if m:
166 loc = m.group(1)
167 name = m.group(2)
168 result_types = extract_result_types(comment)
169 if not result_types:
170 raise Exception('Did not find allowed result types for: %s' % name)
171 for result_type in result_types:
172 add_matcher(result_type, name, 'Matcher<Type>', comment)
173 if loc:
174 add_matcher('%sLoc' % result_type, '%sLoc' % name, 'Matcher<TypeLoc>',
175 comment)
176 return
177
Samuel Benzaquenef7eb022013-06-21 15:51:31 +0000178 m = re.match(r"""^\s*AST_POLYMORPHIC_MATCHER(_P)?(.?)(?:_OVERLOAD)?\(
179 \s*([^\s,]+)\s*,
180 \s*AST_POLYMORPHIC_SUPPORTED_TYPES_([^(]*)\(([^)]*)\)
181 (?:,\s*([^\s,]+)\s*
182 ,\s*([^\s,]+)\s*)?
183 (?:,\s*([^\s,]+)\s*
184 ,\s*([^\s,]+)\s*)?
185 (?:,\s*\d+\s*)?
186 \)\s*{\s*$""", declaration, flags=re.X)
187
188 if m:
189 p, n, name, n_results, results = m.groups()[0:5]
190 args = m.groups()[5:]
191 result_types = [r.strip() for r in results.split(',')]
192 if allowed_types and allowed_types != result_types:
193 raise Exception('Inconsistent documentation for: %s' % name)
194 if n not in ['', '2']:
195 raise Exception('Cannot parse "%s"' % declaration)
196 args = ', '.join('%s %s' % (args[i], args[i+1])
197 for i in range(0, len(args), 2) if args[i])
198 for result_type in result_types:
199 add_matcher(result_type, name, args, comment)
200 return
201
202 m = re.match(r"""^\s*AST_MATCHER(_P)?(.?)(?:_OVERLOAD)?\(
Manuel Klimek95a58d22012-08-27 18:49:12 +0000203 (?:\s*([^\s,]+)\s*,)?
204 \s*([^\s,]+)\s*
205 (?:,\s*([^\s,]+)\s*
206 ,\s*([^\s,]+)\s*)?
207 (?:,\s*([^\s,]+)\s*
208 ,\s*([^\s,]+)\s*)?
Manuel Klimek415514d2013-02-06 20:36:22 +0000209 (?:,\s*\d+\s*)?
Manuel Klimek95a58d22012-08-27 18:49:12 +0000210 \)\s*{\s*$""", declaration, flags=re.X)
211 if m:
Samuel Benzaquenef7eb022013-06-21 15:51:31 +0000212 p, n, result, name = m.groups()[0:4]
213 args = m.groups()[4:]
Manuel Klimek95a58d22012-08-27 18:49:12 +0000214 if not result:
215 if not allowed_types:
216 raise Exception('Did not find allowed result types for: %s' % name)
217 result_types = allowed_types
218 else:
219 result_types = [result]
220 if n not in ['', '2']:
221 raise Exception('Cannot parse "%s"' % declaration)
222 args = ', '.join('%s %s' % (args[i], args[i+1])
223 for i in range(0, len(args), 2) if args[i])
224 for result_type in result_types:
225 add_matcher(result_type, name, args, comment)
226 return
227
228 # Parse free standing matcher functions, like:
229 # Matcher<ResultType> Name(Matcher<ArgumentType> InnerMatcher) {
230 m = re.match(r"""^\s*(.*)\s+
231 ([^\s\(]+)\s*\(
232 (.*)
233 \)\s*{""", declaration, re.X)
234 if m:
235 result, name, args = m.groups()
236 args = ', '.join(p.strip() for p in args.split(','))
Manuel Klimek41df16e2013-01-09 09:38:21 +0000237 m = re.match(r'.*\s+internal::(Bindable)?Matcher<([^>]+)>$', result)
Manuel Klimek95a58d22012-08-27 18:49:12 +0000238 if m:
Manuel Klimek41df16e2013-01-09 09:38:21 +0000239 result_types = [m.group(2)]
Manuel Klimek95a58d22012-08-27 18:49:12 +0000240 else:
241 result_types = extract_result_types(comment)
242 if not result_types:
243 if not comment:
244 # Only overloads don't have their own doxygen comments; ignore those.
245 print 'Ignoring "%s"' % name
246 else:
247 print 'Cannot determine result type for "%s"' % name
248 else:
249 for result_type in result_types:
250 add_matcher(result_type, name, args, comment)
251 else:
252 print '*** Unparsable: "' + declaration + '" ***'
253
254def sort_table(matcher_type, matcher_map):
255 """Returns the sorted html table for the given row map."""
256 table = ''
257 for key in sorted(matcher_map.keys()):
258 table += matcher_map[key] + '\n'
259 return ('<!-- START_%(type)s_MATCHERS -->\n' +
260 '%(table)s' +
261 '<!--END_%(type)s_MATCHERS -->') % {
262 'type': matcher_type,
263 'table': table,
264 }
265
266# Parse the ast matchers.
267# We alternate between two modes:
268# body = True: We parse the definition of a matcher. We need
269# to parse the full definition before adding a matcher, as the
270# definition might contain static asserts that specify the result
271# type.
272# body = False: We parse the comments and declaration of the matcher.
273comment = ''
274declaration = ''
275allowed_types = []
276body = False
277for line in open(MATCHERS_FILE).read().splitlines():
278 if body:
279 if line.strip() and line[0] == '}':
280 if declaration:
281 act_on_decl(declaration, comment, allowed_types)
282 comment = ''
283 declaration = ''
284 allowed_types = []
285 body = False
286 else:
287 m = re.search(r'is_base_of<([^,]+), NodeType>', line)
288 if m and m.group(1):
289 allowed_types += [m.group(1)]
290 continue
291 if line.strip() and line.lstrip()[0] == '/':
292 comment += re.sub(r'/+\s?', '', line) + '\n'
293 else:
294 declaration += ' ' + line
295 if ((not line.strip()) or
296 line.rstrip()[-1] == ';' or
297 line.rstrip()[-1] == '{'):
298 if line.strip() and line.rstrip()[-1] == '{':
299 body = True
300 else:
301 act_on_decl(declaration, comment, allowed_types)
302 comment = ''
303 declaration = ''
304 allowed_types = []
305
306node_matcher_table = sort_table('DECL', node_matchers)
307narrowing_matcher_table = sort_table('NARROWING', narrowing_matchers)
308traversal_matcher_table = sort_table('TRAVERSAL', traversal_matchers)
309
310reference = open('../LibASTMatchersReference.html').read()
311reference = re.sub(r'<!-- START_DECL_MATCHERS.*END_DECL_MATCHERS -->',
312 '%s', reference, flags=re.S) % node_matcher_table
313reference = re.sub(r'<!-- START_NARROWING_MATCHERS.*END_NARROWING_MATCHERS -->',
314 '%s', reference, flags=re.S) % narrowing_matcher_table
315reference = re.sub(r'<!-- START_TRAVERSAL_MATCHERS.*END_TRAVERSAL_MATCHERS -->',
316 '%s', reference, flags=re.S) % traversal_matcher_table
317
318with open('../LibASTMatchersReference.html', 'w') as output:
319 output.write(reference)
320