]> git.uio.no Git - u/mrichter/AliRoot.git/blob - doxygen/thtml2doxy_clang.py
78d217171a6e0b799cd180b4302b87fb0402f559
[u/mrichter/AliRoot.git] / doxygen / thtml2doxy_clang.py
1 #!/usr/bin/env python
2
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 file1 [file2 [file3...]]`
23 #
24 #  @author Dario Berzano <dario.berzano@cern.ch>
25 #  @date 2014-12-05
26
27
28 import sys
29 import os
30 import re
31 import logging
32 import getopt
33 import clang.cindex
34
35
36 ## Brain-dead color output for terminal.
37 class Colt(str):
38
39   def red(self):
40     return self.color('\033[31m')
41
42   def green(self):
43     return self.color('\033[32m')
44
45   def yellow(self):
46     return self.color('\033[33m')
47
48   def blue(self):
49     return self.color('\033[34m')
50
51   def magenta(self):
52     return self.color('\033[35m')
53
54   def cyan(self):
55     return self.color('\033[36m')
56
57   def color(self, c):
58     return c + self + '\033[m'
59
60
61 ## Comment.
62 class Comment:
63
64   def __init__(self, lines, first_line, first_col, last_line, last_col, indent, func):
65     self.lines = lines
66     self.first_line = first_line
67     self.first_col = first_col
68     self.last_line = last_line
69     self.last_col = last_col
70     self.indent = indent
71     self.func = func
72
73   def has_comment(self, line):
74     return line >= self.first_line and line <= self.last_line
75
76   def __str__(self):
77     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)
78
79
80 ## A data member comment.
81 class MemberComment:
82
83   def __init__(self, text, is_transient, array_size, first_line, first_col, func):
84     self.lines = [ text ]
85     self.is_transient = is_transient
86     self.array_size = array_size
87     self.first_line = first_line
88     self.first_col = first_col
89     self.func = func
90
91   def has_comment(self, line):
92     return line == self.first_line
93
94   def __str__(self):
95
96     if self.is_transient:
97       tt = '!transient! '
98     else:
99       tt = ''
100
101     if self.array_size is not None:
102       ars = '[%s] ' % self.array_size
103     else:
104       ars = ''
105
106     return "<MemberComment for %s: [%d,%d] %s%s%s>" % (self.func, self.first_line, self.first_col, tt, ars, self.lines[0])
107
108
109 ## A dummy comment that removes comment lines.
110 class RemoveComment(Comment):
111
112   def __init__(self, first_line, last_line):
113     self.first_line = first_line
114     self.last_line = last_line
115     self.func = '<remove>'
116
117   def __str__(self):
118     return "<RemoveComment: [%d,%d]>" % (self.first_line, self.last_line)
119
120
121 ## Parses method comments.
122 #
123 #  @param cursor   Current libclang parser cursor
124 #  @param comments Array of comments: new ones will be appended there
125 def comment_method(cursor, comments):
126
127   # we are looking for the following structure: method -> compound statement -> comment, i.e. we
128   # need to extract the first comment in the compound statement composing the method
129
130   in_compound_stmt = False
131   expect_comment = False
132   emit_comment = False
133
134   comment = []
135   comment_function = cursor.spelling or cursor.displayname
136   comment_line_start = -1
137   comment_line_end = -1
138   comment_col_start = -1
139   comment_col_end = -1
140   comment_indent = -1
141
142   for token in cursor.get_tokens():
143
144     if token.cursor.kind == clang.cindex.CursorKind.COMPOUND_STMT:
145       if not in_compound_stmt:
146         in_compound_stmt = True
147         expect_comment = True
148         comment_line_end = -1
149     else:
150       if in_compound_stmt:
151         in_compound_stmt = False
152         emit_comment = True
153
154     # tkind = str(token.kind)[str(token.kind).index('.')+1:]
155     # ckind = str(token.cursor.kind)[str(token.cursor.kind).index('.')+1:]
156
157     if in_compound_stmt:
158
159       if expect_comment:
160
161         extent = token.extent
162         line_start = extent.start.line
163         line_end = extent.end.line
164
165         if token.kind == clang.cindex.TokenKind.PUNCTUATION and token.spelling == '{':
166           pass
167
168         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)):
169           comment_line_end = line_end
170           comment_col_end = extent.end.column
171
172           if comment_indent == -1 or (extent.start.column-1) < comment_indent:
173             comment_indent = extent.start.column-1
174
175           if comment_line_start == -1:
176             comment_line_start = line_start
177             comment_col_start = extent.start.column
178           comment.extend( token.spelling.split('\n') )
179
180           # multiline comments are parsed in one go, therefore don't expect subsequent comments
181           if line_end - line_start > 0:
182             emit_comment = True
183             expect_comment = False
184
185         else:
186           emit_comment = True
187           expect_comment = False
188
189     if emit_comment:
190
191       comment = refactor_comment( comment )
192
193       if len(comment) > 0:
194         logging.debug("Comment found for function %s" % Colt(comment_function).magenta())
195         comments.append( Comment(comment, comment_line_start, comment_col_start, comment_line_end, comment_col_end, comment_indent, comment_function) )
196
197       comment = []
198       comment_line_start = -1
199       comment_line_end = -1
200       comment_col_start = -1
201       comment_col_end = -1
202       comment_indent = -1
203
204       emit_comment = False
205       break
206
207
208 ## Parses comments to class data members.
209 #
210 #  @param cursor   Current libclang parser cursor
211 #  @param comments Array of comments: new ones will be appended there
212 def comment_datamember(cursor, comments):
213
214   # Note: libclang 3.5 seems to have problems parsing a certain type of FIELD_DECL, so we revert
215   # to a partial manual parsing. When parsing fails, the cursor's "extent" is not set properly,
216   # returning a line range 0-0. We therefore make the not-so-absurd assumption that the datamember
217   # definition is fully on one line, and we take the line number from cursor.location.
218
219   line_num = cursor.location.line
220   raw = None
221   prev = None
222   found = False
223
224   # Huge overkill
225   with open(str(cursor.location.file)) as fp:
226     cur_line = 0
227     for raw in fp:
228       cur_line = cur_line + 1
229       if cur_line == line_num:
230         found = True
231         break
232       prev = raw
233
234   assert found, 'A line that should exist was not found in file' % cursor.location.file
235
236   recomm = r'(//(!)|///?)(\[(.*?)\])?<?\s*(.*?)\s*$'
237   recomm_doxyary = r'^\s*///\s*(.*?)\s*$'
238
239   mcomm = re.search(recomm, raw)
240   if mcomm:
241     member_name = cursor.spelling;
242     is_transient = mcomm.group(2) is not None
243     array_size = mcomm.group(4)
244     text = mcomm.group(5)
245
246     col_num = mcomm.start()+1;
247
248     if array_size is not None and prev is not None:
249       # ROOT arrays with comments already converted to Doxygen have the member description on the
250       # previous line
251       mcomm_doxyary = re.search(recomm_doxyary, prev)
252       if mcomm_doxyary:
253         text = mcomm_doxyary.group(1)
254         comments.append(RemoveComment(line_num-1, line_num-1))
255
256     logging.debug('Comment found for member %s' % Colt(member_name).magenta())
257
258     comments.append( MemberComment(
259       text,
260       is_transient,
261       array_size,
262       line_num,
263       col_num,
264       member_name ))
265
266   else:
267     assert False, 'Regular expression does not match member comment'
268
269
270 ## Traverse the AST recursively starting from the current cursor.
271 #
272 #  @param cursor    A Clang parser cursor
273 #  @param filename  Name of the current file
274 #  @param comments  Array of comments: new ones will be appended there
275 #  @param recursion Current recursion depth
276 def traverse_ast(cursor, filename, comments, recursion=0):
277
278   # libclang traverses included files as well: we do not want this behavior
279   if cursor.location.file is not None and str(cursor.location.file) != filename:
280     logging.debug("Skipping processing of included %s" % cursor.location.file)
281     return
282
283   text = cursor.spelling or cursor.displayname
284   kind = str(cursor.kind)[str(cursor.kind).index('.')+1:]
285
286   indent = ''
287   for i in range(0, recursion):
288     indent = indent + '  '
289
290   if cursor.kind == clang.cindex.CursorKind.CXX_METHOD or cursor.kind == clang.cindex.CursorKind.CONSTRUCTOR or cursor.kind == clang.cindex.CursorKind.DESTRUCTOR:
291
292     # cursor ran into a C++ method
293     logging.debug( "%5d %s%s(%s)" % (cursor.location.line, indent, Colt(kind).magenta(), Colt(text).blue()) )
294     comment_method(cursor, comments)
295
296   elif cursor.kind == clang.cindex.CursorKind.FIELD_DECL:
297
298     # cursor ran into a data member declaration
299     logging.debug( "%5d %s%s(%s)" % (cursor.location.line, indent, Colt(kind).magenta(), Colt(text).blue()) )
300     comment_datamember(cursor, comments)
301
302   else:
303
304     logging.debug( "%5d %s%s(%s)" % (cursor.location.line, indent, kind, text) )
305
306   for child_cursor in cursor.get_children():
307     traverse_ast(child_cursor, filename, comments, recursion+1)
308
309
310 ## Remove garbage from comments and convert special tags from THtml to Doxygen.
311 #
312 #  @param comment An array containing the lines of the original comment
313 def refactor_comment(comment):
314
315   recomm = r'^(/{2,}|/\*)?\s*(.*?)\s*((/{2,})?\s*|\*/)$'
316   regarbage = r'^[\s*=-_#]+$'
317
318   new_comment = []
319   insert_blank = False
320   wait_first_non_blank = True
321   for line_comment in comment:
322     mcomm = re.search( recomm, line_comment )
323     if mcomm:
324       new_line_comment = mcomm.group(2)
325       mgarbage = re.search( regarbage, new_line_comment )
326
327       if new_line_comment == '' or mgarbage is not None:
328         insert_blank = True
329       else:
330         if insert_blank and not wait_first_non_blank:
331           new_comment.append('')
332         insert_blank = False
333         wait_first_non_blank = False
334         new_comment.append( new_line_comment )
335
336     else:
337       assert False, 'Comment regexp does not match'
338
339   return new_comment
340
341
342 ## Rewrites all comments from the given file handler.
343 #
344 #  @param fhin     The file handler to read from
345 #  @param fhout    The file handler to write to
346 #  @param comments Array of comments
347 def rewrite_comments(fhin, fhout, comments):
348
349   line_num = 0
350   in_comment = False
351   skip_empty = False
352   comm = None
353   prev_comm = None
354
355   rindent = r'^(\s*)'
356
357   for line in fhin:
358
359     line_num = line_num + 1
360
361     # Find current comment
362     prev_comm = comm
363     comm = None
364     for c in comments:
365       if c.has_comment(line_num):
366         comm = c
367
368     if comm:
369
370       if isinstance(comm, MemberComment):
371         non_comment = line[ 0:comm.first_col-1 ]
372
373         if comm.array_size is not None:
374
375           mindent = re.search(rindent, line)
376           if comm.is_transient:
377             tt = '!'
378           else:
379             tt = ''
380
381           # Special case: we need multiple lines not to confuse ROOT's C++ parser
382           fhout.write('%s/// %s\n%s//%s[%s]\n' % (
383             mindent.group(1),
384             comm.lines[0],
385             non_comment,
386             tt,
387             comm.array_size
388           ))
389
390         else:
391
392           if comm.is_transient:
393             tt = '!'
394           else:
395             tt = '/'
396
397           fhout.write('%s//%s< %s\n' % (
398             non_comment,
399             tt,
400             comm.lines[0]
401           ))
402
403       elif isinstance(comm, RemoveComment):
404         # Do nothing: just skip line
405         pass
406
407       elif prev_comm is None:
408         # Beginning of a new comment block of type Comment
409         in_comment = True
410
411         # Extract the non-comment part and print it if it exists
412         non_comment = line[ 0:comm.first_col-1 ].rstrip()
413         if non_comment != '':
414           fhout.write( non_comment + '\n' )
415
416     else:
417
418       if in_comment:
419
420         # We have just exited a comment block of type Comment
421         in_comment = False
422
423         # Dump revamped comment, if applicable
424         text_indent = ''
425         for i in range(0,prev_comm.indent):
426           text_indent = text_indent + ' '
427
428         for lc in prev_comm.lines:
429           fhout.write( "%s/// %s\n" % (text_indent, lc) );
430         fhout.write('\n')
431         skip_empty = True
432
433       line_out = line.rstrip('\n')
434       if skip_empty:
435         skip_empty = False
436         if line_out.strip() != '':
437           fhout.write( line_out + '\n' )
438       else:
439         fhout.write( line_out + '\n' )
440
441
442 ## The main function.
443 #
444 #  Return value is the executable's return value.
445 def main(argv):
446
447   # Setup logging on stderr
448   log_level = logging.INFO
449   logging.basicConfig(
450     level=log_level,
451     format='%(levelname)-8s %(funcName)-20s %(message)s',
452     stream=sys.stderr
453   )
454
455   # Parse command-line options
456   output_on_stdout = False
457   try:
458     opts, args = getopt.getopt( argv, 'od', [ 'debug=', 'stdout' ] )
459     for o, a in opts:
460       if o == '--debug':
461         log_level = getattr( logging, a.upper(), None )
462         if not isinstance(log_level, int):
463           raise getopt.GetoptError('log level must be one of: DEBUG, INFO, WARNING, ERROR, CRITICAL')
464       elif o == '-d':
465         log_level = logging.DEBUG
466       elif o == '-o' or o == '--stdout':
467         logging.debug('Output on stdout instead of replacing original files')
468         output_on_stdout = True
469       else:
470         assert False, 'Unhandled argument'
471   except getopt.GetoptError as e:
472     logging.fatal('Invalid arguments: %s' % e)
473     return 1
474
475   logging.getLogger('').setLevel(log_level)
476
477   # Attempt to load libclang from a list of known locations
478   libclang_locations = [
479     '/usr/lib/llvm-3.5/lib/libclang.so.1',
480     '/usr/lib/libclang.so',
481     '/Library/Developer/CommandLineTools/usr/lib/libclang.dylib'
482   ]
483   libclang_found = False
484
485   for lib in libclang_locations:
486     if os.path.isfile(lib):
487       clang.cindex.Config.set_library_file(lib)
488       libclang_found = True
489       break
490
491   if not libclang_found:
492     logging.fatal('Cannot find libclang')
493     return 1
494
495   # Loop over all files
496   for fn in args:
497
498     logging.info('Input file: %s' % Colt(fn).magenta())
499     index = clang.cindex.Index.create()
500     translation_unit = index.parse(fn, args=['-x', 'c++'])
501
502     comments = []
503     traverse_ast( translation_unit.cursor, fn, comments )
504     for c in comments:
505
506       logging.debug("Comment found for entity %s:" % Colt(c.func).magenta())
507
508       if isinstance(c, MemberComment):
509
510         if c.is_transient:
511           transient_text = Colt('transient ').yellow()
512         else:
513           transient_text = ''
514
515         if c.array_size is not None:
516           array_text = Colt('arraysize=%s ' % c.array_size).yellow()
517         else:
518           array_text = ''
519
520         logging.debug(
521           "%s %s%s{%s}" % ( \
522             Colt("[%d,%d]" % (c.first_line, c.first_col)).green(),
523             transient_text,
524             array_text,
525             Colt(c.lines[0]).cyan()
526         ))
527
528       elif isinstance(c, RemoveComment):
529
530         logging.debug( Colt('[%d,%d]' % (c.first_line, c.last_line)).green() )
531
532       else:
533         for l in c.lines:
534           logging.debug(
535             Colt("[%d,%d:%d,%d] " % (c.first_line, c.first_col, c.last_line, c.last_col)).green() +
536             "{%s}" % Colt(l).cyan()
537           )
538
539     try:
540
541       if output_on_stdout:
542         with open(fn, 'r') as fhin:
543           rewrite_comments( fhin, sys.stdout, comments )
544       else:
545         fn_back = fn + '.thtml2doxy_backup'
546         os.rename( fn, fn_back )
547
548         with open(fn_back, 'r') as fhin, open(fn, 'w') as fhout:
549           rewrite_comments( fhin, fhout, comments )
550
551         os.remove( fn_back )
552         logging.info("File %s converted to Doxygen: check differences before committing!" % Colt(fn).magenta())
553     except (IOError,OSError) as e:
554       logging.error('File operation failed: %s' % e)
555
556   return 0
557
558
559 if __name__ == '__main__':
560   sys.exit( main( sys.argv[1:] ) )