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( refactor_comment(token.spelling) )
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
137 count_line = comment_line_start
138 logging.info("Comment found for function %s" % Colt(comment_function).magenta())
139 for comment_line in comment:
141 Colt("%s [%d:%d] " % (indent, count_line, comment_line_end)).green() +
142 Colt(comment_line).cyan()
144 count_line = count_line + 1
147 comment_line_start = -1
148 comment_line_end = -1
155 logging.debug( "%s%s(%s)" % (indent, kind, text) )
157 for child_cursor in cursor.get_children():
158 traverse_ast(child_cursor, recursion+1)
161 ## Remove garbage from comments and convert special tags from THtml to Doxygen.
163 # @param comment The original comment
164 def refactor_comment(comment):
166 resingle = r'^/{2,}\s*(.*?)\s*(/{2,})?\s*$'
167 remulti_first = r'^/\*\s*(.*?)\s*\*?\s*$'
168 remulti_last = r'^\s*(.*?)\s*\*/$'
170 new_comment = comment.split('\n')
172 if len(new_comment) == 1:
173 msingle = re.search(resingle, comment)
175 new_comment[0] = msingle.group(1)
179 for i in range(0, len(new_comment)):
181 mmulti = re.search(remulti_first, new_comment[i])
183 new_comment[i] = mmulti.group(1)
184 elif i == len(new_comment)-1:
185 mmulti = re.search(remulti_last, new_comment[i])
187 new_comment[i] = mmulti.group(1)
189 new_comment[i] = new_comment[i].strip()
194 ## The main function.
196 # Return value is the executable's return value.
199 # Setup logging on stderr
200 log_level = logging.WARNING
203 format='%(levelname)-8s %(funcName)-20s %(message)s',
207 # Parse command-line options
209 opts, args = getopt.getopt( argv, 'd', [ 'debug=' ] )
212 log_level = getattr( logging, a.upper(), None )
213 if not isinstance(log_level, int):
214 raise getopt.GetoptError('log level must be one of: DEBUG, INFO, WARNING, ERROR, CRITICAL')
216 log_level = logging.DEBUG
218 assert False, 'Unhandled argument'
219 except getopt.GetoptError as e:
220 logging.fatal('Invalid arguments: %s' % e)
223 logging.getLogger('').setLevel(log_level)
225 # Attempt to load libclang from a list of known locations
226 libclang_locations = [
227 '/usr/lib/llvm-3.5/lib/libclang.so.1',
228 '/usr/lib/libclang.so',
229 '/Library/Developer/CommandLineTools/usr/lib/libclang.dylib'
231 libclang_found = False
233 for lib in libclang_locations:
234 if os.path.isfile(lib):
235 clang.cindex.Config.set_library_file(lib)
236 libclang_found = True
239 if not libclang_found:
240 logging.fatal('Cannot find libclang')
243 # Loop over all files
246 logging.info('Input file: %s' % Colt(fn).magenta())
247 index = clang.cindex.Index.create()
248 translation_unit = index.parse(fn, args=['-x', 'c++'])
249 traverse_ast( translation_unit.cursor )
254 if __name__ == '__main__':
255 sys.exit( main( sys.argv[1:] ) )