Debian Codegraph @

clang/docs/tools/dump_ast_matchers.py

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