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