]> git.uio.no Git - u/mrichter/AliRoot.git/blame - doxygen/thtml2doxy_clang.py
doxy: added params description on self-doc
[u/mrichter/AliRoot.git] / doxygen / thtml2doxy_clang.py
CommitLineData
a4057fc9 1#!/usr/bin/env python
2
3## @package thtml2doxy_clang
4# Translates THtml C++ comments to Doxygen using libclang as parser.
5#
6# This code relies on Python bindings for libclang: libclang's interface is pretty unstable, and
7# its Python bindings are unstable as well.
8#
9# AST (Abstract Source Tree) traversal is performed entirely using libclang used as a C++ parser,
10# instead of attempting to write a parser ourselves.
11#
12# This code (expecially AST traversal) was inspired by:
13#
14# - [Implementing a code generator with libclang](http://szelei.me/code-generator/)
15# (this refers to API calls used here)
16# - [Parsing C++ in Python with Clang](http://eli.thegreenplace.net/2011/07/03/parsing-c-in-python-with-clang)
17# (outdated, API calls described there do not work anymore, but useful to understand some basic
18# concepts)
19#
20# Usage:
21#
6a98a5fd 22# `thtml2doxy_clang [--stdout|-o] [-d] [--debug=DEBUG_LEVEL] file1 [file2 [file3...]]`
a4057fc9 23#
6a98a5fd 24# Parameters:
25#
26# - `--stdout|-o`: output all on standard output instead of writing files in place
27# - `-d`: enable debug mode (very verbose output)
28# - `--debug=DEBUG_LEVEL`: set debug level to one of `DEBUG`, `INFO`, `WARNING`, `ERROR`,
29# `CRITICAL`
30#
31# @author Dario Berzano, CERN
a4057fc9 32# @date 2014-12-05
33
34
35import sys
36import os
37import re
62671ba0 38import logging
39import getopt
a4057fc9 40import clang.cindex
41
42
43## Brain-dead color output for terminal.
44class Colt(str):
45
46 def red(self):
47 return self.color('\033[31m')
48
49 def green(self):
50 return self.color('\033[32m')
51
52 def yellow(self):
53 return self.color('\033[33m')
54
55 def blue(self):
56 return self.color('\033[34m')
57
58 def magenta(self):
59 return self.color('\033[35m')
60
61 def cyan(self):
62 return self.color('\033[36m')
63
64 def color(self, c):
65 return c + self + '\033[m'
66
67
10f6b9f8 68## Comment.
69class Comment:
70
72604c43 71 def __init__(self, lines, first_line, first_col, last_line, last_col, indent, func):
10f6b9f8 72 self.lines = lines
73 self.first_line = first_line
9220af47 74 self.first_col = first_col
10f6b9f8 75 self.last_line = last_line
9220af47 76 self.last_col = last_col
72604c43 77 self.indent = indent
10f6b9f8 78 self.func = func
79
72604c43 80 def has_comment(self, line):
81 return line >= self.first_line and line <= self.last_line
82
10f6b9f8 83 def __str__(self):
9220af47 84 return "<Comment for %s: [%d,%d:%d,%d] %s>" % (self.func, self.first_line, self.first_col, self.last_line, self.last_col, self.lines)
10f6b9f8 85
86
3018d1db 87## A data member comment.
88class MemberComment:
89
90 def __init__(self, text, is_transient, array_size, first_line, first_col, func):
91 self.lines = [ text ]
92 self.is_transient = is_transient
93 self.array_size = array_size
94 self.first_line = first_line
95 self.first_col = first_col
96 self.func = func
97
98 def has_comment(self, line):
99 return line == self.first_line
100
101 def __str__(self):
102
103 if self.is_transient:
104 tt = '!transient! '
105 else:
106 tt = ''
107
108 if self.array_size is not None:
109 ars = '[%s] ' % self.array_size
110 else:
111 ars = ''
112
113 return "<MemberComment for %s: [%d,%d] %s%s%s>" % (self.func, self.first_line, self.first_col, tt, ars, self.lines[0])
114
115
3b095296 116## A dummy comment that removes comment lines.
117class RemoveComment(Comment):
118
119 def __init__(self, first_line, last_line):
120 self.first_line = first_line
121 self.last_line = last_line
122 self.func = '<remove>'
123
124 def __str__(self):
125 return "<RemoveComment: [%d,%d]>" % (self.first_line, self.last_line)
126
127
a7136c98 128## Parses method comments.
a4057fc9 129#
a7136c98 130# @param cursor Current libclang parser cursor
131# @param comments Array of comments: new ones will be appended there
132def comment_method(cursor, comments):
133
134 # we are looking for the following structure: method -> compound statement -> comment, i.e. we
135 # need to extract the first comment in the compound statement composing the method
136
137 in_compound_stmt = False
138 expect_comment = False
139 emit_comment = False
140
141 comment = []
142 comment_function = cursor.spelling or cursor.displayname
143 comment_line_start = -1
144 comment_line_end = -1
145 comment_col_start = -1
146 comment_col_end = -1
147 comment_indent = -1
148
149 for token in cursor.get_tokens():
150
151 if token.cursor.kind == clang.cindex.CursorKind.COMPOUND_STMT:
152 if not in_compound_stmt:
153 in_compound_stmt = True
154 expect_comment = True
155 comment_line_end = -1
156 else:
157 if in_compound_stmt:
158 in_compound_stmt = False
159 emit_comment = True
a4057fc9 160
a7136c98 161 # tkind = str(token.kind)[str(token.kind).index('.')+1:]
162 # ckind = str(token.cursor.kind)[str(token.cursor.kind).index('.')+1:]
a4057fc9 163
a7136c98 164 if in_compound_stmt:
a4057fc9 165
a7136c98 166 if expect_comment:
a4057fc9 167
a7136c98 168 extent = token.extent
169 line_start = extent.start.line
170 line_end = extent.end.line
a4057fc9 171
a7136c98 172 if token.kind == clang.cindex.TokenKind.PUNCTUATION and token.spelling == '{':
173 pass
a4057fc9 174
a7136c98 175 elif token.kind == clang.cindex.TokenKind.COMMENT and (comment_line_end == -1 or (line_start == comment_line_end+1 and line_end-line_start == 0)):
176 comment_line_end = line_end
177 comment_col_end = extent.end.column
a4057fc9 178
a7136c98 179 if comment_indent == -1 or (extent.start.column-1) < comment_indent:
180 comment_indent = extent.start.column-1
a4057fc9 181
a7136c98 182 if comment_line_start == -1:
183 comment_line_start = line_start
184 comment_col_start = extent.start.column
185 comment.extend( token.spelling.split('\n') )
186
187 # multiline comments are parsed in one go, therefore don't expect subsequent comments
188 if line_end - line_start > 0:
189 emit_comment = True
190 expect_comment = False
a4057fc9 191
a7136c98 192 else:
193 emit_comment = True
194 expect_comment = False
9a13b5a2 195
a7136c98 196 if emit_comment:
9a13b5a2 197
a7136c98 198 comment = refactor_comment( comment )
4e465d49 199
a7136c98 200 if len(comment) > 0:
201 logging.debug("Comment found for function %s" % Colt(comment_function).magenta())
202 comments.append( Comment(comment, comment_line_start, comment_col_start, comment_line_end, comment_col_end, comment_indent, comment_function) )
72604c43 203
a7136c98 204 comment = []
205 comment_line_start = -1
206 comment_line_end = -1
207 comment_col_start = -1
208 comment_col_end = -1
209 comment_indent = -1
a4057fc9 210
a7136c98 211 emit_comment = False
212 break
78aaad66 213
a4057fc9 214
3018d1db 215## Parses comments to class data members.
216#
217# @param cursor Current libclang parser cursor
218# @param comments Array of comments: new ones will be appended there
219def comment_datamember(cursor, comments):
220
221 # Note: libclang 3.5 seems to have problems parsing a certain type of FIELD_DECL, so we revert
222 # to a partial manual parsing. When parsing fails, the cursor's "extent" is not set properly,
223 # returning a line range 0-0. We therefore make the not-so-absurd assumption that the datamember
224 # definition is fully on one line, and we take the line number from cursor.location.
225
226 line_num = cursor.location.line
227 raw = None
3b095296 228 prev = None
229 found = False
3018d1db 230
231 # Huge overkill
232 with open(str(cursor.location.file)) as fp:
233 cur_line = 0
234 for raw in fp:
235 cur_line = cur_line + 1
236 if cur_line == line_num:
3b095296 237 found = True
3018d1db 238 break
3b095296 239 prev = raw
240
241 assert found, 'A line that should exist was not found in file' % cursor.location.file
3018d1db 242
3e14e47f 243 recomm = r'(//(!)|///?)(\[(.*?)\])?<?\s*(.*?)\s*$'
3b095296 244 recomm_doxyary = r'^\s*///\s*(.*?)\s*$'
3018d1db 245
246 mcomm = re.search(recomm, raw)
247 if mcomm:
248 member_name = cursor.spelling;
249 is_transient = mcomm.group(2) is not None
250 array_size = mcomm.group(4)
251 text = mcomm.group(5)
252
253 col_num = mcomm.start()+1;
254
3b095296 255 if array_size is not None and prev is not None:
256 # ROOT arrays with comments already converted to Doxygen have the member description on the
257 # previous line
258 mcomm_doxyary = re.search(recomm_doxyary, prev)
259 if mcomm_doxyary:
260 text = mcomm_doxyary.group(1)
261 comments.append(RemoveComment(line_num-1, line_num-1))
3018d1db 262
263 logging.debug('Comment found for member %s' % Colt(member_name).magenta())
264
265 comments.append( MemberComment(
266 text,
267 is_transient,
268 array_size,
269 line_num,
270 col_num,
271 member_name ))
272
3b095296 273 else:
274 assert False, 'Regular expression does not match member comment'
275
3018d1db 276
c7ea28e6 277## Parses class description (beginning of file).
278#
279# The clang parser does not work in this case so we do it manually, but it is very simple: we keep
280# the first consecutive sequence of single-line comments (//) we find - provided that it occurs
281# before any other comment found so far in the file (the comments array is inspected to ensure
282# this).
283#
284# Multi-line comments (/* ... */) are not considered as they are commonly used to display
285# copyright notice.
286#
287# @param filename Name of the current file
288# @param comments Array of comments: new ones will be appended there
289def comment_classdesc(filename, comments):
290
291 recomm = r'^\s*///?\s*(.*?)\s*/*\s*$'
a00f7da1 292
acd85b9a 293 reclass_doxy = r'(?i)^\\class:?\s*(.*?)\s*$'
294 class_name_doxy = None
a00f7da1 295
296 reauthor = r'(?i)\\?authors?:?\s*(.*?)\s*(,?\s*([0-9./-]+))?\s*$'
297 redate = r'(?i)\\?date:?\s*([0-9./-]+)\s*$'
298 author = None
299 date = None
300
c7ea28e6 301 comment_lines = []
302
303 start_line = -1
304 end_line = -1
305
306 line_num = 0
307
308 with open(filename, 'r') as fp:
309
310 for raw in fp:
311
312 line_num = line_num + 1
313
314 if raw.strip() == '':
315 # Skip empty lines
316 end_line = line_num - 1
317 continue
318
319 mcomm = re.search(recomm, raw)
320 if mcomm:
321
acd85b9a 322 if start_line == -1 and len(comment_lines) == 0:
c7ea28e6 323
acd85b9a 324 # First line. Check that we do not overlap with other comments
c7ea28e6 325 comment_overlaps = False
326 for c in comments:
327 if c.has_comment(line_num):
328 comment_overlaps = True
329 break
330
331 if comment_overlaps:
332 # No need to look for other comments
333 break
334
335 start_line = line_num
336
a00f7da1 337 append = True
338
acd85b9a 339 mclass_doxy = re.search(reclass_doxy, mcomm.group(1))
340 if mclass_doxy:
341 class_name_doxy = mclass_doxy.group(1)
a00f7da1 342 append = False
acd85b9a 343 else:
a00f7da1 344 mauthor = re.search(reauthor, mcomm.group(1))
345 if mauthor:
346 author = mauthor.group(1)
347 if date is None:
348 # Date specified in the standalone \date field has priority
349 date = mauthor.group(2)
350 append = False
351 else:
352 mdate = re.search(redate, mcomm.group(1))
353 if mdate:
354 date = mdate.group(1)
355 append = False
356
357 if append:
acd85b9a 358 comment_lines.append( mcomm.group(1) )
c7ea28e6 359
360 else:
361 if len(comment_lines) > 0:
362 # End of our comment
363 if end_line == -1:
364 end_line = line_num - 1
365 break
366
acd85b9a 367 if class_name_doxy is None:
c7ea28e6 368
acd85b9a 369 # No \class specified: guess it from file name
c7ea28e6 370 reclass = r'^(.*/)?(.*?)(\..*)?$'
371 mclass = re.search( reclass, filename )
372 if mclass:
acd85b9a 373 class_name_doxy = mclass.group(2)
c7ea28e6 374 else:
375 assert False, 'Regexp unable to extract classname from file'
376
acd85b9a 377 # Prepend \class specifier (and an empty line)
378 comment_lines[:0] = [ '\\class ' + class_name_doxy ]
379
380 # Append author and date if they exist
381 comment_lines.append('')
382
383 if author is not None:
384 comment_lines.append( '\\author ' + author )
385
386 if date is not None:
387 comment_lines.append( '\\date ' + date )
388
389 comment_lines = refactor_comment(comment_lines)
390 logging.debug('Comment found for class %s' % Colt(class_name_doxy).magenta())
391 comments.append(Comment(
392 comment_lines,
393 start_line, 1, end_line, 1,
394 0, class_name_doxy
395 ))
396
397
a7136c98 398## Traverse the AST recursively starting from the current cursor.
399#
400# @param cursor A Clang parser cursor
3bd2e2f0 401# @param filename Name of the current file
a7136c98 402# @param comments Array of comments: new ones will be appended there
403# @param recursion Current recursion depth
3bd2e2f0 404def traverse_ast(cursor, filename, comments, recursion=0):
405
406 # libclang traverses included files as well: we do not want this behavior
407 if cursor.location.file is not None and str(cursor.location.file) != filename:
408 logging.debug("Skipping processing of included %s" % cursor.location.file)
409 return
533918c9 410
a7136c98 411 text = cursor.spelling or cursor.displayname
412 kind = str(cursor.kind)[str(cursor.kind).index('.')+1:]
533918c9 413
a7136c98 414 indent = ''
415 for i in range(0, recursion):
416 indent = indent + ' '
a4057fc9 417
dc396a82 418 if cursor.kind == clang.cindex.CursorKind.CXX_METHOD or cursor.kind == clang.cindex.CursorKind.CONSTRUCTOR or cursor.kind == clang.cindex.CursorKind.DESTRUCTOR:
533918c9 419
a7136c98 420 # cursor ran into a C++ method
1f2b1b91 421 logging.debug( "%5d %s%s(%s)" % (cursor.location.line, indent, Colt(kind).magenta(), Colt(text).blue()) )
a7136c98 422 comment_method(cursor, comments)
a4057fc9 423
3018d1db 424 elif cursor.kind == clang.cindex.CursorKind.FIELD_DECL:
425
426 # cursor ran into a data member declaration
1f2b1b91 427 logging.debug( "%5d %s%s(%s)" % (cursor.location.line, indent, Colt(kind).magenta(), Colt(text).blue()) )
3018d1db 428 comment_datamember(cursor, comments)
429
a4057fc9 430 else:
431
1f2b1b91 432 logging.debug( "%5d %s%s(%s)" % (cursor.location.line, indent, kind, text) )
a4057fc9 433
4e465d49 434 for child_cursor in cursor.get_children():
3bd2e2f0 435 traverse_ast(child_cursor, filename, comments, recursion+1)
a4057fc9 436
c7ea28e6 437 if recursion == 0:
438 comment_classdesc(filename, comments)
439
533918c9 440
4e465d49 441## Remove garbage from comments and convert special tags from THtml to Doxygen.
442#
9eb7bab8 443# @param comment An array containing the lines of the original comment
4e465d49 444def refactor_comment(comment):
a4057fc9 445
9eb7bab8 446 recomm = r'^(/{2,}|/\*)?\s*(.*?)\s*((/{2,})?\s*|\*/)$'
b62a05f1 447 regarbage = r'^[\s*=-_#]+$'
9eb7bab8 448
449 new_comment = []
450 insert_blank = False
451 wait_first_non_blank = True
452 for line_comment in comment:
453 mcomm = re.search( recomm, line_comment )
454 if mcomm:
455 new_line_comment = mcomm.group(2)
b62a05f1 456 mgarbage = re.search( regarbage, new_line_comment )
fc54cb81 457
b62a05f1 458 if new_line_comment == '' or mgarbage is not None:
9eb7bab8 459 insert_blank = True
4e465d49 460 else:
9eb7bab8 461 if insert_blank and not wait_first_non_blank:
462 new_comment.append('')
fc54cb81 463 insert_blank = False
9eb7bab8 464 wait_first_non_blank = False
465 new_comment.append( new_line_comment )
fc54cb81 466
9eb7bab8 467 else:
468 assert False, 'Comment regexp does not match'
4e465d49 469
470 return new_comment
a4057fc9 471
472
72604c43 473## Rewrites all comments from the given file handler.
474#
475# @param fhin The file handler to read from
476# @param fhout The file handler to write to
477# @param comments Array of comments
478def rewrite_comments(fhin, fhout, comments):
479
480 line_num = 0
72604c43 481 in_comment = False
482 skip_empty = False
3b095296 483 comm = None
484 prev_comm = None
72604c43 485
3018d1db 486 rindent = r'^(\s*)'
487
72604c43 488 for line in fhin:
489
490 line_num = line_num + 1
491
3b095296 492 # Find current comment
493 prev_comm = comm
494 comm = None
495 for c in comments:
496 if c.has_comment(line_num):
497 comm = c
498
499 if comm:
72604c43 500
3018d1db 501 if isinstance(comm, MemberComment):
3b095296 502 non_comment = line[ 0:comm.first_col-1 ]
3018d1db 503
504 if comm.array_size is not None:
505
506 mindent = re.search(rindent, line)
507 if comm.is_transient:
508 tt = '!'
509 else:
510 tt = ''
511
512 # Special case: we need multiple lines not to confuse ROOT's C++ parser
3b095296 513 fhout.write('%s/// %s\n%s//%s[%s]\n' % (
3018d1db 514 mindent.group(1),
515 comm.lines[0],
516 non_comment,
517 tt,
518 comm.array_size
519 ))
520
521 else:
522
523 if comm.is_transient:
524 tt = '!'
525 else:
526 tt = '/'
527
528 fhout.write('%s//%s< %s\n' % (
529 non_comment,
530 tt,
531 comm.lines[0]
532 ))
533
3b095296 534 elif isinstance(comm, RemoveComment):
535 # Do nothing: just skip line
536 pass
3018d1db 537
3b095296 538 elif prev_comm is None:
539 # Beginning of a new comment block of type Comment
72604c43 540 in_comment = True
541
3b095296 542 # Extract the non-comment part and print it if it exists
543 non_comment = line[ 0:comm.first_col-1 ].rstrip()
72604c43 544 if non_comment != '':
545 fhout.write( non_comment + '\n' )
546
547 else:
3b095296 548
72604c43 549 if in_comment:
550
3b095296 551 # We have just exited a comment block of type Comment
72604c43 552 in_comment = False
553
3b095296 554 # Dump revamped comment, if applicable
72604c43 555 text_indent = ''
3b095296 556 for i in range(0,prev_comm.indent):
72604c43 557 text_indent = text_indent + ' '
558
3b095296 559 for lc in prev_comm.lines:
72604c43 560 fhout.write( "%s/// %s\n" % (text_indent, lc) );
561 fhout.write('\n')
562 skip_empty = True
563
72604c43 564 line_out = line.rstrip('\n')
565 if skip_empty:
566 skip_empty = False
567 if line_out.strip() != '':
568 fhout.write( line_out + '\n' )
569 else:
570 fhout.write( line_out + '\n' )
571
572
a4057fc9 573## The main function.
574#
62671ba0 575# Return value is the executable's return value.
a4057fc9 576def main(argv):
577
62671ba0 578 # Setup logging on stderr
72604c43 579 log_level = logging.INFO
62671ba0 580 logging.basicConfig(
581 level=log_level,
582 format='%(levelname)-8s %(funcName)-20s %(message)s',
583 stream=sys.stderr
584 )
585
586 # Parse command-line options
43ee56ee 587 output_on_stdout = False
62671ba0 588 try:
43ee56ee 589 opts, args = getopt.getopt( argv, 'od', [ 'debug=', 'stdout' ] )
62671ba0 590 for o, a in opts:
591 if o == '--debug':
592 log_level = getattr( logging, a.upper(), None )
593 if not isinstance(log_level, int):
594 raise getopt.GetoptError('log level must be one of: DEBUG, INFO, WARNING, ERROR, CRITICAL')
595 elif o == '-d':
596 log_level = logging.DEBUG
43ee56ee 597 elif o == '-o' or o == '--stdout':
598 logging.debug('Output on stdout instead of replacing original files')
599 output_on_stdout = True
62671ba0 600 else:
601 assert False, 'Unhandled argument'
602 except getopt.GetoptError as e:
603 logging.fatal('Invalid arguments: %s' % e)
604 return 1
605
606 logging.getLogger('').setLevel(log_level)
607
a4057fc9 608 # Attempt to load libclang from a list of known locations
609 libclang_locations = [
610 '/usr/lib/llvm-3.5/lib/libclang.so.1',
611 '/usr/lib/libclang.so',
612 '/Library/Developer/CommandLineTools/usr/lib/libclang.dylib'
613 ]
614 libclang_found = False
615
616 for lib in libclang_locations:
617 if os.path.isfile(lib):
618 clang.cindex.Config.set_library_file(lib)
619 libclang_found = True
620 break
621
622 if not libclang_found:
62671ba0 623 logging.fatal('Cannot find libclang')
a4057fc9 624 return 1
625
626 # Loop over all files
62671ba0 627 for fn in args:
a4057fc9 628
533918c9 629 logging.info('Input file: %s' % Colt(fn).magenta())
a4057fc9 630 index = clang.cindex.Index.create()
631 translation_unit = index.parse(fn, args=['-x', 'c++'])
10f6b9f8 632
633 comments = []
3bd2e2f0 634 traverse_ast( translation_unit.cursor, fn, comments )
10f6b9f8 635 for c in comments:
3018d1db 636
637 logging.debug("Comment found for entity %s:" % Colt(c.func).magenta())
638
639 if isinstance(c, MemberComment):
640
641 if c.is_transient:
642 transient_text = Colt('transient ').yellow()
643 else:
644 transient_text = ''
645
646 if c.array_size is not None:
647 array_text = Colt('arraysize=%s ' % c.array_size).yellow()
648 else:
649 array_text = ''
650
72604c43 651 logging.debug(
3018d1db 652 "%s %s%s{%s}" % ( \
653 Colt("[%d,%d]" % (c.first_line, c.first_col)).green(),
654 transient_text,
655 array_text,
656 Colt(c.lines[0]).cyan()
657 ))
658
3b095296 659 elif isinstance(c, RemoveComment):
660
661 logging.debug( Colt('[%d,%d]' % (c.first_line, c.last_line)).green() )
662
3018d1db 663 else:
664 for l in c.lines:
665 logging.debug(
666 Colt("[%d,%d:%d,%d] " % (c.first_line, c.first_col, c.last_line, c.last_col)).green() +
667 "{%s}" % Colt(l).cyan()
668 )
a4057fc9 669
72604c43 670 try:
671
43ee56ee 672 if output_on_stdout:
673 with open(fn, 'r') as fhin:
674 rewrite_comments( fhin, sys.stdout, comments )
675 else:
676 fn_back = fn + '.thtml2doxy_backup'
677 os.rename( fn, fn_back )
72604c43 678
43ee56ee 679 with open(fn_back, 'r') as fhin, open(fn, 'w') as fhout:
680 rewrite_comments( fhin, fhout, comments )
72604c43 681
43ee56ee 682 os.remove( fn_back )
683 logging.info("File %s converted to Doxygen: check differences before committing!" % Colt(fn).magenta())
72604c43 684 except (IOError,OSError) as e:
685 logging.error('File operation failed: %s' % e)
686
a4057fc9 687 return 0
688
689
690if __name__ == '__main__':
62671ba0 691 sys.exit( main( sys.argv[1:] ) )