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