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