]> git.uio.no Git - u/mrichter/AliRoot.git/blame - doxygen/thtml2doxy.py
doxy: no trailing empty spaces in comments
[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 ]
424eef90 409 comment_lines.append('')
06ccae0f 410
84039997 411 # Append author and date if they exist
424eef90 412 if author is not None:
413 comment_lines.append( '\\author ' + author )
06ccae0f 414
424eef90 415 if date is not None:
416 comment_lines.append( '\\date ' + date )
417
ee1793c7 418 comment_lines = refactor_comment(comment_lines, do_strip_html=False, infilename=filename)
424eef90 419 logging.debug('Comment found for class %s' % Colt(class_name_doxy).magenta())
420 comments.append(Comment(
421 comment_lines,
422 start_line, 1, end_line, 1,
423 0, class_name_doxy
424 ))
425
426 else:
427
428 logging.warning('No comment found for class %s' % Colt(class_name_doxy).magenta())
06ccae0f 429
430
431## Traverse the AST recursively starting from the current cursor.
432#
433# @param cursor A Clang parser cursor
434# @param filename Name of the current file
435# @param comments Array of comments: new ones will be appended there
436# @param recursion Current recursion depth
84039997 437# @param in_func True if we are inside a function or method
438def traverse_ast(cursor, filename, comments, recursion=0, in_func=False):
06ccae0f 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)
84039997 460 in_func = True
06ccae0f 461
84039997 462 elif not is_macro and not in_func and \
463 cursor.kind in [ clang.cindex.CursorKind.FIELD_DECL, clang.cindex.CursorKind.VAR_DECL ]:
06ccae0f 464
465 # cursor ran into a data member declaration
466 logging.debug( "%5d %s%s(%s)" % (cursor.location.line, indent, Colt(kind).magenta(), Colt(text).blue()) )
467 comment_datamember(cursor, comments)
468
469 else:
470
471 logging.debug( "%5d %s%s(%s)" % (cursor.location.line, indent, kind, text) )
472
473 for child_cursor in cursor.get_children():
84039997 474 traverse_ast(child_cursor, filename, comments, recursion+1, in_func)
06ccae0f 475
476 if recursion == 0:
477 comment_classdesc(filename, comments)
478
479
480## Strip some HTML tags from the given string. Returns clean string.
481#
482# @param s Input string
483def strip_html(s):
798167cb 484 rehtml = r'(?i)</?(P|BR)/?>'
06ccae0f 485 return re.sub(rehtml, '', s)
486
487
488## Remove garbage from comments and convert special tags from THtml to Doxygen.
489#
490# @param comment An array containing the lines of the original comment
ee1793c7 491def refactor_comment(comment, do_strip_html=True, infilename=None):
06ccae0f 492
493 recomm = r'^(/{2,}|/\*)? ?(\s*.*?)\s*((/{2,})?\s*|\*/)$'
494 regarbage = r'^(?i)\s*([\s*=-_#]+|(Begin|End)_Html)\s*$'
495
03a6b7aa 496 # Support for LaTeX blocks spanning on multiple lines
497 relatex = r'(?i)^((.*?)\s+)?(BEGIN|END)_LATEX([.,;:\s]+.*)?$'
498 in_latex = False
499 latex_block = False
500
501 # Support for LaTeX blocks on a single line
9db428b7 502 reinline_latex = r'(?i)(.*)BEGIN_LATEX\s+(.*?)\s+END_LATEX(.*)$'
503
35b193b4 504 # Match <pre> (to turn it into the ~~~ Markdown syntax)
505 reblock = r'(?i)^(\s*)</?PRE>\s*$'
506
ee1793c7 507 # Macro blocks for pictures generation
508 in_macro = False
509 current_macro = []
510 remacro = r'(?i)^\s*(BEGIN|END)_MACRO(\((.*?)\))?\s*$'
511
06ccae0f 512 new_comment = []
513 insert_blank = False
514 wait_first_non_blank = True
515 for line_comment in comment:
516
ee1793c7 517 # Check if we are in a macro block
518 mmacro = re.search(remacro, line_comment)
519 if mmacro:
520 if in_macro:
521 in_macro = False
522
523 # Dump macro
524 outimg = write_macro(infilename, current_macro) + '.png'
525 current_macro = []
526
527 # Insert image
528 new_comment.append( '![Picture from ROOT macro](%s)' % (outimg) )
529
530 logging.debug( 'Found macro for generating image %s' % Colt(outimg).magenta() )
531
532 else:
533 in_macro = True
534
535 continue
536 elif in_macro:
537 current_macro.append( line_comment )
538 continue
539
06ccae0f 540 # Strip some HTML tags
541 if do_strip_html:
542 line_comment = strip_html(line_comment)
543
544 mcomm = re.search( recomm, line_comment )
545 if mcomm:
546 new_line_comment = mcomm.group(2)
547 mgarbage = re.search( regarbage, new_line_comment )
548
549 if new_line_comment == '' or mgarbage is not None:
550 insert_blank = True
551 else:
552 if insert_blank and not wait_first_non_blank:
553 new_comment.append('')
554 insert_blank = False
555 wait_first_non_blank = False
9db428b7 556
557 # Postprocessing: LaTeX formulas in ROOT format
558 # Marked by BEGIN_LATEX ... END_LATEX and they use # in place of \
559 # There can be several ROOT LaTeX forumlas per line
560 while True:
561 minline_latex = re.search( reinline_latex, new_line_comment )
562 if minline_latex:
563 new_line_comment = '%s\\f$%s\\f$%s' % \
564 ( minline_latex.group(1), minline_latex.group(2).replace('#', '\\'),
565 minline_latex.group(3) )
566 else:
567 break
568
03a6b7aa 569 # ROOT LaTeX: do we have a Begin/End_LaTeX block?
570 # Note: the presence of LaTeX "closures" does not exclude the possibility to have a begin
571 # block here left without a corresponding ending block
572 mlatex = re.search( relatex, new_line_comment )
573 if mlatex:
574
575 # before and after parts have been already stripped
576 l_before = mlatex.group(2)
577 l_after = mlatex.group(4)
578 is_begin = mlatex.group(3).upper() == 'BEGIN' # if not, END
579
580 if l_before is None:
581 l_before = ''
582 if l_after is None:
583 l_after = ''
584
585 if is_begin:
586
587 # Begin of LaTeX part
588
589 in_latex = True
590 if l_before == '' and l_after == '':
591
592 # Opening tag alone: mark the beginning of a block: \f[ ... \f]
593 latex_block = True
594 new_comment.append( '\\f[' )
595
596 else:
597 # Mark the beginning of inline: \f$ ... \f$
598 latex_block = False
599 new_comment.append(
600 '%s \\f$%s' % ( l_before, l_after.replace('#', '\\') )
601 )
602
603 else:
604
605 # End of LaTeX part
606 in_latex = False
607
608 if latex_block:
609
610 # Closing a LaTeX block
611 if l_before != '':
612 new_comment.append( l_before.replace('#', '\\') )
613 new_comment.append( '\\f]' )
614 if l_after != '':
615 new_comment.append( l_after )
616
617 else:
618
619 # Closing a LaTeX inline
620 new_comment.append(
621 '%s\\f$%s' % ( l_before.replace('#', '\\'), l_after )
622 )
623
624 # Prevent appending lines (we have already done that)
625 new_line_comment = None
626
35b193b4 627 # If we are not in a LaTeX block, look for <pre> tags and transform them into Doxygen code
628 # blocks (using ~~~ ... ~~~). Only <pre> tags on a single line are supported
629 if new_line_comment is not None and not in_latex:
630
631 mblock = re.search( reblock, new_line_comment )
632 if mblock:
633 new_comment.append( mblock.group(1)+'~~~' )
634 new_line_comment = None
635
03a6b7aa 636 if new_line_comment is not None:
637 if in_latex:
638 new_line_comment = new_line_comment.replace('#', '\\')
639 new_comment.append( new_line_comment )
06ccae0f 640
641 else:
642 assert False, 'Comment regexp does not match'
643
644 return new_comment
645
646
ee1793c7 647## Dumps an image-generating macro to the correct place. Returns a string with the image path,
648# without the extension.
649#
650# @param infilename File name of the source file
651# @param macro_lines Array of macro lines
652def write_macro(infilename, macro_lines):
653
654 # Calculate hash
655 digh = hashlib.sha1()
656 for l in macro_lines:
657 digh.update(l)
658 digh.update('\n')
659 short_digest = digh.hexdigest()[0:7]
660
661 outdir = '%s/imgdoc' % os.path.dirname(infilename)
662 outprefix = '%s/%s_%s' % (
663 outdir,
664 os.path.basename(infilename).replace('.', '_'),
665 short_digest
666 )
667 outmacro = '%s.C' % outprefix
668
669 # Make directory
670 if not os.path.isdir(outdir):
671 # do not catch: let everything die on error
672 logging.debug('Creating directory %s' % Colt(outdir).magenta())
673 os.mkdir(outdir)
674
675 # Create file (do not catch errors either)
676 with open(outmacro, 'w') as omfp:
677 logging.debug('Writing macro %s' % Colt(outmacro).magenta())
678 for l in macro_lines:
679 omfp.write(l)
680 omfp.write('\n')
681
682 return outprefix
683
684
06ccae0f 685## Rewrites all comments from the given file handler.
686#
687# @param fhin The file handler to read from
688# @param fhout The file handler to write to
689# @param comments Array of comments
690def rewrite_comments(fhin, fhout, comments):
691
692 line_num = 0
693 in_comment = False
694 skip_empty = False
695 comm = None
696 prev_comm = None
697
698 rindent = r'^(\s*)'
699
c0094f3c 700 def dump_comment_block(cmt):
fc82f9c7 701 text_indent = ''
702 for i in range(0, cmt.indent):
703 text_indent = text_indent + ' '
704
705 for lc in cmt.lines:
706 fhout.write('%s///' % text_indent )
707 lc = lc.rstrip()
708 if len(lc) != 0:
709 fhout.write(' ')
710 fhout.write(lc)
711 fhout.write('\n')
712
713 # Empty new line at the end of the comment
714 fhout.write('\n')
c0094f3c 715
716
06ccae0f 717 for line in fhin:
718
719 line_num = line_num + 1
720
721 # Find current comment
722 prev_comm = comm
723 comm = None
724 for c in comments:
725 if c.has_comment(line_num):
726 comm = c
727
728 if comm:
729
730 if isinstance(comm, MemberComment):
c0094f3c 731
732 # end comment block
733 if in_comment:
734 dump_comment_block(prev_comm)
735 in_comment = False
736
06ccae0f 737 non_comment = line[ 0:comm.first_col-1 ]
738
21689d7a 739 if comm.array_size is not None or comm.is_dontsplit() or comm.is_ptr():
06ccae0f 740
21689d7a 741 # This is a special case: comment will be split in two lines: one before the comment for
742 # Doxygen as "member description", and the other right after the comment on the same line
743 # to be parsed by ROOT's C++ parser
744
745 # Keep indent on the generated line of comment before member definition
06ccae0f 746 mindent = re.search(rindent, line)
21689d7a 747
748 # Get correct comment flag, if any
749 if comm.comment_flag is not None:
750 cflag = comm.comment_flag
751 else:
752 cflag = ''
753
754 # Get correct array size, if any
755 if comm.array_size is not None:
756 asize = '[%s]' % comm.array_size
06ccae0f 757 else:
21689d7a 758 asize = ''
06ccae0f 759
21689d7a 760 # Write on two lines
761 fhout.write('%s/// %s\n%s//%s%s\n' % (
06ccae0f 762 mindent.group(1),
763 comm.lines[0],
764 non_comment,
21689d7a 765 cflag,
766 asize
06ccae0f 767 ))
768
769 else:
770
21689d7a 771 # Single-line comments with the "transient" flag can be kept on one line in a way that
772 # they are correctly interpreted by both ROOT and Doxygen
773
774 if comm.is_transient():
06ccae0f 775 tt = '!'
776 else:
777 tt = '/'
778
779 fhout.write('%s//%s< %s\n' % (
780 non_comment,
781 tt,
782 comm.lines[0]
783 ))
784
785 elif isinstance(comm, RemoveComment):
c0094f3c 786 # End comment block and skip this line
787 if in_comment:
788 dump_comment_block(prev_comm)
789 in_comment = False
06ccae0f 790
791 elif prev_comm is None:
c0094f3c 792
06ccae0f 793 # Beginning of a new comment block of type Comment
794 in_comment = True
795
796 # Extract the non-comment part and print it if it exists
797 non_comment = line[ 0:comm.first_col-1 ].rstrip()
798 if non_comment != '':
799 fhout.write( non_comment + '\n' )
800
801 else:
802
803 if in_comment:
804
805 # We have just exited a comment block of type Comment
c0094f3c 806 dump_comment_block(prev_comm)
06ccae0f 807 in_comment = False
06ccae0f 808 skip_empty = True
809
810 line_out = line.rstrip('\n')
811 if skip_empty:
812 skip_empty = False
813 if line_out.strip() != '':
814 fhout.write( line_out + '\n' )
815 else:
816 fhout.write( line_out + '\n' )
817
f329fa92 818
819## The main function.
820#
06ccae0f 821# Return value is the executable's return value.
f329fa92 822def main(argv):
823
06ccae0f 824 # Setup logging on stderr
825 log_level = logging.INFO
826 logging.basicConfig(
827 level=log_level,
828 format='%(levelname)-8s %(funcName)-20s %(message)s',
829 stream=sys.stderr
830 )
f329fa92 831
06ccae0f 832 # Parse command-line options
833 output_on_stdout = False
7afec95e 834 include_flags = []
06ccae0f 835 try:
7afec95e 836 opts, args = getopt.getopt( argv, 'odI:', [ 'debug=', 'stdout' ] )
06ccae0f 837 for o, a in opts:
838 if o == '--debug':
839 log_level = getattr( logging, a.upper(), None )
840 if not isinstance(log_level, int):
841 raise getopt.GetoptError('log level must be one of: DEBUG, INFO, WARNING, ERROR, CRITICAL')
842 elif o == '-d':
843 log_level = logging.DEBUG
844 elif o == '-o' or o == '--stdout':
06ccae0f 845 output_on_stdout = True
7afec95e 846 elif o == '-I':
847 if os.path.isdir(a):
848 include_flags.extend( [ '-I', a ] )
849 else:
850 logging.fatal('Include directory not found: %s' % Colt(a).magenta())
851 return 2
06ccae0f 852 else:
853 assert False, 'Unhandled argument'
854 except getopt.GetoptError as e:
855 logging.fatal('Invalid arguments: %s' % e)
856 return 1
f329fa92 857
06ccae0f 858 logging.getLogger('').setLevel(log_level)
f329fa92 859
06ccae0f 860 # Attempt to load libclang from a list of known locations
861 libclang_locations = [
862 '/usr/lib/llvm-3.5/lib/libclang.so.1',
863 '/usr/lib/libclang.so',
864 '/Library/Developer/CommandLineTools/usr/lib/libclang.dylib'
865 ]
866 libclang_found = False
f329fa92 867
06ccae0f 868 for lib in libclang_locations:
869 if os.path.isfile(lib):
870 clang.cindex.Config.set_library_file(lib)
871 libclang_found = True
872 break
f329fa92 873
06ccae0f 874 if not libclang_found:
875 logging.fatal('Cannot find libclang')
876 return 1
877
878 # Loop over all files
879 for fn in args:
880
881 logging.info('Input file: %s' % Colt(fn).magenta())
882 index = clang.cindex.Index.create()
7afec95e 883 clang_args = [ '-x', 'c++' ]
884 clang_args.extend( include_flags )
885 translation_unit = index.parse(fn, args=clang_args)
06ccae0f 886
887 comments = []
888 traverse_ast( translation_unit.cursor, fn, comments )
889 for c in comments:
890
891 logging.debug("Comment found for entity %s:" % Colt(c.func).magenta())
f329fa92 892
06ccae0f 893 if isinstance(c, MemberComment):
894
21689d7a 895 if c.is_transient():
896 flag_text = Colt('transient ').yellow()
897 elif c.is_dontsplit():
898 flag_text = Colt('dontsplit ').yellow()
899 elif c.is_ptr():
900 flag_text = Colt('ptr ').yellow()
06ccae0f 901 else:
21689d7a 902 flag_text = ''
06ccae0f 903
904 if c.array_size is not None:
905 array_text = Colt('arraysize=%s ' % c.array_size).yellow()
906 else:
907 array_text = ''
908
909 logging.debug(
910 "%s %s%s{%s}" % ( \
911 Colt("[%d,%d]" % (c.first_line, c.first_col)).green(),
21689d7a 912 flag_text,
06ccae0f 913 array_text,
914 Colt(c.lines[0]).cyan()
915 ))
916
917 elif isinstance(c, RemoveComment):
918
919 logging.debug( Colt('[%d,%d]' % (c.first_line, c.last_line)).green() )
920
921 else:
922 for l in c.lines:
923 logging.debug(
924 Colt("[%d,%d:%d,%d] " % (c.first_line, c.first_col, c.last_line, c.last_col)).green() +
925 "{%s}" % Colt(l).cyan()
926 )
f329fa92 927
928 try:
06ccae0f 929
930 if output_on_stdout:
931 with open(fn, 'r') as fhin:
932 rewrite_comments( fhin, sys.stdout, comments )
933 else:
934 fn_back = fn + '.thtml2doxy_backup'
935 os.rename( fn, fn_back )
936
937 with open(fn_back, 'r') as fhin, open(fn, 'w') as fhout:
938 rewrite_comments( fhin, fhout, comments )
939
940 os.remove( fn_back )
941 logging.info("File %s converted to Doxygen: check differences before committing!" % Colt(fn).magenta())
942 except (IOError,OSError) as e:
943 logging.error('File operation failed: %s' % e)
f329fa92 944
945 return 0
946
06ccae0f 947
f329fa92 948if __name__ == '__main__':
06ccae0f 949 sys.exit( main( sys.argv[1:] ) )