]> git.uio.no Git - u/mrichter/AliRoot.git/blob - doxygen/thtml2doxy_clang.py
doxy: comments in a separate class
[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, last_line, func):
65     self.lines = lines
66     self.first_line = first_line
67     self.last_line = last_line
68     self.func = func
69
70   def __str__(self):
71     return "<Comment for %s: [%d:%d] %s>" % (self.func, self.first_line, self.last_line, self.lines)
72
73
74 ## Traverse the AST recursively starting from the current cursor.
75 #
76 #  @param cursor    A Clang parser cursor
77 #  @param comments  Array of comments found (of class Comment)
78 #  @param recursion Current recursion depth
79 def traverse_ast(cursor, comments, recursion=0):
80
81   text = cursor.spelling or cursor.displayname
82   kind = str(cursor.kind)[str(cursor.kind).index('.')+1:]
83
84   indent = ''
85   for i in range(0, recursion):
86     indent = indent + '  '
87
88   if cursor.kind == clang.cindex.CursorKind.CXX_METHOD:
89
90     # cursor ran into a C++ method
91     logging.debug( "%s%s(%s)" % (indent, Colt(kind).magenta(), Colt(text).blue()) )
92
93     # we are looking for the following structure: method -> compound statement -> comment, i.e. we
94     # need to extract the first comment in the compound statement composing the method
95
96     in_compound_stmt = False
97     expect_comment = False
98     emit_comment = False
99
100     comment = []
101     comment_function = text
102     comment_line_start = -1
103     comment_line_end = -1
104
105     for token in cursor.get_tokens():
106
107       if token.cursor.kind == clang.cindex.CursorKind.COMPOUND_STMT:
108         if not in_compound_stmt:
109           in_compound_stmt = True
110           expect_comment = True
111           comment_line_end = -1
112       else:
113         if in_compound_stmt:
114           in_compound_stmt = False
115           emit_comment = True
116
117       # tkind = str(token.kind)[str(token.kind).index('.')+1:]
118       # ckind = str(token.cursor.kind)[str(token.cursor.kind).index('.')+1:]
119
120       if in_compound_stmt:
121
122         if expect_comment:
123
124           extent = token.extent
125           line_start = extent.start.line
126           line_end = extent.end.line
127
128           if token.kind == clang.cindex.TokenKind.PUNCTUATION and token.spelling == '{':
129             pass
130
131           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)):
132             comment_line_end = line_end
133
134             if comment_line_start == -1:
135               comment_line_start = line_start
136             comment.extend( token.spelling.split('\n') )
137
138             # multiline comments are parsed in one go, therefore don't expect subsequent comments
139             if line_end - line_start > 0:
140               emit_comment = True
141               expect_comment = False
142
143           else:
144             emit_comment = True
145             expect_comment = False
146
147       if emit_comment:
148
149         comment = refactor_comment( comment )
150
151         if len(comment) > 0:
152           logging.debug("Comment found for function %s" % Colt(comment_function).magenta())
153           comments.append( Comment(comment, comment_line_start, comment_line_end, comment_function) )
154
155         comment = []
156         comment_line_start = -1
157         comment_line_end = -1
158
159         emit_comment = False
160         break
161
162   else:
163
164     logging.debug( "%s%s(%s)" % (indent, kind, text) )
165
166   for child_cursor in cursor.get_children():
167     traverse_ast(child_cursor, comments, recursion+1)
168
169
170 ## Remove garbage from comments and convert special tags from THtml to Doxygen.
171 #
172 #  @param comment An array containing the lines of the original comment
173 def refactor_comment(comment):
174
175   recomm = r'^(/{2,}|/\*)?\s*(.*?)\s*((/{2,})?\s*|\*/)$'
176
177   new_comment = []
178   insert_blank = False
179   wait_first_non_blank = True
180   for line_comment in comment:
181     mcomm = re.search( recomm, line_comment )
182     if mcomm:
183       new_line_comment = mcomm.group(2)
184       if new_line_comment == '':
185         insert_blank = True
186       else:
187         if insert_blank and not wait_first_non_blank:
188           new_comment.append('')
189           insert_blank = False
190         wait_first_non_blank = False
191         new_comment.append( new_line_comment )
192     else:
193       assert False, 'Comment regexp does not match'
194
195   return new_comment
196
197
198 ## The main function.
199 #
200 #  Return value is the executable's return value.
201 def main(argv):
202
203   # Setup logging on stderr
204   log_level = logging.WARNING
205   logging.basicConfig(
206     level=log_level,
207     format='%(levelname)-8s %(funcName)-20s %(message)s',
208     stream=sys.stderr
209   )
210
211   # Parse command-line options
212   try:
213     opts, args = getopt.getopt( argv, 'd', [ 'debug=' ] )
214     for o, a in opts:
215       if o == '--debug':
216         log_level = getattr( logging, a.upper(), None )
217         if not isinstance(log_level, int):
218           raise getopt.GetoptError('log level must be one of: DEBUG, INFO, WARNING, ERROR, CRITICAL')
219       elif o == '-d':
220         log_level = logging.DEBUG
221       else:
222         assert False, 'Unhandled argument'
223   except getopt.GetoptError as e:
224     logging.fatal('Invalid arguments: %s' % e)
225     return 1
226
227   logging.getLogger('').setLevel(log_level)
228
229   # Attempt to load libclang from a list of known locations
230   libclang_locations = [
231     '/usr/lib/llvm-3.5/lib/libclang.so.1',
232     '/usr/lib/libclang.so',
233     '/Library/Developer/CommandLineTools/usr/lib/libclang.dylib'
234   ]
235   libclang_found = False
236
237   for lib in libclang_locations:
238     if os.path.isfile(lib):
239       clang.cindex.Config.set_library_file(lib)
240       libclang_found = True
241       break
242
243   if not libclang_found:
244     logging.fatal('Cannot find libclang')
245     return 1
246
247   # Loop over all files
248   for fn in args:
249
250     logging.info('Input file: %s' % Colt(fn).magenta())
251     index = clang.cindex.Index.create()
252     translation_unit = index.parse(fn, args=['-x', 'c++'])
253
254     comments = []
255     traverse_ast( translation_unit.cursor, comments )
256     for c in comments:
257       logging.info("Comment found for %s:" % Colt(c.func).magenta())
258       for l in c.lines:
259         logging.warning(
260           Colt("[%d:%d] " % (c.first_line, c.last_line)).green() +
261           "{%s}" % Colt(l).cyan()
262         )
263
264   return 0
265
266
267 if __name__ == '__main__':
268   sys.exit( main( sys.argv[1:] ) )