]> git.uio.no Git - u/mrichter/AliRoot.git/blob - doxygen/thtml2doxy.py
doxy: some classes use Origin: instead of Author:
[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 hashlib
41 import clang.cindex
42
43
44 ## Brain-dead color output for terminal.
45 class Colt(str):
46
47   def red(self):
48     return self.color('\033[31m')
49
50   def green(self):
51     return self.color('\033[32m')
52
53   def yellow(self):
54     return self.color('\033[33m')
55
56   def blue(self):
57     return self.color('\033[34m')
58
59   def magenta(self):
60     return self.color('\033[35m')
61
62   def cyan(self):
63     return self.color('\033[36m')
64
65   def color(self, c):
66     return c + self + '\033[m'
67
68
69 ## Comment.
70 class Comment(object):
71
72   def __init__(self, lines, first_line, first_col, last_line, last_col, indent, func, \
73     append_empty=True):
74
75     assert first_line > 0 and last_line >= first_line, 'Wrong line numbers'
76     self.lines = lines
77     self.first_line = first_line
78     self.first_col = first_col
79     self.last_line = last_line
80     self.last_col = last_col
81     self.indent = indent
82     self.func = func
83     self.append_empty = append_empty
84
85   def has_comment(self, line):
86     return line >= self.first_line and line <= self.last_line
87
88   def __str__(self):
89     return "<%s for %s: [%d,%d:%d,%d] %s>" % ( \
90       self.__class__.__name__, self.func,
91       self.first_line, self.first_col, self.last_line, self.last_col,
92       self.lines)
93
94
95 ## Prepend comment.
96 class PrependComment(Comment):
97
98   def __init__(self, lines, first_line, first_col, last_line, last_col, indent, func, \
99     append_empty=False):
100     super(PrependComment, self).__init__( \
101       lines, first_line, first_col, last_line, last_col, indent, func, append_empty)
102
103
104 ## A data member comment.
105 class MemberComment:
106
107   def __init__(self, text, comment_flag, array_size, first_line, first_col, func):
108     assert first_line > 0, 'Wrong line number'
109     assert comment_flag is None or comment_flag == '!' or comment_flag in [ '!', '||', '->' ]
110     self.lines = [ text ]
111     self.comment_flag = comment_flag
112     self.array_size = array_size
113     self.first_line = first_line
114     self.first_col = first_col
115     self.func = func
116
117   def is_transient(self):
118     return self.comment_flag == '!'
119
120   def is_dontsplit(self):
121     return self.comment_flag == '||'
122
123   def is_ptr(self):
124     return self.comment_flag == '->'
125
126   def has_comment(self, line):
127     return line == self.first_line
128
129   def __str__(self):
130
131     if self.is_transient():
132       tt = '!transient! '
133     elif self.is_dontsplit():
134       tt = '!dontsplit! '
135     elif self.is_ptr():
136       tt = '!ptr! '
137     else:
138       tt = ''
139
140     if self.array_size is not None:
141       ars = '[%s] ' % self.array_size
142     else:
143       ars = ''
144
145     return "<MemberComment for %s: [%d,%d] %s%s%s>" % (self.func, self.first_line, self.first_col, tt, ars, self.lines[0])
146
147
148 ## A dummy comment that removes comment lines.
149 class RemoveComment(Comment):
150
151   def __init__(self, first_line, last_line):
152     assert first_line > 0 and last_line >= first_line, 'Wrong line numbers'
153     self.first_line = first_line
154     self.last_line = last_line
155     self.func = '<remove>'
156
157   def __str__(self):
158     return "<RemoveComment: [%d,%d]>" % (self.first_line, self.last_line)
159
160
161 ## Parses method comments.
162 #
163 #  @param cursor   Current libclang parser cursor
164 #  @param comments Array of comments: new ones will be appended there
165 def comment_method(cursor, comments):
166
167   # we are looking for the following structure: method -> compound statement -> comment, i.e. we
168   # need to extract the first comment in the compound statement composing the method
169
170   in_compound_stmt = False
171   expect_comment = False
172   emit_comment = False
173
174   comment = []
175   comment_function = cursor.spelling or cursor.displayname
176   comment_line_start = -1
177   comment_line_end = -1
178   comment_col_start = -1
179   comment_col_end = -1
180   comment_indent = -1
181
182   for token in cursor.get_tokens():
183
184     if token.cursor.kind == clang.cindex.CursorKind.COMPOUND_STMT:
185       if not in_compound_stmt:
186         in_compound_stmt = True
187         expect_comment = True
188         comment_line_end = -1
189     else:
190       if in_compound_stmt:
191         in_compound_stmt = False
192         emit_comment = True
193
194     # tkind = str(token.kind)[str(token.kind).index('.')+1:]
195     # ckind = str(token.cursor.kind)[str(token.cursor.kind).index('.')+1:]
196
197     if in_compound_stmt:
198
199       if expect_comment:
200
201         extent = token.extent
202         line_start = extent.start.line
203         line_end = extent.end.line
204
205         if token.kind == clang.cindex.TokenKind.PUNCTUATION and token.spelling == '{':
206           pass
207
208         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)):
209           comment_line_end = line_end
210           comment_col_end = extent.end.column
211
212           if comment_indent == -1 or (extent.start.column-1) < comment_indent:
213             comment_indent = extent.start.column-1
214
215           if comment_line_start == -1:
216             comment_line_start = line_start
217             comment_col_start = extent.start.column
218           comment.extend( token.spelling.split('\n') )
219
220           # multiline comments are parsed in one go, therefore don't expect subsequent comments
221           if line_end - line_start > 0:
222             emit_comment = True
223             expect_comment = False
224
225         else:
226           emit_comment = True
227           expect_comment = False
228
229     if emit_comment:
230
231       if comment_line_start > 0:
232
233         comment = refactor_comment( comment, infilename=str(cursor.location.file) )
234
235         if len(comment) > 0:
236           logging.debug("Comment found for function %s" % Colt(comment_function).magenta())
237           comments.append( Comment(comment, comment_line_start, comment_col_start, comment_line_end, comment_col_end, comment_indent, comment_function) )
238         else:
239           logging.debug('Empty comment found for function %s: collapsing' % Colt(comment_function).magenta())
240           comments.append( Comment([''], comment_line_start, comment_col_start, comment_line_end, comment_col_end, comment_indent, comment_function) )
241           #comments.append(RemoveComment(comment_line_start, comment_line_end))
242
243       else:
244         logging.warning('No comment found for function %s' % Colt(comment_function).magenta())
245
246       comment = []
247       comment_line_start = -1
248       comment_line_end = -1
249       comment_col_start = -1
250       comment_col_end = -1
251       comment_indent = -1
252
253       emit_comment = False
254       break
255
256
257 ## Parses comments to class data members.
258 #
259 #  @param cursor   Current libclang parser cursor
260 #  @param comments Array of comments: new ones will be appended there
261 def comment_datamember(cursor, comments):
262
263   # Note: libclang 3.5 seems to have problems parsing a certain type of FIELD_DECL, so we revert
264   # to a partial manual parsing. When parsing fails, the cursor's "extent" is not set properly,
265   # returning a line range 0-0. We therefore make the not-so-absurd assumption that the datamember
266   # definition is fully on one line, and we take the line number from cursor.location.
267
268   line_num = cursor.location.line
269   raw = None
270   prev = None
271   found = False
272
273   # Huge overkill: current line saved in "raw", previous in "prev"
274   with open(str(cursor.location.file)) as fp:
275     cur_line = 0
276     for raw in fp:
277       cur_line = cur_line + 1
278       if cur_line == line_num:
279         found = True
280         break
281       prev = raw
282
283   assert found, 'A line that should exist was not found in file' % cursor.location.file
284
285   recomm = r'(//(!|\|\||->)|///?)(\[(.+?)\])?<?\s*(.*?)\s*$'
286   recomm_prevline = r'^\s*///\s*(.*?)\s*$'
287
288   mcomm = re.search(recomm, raw)
289   if mcomm:
290     # If it does not match, we do not have a comment
291     member_name = cursor.spelling;
292     comment_flag = mcomm.group(2)
293     array_size = mcomm.group(4)
294     text = mcomm.group(5)
295
296     col_num = mcomm.start()+1;
297
298     if array_size is not None and prev is not None:
299       # ROOT arrays with comments already converted to Doxygen have the member description on the
300       # previous line
301       mcomm_prevline = re.search(recomm_prevline, prev)
302       if mcomm_prevline:
303         text = mcomm_prevline.group(1)
304         comments.append(RemoveComment(line_num-1, line_num-1))
305
306     logging.debug('Comment found for member %s' % Colt(member_name).magenta())
307
308     comments.append( MemberComment(
309       text,
310       comment_flag,
311       array_size,
312       line_num,
313       col_num,
314       member_name ))
315
316
317 ## Parses class description (beginning of file).
318 #
319 #  The clang parser does not work in this case so we do it manually, but it is very simple: we keep
320 #  the first consecutive sequence of single-line comments (//) we find - provided that it occurs
321 #  before any other comment found so far in the file (the comments array is inspected to ensure
322 #  this).
323 #
324 #  Multi-line comments (/* ... */) are not considered as they are commonly used to display
325 #  copyright notice.
326 #
327 #  @param filename Name of the current file
328 #  @param comments Array of comments: new ones will be appended there
329 #  @param look_no_further_than_line Stop before reaching this line when looking for class comment
330 def comment_classdesc(filename, comments, look_no_further_than_line):
331
332   recomm = r'^\s*///?(\s*.*?)\s*/*\s*$'
333
334   reclass_doxy = r'(?i)^\s*\\(class|file):?\s*([^.]*)'
335   class_name_doxy = None
336
337   reauthor = r'(?i)^\s*\\?(authors?|origin):?\s*(.*?)\s*(,?\s*([0-9./-]+))?\s*$'
338   redate = r'(?i)^\s*\\?date:?\s*([0-9./-]+)\s*$'
339   author = None
340   date = None
341
342   comment_lines = []
343
344   start_line = -1
345   end_line = -1
346
347   line_num = 0
348
349   is_macro = filename.endswith('.C')
350
351   with open(filename, 'r') as fp:
352
353     for raw in fp:
354
355       line_num = line_num + 1
356
357       if look_no_further_than_line is not None and line_num == look_no_further_than_line:
358         logging.debug('Stopping at line %d while looking for class/file description' % \
359           look_no_further_than_line)
360         break
361
362       if raw.strip() == '' and start_line > 0:
363         # Skip empty lines
364         continue
365
366       stripped = strip_html(raw)
367       mcomm = re.search(recomm, stripped)
368       if mcomm:
369
370         if start_line == -1:
371
372           # First line. Check that we do not overlap with other comments
373           comment_overlaps = False
374           for c in comments:
375             if c.has_comment(line_num):
376               comment_overlaps = True
377               break
378
379           if comment_overlaps:
380             # No need to look for other comments
381             break
382
383           start_line = line_num
384
385         end_line = line_num
386         append = True
387
388         mclass_doxy = re.search(reclass_doxy, mcomm.group(1))
389         if mclass_doxy:
390           class_name_doxy = mclass_doxy.group(2)
391           append = False
392         else:
393           mauthor = re.search(reauthor, mcomm.group(1))
394           if mauthor:
395             author = mauthor.group(2)
396             if date is None:
397               # Date specified in the standalone \date field has priority
398               date = mauthor.group(4)
399             append = False
400           else:
401             mdate = re.search(redate, mcomm.group(1))
402             if mdate:
403               date = mdate.group(1)
404               append = False
405
406         if append:
407           comment_lines.append( mcomm.group(1) )
408
409       else:
410         if start_line > 0:
411           break
412
413   if class_name_doxy is None:
414
415     # No \class specified: guess it from file name
416     reclass = r'^(.*/)?(.*?)(\..*)?$'
417     mclass = re.search( reclass, filename )
418     if mclass:
419       class_name_doxy = mclass.group(2)
420     else:
421       assert False, 'Regexp unable to extract classname from file'
422
423   # Macro or class?
424   if is_macro:
425     file_class_line = '\\file ' + class_name_doxy + '.C'
426   else:
427     file_class_line = '\\class ' + class_name_doxy
428
429   if start_line > 0:
430
431     # Prepend \class or \file specifier (and an empty line)
432     comment_lines[:0] = [ file_class_line ]
433     comment_lines.append('')
434
435     # Append author and date if they exist
436     if author is not None:
437       comment_lines.append( '\\author ' + author )
438
439     if date is not None:
440       comment_lines.append( '\\date ' + date )
441
442     comment_lines = refactor_comment(comment_lines, do_strip_html=False, infilename=filename)
443     logging.debug('Comment found for class %s' % Colt(class_name_doxy).magenta())
444     comments.append(Comment(
445       comment_lines,
446       start_line, 1, end_line, 1,
447       0, class_name_doxy
448     ))
449
450   else:
451
452     logging.warning('No comment found for class %s: creating a dummy entry at the beginning' % \
453       Colt(class_name_doxy).magenta())
454
455     comments.append(PrependComment(
456       [ file_class_line ],
457       1, 1, 1, 1,
458       0, class_name_doxy, append_empty=True
459     ))
460
461
462 ## Looks for a special ROOT ClassImp() entry.
463 #
464 #  Doxygen might get confused by `ClassImp()` entries as they are macros normally written without
465 #  the ending `;`: this function wraps the definition inside a condition in order to make Doxygen
466 #  ignore it.
467 #
468 #  @param filename Name of the current file
469 #  @param comments Array of comments: new ones will be appended there
470 def comment_classimp(filename, comments):
471
472   recomm = r'^\s*///?(\s*.*?)\s*/*\s*$'
473
474   line_num = 0
475   reclassimp = r'^(\s*)ClassImp\((.*?)\)\s*;?\s*$'
476
477   in_classimp_cond = False
478   restartcond = r'^\s*///\s*\\cond\s+CLASSIMP\s*$'
479   reendcond = r'^\s*///\s*\\endcond\s*$'
480
481   with open(filename, 'r') as fp:
482
483     line_classimp = -1
484     line_startcond = -1
485     line_endcond = -1
486     classimp_class = None
487     classimp_indent = None
488
489     for line in fp:
490
491       line_num = line_num + 1
492
493       mclassimp = re.search(reclassimp, line)
494       if mclassimp:
495
496         # Adjust indent
497         classimp_indent = len( mclassimp.group(1) )
498
499         line_classimp = line_num
500         classimp_class = mclassimp.group(2)
501         logging.debug(
502           'Comment found for ' +
503           Colt( 'ClassImp(' ).magenta() +
504           Colt( classimp_class ).cyan() +
505           Colt( ')' ).magenta() )
506
507       else:
508
509         mstartcond = re.search(restartcond, line)
510         if mstartcond:
511           logging.debug('Found Doxygen opening condition for ClassImp in {%s}' % line)
512           in_classimp_cond = True
513           line_startcond = line_num
514
515         elif in_classimp_cond:
516
517           mendcond = re.search(reendcond, line)
518           if mendcond:
519             logging.debug('Found Doxygen closing condition for ClassImp')
520             in_classimp_cond = False
521             line_endcond = line_num
522
523   # Did we find something?
524   if line_classimp != -1:
525
526     if line_startcond != -1:
527       comments.append(Comment(
528         ['\cond CLASSIMP'],
529         line_startcond, 1, line_startcond, 1,
530         classimp_indent, 'ClassImp(%s)' % classimp_class,
531         append_empty=False
532       ))
533     else:
534       comments.append(PrependComment(
535         ['\cond CLASSIMP'],
536         line_classimp, 1, line_classimp, 1,
537         classimp_indent, 'ClassImp(%s)' % classimp_class
538       ))
539
540     if line_endcond != -1:
541       comments.append(Comment(
542         ['\endcond'],
543         line_endcond, 1, line_endcond, 1,
544         classimp_indent, 'ClassImp(%s)' % classimp_class,
545         append_empty=False
546       ))
547     else:
548       comments.append(PrependComment(
549         ['\endcond'],
550         line_classimp+1, 1, line_classimp+1, 1,
551         classimp_indent, 'ClassImp(%s)' % classimp_class
552       ))
553
554
555 ## Traverse the AST recursively starting from the current cursor.
556 #
557 #  @param cursor    A Clang parser cursor
558 #  @param filename  Name of the current file
559 #  @param comments  Array of comments: new ones will be appended there
560 #  @param recursion Current recursion depth
561 #  @param in_func   True if we are inside a function or method
562 #  @param classdesc_line_limit  Do not look for comments after this line
563 #
564 #  @return A tuple containing the classdesc_line_limit as first item
565 def traverse_ast(cursor, filename, comments, recursion=0, in_func=False, classdesc_line_limit=None):
566
567   # libclang traverses included files as well: we do not want this behavior
568   if cursor.location.file is not None and str(cursor.location.file) != filename:
569     logging.debug("Skipping processing of included %s" % cursor.location.file)
570     return
571
572   text = cursor.spelling or cursor.displayname
573   kind = str(cursor.kind)[str(cursor.kind).index('.')+1:]
574
575   is_macro = filename.endswith('.C')
576
577   indent = ''
578   for i in range(0, recursion):
579     indent = indent + '  '
580
581   if cursor.kind in [ clang.cindex.CursorKind.CXX_METHOD, clang.cindex.CursorKind.CONSTRUCTOR,
582     clang.cindex.CursorKind.DESTRUCTOR, clang.cindex.CursorKind.FUNCTION_DECL ]:
583
584     if classdesc_line_limit is None:
585       classdesc_line_limit = cursor.location.line
586
587     # cursor ran into a C++ method
588     logging.debug( "%5d %s%s(%s)" % (cursor.location.line, indent, Colt(kind).magenta(), Colt(text).blue()) )
589     comment_method(cursor, comments)
590     in_func = True
591
592   elif not is_macro and not in_func and \
593     cursor.kind in [ clang.cindex.CursorKind.FIELD_DECL, clang.cindex.CursorKind.VAR_DECL ]:
594
595     if classdesc_line_limit is None:
596       classdesc_line_limit = cursor.location.line
597
598     # cursor ran into a data member declaration
599     logging.debug( "%5d %s%s(%s)" % (cursor.location.line, indent, Colt(kind).magenta(), Colt(text).blue()) )
600     comment_datamember(cursor, comments)
601
602   else:
603
604     logging.debug( "%5d %s%s(%s)" % (cursor.location.line, indent, kind, text) )
605
606   for child_cursor in cursor.get_children():
607     classdesc_line_limit = traverse_ast(child_cursor, filename, comments, recursion+1, in_func, classdesc_line_limit)
608
609   if recursion == 0:
610     comment_classimp(filename, comments)
611     comment_classdesc(filename, comments, classdesc_line_limit)
612
613   return classdesc_line_limit
614
615
616 ## Strip some HTML tags from the given string. Returns clean string.
617 #
618 #  @param s Input string
619 def strip_html(s):
620   rehtml = r'(?i)</?(P|BR)/?>'
621   return re.sub(rehtml, '', s)
622
623
624 ## Remove garbage from comments and convert special tags from THtml to Doxygen.
625 #
626 #  @param comment An array containing the lines of the original comment
627 def refactor_comment(comment, do_strip_html=True, infilename=None):
628
629   recomm = r'^(/{2,}|/\*)? ?(\s*.*?)\s*((/{2,})?\s*|\*/)$'
630   regarbage = r'^(?i)\s*([\s*=-_#]+|(Begin|End)_Html)\s*$'
631
632   # Support for LaTeX blocks spanning on multiple lines
633   relatex = r'(?i)^((.*?)\s+)?(BEGIN|END)_LATEX([.,;:\s]+.*)?$'
634   in_latex = False
635   latex_block = False
636
637   # Support for LaTeX blocks on a single line
638   reinline_latex = r'(?i)(.*)BEGIN_LATEX\s+(.*?)\s+END_LATEX(.*)$'
639
640   # Match <pre> (to turn it into the ~~~ Markdown syntax)
641   reblock = r'(?i)^(\s*)</?PRE>\s*$'
642
643   # Macro blocks for pictures generation
644   in_macro = False
645   current_macro = []
646   remacro = r'(?i)^\s*(BEGIN|END)_MACRO(\((.*?)\))?\s*$'
647
648   new_comment = []
649   insert_blank = False
650   wait_first_non_blank = True
651   for line_comment in comment:
652
653     # Check if we are in a macro block
654     mmacro = re.search(remacro, line_comment)
655     if mmacro:
656       if in_macro:
657         in_macro = False
658
659         # Dump macro
660         outimg = write_macro(infilename, current_macro) + '.png'
661         current_macro = []
662
663         # Insert image
664         new_comment.append( '![Picture from ROOT macro](%s)' % (outimg) )
665
666         logging.debug( 'Found macro for generating image %s' % Colt(outimg).magenta() )
667
668       else:
669         in_macro = True
670
671       continue
672     elif in_macro:
673       current_macro.append( line_comment )
674       continue
675
676     # Strip some HTML tags
677     if do_strip_html:
678       line_comment = strip_html(line_comment)
679
680     mcomm = re.search( recomm, line_comment )
681     if mcomm:
682       new_line_comment = mcomm.group(2)
683       mgarbage = re.search( regarbage, new_line_comment )
684
685       if new_line_comment == '' or mgarbage is not None:
686         insert_blank = True
687       else:
688         if insert_blank and not wait_first_non_blank:
689           new_comment.append('')
690         insert_blank = False
691         wait_first_non_blank = False
692
693         # Postprocessing: LaTeX formulas in ROOT format
694         # Marked by BEGIN_LATEX ... END_LATEX and they use # in place of \
695         # There can be several ROOT LaTeX forumlas per line
696         while True:
697           minline_latex = re.search( reinline_latex, new_line_comment )
698           if minline_latex:
699             new_line_comment = '%s\\f$%s\\f$%s' % \
700               ( minline_latex.group(1), minline_latex.group(2).replace('#', '\\'),
701                 minline_latex.group(3) )
702           else:
703             break
704
705         # ROOT LaTeX: do we have a Begin/End_LaTeX block?
706         # Note: the presence of LaTeX "closures" does not exclude the possibility to have a begin
707         # block here left without a corresponding ending block
708         mlatex = re.search( relatex, new_line_comment )
709         if mlatex:
710
711           # before and after parts have been already stripped
712           l_before = mlatex.group(2)
713           l_after = mlatex.group(4)
714           is_begin = mlatex.group(3).upper() == 'BEGIN'  # if not, END
715
716           if l_before is None:
717             l_before = ''
718           if l_after is None:
719             l_after = ''
720
721           if is_begin:
722
723             # Begin of LaTeX part
724
725             in_latex = True
726             if l_before == '' and l_after == '':
727
728               # Opening tag alone: mark the beginning of a block: \f[ ... \f]
729               latex_block = True
730               new_comment.append( '\\f[' )
731
732             else:
733               # Mark the beginning of inline: \f$ ... \f$
734               latex_block = False
735               new_comment.append(
736                 '%s \\f$%s' % ( l_before, l_after.replace('#', '\\') )
737               )
738
739           else:
740
741             # End of LaTeX part
742             in_latex = False
743
744             if latex_block:
745
746               # Closing a LaTeX block
747               if l_before != '':
748                 new_comment.append( l_before.replace('#', '\\') )
749               new_comment.append( '\\f]' )
750               if l_after != '':
751                 new_comment.append( l_after )
752
753             else:
754
755               # Closing a LaTeX inline
756               new_comment.append(
757                 '%s\\f$%s' % ( l_before.replace('#', '\\'), l_after )
758               )
759
760           # Prevent appending lines (we have already done that)
761           new_line_comment = None
762
763         # If we are not in a LaTeX block, look for <pre> tags and transform them into Doxygen code
764         # blocks (using ~~~ ... ~~~). Only <pre> tags on a single line are supported
765         if new_line_comment is not None and not in_latex:
766
767           mblock = re.search( reblock, new_line_comment  )
768           if mblock:
769             new_comment.append( mblock.group(1)+'~~~' )
770             new_line_comment = None
771
772         if new_line_comment is not None:
773           if in_latex:
774             new_line_comment = new_line_comment.replace('#', '\\')
775           new_comment.append( new_line_comment )
776
777     else:
778       assert False, 'Comment regexp does not match'
779
780   return new_comment
781
782
783 ## Dumps an image-generating macro to the correct place. Returns a string with the image path,
784 #  without the extension.
785 #
786 #  @param infilename  File name of the source file
787 #  @param macro_lines Array of macro lines
788 def write_macro(infilename, macro_lines):
789
790   # Calculate hash
791   digh = hashlib.sha1()
792   for l in macro_lines:
793     digh.update(l)
794     digh.update('\n')
795   short_digest = digh.hexdigest()[0:7]
796
797   outdir = '%s/imgdoc' % os.path.dirname(infilename)
798   outprefix = '%s/%s_%s' % (
799     outdir,
800     os.path.basename(infilename).replace('.', '_'),
801     short_digest
802   )
803   outmacro = '%s.C' % outprefix
804
805   # Make directory
806   if not os.path.isdir(outdir):
807     # do not catch: let everything die on error
808     logging.debug('Creating directory %s' % Colt(outdir).magenta())
809     os.mkdir(outdir)
810
811   # Create file (do not catch errors either)
812   with open(outmacro, 'w') as omfp:
813     logging.debug('Writing macro %s' % Colt(outmacro).magenta())
814     for l in macro_lines:
815       omfp.write(l)
816       omfp.write('\n')
817
818   return outprefix
819
820
821 ## Rewrites all comments from the given file handler.
822 #
823 #  @param fhin     The file handler to read from
824 #  @param fhout    The file handler to write to
825 #  @param comments Array of comments
826 def rewrite_comments(fhin, fhout, comments):
827
828   line_num = 0
829   in_comment = False
830   skip_empty = False
831   comm = None
832   prev_comm = None
833   restore_lines = None
834
835   rindent = r'^(\s*)'
836
837   def dump_comment_block(cmt, restore=None):
838     text_indent = ''
839     ask_skip_empty = False
840
841     for i in range(0, cmt.indent):
842       text_indent = text_indent + ' '
843
844     for lc in cmt.lines:
845       fhout.write('%s///' % text_indent )
846       lc = lc.rstrip()
847       if len(lc) != 0:
848         fhout.write(' ')
849         fhout.write(lc)
850       fhout.write('\n')
851
852     # Empty new line at the end of the comment
853     if cmt.append_empty:
854       fhout.write('\n')
855       ask_skip_empty = True
856
857     # Restore lines if possible
858     if restore:
859       for lr in restore:
860         fhout.write(lr)
861         fhout.write('\n')
862
863     # Tell the caller whether it should skip the next empty line found
864     return ask_skip_empty
865
866
867   for line in fhin:
868
869     line_num = line_num + 1
870
871     # Find current comment
872     prev_comm = comm
873     comm = None
874     for c in comments:
875       if c.has_comment(line_num):
876         comm = c
877
878     if comm:
879
880       # First thing to check: are we in the same comment as before?
881       if comm is not prev_comm and isinstance(comm, Comment) and isinstance(prev_comm, Comment) \
882         and not isinstance(prev_comm, RemoveComment):
883
884         skip_empty = dump_comment_block(prev_comm, restore_lines)
885         in_comment = False
886         restore_lines = None
887         prev_comm = None  # we have just dumped it: pretend it never existed in this loop
888
889       #
890       # Check type of comment and react accordingly
891       #
892
893       if isinstance(comm, MemberComment):
894
895         # end comment block
896         if in_comment:
897           skip_empty = dump_comment_block(prev_comm, restore_lines)
898           in_comment = False
899           restore_lines = None
900
901         non_comment = line[ 0:comm.first_col-1 ]
902
903         if comm.array_size is not None or comm.is_dontsplit() or comm.is_ptr():
904
905           # This is a special case: comment will be split in two lines: one before the comment for
906           # Doxygen as "member description", and the other right after the comment on the same line
907           # to be parsed by ROOT's C++ parser
908
909           # Keep indent on the generated line of comment before member definition
910           mindent = re.search(rindent, line)
911
912           # Get correct comment flag, if any
913           if comm.comment_flag is not None:
914             cflag = comm.comment_flag
915           else:
916             cflag = ''
917
918           # Get correct array size, if any
919           if comm.array_size is not None:
920             asize = '[%s]' % comm.array_size
921           else:
922             asize = ''
923
924           # Write on two lines
925           fhout.write('%s/// %s\n%s//%s%s\n' % (
926             mindent.group(1),
927             comm.lines[0],
928             non_comment,
929             cflag,
930             asize
931           ))
932
933         else:
934
935           # Single-line comments with the "transient" flag can be kept on one line in a way that
936           # they are correctly interpreted by both ROOT and Doxygen
937
938           if comm.is_transient():
939             tt = '!'
940           else:
941             tt = '/'
942
943           fhout.write('%s//%s< %s\n' % (
944             non_comment,
945             tt,
946             comm.lines[0]
947           ))
948
949       elif isinstance(comm, RemoveComment):
950         # End comment block and skip this line
951         if in_comment:
952           skip_empty = dump_comment_block(prev_comm, restore_lines)
953           in_comment = False
954           restore_lines = None
955
956       elif prev_comm is None:
957
958         # Beginning of a new comment block of type Comment or PrependComment
959         in_comment = True
960
961         if isinstance(comm, PrependComment):
962           # Prepare array of lines to dump right after the comment
963           restore_lines = [ line.rstrip('\n') ]
964         else:
965           # Extract the non-comment part and print it if it exists
966           non_comment = line[ 0:comm.first_col-1 ].rstrip()
967           if non_comment != '':
968             fhout.write( non_comment + '\n' )
969
970       elif isinstance(comm, Comment):
971
972         if restore_lines is not None:
973           # From the 2nd line on of comment to prepend
974           restore_lines.append( line.rstrip('\n') )
975
976       else:
977         assert False, 'Unhandled parser state. line=%d comm=%s prev_comm=%s' % \
978           (line_num, comm, prev_comm)
979
980     else:
981
982       # Not a comment line
983
984       if in_comment:
985
986         # We have just exited a comment block of type Comment
987         skip_empty = dump_comment_block(prev_comm, restore_lines)
988         in_comment = False
989         restore_lines = None
990
991       # Dump the non-comment line
992       line_out = line.rstrip('\n')
993       if skip_empty:
994         skip_empty = False
995         if line_out.strip() != '':
996           fhout.write( line_out + '\n' )
997       else:
998         fhout.write( line_out + '\n' )
999
1000
1001 ## The main function.
1002 #
1003 #  Return value is the executable's return value.
1004 def main(argv):
1005
1006   # Setup logging on stderr
1007   log_level = logging.INFO
1008   logging.basicConfig(
1009     level=log_level,
1010     format='%(levelname)-8s %(funcName)-20s %(message)s',
1011     stream=sys.stderr
1012   )
1013
1014   # Parse command-line options
1015   output_on_stdout = False
1016   include_flags = []
1017   try:
1018     opts, args = getopt.getopt( argv, 'odI:', [ 'debug=', 'stdout' ] )
1019     for o, a in opts:
1020       if o == '--debug':
1021         log_level = getattr( logging, a.upper(), None )
1022         if not isinstance(log_level, int):
1023           raise getopt.GetoptError('log level must be one of: DEBUG, INFO, WARNING, ERROR, CRITICAL')
1024       elif o == '-d':
1025         log_level = logging.DEBUG
1026       elif o == '-o' or o == '--stdout':
1027         output_on_stdout = True
1028       elif o == '-I':
1029         if os.path.isdir(a):
1030           include_flags.extend( [ '-I', a ] )
1031         else:
1032           logging.fatal('Include directory not found: %s' % Colt(a).magenta())
1033           return 2
1034       else:
1035         assert False, 'Unhandled argument'
1036   except getopt.GetoptError as e:
1037     logging.fatal('Invalid arguments: %s' % e)
1038     return 1
1039
1040   logging.getLogger('').setLevel(log_level)
1041
1042   # Attempt to load libclang from a list of known locations
1043   libclang_locations = [
1044     '/usr/lib/llvm-3.5/lib/libclang.so.1',
1045     '/usr/lib/libclang.so',
1046     '/Library/Developer/CommandLineTools/usr/lib/libclang.dylib'
1047   ]
1048   libclang_found = False
1049
1050   for lib in libclang_locations:
1051     if os.path.isfile(lib):
1052       clang.cindex.Config.set_library_file(lib)
1053       libclang_found = True
1054       break
1055
1056   if not libclang_found:
1057     logging.fatal('Cannot find libclang')
1058     return 1
1059
1060   # Loop over all files
1061   for fn in args:
1062
1063     logging.info('Input file: %s' % Colt(fn).magenta())
1064     index = clang.cindex.Index.create()
1065     clang_args = [ '-x', 'c++' ]
1066     clang_args.extend( include_flags )
1067     translation_unit = index.parse(fn, args=clang_args)
1068
1069     comments = []
1070     traverse_ast( translation_unit.cursor, fn, comments )
1071     for c in comments:
1072
1073       logging.debug("Comment found for entity %s:" % Colt(c.func).magenta())
1074
1075       if isinstance(c, MemberComment):
1076
1077         if c.is_transient():
1078           flag_text = Colt('transient ').yellow()
1079         elif c.is_dontsplit():
1080           flag_text = Colt('dontsplit ').yellow()
1081         elif c.is_ptr():
1082           flag_text = Colt('ptr ').yellow()
1083         else:
1084           flag_text = ''
1085
1086         if c.array_size is not None:
1087           array_text = Colt('arraysize=%s ' % c.array_size).yellow()
1088         else:
1089           array_text = ''
1090
1091         logging.debug(
1092           "%s %s%s{%s}" % ( \
1093             Colt("[%d,%d]" % (c.first_line, c.first_col)).green(),
1094             flag_text,
1095             array_text,
1096             Colt(c.lines[0]).cyan()
1097         ))
1098
1099       elif isinstance(c, RemoveComment):
1100
1101         logging.debug( Colt('[%d,%d]' % (c.first_line, c.last_line)).green() )
1102
1103       else:
1104         for l in c.lines:
1105           logging.debug(
1106             Colt("[%d,%d:%d,%d] " % (c.first_line, c.first_col, c.last_line, c.last_col)).green() +
1107             "{%s}" % Colt(l).cyan()
1108           )
1109
1110     try:
1111
1112       if output_on_stdout:
1113         with open(fn, 'r') as fhin:
1114           rewrite_comments( fhin, sys.stdout, comments )
1115       else:
1116         fn_back = fn + '.thtml2doxy_backup'
1117         os.rename( fn, fn_back )
1118
1119         with open(fn_back, 'r') as fhin, open(fn, 'w') as fhout:
1120           rewrite_comments( fhin, fhout, comments )
1121
1122         os.remove( fn_back )
1123         logging.info("File %s converted to Doxygen: check differences before committing!" % Colt(fn).magenta())
1124     except (IOError,OSError) as e:
1125       logging.error('File operation failed: %s' % e)
1126
1127   return 0
1128
1129
1130 if __name__ == '__main__':
1131   sys.exit( main( sys.argv[1:] ) )