]> git.uio.no Git - u/mrichter/AliRoot.git/blob - doxygen/thtml2doxy.py
doxy: support inline LaTeX
[u/mrichter/AliRoot.git] / doxygen / thtml2doxy.py
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 #
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
35 import sys
36 import os
37 import re
38 import logging
39 import getopt
40 import clang.cindex
41
42
43 ## Brain-dead color output for terminal.
44 class 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
68 ## Comment.
69 class Comment:
70
71   def __init__(self, lines, first_line, first_col, last_line, last_col, indent, func):
72     assert first_line > 0 and last_line >= first_line, 'Wrong line numbers'
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.
89 class MemberComment:
90
91   def __init__(self, text, is_transient, array_size, first_line, first_col, func):
92     assert first_line > 0, 'Wrong line number'
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.
119 class RemoveComment(Comment):
120
121   def __init__(self, first_line, last_line):
122     assert first_line > 0 and last_line >= first_line, 'Wrong line numbers'
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.
132 #
133 #  @param cursor   Current libclang parser cursor
134 #  @param comments Array of comments: new ones will be appended there
135 def 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
201       if comment_line_start > 0:
202
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:
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))
212
213       else:
214         logging.warning('No comment found for function %s' % Colt(comment_function).magenta())
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
231 def 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:
260     # If it does not match, we do not have a comment
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
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).
293 #
294 #  Multi-line comments (/* ... */) are not considered as they are commonly used to display
295 #  copyright notice.
296 #
297 #  @param filename Name of the current file
298 #  @param comments Array of comments: new ones will be appended there
299 def 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
324       if raw.strip() == '' and start_line > 0:
325         # Skip empty lines
326         continue
327
328       stripped = strip_html(raw)
329       mcomm = re.search(recomm, stripped)
330       if mcomm:
331
332         if start_line == -1:
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
347         end_line = line_num
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:
372         if start_line > 0:
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
385   if start_line > 0:
386
387     # Prepend \class specifier (and an empty line)
388     comment_lines[:0] = [ '\\class ' + class_name_doxy ]
389
390     # Append author and date if they exist
391     comment_lines.append('')
392
393     if author is not None:
394       comment_lines.append( '\\author ' + author )
395
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())
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
418 def 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
458 def 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
466 def 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   reinline_latex = r'(?i)(.*)BEGIN_LATEX\s+(.*?)\s+END_LATEX(.*)$'
472
473   new_comment = []
474   insert_blank = False
475   wait_first_non_blank = True
476   for line_comment in comment:
477
478     # Strip some HTML tags
479     if do_strip_html:
480       line_comment = strip_html(line_comment)
481
482     mcomm = re.search( recomm, line_comment )
483     if mcomm:
484       new_line_comment = mcomm.group(2)
485       mgarbage = re.search( regarbage, new_line_comment )
486
487       if new_line_comment == '' or mgarbage is not None:
488         insert_blank = True
489       else:
490         if insert_blank and not wait_first_non_blank:
491           new_comment.append('')
492         insert_blank = False
493         wait_first_non_blank = False
494
495         # Postprocessing: LaTeX formulas in ROOT format
496         # Marked by BEGIN_LATEX ... END_LATEX and they use # in place of \
497         # There can be several ROOT LaTeX forumlas per line
498         while True:
499           minline_latex = re.search( reinline_latex, new_line_comment )
500           if minline_latex:
501             new_line_comment = '%s\\f$%s\\f$%s' % \
502               ( minline_latex.group(1), minline_latex.group(2).replace('#', '\\'),
503                 minline_latex.group(3) )
504           else:
505             break
506
507         new_comment.append( new_line_comment )
508
509     else:
510       assert False, 'Comment regexp does not match'
511
512   return new_comment
513
514
515 ## Rewrites all comments from the given file handler.
516 #
517 #  @param fhin     The file handler to read from
518 #  @param fhout    The file handler to write to
519 #  @param comments Array of comments
520 def rewrite_comments(fhin, fhout, comments):
521
522   line_num = 0
523   in_comment = False
524   skip_empty = False
525   comm = None
526   prev_comm = None
527
528   rindent = r'^(\s*)'
529
530   for line in fhin:
531
532     line_num = line_num + 1
533
534     # Find current comment
535     prev_comm = comm
536     comm = None
537     for c in comments:
538       if c.has_comment(line_num):
539         comm = c
540
541     if comm:
542
543       if isinstance(comm, MemberComment):
544         non_comment = line[ 0:comm.first_col-1 ]
545
546         if comm.array_size is not None:
547
548           mindent = re.search(rindent, line)
549           if comm.is_transient:
550             tt = '!'
551           else:
552             tt = ''
553
554           # Special case: we need multiple lines not to confuse ROOT's C++ parser
555           fhout.write('%s/// %s\n%s//%s[%s]\n' % (
556             mindent.group(1),
557             comm.lines[0],
558             non_comment,
559             tt,
560             comm.array_size
561           ))
562
563         else:
564
565           if comm.is_transient:
566             tt = '!'
567           else:
568             tt = '/'
569
570           fhout.write('%s//%s< %s\n' % (
571             non_comment,
572             tt,
573             comm.lines[0]
574           ))
575
576       elif isinstance(comm, RemoveComment):
577         # Do nothing: just skip line
578         pass
579
580       elif prev_comm is None:
581         # Beginning of a new comment block of type Comment
582         in_comment = True
583
584         # Extract the non-comment part and print it if it exists
585         non_comment = line[ 0:comm.first_col-1 ].rstrip()
586         if non_comment != '':
587           fhout.write( non_comment + '\n' )
588
589     else:
590
591       if in_comment:
592
593         # We have just exited a comment block of type Comment
594         in_comment = False
595
596         # Dump revamped comment, if applicable
597         text_indent = ''
598         for i in range(0,prev_comm.indent):
599           text_indent = text_indent + ' '
600
601         for lc in prev_comm.lines:
602           fhout.write( "%s/// %s\n" % (text_indent, lc) );
603         fhout.write('\n')
604         skip_empty = True
605
606       line_out = line.rstrip('\n')
607       if skip_empty:
608         skip_empty = False
609         if line_out.strip() != '':
610           fhout.write( line_out + '\n' )
611       else:
612         fhout.write( line_out + '\n' )
613
614
615 ## The main function.
616 #
617 #  Return value is the executable's return value.
618 def main(argv):
619
620   # Setup logging on stderr
621   log_level = logging.INFO
622   logging.basicConfig(
623     level=log_level,
624     format='%(levelname)-8s %(funcName)-20s %(message)s',
625     stream=sys.stderr
626   )
627
628   # Parse command-line options
629   output_on_stdout = False
630   include_flags = []
631   try:
632     opts, args = getopt.getopt( argv, 'odI:', [ 'debug=', 'stdout' ] )
633     for o, a in opts:
634       if o == '--debug':
635         log_level = getattr( logging, a.upper(), None )
636         if not isinstance(log_level, int):
637           raise getopt.GetoptError('log level must be one of: DEBUG, INFO, WARNING, ERROR, CRITICAL')
638       elif o == '-d':
639         log_level = logging.DEBUG
640       elif o == '-o' or o == '--stdout':
641         output_on_stdout = True
642       elif o == '-I':
643         if os.path.isdir(a):
644           include_flags.extend( [ '-I', a ] )
645         else:
646           logging.fatal('Include directory not found: %s' % Colt(a).magenta())
647           return 2
648       else:
649         assert False, 'Unhandled argument'
650   except getopt.GetoptError as e:
651     logging.fatal('Invalid arguments: %s' % e)
652     return 1
653
654   logging.getLogger('').setLevel(log_level)
655
656   # Attempt to load libclang from a list of known locations
657   libclang_locations = [
658     '/usr/lib/llvm-3.5/lib/libclang.so.1',
659     '/usr/lib/libclang.so',
660     '/Library/Developer/CommandLineTools/usr/lib/libclang.dylib'
661   ]
662   libclang_found = False
663
664   for lib in libclang_locations:
665     if os.path.isfile(lib):
666       clang.cindex.Config.set_library_file(lib)
667       libclang_found = True
668       break
669
670   if not libclang_found:
671     logging.fatal('Cannot find libclang')
672     return 1
673
674   # Loop over all files
675   for fn in args:
676
677     logging.info('Input file: %s' % Colt(fn).magenta())
678     index = clang.cindex.Index.create()
679     clang_args = [ '-x', 'c++' ]
680     clang_args.extend( include_flags )
681     translation_unit = index.parse(fn, args=clang_args)
682
683     comments = []
684     traverse_ast( translation_unit.cursor, fn, comments )
685     for c in comments:
686
687       logging.debug("Comment found for entity %s:" % Colt(c.func).magenta())
688
689       if isinstance(c, MemberComment):
690
691         if c.is_transient:
692           transient_text = Colt('transient ').yellow()
693         else:
694           transient_text = ''
695
696         if c.array_size is not None:
697           array_text = Colt('arraysize=%s ' % c.array_size).yellow()
698         else:
699           array_text = ''
700
701         logging.debug(
702           "%s %s%s{%s}" % ( \
703             Colt("[%d,%d]" % (c.first_line, c.first_col)).green(),
704             transient_text,
705             array_text,
706             Colt(c.lines[0]).cyan()
707         ))
708
709       elif isinstance(c, RemoveComment):
710
711         logging.debug( Colt('[%d,%d]' % (c.first_line, c.last_line)).green() )
712
713       else:
714         for l in c.lines:
715           logging.debug(
716             Colt("[%d,%d:%d,%d] " % (c.first_line, c.first_col, c.last_line, c.last_col)).green() +
717             "{%s}" % Colt(l).cyan()
718           )
719
720     try:
721
722       if output_on_stdout:
723         with open(fn, 'r') as fhin:
724           rewrite_comments( fhin, sys.stdout, comments )
725       else:
726         fn_back = fn + '.thtml2doxy_backup'
727         os.rename( fn, fn_back )
728
729         with open(fn_back, 'r') as fhin, open(fn, 'w') as fhout:
730           rewrite_comments( fhin, fhout, comments )
731
732         os.remove( fn_back )
733         logging.info("File %s converted to Doxygen: check differences before committing!" % Colt(fn).magenta())
734     except (IOError,OSError) as e:
735       logging.error('File operation failed: %s' % e)
736
737   return 0
738
739
740 if __name__ == '__main__':
741   sys.exit( main( sys.argv[1:] ) )