]> git.uio.no Git - u/mrichter/AliRoot.git/blob - doxygen/thtml2doxy.py
doxy: extract ROOT macros for picture generation
[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:
71
72   def __init__(self, lines, first_line, first_col, last_line, last_col, indent, func):
73     assert first_line > 0 and last_line >= first_line, 'Wrong line numbers'
74     self.lines = lines
75     self.first_line = first_line
76     self.first_col = first_col
77     self.last_line = last_line
78     self.last_col = last_col
79     self.indent = indent
80     self.func = func
81
82   def has_comment(self, line):
83     return line >= self.first_line and line <= self.last_line
84
85   def __str__(self):
86     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)
87
88
89 ## A data member comment.
90 class MemberComment:
91
92   def __init__(self, text, is_transient, array_size, first_line, first_col, func):
93     assert first_line > 0, 'Wrong line number'
94     self.lines = [ text ]
95     self.is_transient = is_transient
96     self.array_size = array_size
97     self.first_line = first_line
98     self.first_col = first_col
99     self.func = func
100
101   def has_comment(self, line):
102     return line == self.first_line
103
104   def __str__(self):
105
106     if self.is_transient:
107       tt = '!transient! '
108     else:
109       tt = ''
110
111     if self.array_size is not None:
112       ars = '[%s] ' % self.array_size
113     else:
114       ars = ''
115
116     return "<MemberComment for %s: [%d,%d] %s%s%s>" % (self.func, self.first_line, self.first_col, tt, ars, self.lines[0])
117
118
119 ## A dummy comment that removes comment lines.
120 class RemoveComment(Comment):
121
122   def __init__(self, first_line, last_line):
123     assert first_line > 0 and last_line >= first_line, 'Wrong line numbers'
124     self.first_line = first_line
125     self.last_line = last_line
126     self.func = '<remove>'
127
128   def __str__(self):
129     return "<RemoveComment: [%d,%d]>" % (self.first_line, self.last_line)
130
131
132 ## Parses method comments.
133 #
134 #  @param cursor   Current libclang parser cursor
135 #  @param comments Array of comments: new ones will be appended there
136 def comment_method(cursor, comments):
137
138   # we are looking for the following structure: method -> compound statement -> comment, i.e. we
139   # need to extract the first comment in the compound statement composing the method
140
141   in_compound_stmt = False
142   expect_comment = False
143   emit_comment = False
144
145   comment = []
146   comment_function = cursor.spelling or cursor.displayname
147   comment_line_start = -1
148   comment_line_end = -1
149   comment_col_start = -1
150   comment_col_end = -1
151   comment_indent = -1
152
153   for token in cursor.get_tokens():
154
155     if token.cursor.kind == clang.cindex.CursorKind.COMPOUND_STMT:
156       if not in_compound_stmt:
157         in_compound_stmt = True
158         expect_comment = True
159         comment_line_end = -1
160     else:
161       if in_compound_stmt:
162         in_compound_stmt = False
163         emit_comment = True
164
165     # tkind = str(token.kind)[str(token.kind).index('.')+1:]
166     # ckind = str(token.cursor.kind)[str(token.cursor.kind).index('.')+1:]
167
168     if in_compound_stmt:
169
170       if expect_comment:
171
172         extent = token.extent
173         line_start = extent.start.line
174         line_end = extent.end.line
175
176         if token.kind == clang.cindex.TokenKind.PUNCTUATION and token.spelling == '{':
177           pass
178
179         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)):
180           comment_line_end = line_end
181           comment_col_end = extent.end.column
182
183           if comment_indent == -1 or (extent.start.column-1) < comment_indent:
184             comment_indent = extent.start.column-1
185
186           if comment_line_start == -1:
187             comment_line_start = line_start
188             comment_col_start = extent.start.column
189           comment.extend( token.spelling.split('\n') )
190
191           # multiline comments are parsed in one go, therefore don't expect subsequent comments
192           if line_end - line_start > 0:
193             emit_comment = True
194             expect_comment = False
195
196         else:
197           emit_comment = True
198           expect_comment = False
199
200     if emit_comment:
201
202       if comment_line_start > 0:
203
204         comment = refactor_comment( comment, infilename=str(cursor.location.file) )
205
206         if len(comment) > 0:
207           logging.debug("Comment found for function %s" % Colt(comment_function).magenta())
208           comments.append( Comment(comment, comment_line_start, comment_col_start, comment_line_end, comment_col_end, comment_indent, comment_function) )
209         else:
210           logging.debug('Empty comment found for function %s: collapsing' % Colt(comment_function).magenta())
211           comments.append( Comment([''], comment_line_start, comment_col_start, comment_line_end, comment_col_end, comment_indent, comment_function) )
212           #comments.append(RemoveComment(comment_line_start, comment_line_end))
213
214       else:
215         logging.warning('No comment found for function %s' % Colt(comment_function).magenta())
216
217       comment = []
218       comment_line_start = -1
219       comment_line_end = -1
220       comment_col_start = -1
221       comment_col_end = -1
222       comment_indent = -1
223
224       emit_comment = False
225       break
226
227
228 ## Parses comments to class data members.
229 #
230 #  @param cursor   Current libclang parser cursor
231 #  @param comments Array of comments: new ones will be appended there
232 def comment_datamember(cursor, comments):
233
234   # Note: libclang 3.5 seems to have problems parsing a certain type of FIELD_DECL, so we revert
235   # to a partial manual parsing. When parsing fails, the cursor's "extent" is not set properly,
236   # returning a line range 0-0. We therefore make the not-so-absurd assumption that the datamember
237   # definition is fully on one line, and we take the line number from cursor.location.
238
239   line_num = cursor.location.line
240   raw = None
241   prev = None
242   found = False
243
244   # Huge overkill
245   with open(str(cursor.location.file)) as fp:
246     cur_line = 0
247     for raw in fp:
248       cur_line = cur_line + 1
249       if cur_line == line_num:
250         found = True
251         break
252       prev = raw
253
254   assert found, 'A line that should exist was not found in file' % cursor.location.file
255
256   recomm = r'(//(!)|///?)(\[(.*?)\])?<?\s*(.*?)\s*$'
257   recomm_doxyary = r'^\s*///\s*(.*?)\s*$'
258
259   mcomm = re.search(recomm, raw)
260   if mcomm:
261     # If it does not match, we do not have a comment
262     member_name = cursor.spelling;
263     is_transient = mcomm.group(2) is not None
264     array_size = mcomm.group(4)
265     text = mcomm.group(5)
266
267     col_num = mcomm.start()+1;
268
269     if array_size is not None and prev is not None:
270       # ROOT arrays with comments already converted to Doxygen have the member description on the
271       # previous line
272       mcomm_doxyary = re.search(recomm_doxyary, prev)
273       if mcomm_doxyary:
274         text = mcomm_doxyary.group(1)
275         comments.append(RemoveComment(line_num-1, line_num-1))
276
277     logging.debug('Comment found for member %s' % Colt(member_name).magenta())
278
279     comments.append( MemberComment(
280       text,
281       is_transient,
282       array_size,
283       line_num,
284       col_num,
285       member_name ))
286
287
288 ## Parses class description (beginning of file).
289 #
290 #  The clang parser does not work in this case so we do it manually, but it is very simple: we keep
291 #  the first consecutive sequence of single-line comments (//) we find - provided that it occurs
292 #  before any other comment found so far in the file (the comments array is inspected to ensure
293 #  this).
294 #
295 #  Multi-line comments (/* ... */) are not considered as they are commonly used to display
296 #  copyright notice.
297 #
298 #  @param filename Name of the current file
299 #  @param comments Array of comments: new ones will be appended there
300 def comment_classdesc(filename, comments):
301
302   recomm = r'^\s*///?(\s*.*?)\s*/*\s*$'
303
304   reclass_doxy = r'(?i)^\s*\\class:?\s*(.*?)\s*$'
305   class_name_doxy = None
306
307   reauthor = r'(?i)^\s*\\?authors?:?\s*(.*?)\s*(,?\s*([0-9./-]+))?\s*$'
308   redate = r'(?i)^\s*\\?date:?\s*([0-9./-]+)\s*$'
309   author = None
310   date = None
311
312   comment_lines = []
313
314   start_line = -1
315   end_line = -1
316
317   line_num = 0
318
319   with open(filename, 'r') as fp:
320
321     for raw in fp:
322
323       line_num = line_num + 1
324
325       if raw.strip() == '' and start_line > 0:
326         # Skip empty lines
327         continue
328
329       stripped = strip_html(raw)
330       mcomm = re.search(recomm, stripped)
331       if mcomm:
332
333         if start_line == -1:
334
335           # First line. Check that we do not overlap with other comments
336           comment_overlaps = False
337           for c in comments:
338             if c.has_comment(line_num):
339               comment_overlaps = True
340               break
341
342           if comment_overlaps:
343             # No need to look for other comments
344             break
345
346           start_line = line_num
347
348         end_line = line_num
349         append = True
350
351         mclass_doxy = re.search(reclass_doxy, mcomm.group(1))
352         if mclass_doxy:
353           class_name_doxy = mclass_doxy.group(1)
354           append = False
355         else:
356           mauthor = re.search(reauthor, mcomm.group(1))
357           if mauthor:
358             author = mauthor.group(1)
359             if date is None:
360               # Date specified in the standalone \date field has priority
361               date = mauthor.group(2)
362             append = False
363           else:
364             mdate = re.search(redate, mcomm.group(1))
365             if mdate:
366               date = mdate.group(1)
367               append = False
368
369         if append:
370           comment_lines.append( mcomm.group(1) )
371
372       else:
373         if start_line > 0:
374           break
375
376   if class_name_doxy is None:
377
378     # No \class specified: guess it from file name
379     reclass = r'^(.*/)?(.*?)(\..*)?$'
380     mclass = re.search( reclass, filename )
381     if mclass:
382       class_name_doxy = mclass.group(2)
383     else:
384       assert False, 'Regexp unable to extract classname from file'
385
386   if start_line > 0:
387
388     # Prepend \class specifier (and an empty line)
389     comment_lines[:0] = [ '\\class ' + class_name_doxy ]
390
391     # Append author and date if they exist
392     comment_lines.append('')
393
394     if author is not None:
395       comment_lines.append( '\\author ' + author )
396
397     if date is not None:
398       comment_lines.append( '\\date ' + date )
399
400     comment_lines = refactor_comment(comment_lines, do_strip_html=False, infilename=filename)
401     logging.debug('Comment found for class %s' % Colt(class_name_doxy).magenta())
402     comments.append(Comment(
403       comment_lines,
404       start_line, 1, end_line, 1,
405       0, class_name_doxy
406     ))
407
408   else:
409
410     logging.warning('No comment found for class %s' % Colt(class_name_doxy).magenta())
411
412
413 ## Traverse the AST recursively starting from the current cursor.
414 #
415 #  @param cursor    A Clang parser cursor
416 #  @param filename  Name of the current file
417 #  @param comments  Array of comments: new ones will be appended there
418 #  @param recursion Current recursion depth
419 def traverse_ast(cursor, filename, comments, recursion=0):
420
421   # libclang traverses included files as well: we do not want this behavior
422   if cursor.location.file is not None and str(cursor.location.file) != filename:
423     logging.debug("Skipping processing of included %s" % cursor.location.file)
424     return
425
426   text = cursor.spelling or cursor.displayname
427   kind = str(cursor.kind)[str(cursor.kind).index('.')+1:]
428
429   indent = ''
430   for i in range(0, recursion):
431     indent = indent + '  '
432
433   if cursor.kind == clang.cindex.CursorKind.CXX_METHOD or cursor.kind == clang.cindex.CursorKind.CONSTRUCTOR or cursor.kind == clang.cindex.CursorKind.DESTRUCTOR:
434
435     # cursor ran into a C++ method
436     logging.debug( "%5d %s%s(%s)" % (cursor.location.line, indent, Colt(kind).magenta(), Colt(text).blue()) )
437     comment_method(cursor, comments)
438
439   elif cursor.kind == clang.cindex.CursorKind.FIELD_DECL:
440
441     # cursor ran into a data member declaration
442     logging.debug( "%5d %s%s(%s)" % (cursor.location.line, indent, Colt(kind).magenta(), Colt(text).blue()) )
443     comment_datamember(cursor, comments)
444
445   else:
446
447     logging.debug( "%5d %s%s(%s)" % (cursor.location.line, indent, kind, text) )
448
449   for child_cursor in cursor.get_children():
450     traverse_ast(child_cursor, filename, comments, recursion+1)
451
452   if recursion == 0:
453     comment_classdesc(filename, comments)
454
455
456 ## Strip some HTML tags from the given string. Returns clean string.
457 #
458 #  @param s Input string
459 def strip_html(s):
460   rehtml = r'(?i)</?(P|BR)/?>'
461   return re.sub(rehtml, '', s)
462
463
464 ## Remove garbage from comments and convert special tags from THtml to Doxygen.
465 #
466 #  @param comment An array containing the lines of the original comment
467 def refactor_comment(comment, do_strip_html=True, infilename=None):
468
469   recomm = r'^(/{2,}|/\*)? ?(\s*.*?)\s*((/{2,})?\s*|\*/)$'
470   regarbage = r'^(?i)\s*([\s*=-_#]+|(Begin|End)_Html)\s*$'
471
472   # Support for LaTeX blocks spanning on multiple lines
473   relatex = r'(?i)^((.*?)\s+)?(BEGIN|END)_LATEX([.,;:\s]+.*)?$'
474   in_latex = False
475   latex_block = False
476
477   # Support for LaTeX blocks on a single line
478   reinline_latex = r'(?i)(.*)BEGIN_LATEX\s+(.*?)\s+END_LATEX(.*)$'
479
480   # Match <pre> (to turn it into the ~~~ Markdown syntax)
481   reblock = r'(?i)^(\s*)</?PRE>\s*$'
482
483   # Macro blocks for pictures generation
484   in_macro = False
485   current_macro = []
486   remacro = r'(?i)^\s*(BEGIN|END)_MACRO(\((.*?)\))?\s*$'
487
488   new_comment = []
489   insert_blank = False
490   wait_first_non_blank = True
491   for line_comment in comment:
492
493     # Check if we are in a macro block
494     mmacro = re.search(remacro, line_comment)
495     if mmacro:
496       if in_macro:
497         in_macro = False
498
499         # Dump macro
500         outimg = write_macro(infilename, current_macro) + '.png'
501         current_macro = []
502
503         # Insert image
504         new_comment.append( '![Picture from ROOT macro](%s)' % (outimg) )
505
506         logging.debug( 'Found macro for generating image %s' % Colt(outimg).magenta() )
507
508       else:
509         in_macro = True
510
511       continue
512     elif in_macro:
513       current_macro.append( line_comment )
514       continue
515
516     # Strip some HTML tags
517     if do_strip_html:
518       line_comment = strip_html(line_comment)
519
520     mcomm = re.search( recomm, line_comment )
521     if mcomm:
522       new_line_comment = mcomm.group(2)
523       mgarbage = re.search( regarbage, new_line_comment )
524
525       if new_line_comment == '' or mgarbage is not None:
526         insert_blank = True
527       else:
528         if insert_blank and not wait_first_non_blank:
529           new_comment.append('')
530         insert_blank = False
531         wait_first_non_blank = False
532
533         # Postprocessing: LaTeX formulas in ROOT format
534         # Marked by BEGIN_LATEX ... END_LATEX and they use # in place of \
535         # There can be several ROOT LaTeX forumlas per line
536         while True:
537           minline_latex = re.search( reinline_latex, new_line_comment )
538           if minline_latex:
539             new_line_comment = '%s\\f$%s\\f$%s' % \
540               ( minline_latex.group(1), minline_latex.group(2).replace('#', '\\'),
541                 minline_latex.group(3) )
542           else:
543             break
544
545         # ROOT LaTeX: do we have a Begin/End_LaTeX block?
546         # Note: the presence of LaTeX "closures" does not exclude the possibility to have a begin
547         # block here left without a corresponding ending block
548         mlatex = re.search( relatex, new_line_comment )
549         if mlatex:
550
551           # before and after parts have been already stripped
552           l_before = mlatex.group(2)
553           l_after = mlatex.group(4)
554           is_begin = mlatex.group(3).upper() == 'BEGIN'  # if not, END
555
556           if l_before is None:
557             l_before = ''
558           if l_after is None:
559             l_after = ''
560
561           if is_begin:
562
563             # Begin of LaTeX part
564
565             in_latex = True
566             if l_before == '' and l_after == '':
567
568               # Opening tag alone: mark the beginning of a block: \f[ ... \f]
569               latex_block = True
570               new_comment.append( '\\f[' )
571
572             else:
573               # Mark the beginning of inline: \f$ ... \f$
574               latex_block = False
575               new_comment.append(
576                 '%s \\f$%s' % ( l_before, l_after.replace('#', '\\') )
577               )
578
579           else:
580
581             # End of LaTeX part
582             in_latex = False
583
584             if latex_block:
585
586               # Closing a LaTeX block
587               if l_before != '':
588                 new_comment.append( l_before.replace('#', '\\') )
589               new_comment.append( '\\f]' )
590               if l_after != '':
591                 new_comment.append( l_after )
592
593             else:
594
595               # Closing a LaTeX inline
596               new_comment.append(
597                 '%s\\f$%s' % ( l_before.replace('#', '\\'), l_after )
598               )
599
600           # Prevent appending lines (we have already done that)
601           new_line_comment = None
602
603         # If we are not in a LaTeX block, look for <pre> tags and transform them into Doxygen code
604         # blocks (using ~~~ ... ~~~). Only <pre> tags on a single line are supported
605         if new_line_comment is not None and not in_latex:
606
607           mblock = re.search( reblock, new_line_comment  )
608           if mblock:
609             new_comment.append( mblock.group(1)+'~~~' )
610             new_line_comment = None
611
612         if new_line_comment is not None:
613           if in_latex:
614             new_line_comment = new_line_comment.replace('#', '\\')
615           new_comment.append( new_line_comment )
616
617     else:
618       assert False, 'Comment regexp does not match'
619
620   return new_comment
621
622
623 ## Dumps an image-generating macro to the correct place. Returns a string with the image path,
624 #  without the extension.
625 #
626 #  @param infilename  File name of the source file
627 #  @param macro_lines Array of macro lines
628 def write_macro(infilename, macro_lines):
629
630   # Calculate hash
631   digh = hashlib.sha1()
632   for l in macro_lines:
633     digh.update(l)
634     digh.update('\n')
635   short_digest = digh.hexdigest()[0:7]
636
637   outdir = '%s/imgdoc' % os.path.dirname(infilename)
638   outprefix = '%s/%s_%s' % (
639     outdir,
640     os.path.basename(infilename).replace('.', '_'),
641     short_digest
642   )
643   outmacro = '%s.C' % outprefix
644
645   # Make directory
646   if not os.path.isdir(outdir):
647     # do not catch: let everything die on error
648     logging.debug('Creating directory %s' % Colt(outdir).magenta())
649     os.mkdir(outdir)
650
651   # Create file (do not catch errors either)
652   with open(outmacro, 'w') as omfp:
653     logging.debug('Writing macro %s' % Colt(outmacro).magenta())
654     for l in macro_lines:
655       omfp.write(l)
656       omfp.write('\n')
657
658   return outprefix
659
660
661 ## Rewrites all comments from the given file handler.
662 #
663 #  @param fhin     The file handler to read from
664 #  @param fhout    The file handler to write to
665 #  @param comments Array of comments
666 def rewrite_comments(fhin, fhout, comments):
667
668   line_num = 0
669   in_comment = False
670   skip_empty = False
671   comm = None
672   prev_comm = None
673
674   rindent = r'^(\s*)'
675
676   for line in fhin:
677
678     line_num = line_num + 1
679
680     # Find current comment
681     prev_comm = comm
682     comm = None
683     for c in comments:
684       if c.has_comment(line_num):
685         comm = c
686
687     if comm:
688
689       if isinstance(comm, MemberComment):
690         non_comment = line[ 0:comm.first_col-1 ]
691
692         if comm.array_size is not None:
693
694           mindent = re.search(rindent, line)
695           if comm.is_transient:
696             tt = '!'
697           else:
698             tt = ''
699
700           # Special case: we need multiple lines not to confuse ROOT's C++ parser
701           fhout.write('%s/// %s\n%s//%s[%s]\n' % (
702             mindent.group(1),
703             comm.lines[0],
704             non_comment,
705             tt,
706             comm.array_size
707           ))
708
709         else:
710
711           if comm.is_transient:
712             tt = '!'
713           else:
714             tt = '/'
715
716           fhout.write('%s//%s< %s\n' % (
717             non_comment,
718             tt,
719             comm.lines[0]
720           ))
721
722       elif isinstance(comm, RemoveComment):
723         # Do nothing: just skip line
724         pass
725
726       elif prev_comm is None:
727         # Beginning of a new comment block of type Comment
728         in_comment = True
729
730         # Extract the non-comment part and print it if it exists
731         non_comment = line[ 0:comm.first_col-1 ].rstrip()
732         if non_comment != '':
733           fhout.write( non_comment + '\n' )
734
735     else:
736
737       if in_comment:
738
739         # We have just exited a comment block of type Comment
740         in_comment = False
741
742         # Dump revamped comment, if applicable
743         text_indent = ''
744         for i in range(0,prev_comm.indent):
745           text_indent = text_indent + ' '
746
747         for lc in prev_comm.lines:
748           fhout.write( "%s/// %s\n" % (text_indent, lc) );
749         fhout.write('\n')
750         skip_empty = True
751
752       line_out = line.rstrip('\n')
753       if skip_empty:
754         skip_empty = False
755         if line_out.strip() != '':
756           fhout.write( line_out + '\n' )
757       else:
758         fhout.write( line_out + '\n' )
759
760
761 ## The main function.
762 #
763 #  Return value is the executable's return value.
764 def main(argv):
765
766   # Setup logging on stderr
767   log_level = logging.INFO
768   logging.basicConfig(
769     level=log_level,
770     format='%(levelname)-8s %(funcName)-20s %(message)s',
771     stream=sys.stderr
772   )
773
774   # Parse command-line options
775   output_on_stdout = False
776   include_flags = []
777   try:
778     opts, args = getopt.getopt( argv, 'odI:', [ 'debug=', 'stdout' ] )
779     for o, a in opts:
780       if o == '--debug':
781         log_level = getattr( logging, a.upper(), None )
782         if not isinstance(log_level, int):
783           raise getopt.GetoptError('log level must be one of: DEBUG, INFO, WARNING, ERROR, CRITICAL')
784       elif o == '-d':
785         log_level = logging.DEBUG
786       elif o == '-o' or o == '--stdout':
787         output_on_stdout = True
788       elif o == '-I':
789         if os.path.isdir(a):
790           include_flags.extend( [ '-I', a ] )
791         else:
792           logging.fatal('Include directory not found: %s' % Colt(a).magenta())
793           return 2
794       else:
795         assert False, 'Unhandled argument'
796   except getopt.GetoptError as e:
797     logging.fatal('Invalid arguments: %s' % e)
798     return 1
799
800   logging.getLogger('').setLevel(log_level)
801
802   # Attempt to load libclang from a list of known locations
803   libclang_locations = [
804     '/usr/lib/llvm-3.5/lib/libclang.so.1',
805     '/usr/lib/libclang.so',
806     '/Library/Developer/CommandLineTools/usr/lib/libclang.dylib'
807   ]
808   libclang_found = False
809
810   for lib in libclang_locations:
811     if os.path.isfile(lib):
812       clang.cindex.Config.set_library_file(lib)
813       libclang_found = True
814       break
815
816   if not libclang_found:
817     logging.fatal('Cannot find libclang')
818     return 1
819
820   # Loop over all files
821   for fn in args:
822
823     logging.info('Input file: %s' % Colt(fn).magenta())
824     index = clang.cindex.Index.create()
825     clang_args = [ '-x', 'c++' ]
826     clang_args.extend( include_flags )
827     translation_unit = index.parse(fn, args=clang_args)
828
829     comments = []
830     traverse_ast( translation_unit.cursor, fn, comments )
831     for c in comments:
832
833       logging.debug("Comment found for entity %s:" % Colt(c.func).magenta())
834
835       if isinstance(c, MemberComment):
836
837         if c.is_transient:
838           transient_text = Colt('transient ').yellow()
839         else:
840           transient_text = ''
841
842         if c.array_size is not None:
843           array_text = Colt('arraysize=%s ' % c.array_size).yellow()
844         else:
845           array_text = ''
846
847         logging.debug(
848           "%s %s%s{%s}" % ( \
849             Colt("[%d,%d]" % (c.first_line, c.first_col)).green(),
850             transient_text,
851             array_text,
852             Colt(c.lines[0]).cyan()
853         ))
854
855       elif isinstance(c, RemoveComment):
856
857         logging.debug( Colt('[%d,%d]' % (c.first_line, c.last_line)).green() )
858
859       else:
860         for l in c.lines:
861           logging.debug(
862             Colt("[%d,%d:%d,%d] " % (c.first_line, c.first_col, c.last_line, c.last_col)).green() +
863             "{%s}" % Colt(l).cyan()
864           )
865
866     try:
867
868       if output_on_stdout:
869         with open(fn, 'r') as fhin:
870           rewrite_comments( fhin, sys.stdout, comments )
871       else:
872         fn_back = fn + '.thtml2doxy_backup'
873         os.rename( fn, fn_back )
874
875         with open(fn_back, 'r') as fhin, open(fn, 'w') as fhout:
876           rewrite_comments( fhin, fhout, comments )
877
878         os.remove( fn_back )
879         logging.info("File %s converted to Doxygen: check differences before committing!" % Colt(fn).magenta())
880     except (IOError,OSError) as e:
881       logging.error('File operation failed: %s' % e)
882
883   return 0
884
885
886 if __name__ == '__main__':
887   sys.exit( main( sys.argv[1:] ) )