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