]> git.uio.no Git - u/mrichter/AliRoot.git/blame - doxygen/thtml2doxy.py
doxy: removed old script, kept only libclang one
[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):
72 self.lines = lines
73 self.first_line = first_line
74 self.first_col = first_col
75 self.last_line = last_line
76 self.last_col = last_col
77 self.indent = indent
78 self.func = func
79
80 def has_comment(self, line):
81 return line >= self.first_line and line <= self.last_line
82
83 def __str__(self):
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)
85
86
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
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
128## Parses method comments.
f329fa92 129#
06ccae0f 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
160
161 # tkind = str(token.kind)[str(token.kind).index('.')+1:]
162 # ckind = str(token.cursor.kind)[str(token.cursor.kind).index('.')+1:]
163
164 if in_compound_stmt:
165
166 if expect_comment:
167
168 extent = token.extent
169 line_start = extent.start.line
170 line_end = extent.end.line
171
172 if token.kind == clang.cindex.TokenKind.PUNCTUATION and token.spelling == '{':
173 pass
174
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
178
179 if comment_indent == -1 or (extent.start.column-1) < comment_indent:
180 comment_indent = extent.start.column-1
181
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
191
192 else:
193 emit_comment = True
194 expect_comment = False
195
196 if emit_comment:
197
198 comment = refactor_comment( comment )
199
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) )
203
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
210
211 emit_comment = False
212 break
213
214
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
228 prev = None
229 found = False
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:
237 found = True
238 break
239 prev = raw
240
241 assert found, 'A line that should exist was not found in file' % cursor.location.file
242
243 recomm = r'(//(!)|///?)(\[(.*?)\])?<?\s*(.*?)\s*$'
244 recomm_doxyary = r'^\s*///\s*(.*?)\s*$'
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
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))
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
273 else:
274 assert False, 'Regular expression does not match member comment'
275
276
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).
f329fa92 283#
06ccae0f 284# Multi-line comments (/* ... */) are not considered as they are commonly used to display
285# copyright notice.
f329fa92 286#
06ccae0f 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*$'
292
293 reclass_doxy = r'(?i)^\s*\\class:?\s*(.*?)\s*$'
294 class_name_doxy = None
295
296 reauthor = r'(?i)^\s*\\?authors?:?\s*(.*?)\s*(,?\s*([0-9./-]+))?\s*$'
297 redate = r'(?i)^\s*\\?date:?\s*([0-9./-]+)\s*$'
298 author = None
299 date = None
300
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 stripped = strip_html(raw)
320 mcomm = re.search(recomm, stripped)
321 if mcomm:
322
323 if start_line == -1 and len(comment_lines) == 0:
324
325 # First line. Check that we do not overlap with other comments
326 comment_overlaps = False
327 for c in comments:
328 if c.has_comment(line_num):
329 comment_overlaps = True
330 break
331
332 if comment_overlaps:
333 # No need to look for other comments
334 break
335
336 start_line = line_num
337
338 append = True
339
340 mclass_doxy = re.search(reclass_doxy, mcomm.group(1))
341 if mclass_doxy:
342 class_name_doxy = mclass_doxy.group(1)
343 append = False
344 else:
345 mauthor = re.search(reauthor, mcomm.group(1))
346 if mauthor:
347 author = mauthor.group(1)
348 if date is None:
349 # Date specified in the standalone \date field has priority
350 date = mauthor.group(2)
351 append = False
352 else:
353 mdate = re.search(redate, mcomm.group(1))
354 if mdate:
355 date = mdate.group(1)
356 append = False
357
358 if append:
359 comment_lines.append( mcomm.group(1) )
360
361 else:
362 if len(comment_lines) > 0:
363 # End of our comment
364 if end_line == -1:
365 end_line = line_num - 1
366 break
367
368 if class_name_doxy is None:
369
370 # No \class specified: guess it from file name
371 reclass = r'^(.*/)?(.*?)(\..*)?$'
372 mclass = re.search( reclass, filename )
373 if mclass:
374 class_name_doxy = mclass.group(2)
375 else:
376 assert False, 'Regexp unable to extract classname from file'
377
378 # Prepend \class specifier (and an empty line)
379 comment_lines[:0] = [ '\\class ' + class_name_doxy ]
380
381 # Append author and date if they exist
382 comment_lines.append('')
383
384 if author is not None:
385 comment_lines.append( '\\author ' + author )
386
387 if date is not None:
388 comment_lines.append( '\\date ' + date )
389
390 comment_lines = refactor_comment(comment_lines, do_strip_html=False)
391 logging.debug('Comment found for class %s' % Colt(class_name_doxy).magenta())
392 comments.append(Comment(
393 comment_lines,
394 start_line, 1, end_line, 1,
395 0, class_name_doxy
396 ))
397
398
399## Traverse the AST recursively starting from the current cursor.
400#
401# @param cursor A Clang parser cursor
402# @param filename Name of the current file
403# @param comments Array of comments: new ones will be appended there
404# @param recursion Current recursion depth
405def traverse_ast(cursor, filename, comments, recursion=0):
406
407 # libclang traverses included files as well: we do not want this behavior
408 if cursor.location.file is not None and str(cursor.location.file) != filename:
409 logging.debug("Skipping processing of included %s" % cursor.location.file)
410 return
411
412 text = cursor.spelling or cursor.displayname
413 kind = str(cursor.kind)[str(cursor.kind).index('.')+1:]
414
415 indent = ''
416 for i in range(0, recursion):
417 indent = indent + ' '
418
419 if cursor.kind == clang.cindex.CursorKind.CXX_METHOD or cursor.kind == clang.cindex.CursorKind.CONSTRUCTOR or cursor.kind == clang.cindex.CursorKind.DESTRUCTOR:
420
421 # cursor ran into a C++ method
422 logging.debug( "%5d %s%s(%s)" % (cursor.location.line, indent, Colt(kind).magenta(), Colt(text).blue()) )
423 comment_method(cursor, comments)
424
425 elif cursor.kind == clang.cindex.CursorKind.FIELD_DECL:
426
427 # cursor ran into a data member declaration
428 logging.debug( "%5d %s%s(%s)" % (cursor.location.line, indent, Colt(kind).magenta(), Colt(text).blue()) )
429 comment_datamember(cursor, comments)
430
431 else:
432
433 logging.debug( "%5d %s%s(%s)" % (cursor.location.line, indent, kind, text) )
434
435 for child_cursor in cursor.get_children():
436 traverse_ast(child_cursor, filename, comments, recursion+1)
437
438 if recursion == 0:
439 comment_classdesc(filename, comments)
440
441
442## Strip some HTML tags from the given string. Returns clean string.
443#
444# @param s Input string
445def strip_html(s):
446 rehtml = r'(?i)</?(P|H[0-9]|BR)/?>'
447 return re.sub(rehtml, '', s)
448
449
450## Remove garbage from comments and convert special tags from THtml to Doxygen.
451#
452# @param comment An array containing the lines of the original comment
453def refactor_comment(comment, do_strip_html=True):
454
455 recomm = r'^(/{2,}|/\*)? ?(\s*.*?)\s*((/{2,})?\s*|\*/)$'
456 regarbage = r'^(?i)\s*([\s*=-_#]+|(Begin|End)_Html)\s*$'
457
458 new_comment = []
459 insert_blank = False
460 wait_first_non_blank = True
461 for line_comment in comment:
462
463 # Strip some HTML tags
464 if do_strip_html:
465 line_comment = strip_html(line_comment)
466
467 mcomm = re.search( recomm, line_comment )
468 if mcomm:
469 new_line_comment = mcomm.group(2)
470 mgarbage = re.search( regarbage, new_line_comment )
471
472 if new_line_comment == '' or mgarbage is not None:
473 insert_blank = True
474 else:
475 if insert_blank and not wait_first_non_blank:
476 new_comment.append('')
477 insert_blank = False
478 wait_first_non_blank = False
479 new_comment.append( new_line_comment )
480
481 else:
482 assert False, 'Comment regexp does not match'
483
484 return new_comment
485
486
487## Rewrites all comments from the given file handler.
488#
489# @param fhin The file handler to read from
490# @param fhout The file handler to write to
491# @param comments Array of comments
492def rewrite_comments(fhin, fhout, comments):
493
494 line_num = 0
495 in_comment = False
496 skip_empty = False
497 comm = None
498 prev_comm = None
499
500 rindent = r'^(\s*)'
501
502 for line in fhin:
503
504 line_num = line_num + 1
505
506 # Find current comment
507 prev_comm = comm
508 comm = None
509 for c in comments:
510 if c.has_comment(line_num):
511 comm = c
512
513 if comm:
514
515 if isinstance(comm, MemberComment):
516 non_comment = line[ 0:comm.first_col-1 ]
517
518 if comm.array_size is not None:
519
520 mindent = re.search(rindent, line)
521 if comm.is_transient:
522 tt = '!'
523 else:
524 tt = ''
525
526 # Special case: we need multiple lines not to confuse ROOT's C++ parser
527 fhout.write('%s/// %s\n%s//%s[%s]\n' % (
528 mindent.group(1),
529 comm.lines[0],
530 non_comment,
531 tt,
532 comm.array_size
533 ))
534
535 else:
536
537 if comm.is_transient:
538 tt = '!'
539 else:
540 tt = '/'
541
542 fhout.write('%s//%s< %s\n' % (
543 non_comment,
544 tt,
545 comm.lines[0]
546 ))
547
548 elif isinstance(comm, RemoveComment):
549 # Do nothing: just skip line
550 pass
551
552 elif prev_comm is None:
553 # Beginning of a new comment block of type Comment
554 in_comment = True
555
556 # Extract the non-comment part and print it if it exists
557 non_comment = line[ 0:comm.first_col-1 ].rstrip()
558 if non_comment != '':
559 fhout.write( non_comment + '\n' )
560
561 else:
562
563 if in_comment:
564
565 # We have just exited a comment block of type Comment
566 in_comment = False
567
568 # Dump revamped comment, if applicable
569 text_indent = ''
570 for i in range(0,prev_comm.indent):
571 text_indent = text_indent + ' '
572
573 for lc in prev_comm.lines:
574 fhout.write( "%s/// %s\n" % (text_indent, lc) );
575 fhout.write('\n')
576 skip_empty = True
577
578 line_out = line.rstrip('\n')
579 if skip_empty:
580 skip_empty = False
581 if line_out.strip() != '':
582 fhout.write( line_out + '\n' )
583 else:
584 fhout.write( line_out + '\n' )
585
f329fa92 586
587## The main function.
588#
06ccae0f 589# Return value is the executable's return value.
f329fa92 590def main(argv):
591
06ccae0f 592 # Setup logging on stderr
593 log_level = logging.INFO
594 logging.basicConfig(
595 level=log_level,
596 format='%(levelname)-8s %(funcName)-20s %(message)s',
597 stream=sys.stderr
598 )
f329fa92 599
06ccae0f 600 # Parse command-line options
601 output_on_stdout = False
602 try:
603 opts, args = getopt.getopt( argv, 'od', [ 'debug=', 'stdout' ] )
604 for o, a in opts:
605 if o == '--debug':
606 log_level = getattr( logging, a.upper(), None )
607 if not isinstance(log_level, int):
608 raise getopt.GetoptError('log level must be one of: DEBUG, INFO, WARNING, ERROR, CRITICAL')
609 elif o == '-d':
610 log_level = logging.DEBUG
611 elif o == '-o' or o == '--stdout':
612 logging.debug('Output on stdout instead of replacing original files')
613 output_on_stdout = True
614 else:
615 assert False, 'Unhandled argument'
616 except getopt.GetoptError as e:
617 logging.fatal('Invalid arguments: %s' % e)
618 return 1
f329fa92 619
06ccae0f 620 logging.getLogger('').setLevel(log_level)
f329fa92 621
06ccae0f 622 # Attempt to load libclang from a list of known locations
623 libclang_locations = [
624 '/usr/lib/llvm-3.5/lib/libclang.so.1',
625 '/usr/lib/libclang.so',
626 '/Library/Developer/CommandLineTools/usr/lib/libclang.dylib'
627 ]
628 libclang_found = False
f329fa92 629
06ccae0f 630 for lib in libclang_locations:
631 if os.path.isfile(lib):
632 clang.cindex.Config.set_library_file(lib)
633 libclang_found = True
634 break
f329fa92 635
06ccae0f 636 if not libclang_found:
637 logging.fatal('Cannot find libclang')
638 return 1
639
640 # Loop over all files
641 for fn in args:
642
643 logging.info('Input file: %s' % Colt(fn).magenta())
644 index = clang.cindex.Index.create()
645 translation_unit = index.parse(fn, args=['-x', 'c++'])
646
647 comments = []
648 traverse_ast( translation_unit.cursor, fn, comments )
649 for c in comments:
650
651 logging.debug("Comment found for entity %s:" % Colt(c.func).magenta())
f329fa92 652
06ccae0f 653 if isinstance(c, MemberComment):
654
655 if c.is_transient:
656 transient_text = Colt('transient ').yellow()
657 else:
658 transient_text = ''
659
660 if c.array_size is not None:
661 array_text = Colt('arraysize=%s ' % c.array_size).yellow()
662 else:
663 array_text = ''
664
665 logging.debug(
666 "%s %s%s{%s}" % ( \
667 Colt("[%d,%d]" % (c.first_line, c.first_col)).green(),
668 transient_text,
669 array_text,
670 Colt(c.lines[0]).cyan()
671 ))
672
673 elif isinstance(c, RemoveComment):
674
675 logging.debug( Colt('[%d,%d]' % (c.first_line, c.last_line)).green() )
676
677 else:
678 for l in c.lines:
679 logging.debug(
680 Colt("[%d,%d:%d,%d] " % (c.first_line, c.first_col, c.last_line, c.last_col)).green() +
681 "{%s}" % Colt(l).cyan()
682 )
f329fa92 683
684 try:
06ccae0f 685
686 if output_on_stdout:
687 with open(fn, 'r') as fhin:
688 rewrite_comments( fhin, sys.stdout, comments )
689 else:
690 fn_back = fn + '.thtml2doxy_backup'
691 os.rename( fn, fn_back )
692
693 with open(fn_back, 'r') as fhin, open(fn, 'w') as fhout:
694 rewrite_comments( fhin, fhout, comments )
695
696 os.remove( fn_back )
697 logging.info("File %s converted to Doxygen: check differences before committing!" % Colt(fn).magenta())
698 except (IOError,OSError) as e:
699 logging.error('File operation failed: %s' % e)
f329fa92 700
701 return 0
702
06ccae0f 703
f329fa92 704if __name__ == '__main__':
06ccae0f 705 sys.exit( main( sys.argv[1:] ) )