3 ## @package thtml2doxy_clang
4 # Translates THtml C++ comments to Doxygen using libclang as parser.
6 # This code relies on Python bindings for libclang: libclang's interface is pretty unstable, and
7 # its Python bindings are unstable as well.
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.
12 # This code (expecially AST traversal) was inspired by:
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
22 # `thtml2doxy_clang file1 [file2 [file3...]]`
24 # @author Dario Berzano <dario.berzano@cern.ch>
36 ## Brain-dead color output for terminal.
40 return self.color('\033[31m')
43 return self.color('\033[32m')
46 return self.color('\033[33m')
49 return self.color('\033[34m')
52 return self.color('\033[35m')
55 return self.color('\033[36m')
58 return c + self + '\033[m'
61 ## Traverse the AST recursively starting from the current cursor.
63 # @param cursor A Clang parser cursor
64 # @param recursion Current recursion depth
65 def traverse_ast(cursor, recursion=0):
67 text = cursor.spelling or cursor.displayname
68 kind = str(cursor.kind)[str(cursor.kind).index('.')+1:]
71 for i in range(0, recursion):
74 if cursor.kind == clang.cindex.CursorKind.CXX_METHOD:
76 # cursor ran into a C++ method
77 logging.debug( "%s%s(%s)" % (indent, Colt(kind).magenta(), Colt(text).blue()) )
79 # we are looking for the following structure: method -> compound statement -> comment, i.e. we
80 # need to extract the first comment in the compound statement composing the method
82 in_compound_stmt = False
83 expect_comment = False
87 comment_function = text
88 comment_line_start = -1
91 for token in cursor.get_tokens():
93 if token.cursor.kind == clang.cindex.CursorKind.COMPOUND_STMT:
94 if not in_compound_stmt:
95 in_compound_stmt = True
100 in_compound_stmt = False
103 # tkind = str(token.kind)[str(token.kind).index('.')+1:]
104 # ckind = str(token.cursor.kind)[str(token.cursor.kind).index('.')+1:]
110 extent = token.extent
111 line_start = extent.start.line
112 line_end = extent.end.line
114 if token.kind == clang.cindex.TokenKind.PUNCTUATION and token.spelling == '{':
117 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)):
118 comment_line_end = line_end
120 if comment_line_start == -1:
121 comment_line_start = line_start
122 comment.extend( token.spelling.split('\n') )
124 # multiline comments are parsed in one go, therefore don't expect subsequent comments
125 if line_end - line_start > 0:
127 expect_comment = False
131 expect_comment = False
135 comment = refactor_comment( comment )
138 logging.info("Comment found for function %s" % Colt(comment_function).magenta())
139 for comment_line in comment:
141 Colt("[%d:%d] " % (comment_line_start, comment_line_end)).green() + "{" +
142 Colt(comment_line).cyan() + "}"
146 comment_line_start = -1
147 comment_line_end = -1
154 logging.debug( "%s%s(%s)" % (indent, kind, text) )
156 for child_cursor in cursor.get_children():
157 traverse_ast(child_cursor, recursion+1)
160 ## Remove garbage from comments and convert special tags from THtml to Doxygen.
162 # @param comment An array containing the lines of the original comment
163 def refactor_comment(comment):
165 recomm = r'^(/{2,}|/\*)?\s*(.*?)\s*((/{2,})?\s*|\*/)$'
169 wait_first_non_blank = True
170 for line_comment in comment:
171 mcomm = re.search( recomm, line_comment )
173 new_line_comment = mcomm.group(2)
174 if new_line_comment == '':
177 if insert_blank and not wait_first_non_blank:
178 new_comment.append('')
180 wait_first_non_blank = False
181 new_comment.append( new_line_comment )
183 assert False, 'Comment regexp does not match'
188 ## The main function.
190 # Return value is the executable's return value.
193 # Setup logging on stderr
194 log_level = logging.WARNING
197 format='%(levelname)-8s %(funcName)-20s %(message)s',
201 # Parse command-line options
203 opts, args = getopt.getopt( argv, 'd', [ 'debug=' ] )
206 log_level = getattr( logging, a.upper(), None )
207 if not isinstance(log_level, int):
208 raise getopt.GetoptError('log level must be one of: DEBUG, INFO, WARNING, ERROR, CRITICAL')
210 log_level = logging.DEBUG
212 assert False, 'Unhandled argument'
213 except getopt.GetoptError as e:
214 logging.fatal('Invalid arguments: %s' % e)
217 logging.getLogger('').setLevel(log_level)
219 # Attempt to load libclang from a list of known locations
220 libclang_locations = [
221 '/usr/lib/llvm-3.5/lib/libclang.so.1',
222 '/usr/lib/libclang.so',
223 '/Library/Developer/CommandLineTools/usr/lib/libclang.dylib'
225 libclang_found = False
227 for lib in libclang_locations:
228 if os.path.isfile(lib):
229 clang.cindex.Config.set_library_file(lib)
230 libclang_found = True
233 if not libclang_found:
234 logging.fatal('Cannot find libclang')
237 # Loop over all files
240 logging.info('Input file: %s' % Colt(fn).magenta())
241 index = clang.cindex.Index.create()
242 translation_unit = index.parse(fn, args=['-x', 'c++'])
243 traverse_ast( translation_unit.cursor )
248 if __name__ == '__main__':
249 sys.exit( main( sys.argv[1:] ) )