]> git.uio.no Git - u/mrichter/AliRoot.git/blob - doxygen/thtml2doxy.py
doxy: images from TPCbase
[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   rebrief = r'(?i)^\s*\\brief\s*(.*)\s*$'
340   author = None
341   date = None
342   brief = None
343   brief_len_threshold = 80
344
345   comment_lines = []
346
347   start_line = -1
348   end_line = -1
349
350   line_num = 0
351
352   is_macro = filename.endswith('.C')
353
354   with open(filename, 'r') as fp:
355
356     for raw in fp:
357
358       line_num = line_num + 1
359
360       if look_no_further_than_line is not None and line_num == look_no_further_than_line:
361         logging.debug('Stopping at line %d while looking for class/file description' % \
362           look_no_further_than_line)
363         break
364
365       if raw.strip() == '' and start_line > 0:
366         # Skip empty lines
367         continue
368
369       stripped = strip_html(raw)
370       mcomm = re.search(recomm, stripped)
371       if mcomm:
372
373         if start_line == -1:
374
375           # First line. Check that we do not overlap with other comments
376           comment_overlaps = False
377           for c in comments:
378             if c.has_comment(line_num):
379               comment_overlaps = True
380               break
381
382           if comment_overlaps:
383             # No need to look for other comments
384             break
385
386           start_line = line_num
387
388         end_line = line_num
389         append = True
390
391         mclass_doxy = re.search(reclass_doxy, mcomm.group(1))
392         if mclass_doxy:
393           class_name_doxy = mclass_doxy.group(2)
394           append = False
395         else:
396           mauthor = re.search(reauthor, mcomm.group(1))
397           if mauthor:
398             author = mauthor.group(2)
399             if date is None:
400               # Date specified in the standalone \date field has priority
401               date = mauthor.group(4)
402             append = False
403           else:
404             mdate = re.search(redate, mcomm.group(1))
405             if mdate:
406               date = mdate.group(1)
407               append = False
408             else:
409               mbrief = re.search(rebrief, mcomm.group(1))
410               if mbrief:
411                 brief = mbrief.group(1)
412                 append = False
413
414         if append:
415           comment_lines.append( mcomm.group(1) )
416
417       else:
418         if start_line > 0:
419           break
420
421   if class_name_doxy is None:
422
423     # No \class specified: guess it from file name
424     reclass = r'^(.*/)?(.*?)(\..*)?$'
425     mclass = re.search( reclass, filename )
426     if mclass:
427       class_name_doxy = mclass.group(2)
428     else:
429       assert False, 'Regexp unable to extract classname from file'
430
431   # Macro or class?
432   if is_macro:
433     file_class_line = '\\file ' + class_name_doxy + '.C'
434   else:
435     file_class_line = '\\class ' + class_name_doxy
436
437   if start_line > 0:
438
439     prepend_to_comment = []
440
441     # Prepend \class or \file specifier, then the \brief, then an empty line
442     prepend_to_comment.append( file_class_line )
443
444     if brief is not None:
445       prepend_to_comment.append( '\\brief ' + brief )
446     prepend_to_comment.append( '' )
447
448     comment_lines = prepend_to_comment + comment_lines  # join lists
449
450     # Append author and date if they exist
451     if author is not None:
452       comment_lines.append( '\\author ' + author )
453
454     if date is not None:
455       comment_lines.append( '\\date ' + date )
456
457     comment_lines = refactor_comment(comment_lines, do_strip_html=False, infilename=filename)
458
459     # Now we look for a possible \brief
460     if brief is None:
461       comm_idx = 0
462       for comm in comment_lines:
463         if comm.startswith('\\class') or comm.startswith('\\file') or comm == '':
464           pass
465         else:
466           if len(comm) <= brief_len_threshold:
467             brief = comm
468           break
469         comm_idx = comm_idx + 1
470       if brief is not None:
471         comment_lines = refactor_comment(
472           [ comment_lines[0], '\\brief ' + brief ] + comment_lines[1:comm_idx] + comment_lines[comm_idx+1:],
473           do_strip_html=False, infilename=filename)
474
475     logging.debug('Comment found for class %s' % Colt(class_name_doxy).magenta())
476     comments.append(Comment(
477       comment_lines,
478       start_line, 1, end_line, 1,
479       0, class_name_doxy
480     ))
481
482   else:
483
484     logging.warning('No comment found for class %s: creating a dummy entry at the beginning' % \
485       Colt(class_name_doxy).magenta())
486
487     comments.append(PrependComment(
488       [ file_class_line ],
489       1, 1, 1, 1,
490       0, class_name_doxy, append_empty=True
491     ))
492
493
494 ## Looks for a special ROOT ClassImp() entry.
495 #
496 #  Doxygen might get confused by `ClassImp()` entries as they are macros normally written without
497 #  the ending `;`: this function wraps the definition inside a condition in order to make Doxygen
498 #  ignore it.
499 #
500 #  @param filename Name of the current file
501 #  @param comments Array of comments: new ones will be appended there
502 def comment_classimp(filename, comments):
503
504   recomm = r'^\s*///?(\s*.*?)\s*/*\s*$'
505
506   line_num = 0
507   reclassimp = r'^(\s*)Class(Imp|Def)\((.*?)\).*$'
508
509   in_classimp_cond = False
510   restartcond = r'^\s*///\s*\\cond\s+CLASSIMP\s*$'
511   reendcond = r'^\s*///\s*\\endcond\s*$'
512
513   with open(filename, 'r') as fp:
514
515     for line in fp:
516
517       # Reset to nothing found
518       line_classimp = -1
519       line_startcond = -1
520       line_endcond = -1
521       classimp_class = None
522       classimp_indent = None
523
524       line_num = line_num + 1
525
526       mclassimp = re.search(reclassimp, line)
527       if mclassimp:
528
529         # Adjust indent
530         classimp_indent = len( mclassimp.group(1) )
531
532         line_classimp = line_num
533         classimp_class = mclassimp.group(3)
534         imp_or_def = mclassimp.group(2)
535         logging.debug(
536           'Comment found for ' +
537           Colt( 'Class%s(' % imp_or_def ).magenta() +
538           Colt( classimp_class ).cyan() +
539           Colt( ')' ).magenta() )
540
541       else:
542
543         mstartcond = re.search(restartcond, line)
544         if mstartcond:
545           logging.debug('Found Doxygen opening condition for ClassImp in {%s}' % line)
546           in_classimp_cond = True
547           line_startcond = line_num
548
549         elif in_classimp_cond:
550
551           mendcond = re.search(reendcond, line)
552           if mendcond:
553             logging.debug('Found Doxygen closing condition for ClassImp')
554             in_classimp_cond = False
555             line_endcond = line_num
556
557       # Did we find something?
558       if line_classimp != -1:
559
560         if line_startcond != -1:
561           comments.append(Comment(
562             ['\cond CLASSIMP'],
563             line_startcond, 1, line_startcond, 1,
564             classimp_indent, 'ClassImp/Def(%s)' % classimp_class,
565             append_empty=False
566           ))
567         else:
568           comments.append(PrependComment(
569             ['\cond CLASSIMP'],
570             line_classimp, 1, line_classimp, 1,
571             classimp_indent, 'ClassImp/Def(%s)' % classimp_class
572           ))
573
574         if line_endcond != -1:
575           comments.append(Comment(
576             ['\endcond'],
577             line_endcond, 1, line_endcond, 1,
578             classimp_indent, 'ClassImp/Def(%s)' % classimp_class,
579             append_empty=False
580           ))
581         else:
582           comments.append(PrependComment(
583             ['\endcond'],
584             line_classimp+1, 1, line_classimp+1, 1,
585             classimp_indent, 'ClassImp/Def(%s)' % classimp_class
586           ))
587
588
589 ## Traverse the AST recursively starting from the current cursor.
590 #
591 #  @param cursor    A Clang parser cursor
592 #  @param filename  Name of the current file
593 #  @param comments  Array of comments: new ones will be appended there
594 #  @param recursion Current recursion depth
595 #  @param in_func   True if we are inside a function or method
596 #  @param classdesc_line_limit  Do not look for comments after this line
597 #
598 #  @return A tuple containing the classdesc_line_limit as first item
599 def traverse_ast(cursor, filename, comments, recursion=0, in_func=False, classdesc_line_limit=None):
600
601   # libclang traverses included files as well: we do not want this behavior
602   if cursor.location.file is not None and str(cursor.location.file) != filename:
603     logging.debug("Skipping processing of included %s" % cursor.location.file)
604     return
605
606   text = cursor.spelling or cursor.displayname
607   kind = str(cursor.kind)[str(cursor.kind).index('.')+1:]
608
609   is_macro = filename.endswith('.C')
610
611   indent = ''
612   for i in range(0, recursion):
613     indent = indent + '  '
614
615   if cursor.kind in [ clang.cindex.CursorKind.CXX_METHOD, clang.cindex.CursorKind.CONSTRUCTOR,
616     clang.cindex.CursorKind.DESTRUCTOR, clang.cindex.CursorKind.FUNCTION_DECL ]:
617
618     if classdesc_line_limit is None:
619       classdesc_line_limit = cursor.location.line
620
621     # cursor ran into a C++ method
622     logging.debug( "%5d %s%s(%s)" % (cursor.location.line, indent, Colt(kind).magenta(), Colt(text).blue()) )
623     comment_method(cursor, comments)
624     in_func = True
625
626   elif not is_macro and not in_func and \
627     cursor.kind in [ clang.cindex.CursorKind.FIELD_DECL, clang.cindex.CursorKind.VAR_DECL ]:
628
629     if classdesc_line_limit is None:
630       classdesc_line_limit = cursor.location.line
631
632     # cursor ran into a data member declaration
633     logging.debug( "%5d %s%s(%s)" % (cursor.location.line, indent, Colt(kind).magenta(), Colt(text).blue()) )
634     comment_datamember(cursor, comments)
635
636   else:
637
638     logging.debug( "%5d %s%s(%s)" % (cursor.location.line, indent, kind, text) )
639
640   for child_cursor in cursor.get_children():
641     classdesc_line_limit = traverse_ast(child_cursor, filename, comments, recursion+1, in_func, classdesc_line_limit)
642
643   if recursion == 0:
644     comment_classimp(filename, comments)
645     comment_classdesc(filename, comments, classdesc_line_limit)
646
647   return classdesc_line_limit
648
649
650 ## Strip some HTML tags from the given string. Returns clean string.
651 #
652 #  @param s Input string
653 def strip_html(s):
654   rehtml = r'(?i)</?(P|BR)/?>'
655   return re.sub(rehtml, '', s)
656
657
658 ## Remove garbage from comments and convert special tags from THtml to Doxygen.
659 #
660 #  @param comment An array containing the lines of the original comment
661 def refactor_comment(comment, do_strip_html=True, infilename=None):
662
663   recomm = r'^(/{2,}|/\*)? ?(\s*)(.*?)\s*((/{2,})?\s*|\*/)$'
664   regarbage = r'^(?i)\s*([\s*=_#-]+|(Begin|End)_Html)\s*$'
665
666   # Support for LaTeX blocks spanning on multiple lines
667   relatex = r'(?i)^((.*?)\s+)?(BEGIN|END)_LATEX([.,;:\s]+.*)?$'
668   in_latex = False
669   latex_block = False
670
671   # Support for LaTeX blocks on a single line
672   reinline_latex = r'(?i)(.*)BEGIN_LATEX\s+(.*?)\s+END_LATEX(.*)$'
673
674   # Match <pre> (to turn it into the ~~~ Markdown syntax)
675   reblock = r'(?i)^(\s*)</?PRE>\s*$'
676
677   # Macro blocks for pictures generation
678   in_macro = False
679   current_macro = []
680   remacro = r'(?i)^\s*(BEGIN|END)_MACRO(\((.*?)\))?\s*$'
681
682   # Minimum indent level: scale back everything
683   lowest_indent_level = None
684
685   # Indentation threshold: if too much indented, don't indent at all
686   indent_level_threshold = 7
687
688   new_comment = []
689   insert_blank = False
690   wait_first_non_blank = True
691   for line_comment in comment:
692
693     # Check if we are in a macro block
694     mmacro = re.search(remacro, line_comment)
695     if mmacro:
696       if in_macro:
697         in_macro = False
698
699         # Dump macro
700         outimg = write_macro(infilename, current_macro) + '.png'
701         current_macro = []
702
703         # Insert image
704         new_comment.append( '![Picture from ROOT macro](%s)' % (os.path.basename(outimg)) )
705
706         logging.debug( 'Found macro for generating image %s' % Colt(outimg).magenta() )
707
708       else:
709         in_macro = True
710
711       continue
712     elif in_macro:
713       current_macro.append( line_comment )
714       continue
715
716     # Strip some HTML tags
717     if do_strip_html:
718       line_comment = strip_html(line_comment)
719
720     mcomm = re.search( recomm, line_comment )
721     if mcomm:
722       new_line_comment = mcomm.group(2) + mcomm.group(3)  # indent + comm
723
724       mgarbage = re.search( regarbage, new_line_comment )
725
726       if mgarbage is None and not mcomm.group(3).startswith('\\') and mcomm.group(3) != '':
727         # not a special command line: count indent
728         indent_level = len( mcomm.group(2) )
729         if lowest_indent_level is None or indent_level < lowest_indent_level:
730           lowest_indent_level = indent_level
731
732         # if indentation level is too much, consider it zero
733         if indent_level > indent_level_threshold:
734           new_line_comment = mcomm.group(3)  # remove ALL indentation
735
736       if new_line_comment == '' or mgarbage is not None:
737         insert_blank = True
738       else:
739         if insert_blank and not wait_first_non_blank:
740           new_comment.append('')
741         insert_blank = False
742         wait_first_non_blank = False
743
744         # Postprocessing: LaTeX formulas in ROOT format
745         # Marked by BEGIN_LATEX ... END_LATEX and they use # in place of \
746         # There can be several ROOT LaTeX forumlas per line
747         while True:
748           minline_latex = re.search( reinline_latex, new_line_comment )
749           if minline_latex:
750             new_line_comment = '%s\\f$%s\\f$%s' % \
751               ( minline_latex.group(1), minline_latex.group(2).replace('#', '\\'),
752                 minline_latex.group(3) )
753           else:
754             break
755
756         # ROOT LaTeX: do we have a Begin/End_LaTeX block?
757         # Note: the presence of LaTeX "closures" does not exclude the possibility to have a begin
758         # block here left without a corresponding ending block
759         mlatex = re.search( relatex, new_line_comment )
760         if mlatex:
761
762           # before and after parts have been already stripped
763           l_before = mlatex.group(2)
764           l_after = mlatex.group(4)
765           is_begin = mlatex.group(3).upper() == 'BEGIN'  # if not, END
766
767           if l_before is None:
768             l_before = ''
769           if l_after is None:
770             l_after = ''
771
772           if is_begin:
773
774             # Begin of LaTeX part
775
776             in_latex = True
777             if l_before == '' and l_after == '':
778
779               # Opening tag alone: mark the beginning of a block: \f[ ... \f]
780               latex_block = True
781               new_comment.append( '\\f[' )
782
783             else:
784               # Mark the beginning of inline: \f$ ... \f$
785               latex_block = False
786               new_comment.append(
787                 '%s \\f$%s' % ( l_before, l_after.replace('#', '\\') )
788               )
789
790           else:
791
792             # End of LaTeX part
793             in_latex = False
794
795             if latex_block:
796
797               # Closing a LaTeX block
798               if l_before != '':
799                 new_comment.append( l_before.replace('#', '\\') )
800               new_comment.append( '\\f]' )
801               if l_after != '':
802                 new_comment.append( l_after )
803
804             else:
805
806               # Closing a LaTeX inline
807               new_comment.append(
808                 '%s\\f$%s' % ( l_before.replace('#', '\\'), l_after )
809               )
810
811           # Prevent appending lines (we have already done that)
812           new_line_comment = None
813
814         # If we are not in a LaTeX block, look for <pre> tags and transform them into Doxygen code
815         # blocks (using ~~~ ... ~~~). Only <pre> tags on a single line are supported
816         if new_line_comment is not None and not in_latex:
817
818           mblock = re.search( reblock, new_line_comment  )
819           if mblock:
820             new_comment.append( mblock.group(1)+'~~~' )
821             new_line_comment = None
822
823         if new_line_comment is not None:
824           if in_latex:
825             new_line_comment = new_line_comment.replace('#', '\\')
826           new_comment.append( new_line_comment )
827
828     else:
829       assert False, 'Comment regexp does not match'
830
831   # Fixing indentation level
832   if lowest_indent_level is not None:
833     logging.debug('Lowest indentation level found: %d' % lowest_indent_level)
834
835     new_comment_indent = []
836     reblankstart = r'^\s+'
837     for line in new_comment:
838       if re.search(reblankstart, line):
839         new_comment_indent.append( line[lowest_indent_level:] )
840       else:
841         new_comment_indent.append( line )
842
843     new_comment = new_comment_indent
844
845   else:
846     logging.debug('No indentation scaling applied')
847
848   return new_comment
849
850
851 ## Dumps an image-generating macro to the correct place. Returns a string with the image path,
852 #  without the extension.
853 #
854 #  @param infilename  File name of the source file
855 #  @param macro_lines Array of macro lines
856 def write_macro(infilename, macro_lines):
857
858   # Calculate hash
859   digh = hashlib.sha1()
860   for l in macro_lines:
861     digh.update(l)
862     digh.update('\n')
863   short_digest = digh.hexdigest()[0:7]
864
865   outdir = '%s/imgdoc' % os.path.dirname(infilename)
866   outprefix = '%s/%s_%s' % (
867     outdir,
868     os.path.basename(infilename).replace('.', '_'),
869     short_digest
870   )
871   outmacro = '%s.C' % outprefix
872
873   # Make directory
874   if not os.path.isdir(outdir):
875     # do not catch: let everything die on error
876     logging.debug('Creating directory %s' % Colt(outdir).magenta())
877     os.mkdir(outdir)
878
879   # Create file (do not catch errors either)
880   with open(outmacro, 'w') as omfp:
881     logging.debug('Writing macro %s' % Colt(outmacro).magenta())
882     for l in macro_lines:
883       omfp.write(l)
884       omfp.write('\n')
885
886   return outprefix
887
888
889 ## Rewrites all comments from the given file handler.
890 #
891 #  @param fhin     The file handler to read from
892 #  @param fhout    The file handler to write to
893 #  @param comments Array of comments
894 def rewrite_comments(fhin, fhout, comments):
895
896   line_num = 0
897   in_comment = False
898   skip_empty = False
899   comm = None
900   prev_comm = None
901   restore_lines = None
902
903   rindent = r'^(\s*)'
904
905   def dump_comment_block(cmt, restore=None):
906     text_indent = ''
907     ask_skip_empty = False
908
909     for i in range(0, cmt.indent):
910       text_indent = text_indent + ' '
911
912     for lc in cmt.lines:
913       fhout.write('%s///' % text_indent )
914       lc = lc.rstrip()
915       if len(lc) != 0:
916         fhout.write(' ')
917         fhout.write(lc)
918       fhout.write('\n')
919
920     # Empty new line at the end of the comment
921     if cmt.append_empty:
922       fhout.write('\n')
923       ask_skip_empty = True
924
925     # Restore lines if possible
926     if restore:
927       for lr in restore:
928         fhout.write(lr)
929         fhout.write('\n')
930
931     # Tell the caller whether it should skip the next empty line found
932     return ask_skip_empty
933
934
935   for line in fhin:
936
937     line_num = line_num + 1
938
939     # Find current comment
940     prev_comm = comm
941     comm = None
942     comm_list = []
943     for c in comments:
944       if c.has_comment(line_num):
945         comm = c
946         comm_list.append(c)
947
948     if len(comm_list) > 1:
949
950       merged = True
951
952       if len(comm_list) == 2:
953         c1,c2 = comm_list
954         if isinstance(c1, Comment) and isinstance(c2, Comment):
955           c1.lines = c1.lines + c2.lines  # list merge
956           comm = c1
957           logging.debug('Two adjacent comments merged. Result: {%s}' % Colt(comm).cyan())
958         else:
959           merged = False
960       else:
961         merged = False
962
963       if merged == False:
964         logging.warning('Too many unmergeable comments on the same line (%d), picking the last one' % len(comm_list))
965         for c in comm_list:
966           logging.warning('>> %s' % c)
967           comm = c  # considering the last one
968
969     if comm:
970
971       # First thing to check: are we in the same comment as before?
972       if comm is not prev_comm and \
973          isinstance(comm, Comment) and \
974          isinstance(prev_comm, Comment) and \
975          not isinstance(prev_comm, RemoveComment):
976
977         # We are NOT in the same comment as before, and this comment is dumpable
978
979         skip_empty = dump_comment_block(prev_comm, restore_lines)
980         in_comment = False
981         restore_lines = None
982         prev_comm = None  # we have just dumped it: pretend it never existed in this loop
983
984       #
985       # Check type of comment and react accordingly
986       #
987
988       if isinstance(comm, MemberComment):
989
990         # end comment block
991         if in_comment:
992           skip_empty = dump_comment_block(prev_comm, restore_lines)
993           in_comment = False
994           restore_lines = None
995
996         non_comment = line[ 0:comm.first_col-1 ]
997
998         if comm.array_size is not None or comm.is_dontsplit() or comm.is_ptr():
999
1000           # This is a special case: comment will be split in two lines: one before the comment for
1001           # Doxygen as "member description", and the other right after the comment on the same line
1002           # to be parsed by ROOT's C++ parser
1003
1004           # Keep indent on the generated line of comment before member definition
1005           mindent = re.search(rindent, line)
1006
1007           # Get correct comment flag, if any
1008           if comm.comment_flag is not None:
1009             cflag = comm.comment_flag
1010           else:
1011             cflag = ''
1012
1013           # Get correct array size, if any
1014           if comm.array_size is not None:
1015             asize = '[%s]' % comm.array_size
1016           else:
1017             asize = ''
1018
1019           # Write on two lines
1020           fhout.write('%s/// %s\n%s//%s%s\n' % (
1021             mindent.group(1),
1022             comm.lines[0],
1023             non_comment,
1024             cflag,
1025             asize
1026           ))
1027
1028         else:
1029
1030           # Single-line comments with the "transient" flag can be kept on one line in a way that
1031           # they are correctly interpreted by both ROOT and Doxygen
1032
1033           if comm.is_transient():
1034             tt = '!'
1035           else:
1036             tt = '/'
1037
1038           fhout.write('%s//%s< %s\n' % (
1039             non_comment,
1040             tt,
1041             comm.lines[0]
1042           ))
1043
1044       elif isinstance(comm, RemoveComment):
1045         # End comment block and skip this line
1046         if in_comment:
1047           skip_empty = dump_comment_block(prev_comm, restore_lines)
1048           in_comment = False
1049           restore_lines = None
1050
1051       elif restore_lines is None:
1052
1053         # Beginning of a new comment block of type Comment or PrependComment
1054         in_comment = True
1055
1056         if isinstance(comm, PrependComment):
1057           # Prepare array of lines to dump right after the comment
1058           restore_lines = [ line.rstrip('\n') ]
1059           logging.debug('Commencing lines to restore: {%s}' % Colt(restore_lines[0]).cyan())
1060         else:
1061           # Extract the non-comment part and print it if it exists
1062           non_comment = line[ 0:comm.first_col-1 ].rstrip()
1063           if non_comment != '':
1064             fhout.write( non_comment + '\n' )
1065
1066       elif isinstance(comm, Comment):
1067
1068         if restore_lines is not None:
1069           # From the 2nd line on of comment to prepend
1070           restore_lines.append( line.rstrip('\n') )
1071           logging.debug('Appending lines to restore. All lines: {%s}' % Colt(restore_lines).cyan())
1072
1073       else:
1074         assert False, 'Unhandled parser state: line=%d comm={%s} prev_comm={%s}' % \
1075           (line_num, comm, prev_comm)
1076
1077     else:
1078
1079       # Not a comment line
1080
1081       if in_comment:
1082
1083         # We have just exited a comment block of type Comment
1084         skip_empty = dump_comment_block(prev_comm, restore_lines)
1085         in_comment = False
1086         restore_lines = None
1087
1088       # Dump the non-comment line
1089       line_out = line.rstrip('\n')
1090       if skip_empty:
1091         skip_empty = False
1092         if line_out.strip() != '':
1093           fhout.write( line_out + '\n' )
1094       else:
1095         fhout.write( line_out + '\n' )
1096
1097   # Is there some comment left here?
1098   if restore_lines is not None:
1099     dump_comment_block(comm, restore_lines)
1100
1101   # Is there some other comment beyond the last line?
1102   for c in comments:
1103     if c.has_comment(line_num+1):
1104       dump_comment_block(c, None)
1105       break
1106
1107
1108 ## The main function.
1109 #
1110 #  Return value is the executable's return value.
1111 def main(argv):
1112
1113   # Setup logging on stderr
1114   log_level = logging.INFO
1115   logging.basicConfig(
1116     level=log_level,
1117     format='%(levelname)-8s %(funcName)-20s %(message)s',
1118     stream=sys.stderr
1119   )
1120
1121   # Parse command-line options
1122   output_on_stdout = False
1123   include_flags = []
1124   try:
1125     opts, args = getopt.getopt( argv, 'odI:', [ 'debug=', 'stdout' ] )
1126     for o, a in opts:
1127       if o == '--debug':
1128         log_level = getattr( logging, a.upper(), None )
1129         if not isinstance(log_level, int):
1130           raise getopt.GetoptError('log level must be one of: DEBUG, INFO, WARNING, ERROR, CRITICAL')
1131       elif o == '-d':
1132         log_level = logging.DEBUG
1133       elif o == '-o' or o == '--stdout':
1134         output_on_stdout = True
1135       elif o == '-I':
1136         if os.path.isdir(a):
1137           include_flags.extend( [ '-I', a ] )
1138         else:
1139           logging.fatal('Include directory not found: %s' % Colt(a).magenta())
1140           return 2
1141       else:
1142         assert False, 'Unhandled argument'
1143   except getopt.GetoptError as e:
1144     logging.fatal('Invalid arguments: %s' % e)
1145     return 1
1146
1147   logging.getLogger('').setLevel(log_level)
1148
1149   # Attempt to load libclang from a list of known locations
1150   libclang_locations = [
1151     '/usr/lib/llvm-3.5/lib/libclang.so.1',
1152     '/usr/lib/libclang.so',
1153     '/Library/Developer/CommandLineTools/usr/lib/libclang.dylib'
1154   ]
1155   libclang_found = False
1156
1157   for lib in libclang_locations:
1158     if os.path.isfile(lib):
1159       clang.cindex.Config.set_library_file(lib)
1160       libclang_found = True
1161       break
1162
1163   if not libclang_found:
1164     logging.fatal('Cannot find libclang')
1165     return 1
1166
1167   # Loop over all files
1168   for fn in args:
1169
1170     logging.info('Input file: %s' % Colt(fn).magenta())
1171     index = clang.cindex.Index.create()
1172     clang_args = [ '-x', 'c++' ]
1173     clang_args.extend( include_flags )
1174     translation_unit = index.parse(fn, args=clang_args)
1175
1176     comments = []
1177     traverse_ast( translation_unit.cursor, fn, comments )
1178     for c in comments:
1179
1180       logging.debug("Comment found for entity %s:" % Colt(c.func).magenta())
1181
1182       if isinstance(c, MemberComment):
1183
1184         if c.is_transient():
1185           flag_text = Colt('transient ').yellow()
1186         elif c.is_dontsplit():
1187           flag_text = Colt('dontsplit ').yellow()
1188         elif c.is_ptr():
1189           flag_text = Colt('ptr ').yellow()
1190         else:
1191           flag_text = ''
1192
1193         if c.array_size is not None:
1194           array_text = Colt('arraysize=%s ' % c.array_size).yellow()
1195         else:
1196           array_text = ''
1197
1198         logging.debug(
1199           "%s %s%s{%s}" % ( \
1200             Colt("[%d,%d]" % (c.first_line, c.first_col)).green(),
1201             flag_text,
1202             array_text,
1203             Colt(c.lines[0]).cyan()
1204         ))
1205
1206       elif isinstance(c, RemoveComment):
1207
1208         logging.debug( Colt('[%d,%d]' % (c.first_line, c.last_line)).green() )
1209
1210       else:
1211         for l in c.lines:
1212           logging.debug(
1213             Colt("[%d,%d:%d,%d] " % (c.first_line, c.first_col, c.last_line, c.last_col)).green() +
1214             "{%s}" % Colt(l).cyan()
1215           )
1216
1217     try:
1218
1219       if output_on_stdout:
1220         with open(fn, 'r') as fhin:
1221           rewrite_comments( fhin, sys.stdout, comments )
1222       else:
1223         fn_back = fn + '.thtml2doxy_backup'
1224         os.rename( fn, fn_back )
1225
1226         with open(fn_back, 'r') as fhin, open(fn, 'w') as fhout:
1227           rewrite_comments( fhin, fhout, comments )
1228
1229         os.remove( fn_back )
1230         logging.info("File %s converted to Doxygen: check differences before committing!" % Colt(fn).magenta())
1231     except (IOError,OSError) as e:
1232       logging.error('File operation failed: %s' % e)
1233
1234   return 0
1235
1236
1237 if __name__ == '__main__':
1238   sys.exit( main( sys.argv[1:] ) )