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