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