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