]>
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 | |
40 | import clang.cindex | |
41 | ||
42 | ||
43 | ## Brain-dead color output for terminal. | |
44 | class Colt(str): | |
45 | ||
46 | def red(self): | |
47 | return self.color('\033[31m') | |
48 | ||
49 | def green(self): | |
50 | return self.color('\033[32m') | |
51 | ||
52 | def yellow(self): | |
53 | return self.color('\033[33m') | |
54 | ||
55 | def blue(self): | |
56 | return self.color('\033[34m') | |
57 | ||
58 | def magenta(self): | |
59 | return self.color('\033[35m') | |
60 | ||
61 | def cyan(self): | |
62 | return self.color('\033[36m') | |
63 | ||
64 | def color(self, c): | |
65 | return c + self + '\033[m' | |
66 | ||
f329fa92 | 67 | |
06ccae0f | 68 | ## Comment. |
69 | class Comment: | |
70 | ||
71 | def __init__(self, lines, first_line, first_col, last_line, last_col, indent, func): | |
3896b0ea | 72 | assert first_line > 0 and last_line >= first_line, 'Wrong line numbers' |
06ccae0f | 73 | self.lines = lines |
74 | self.first_line = first_line | |
75 | self.first_col = first_col | |
76 | self.last_line = last_line | |
77 | self.last_col = last_col | |
78 | self.indent = indent | |
79 | self.func = func | |
80 | ||
81 | def has_comment(self, line): | |
82 | return line >= self.first_line and line <= self.last_line | |
83 | ||
84 | def __str__(self): | |
85 | return "<Comment for %s: [%d,%d:%d,%d] %s>" % (self.func, self.first_line, self.first_col, self.last_line, self.last_col, self.lines) | |
86 | ||
87 | ||
88 | ## A data member comment. | |
89 | class MemberComment: | |
90 | ||
91 | def __init__(self, text, is_transient, array_size, first_line, first_col, func): | |
3896b0ea | 92 | assert first_line > 0, 'Wrong line number' |
06ccae0f | 93 | self.lines = [ text ] |
94 | self.is_transient = is_transient | |
95 | self.array_size = array_size | |
96 | self.first_line = first_line | |
97 | self.first_col = first_col | |
98 | self.func = func | |
99 | ||
100 | def has_comment(self, line): | |
101 | return line == self.first_line | |
102 | ||
103 | def __str__(self): | |
104 | ||
105 | if self.is_transient: | |
106 | tt = '!transient! ' | |
107 | else: | |
108 | tt = '' | |
109 | ||
110 | if self.array_size is not None: | |
111 | ars = '[%s] ' % self.array_size | |
112 | else: | |
113 | ars = '' | |
114 | ||
115 | return "<MemberComment for %s: [%d,%d] %s%s%s>" % (self.func, self.first_line, self.first_col, tt, ars, self.lines[0]) | |
116 | ||
117 | ||
118 | ## A dummy comment that removes comment lines. | |
119 | class RemoveComment(Comment): | |
120 | ||
121 | def __init__(self, first_line, last_line): | |
3896b0ea | 122 | assert first_line > 0 and last_line >= first_line, 'Wrong line numbers' |
06ccae0f | 123 | self.first_line = first_line |
124 | self.last_line = last_line | |
125 | self.func = '<remove>' | |
126 | ||
127 | def __str__(self): | |
128 | return "<RemoveComment: [%d,%d]>" % (self.first_line, self.last_line) | |
129 | ||
130 | ||
131 | ## Parses method comments. | |
f329fa92 | 132 | # |
06ccae0f | 133 | # @param cursor Current libclang parser cursor |
134 | # @param comments Array of comments: new ones will be appended there | |
135 | def comment_method(cursor, comments): | |
136 | ||
137 | # we are looking for the following structure: method -> compound statement -> comment, i.e. we | |
138 | # need to extract the first comment in the compound statement composing the method | |
139 | ||
140 | in_compound_stmt = False | |
141 | expect_comment = False | |
142 | emit_comment = False | |
143 | ||
144 | comment = [] | |
145 | comment_function = cursor.spelling or cursor.displayname | |
146 | comment_line_start = -1 | |
147 | comment_line_end = -1 | |
148 | comment_col_start = -1 | |
149 | comment_col_end = -1 | |
150 | comment_indent = -1 | |
151 | ||
152 | for token in cursor.get_tokens(): | |
153 | ||
154 | if token.cursor.kind == clang.cindex.CursorKind.COMPOUND_STMT: | |
155 | if not in_compound_stmt: | |
156 | in_compound_stmt = True | |
157 | expect_comment = True | |
158 | comment_line_end = -1 | |
159 | else: | |
160 | if in_compound_stmt: | |
161 | in_compound_stmt = False | |
162 | emit_comment = True | |
163 | ||
164 | # tkind = str(token.kind)[str(token.kind).index('.')+1:] | |
165 | # ckind = str(token.cursor.kind)[str(token.cursor.kind).index('.')+1:] | |
166 | ||
167 | if in_compound_stmt: | |
168 | ||
169 | if expect_comment: | |
170 | ||
171 | extent = token.extent | |
172 | line_start = extent.start.line | |
173 | line_end = extent.end.line | |
174 | ||
175 | if token.kind == clang.cindex.TokenKind.PUNCTUATION and token.spelling == '{': | |
176 | pass | |
177 | ||
178 | 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)): | |
179 | comment_line_end = line_end | |
180 | comment_col_end = extent.end.column | |
181 | ||
182 | if comment_indent == -1 or (extent.start.column-1) < comment_indent: | |
183 | comment_indent = extent.start.column-1 | |
184 | ||
185 | if comment_line_start == -1: | |
186 | comment_line_start = line_start | |
187 | comment_col_start = extent.start.column | |
188 | comment.extend( token.spelling.split('\n') ) | |
189 | ||
190 | # multiline comments are parsed in one go, therefore don't expect subsequent comments | |
191 | if line_end - line_start > 0: | |
192 | emit_comment = True | |
193 | expect_comment = False | |
194 | ||
195 | else: | |
196 | emit_comment = True | |
197 | expect_comment = False | |
198 | ||
199 | if emit_comment: | |
200 | ||
201 | comment = refactor_comment( comment ) | |
202 | ||
203 | if len(comment) > 0: | |
204 | logging.debug("Comment found for function %s" % Colt(comment_function).magenta()) | |
205 | comments.append( Comment(comment, comment_line_start, comment_col_start, comment_line_end, comment_col_end, comment_indent, comment_function) ) | |
206 | ||
207 | comment = [] | |
208 | comment_line_start = -1 | |
209 | comment_line_end = -1 | |
210 | comment_col_start = -1 | |
211 | comment_col_end = -1 | |
212 | comment_indent = -1 | |
213 | ||
214 | emit_comment = False | |
215 | break | |
216 | ||
217 | ||
218 | ## Parses comments to class data members. | |
219 | # | |
220 | # @param cursor Current libclang parser cursor | |
221 | # @param comments Array of comments: new ones will be appended there | |
222 | def comment_datamember(cursor, comments): | |
223 | ||
224 | # Note: libclang 3.5 seems to have problems parsing a certain type of FIELD_DECL, so we revert | |
225 | # to a partial manual parsing. When parsing fails, the cursor's "extent" is not set properly, | |
226 | # returning a line range 0-0. We therefore make the not-so-absurd assumption that the datamember | |
227 | # definition is fully on one line, and we take the line number from cursor.location. | |
228 | ||
229 | line_num = cursor.location.line | |
230 | raw = None | |
231 | prev = None | |
232 | found = False | |
233 | ||
234 | # Huge overkill | |
235 | with open(str(cursor.location.file)) as fp: | |
236 | cur_line = 0 | |
237 | for raw in fp: | |
238 | cur_line = cur_line + 1 | |
239 | if cur_line == line_num: | |
240 | found = True | |
241 | break | |
242 | prev = raw | |
243 | ||
244 | assert found, 'A line that should exist was not found in file' % cursor.location.file | |
245 | ||
246 | recomm = r'(//(!)|///?)(\[(.*?)\])?<?\s*(.*?)\s*$' | |
247 | recomm_doxyary = r'^\s*///\s*(.*?)\s*$' | |
248 | ||
249 | mcomm = re.search(recomm, raw) | |
250 | if mcomm: | |
54203c62 | 251 | # If it does not match, we do not have a comment |
06ccae0f | 252 | member_name = cursor.spelling; |
253 | is_transient = mcomm.group(2) is not None | |
254 | array_size = mcomm.group(4) | |
255 | text = mcomm.group(5) | |
256 | ||
257 | col_num = mcomm.start()+1; | |
258 | ||
259 | if array_size is not None and prev is not None: | |
260 | # ROOT arrays with comments already converted to Doxygen have the member description on the | |
261 | # previous line | |
262 | mcomm_doxyary = re.search(recomm_doxyary, prev) | |
263 | if mcomm_doxyary: | |
264 | text = mcomm_doxyary.group(1) | |
265 | comments.append(RemoveComment(line_num-1, line_num-1)) | |
266 | ||
267 | logging.debug('Comment found for member %s' % Colt(member_name).magenta()) | |
268 | ||
269 | comments.append( MemberComment( | |
270 | text, | |
271 | is_transient, | |
272 | array_size, | |
273 | line_num, | |
274 | col_num, | |
275 | member_name )) | |
276 | ||
06ccae0f | 277 | |
278 | ## Parses class description (beginning of file). | |
279 | # | |
280 | # The clang parser does not work in this case so we do it manually, but it is very simple: we keep | |
281 | # the first consecutive sequence of single-line comments (//) we find - provided that it occurs | |
282 | # before any other comment found so far in the file (the comments array is inspected to ensure | |
283 | # this). | |
f329fa92 | 284 | # |
06ccae0f | 285 | # Multi-line comments (/* ... */) are not considered as they are commonly used to display |
286 | # copyright notice. | |
f329fa92 | 287 | # |
06ccae0f | 288 | # @param filename Name of the current file |
289 | # @param comments Array of comments: new ones will be appended there | |
290 | def comment_classdesc(filename, comments): | |
291 | ||
292 | recomm = r'^\s*///?(\s*.*?)\s*/*\s*$' | |
293 | ||
294 | reclass_doxy = r'(?i)^\s*\\class:?\s*(.*?)\s*$' | |
295 | class_name_doxy = None | |
296 | ||
297 | reauthor = r'(?i)^\s*\\?authors?:?\s*(.*?)\s*(,?\s*([0-9./-]+))?\s*$' | |
298 | redate = r'(?i)^\s*\\?date:?\s*([0-9./-]+)\s*$' | |
299 | author = None | |
300 | date = None | |
301 | ||
302 | comment_lines = [] | |
303 | ||
304 | start_line = -1 | |
305 | end_line = -1 | |
306 | ||
307 | line_num = 0 | |
308 | ||
309 | with open(filename, 'r') as fp: | |
310 | ||
311 | for raw in fp: | |
312 | ||
313 | line_num = line_num + 1 | |
314 | ||
315 | if raw.strip() == '': | |
316 | # Skip empty lines | |
317 | end_line = line_num - 1 | |
318 | continue | |
319 | ||
320 | stripped = strip_html(raw) | |
321 | mcomm = re.search(recomm, stripped) | |
322 | if mcomm: | |
323 | ||
324 | if start_line == -1 and len(comment_lines) == 0: | |
325 | ||
326 | # First line. Check that we do not overlap with other comments | |
327 | comment_overlaps = False | |
328 | for c in comments: | |
329 | if c.has_comment(line_num): | |
330 | comment_overlaps = True | |
331 | break | |
332 | ||
333 | if comment_overlaps: | |
334 | # No need to look for other comments | |
335 | break | |
336 | ||
337 | start_line = line_num | |
338 | ||
339 | append = True | |
340 | ||
341 | mclass_doxy = re.search(reclass_doxy, mcomm.group(1)) | |
342 | if mclass_doxy: | |
343 | class_name_doxy = mclass_doxy.group(1) | |
344 | append = False | |
345 | else: | |
346 | mauthor = re.search(reauthor, mcomm.group(1)) | |
347 | if mauthor: | |
348 | author = mauthor.group(1) | |
349 | if date is None: | |
350 | # Date specified in the standalone \date field has priority | |
351 | date = mauthor.group(2) | |
352 | append = False | |
353 | else: | |
354 | mdate = re.search(redate, mcomm.group(1)) | |
355 | if mdate: | |
356 | date = mdate.group(1) | |
357 | append = False | |
358 | ||
359 | if append: | |
360 | comment_lines.append( mcomm.group(1) ) | |
361 | ||
362 | else: | |
363 | if len(comment_lines) > 0: | |
364 | # End of our comment | |
365 | if end_line == -1: | |
366 | end_line = line_num - 1 | |
367 | break | |
368 | ||
369 | if class_name_doxy is None: | |
370 | ||
371 | # No \class specified: guess it from file name | |
372 | reclass = r'^(.*/)?(.*?)(\..*)?$' | |
373 | mclass = re.search( reclass, filename ) | |
374 | if mclass: | |
375 | class_name_doxy = mclass.group(2) | |
376 | else: | |
377 | assert False, 'Regexp unable to extract classname from file' | |
378 | ||
379 | # Prepend \class specifier (and an empty line) | |
380 | comment_lines[:0] = [ '\\class ' + class_name_doxy ] | |
381 | ||
382 | # Append author and date if they exist | |
383 | comment_lines.append('') | |
384 | ||
385 | if author is not None: | |
386 | comment_lines.append( '\\author ' + author ) | |
387 | ||
388 | if date is not None: | |
389 | comment_lines.append( '\\date ' + date ) | |
390 | ||
391 | comment_lines = refactor_comment(comment_lines, do_strip_html=False) | |
392 | logging.debug('Comment found for class %s' % Colt(class_name_doxy).magenta()) | |
393 | comments.append(Comment( | |
394 | comment_lines, | |
395 | start_line, 1, end_line, 1, | |
396 | 0, class_name_doxy | |
397 | )) | |
398 | ||
399 | ||
400 | ## Traverse the AST recursively starting from the current cursor. | |
401 | # | |
402 | # @param cursor A Clang parser cursor | |
403 | # @param filename Name of the current file | |
404 | # @param comments Array of comments: new ones will be appended there | |
405 | # @param recursion Current recursion depth | |
406 | def traverse_ast(cursor, filename, comments, recursion=0): | |
407 | ||
408 | # libclang traverses included files as well: we do not want this behavior | |
409 | if cursor.location.file is not None and str(cursor.location.file) != filename: | |
410 | logging.debug("Skipping processing of included %s" % cursor.location.file) | |
411 | return | |
412 | ||
413 | text = cursor.spelling or cursor.displayname | |
414 | kind = str(cursor.kind)[str(cursor.kind).index('.')+1:] | |
415 | ||
416 | indent = '' | |
417 | for i in range(0, recursion): | |
418 | indent = indent + ' ' | |
419 | ||
420 | if cursor.kind == clang.cindex.CursorKind.CXX_METHOD or cursor.kind == clang.cindex.CursorKind.CONSTRUCTOR or cursor.kind == clang.cindex.CursorKind.DESTRUCTOR: | |
421 | ||
422 | # cursor ran into a C++ method | |
423 | logging.debug( "%5d %s%s(%s)" % (cursor.location.line, indent, Colt(kind).magenta(), Colt(text).blue()) ) | |
424 | comment_method(cursor, comments) | |
425 | ||
426 | elif cursor.kind == clang.cindex.CursorKind.FIELD_DECL: | |
427 | ||
428 | # cursor ran into a data member declaration | |
429 | logging.debug( "%5d %s%s(%s)" % (cursor.location.line, indent, Colt(kind).magenta(), Colt(text).blue()) ) | |
430 | comment_datamember(cursor, comments) | |
431 | ||
432 | else: | |
433 | ||
434 | logging.debug( "%5d %s%s(%s)" % (cursor.location.line, indent, kind, text) ) | |
435 | ||
436 | for child_cursor in cursor.get_children(): | |
437 | traverse_ast(child_cursor, filename, comments, recursion+1) | |
438 | ||
439 | if recursion == 0: | |
440 | comment_classdesc(filename, comments) | |
441 | ||
442 | ||
443 | ## Strip some HTML tags from the given string. Returns clean string. | |
444 | # | |
445 | # @param s Input string | |
446 | def strip_html(s): | |
447 | rehtml = r'(?i)</?(P|H[0-9]|BR)/?>' | |
448 | return re.sub(rehtml, '', s) | |
449 | ||
450 | ||
451 | ## Remove garbage from comments and convert special tags from THtml to Doxygen. | |
452 | # | |
453 | # @param comment An array containing the lines of the original comment | |
454 | def refactor_comment(comment, do_strip_html=True): | |
455 | ||
456 | recomm = r'^(/{2,}|/\*)? ?(\s*.*?)\s*((/{2,})?\s*|\*/)$' | |
457 | regarbage = r'^(?i)\s*([\s*=-_#]+|(Begin|End)_Html)\s*$' | |
458 | ||
459 | new_comment = [] | |
460 | insert_blank = False | |
461 | wait_first_non_blank = True | |
462 | for line_comment in comment: | |
463 | ||
464 | # Strip some HTML tags | |
465 | if do_strip_html: | |
466 | line_comment = strip_html(line_comment) | |
467 | ||
468 | mcomm = re.search( recomm, line_comment ) | |
469 | if mcomm: | |
470 | new_line_comment = mcomm.group(2) | |
471 | mgarbage = re.search( regarbage, new_line_comment ) | |
472 | ||
473 | if new_line_comment == '' or mgarbage is not None: | |
474 | insert_blank = True | |
475 | else: | |
476 | if insert_blank and not wait_first_non_blank: | |
477 | new_comment.append('') | |
478 | insert_blank = False | |
479 | wait_first_non_blank = False | |
480 | new_comment.append( new_line_comment ) | |
481 | ||
482 | else: | |
483 | assert False, 'Comment regexp does not match' | |
484 | ||
485 | return new_comment | |
486 | ||
487 | ||
488 | ## Rewrites all comments from the given file handler. | |
489 | # | |
490 | # @param fhin The file handler to read from | |
491 | # @param fhout The file handler to write to | |
492 | # @param comments Array of comments | |
493 | def rewrite_comments(fhin, fhout, comments): | |
494 | ||
495 | line_num = 0 | |
496 | in_comment = False | |
497 | skip_empty = False | |
498 | comm = None | |
499 | prev_comm = None | |
500 | ||
501 | rindent = r'^(\s*)' | |
502 | ||
503 | for line in fhin: | |
504 | ||
505 | line_num = line_num + 1 | |
506 | ||
507 | # Find current comment | |
508 | prev_comm = comm | |
509 | comm = None | |
510 | for c in comments: | |
511 | if c.has_comment(line_num): | |
512 | comm = c | |
513 | ||
514 | if comm: | |
515 | ||
516 | if isinstance(comm, MemberComment): | |
517 | non_comment = line[ 0:comm.first_col-1 ] | |
518 | ||
519 | if comm.array_size is not None: | |
520 | ||
521 | mindent = re.search(rindent, line) | |
522 | if comm.is_transient: | |
523 | tt = '!' | |
524 | else: | |
525 | tt = '' | |
526 | ||
527 | # Special case: we need multiple lines not to confuse ROOT's C++ parser | |
528 | fhout.write('%s/// %s\n%s//%s[%s]\n' % ( | |
529 | mindent.group(1), | |
530 | comm.lines[0], | |
531 | non_comment, | |
532 | tt, | |
533 | comm.array_size | |
534 | )) | |
535 | ||
536 | else: | |
537 | ||
538 | if comm.is_transient: | |
539 | tt = '!' | |
540 | else: | |
541 | tt = '/' | |
542 | ||
543 | fhout.write('%s//%s< %s\n' % ( | |
544 | non_comment, | |
545 | tt, | |
546 | comm.lines[0] | |
547 | )) | |
548 | ||
549 | elif isinstance(comm, RemoveComment): | |
550 | # Do nothing: just skip line | |
551 | pass | |
552 | ||
553 | elif prev_comm is None: | |
554 | # Beginning of a new comment block of type Comment | |
555 | in_comment = True | |
556 | ||
557 | # Extract the non-comment part and print it if it exists | |
558 | non_comment = line[ 0:comm.first_col-1 ].rstrip() | |
559 | if non_comment != '': | |
560 | fhout.write( non_comment + '\n' ) | |
561 | ||
562 | else: | |
563 | ||
564 | if in_comment: | |
565 | ||
566 | # We have just exited a comment block of type Comment | |
567 | in_comment = False | |
568 | ||
569 | # Dump revamped comment, if applicable | |
570 | text_indent = '' | |
571 | for i in range(0,prev_comm.indent): | |
572 | text_indent = text_indent + ' ' | |
573 | ||
574 | for lc in prev_comm.lines: | |
575 | fhout.write( "%s/// %s\n" % (text_indent, lc) ); | |
576 | fhout.write('\n') | |
577 | skip_empty = True | |
578 | ||
579 | line_out = line.rstrip('\n') | |
580 | if skip_empty: | |
581 | skip_empty = False | |
582 | if line_out.strip() != '': | |
583 | fhout.write( line_out + '\n' ) | |
584 | else: | |
585 | fhout.write( line_out + '\n' ) | |
586 | ||
f329fa92 | 587 | |
588 | ## The main function. | |
589 | # | |
06ccae0f | 590 | # Return value is the executable's return value. |
f329fa92 | 591 | def main(argv): |
592 | ||
06ccae0f | 593 | # Setup logging on stderr |
594 | log_level = logging.INFO | |
595 | logging.basicConfig( | |
596 | level=log_level, | |
597 | format='%(levelname)-8s %(funcName)-20s %(message)s', | |
598 | stream=sys.stderr | |
599 | ) | |
f329fa92 | 600 | |
06ccae0f | 601 | # Parse command-line options |
602 | output_on_stdout = False | |
603 | try: | |
604 | opts, args = getopt.getopt( argv, 'od', [ 'debug=', 'stdout' ] ) | |
605 | for o, a in opts: | |
606 | if o == '--debug': | |
607 | log_level = getattr( logging, a.upper(), None ) | |
608 | if not isinstance(log_level, int): | |
609 | raise getopt.GetoptError('log level must be one of: DEBUG, INFO, WARNING, ERROR, CRITICAL') | |
610 | elif o == '-d': | |
611 | log_level = logging.DEBUG | |
612 | elif o == '-o' or o == '--stdout': | |
613 | logging.debug('Output on stdout instead of replacing original files') | |
614 | output_on_stdout = True | |
615 | else: | |
616 | assert False, 'Unhandled argument' | |
617 | except getopt.GetoptError as e: | |
618 | logging.fatal('Invalid arguments: %s' % e) | |
619 | return 1 | |
f329fa92 | 620 | |
06ccae0f | 621 | logging.getLogger('').setLevel(log_level) |
f329fa92 | 622 | |
06ccae0f | 623 | # Attempt to load libclang from a list of known locations |
624 | libclang_locations = [ | |
625 | '/usr/lib/llvm-3.5/lib/libclang.so.1', | |
626 | '/usr/lib/libclang.so', | |
627 | '/Library/Developer/CommandLineTools/usr/lib/libclang.dylib' | |
628 | ] | |
629 | libclang_found = False | |
f329fa92 | 630 | |
06ccae0f | 631 | for lib in libclang_locations: |
632 | if os.path.isfile(lib): | |
633 | clang.cindex.Config.set_library_file(lib) | |
634 | libclang_found = True | |
635 | break | |
f329fa92 | 636 | |
06ccae0f | 637 | if not libclang_found: |
638 | logging.fatal('Cannot find libclang') | |
639 | return 1 | |
640 | ||
641 | # Loop over all files | |
642 | for fn in args: | |
643 | ||
644 | logging.info('Input file: %s' % Colt(fn).magenta()) | |
645 | index = clang.cindex.Index.create() | |
646 | translation_unit = index.parse(fn, args=['-x', 'c++']) | |
647 | ||
648 | comments = [] | |
649 | traverse_ast( translation_unit.cursor, fn, comments ) | |
650 | for c in comments: | |
651 | ||
652 | logging.debug("Comment found for entity %s:" % Colt(c.func).magenta()) | |
f329fa92 | 653 | |
06ccae0f | 654 | if isinstance(c, MemberComment): |
655 | ||
656 | if c.is_transient: | |
657 | transient_text = Colt('transient ').yellow() | |
658 | else: | |
659 | transient_text = '' | |
660 | ||
661 | if c.array_size is not None: | |
662 | array_text = Colt('arraysize=%s ' % c.array_size).yellow() | |
663 | else: | |
664 | array_text = '' | |
665 | ||
666 | logging.debug( | |
667 | "%s %s%s{%s}" % ( \ | |
668 | Colt("[%d,%d]" % (c.first_line, c.first_col)).green(), | |
669 | transient_text, | |
670 | array_text, | |
671 | Colt(c.lines[0]).cyan() | |
672 | )) | |
673 | ||
674 | elif isinstance(c, RemoveComment): | |
675 | ||
676 | logging.debug( Colt('[%d,%d]' % (c.first_line, c.last_line)).green() ) | |
677 | ||
678 | else: | |
679 | for l in c.lines: | |
680 | logging.debug( | |
681 | Colt("[%d,%d:%d,%d] " % (c.first_line, c.first_col, c.last_line, c.last_col)).green() + | |
682 | "{%s}" % Colt(l).cyan() | |
683 | ) | |
f329fa92 | 684 | |
685 | try: | |
06ccae0f | 686 | |
687 | if output_on_stdout: | |
688 | with open(fn, 'r') as fhin: | |
689 | rewrite_comments( fhin, sys.stdout, comments ) | |
690 | else: | |
691 | fn_back = fn + '.thtml2doxy_backup' | |
692 | os.rename( fn, fn_back ) | |
693 | ||
694 | with open(fn_back, 'r') as fhin, open(fn, 'w') as fhout: | |
695 | rewrite_comments( fhin, fhout, comments ) | |
696 | ||
697 | os.remove( fn_back ) | |
698 | logging.info("File %s converted to Doxygen: check differences before committing!" % Colt(fn).magenta()) | |
699 | except (IOError,OSError) as e: | |
700 | logging.error('File operation failed: %s' % e) | |
f329fa92 | 701 | |
702 | return 0 | |
703 | ||
06ccae0f | 704 | |
f329fa92 | 705 | if __name__ == '__main__': |
06ccae0f | 706 | sys.exit( main( sys.argv[1:] ) ) |