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
84 last_comment_line = -1
86 for token in cursor.get_tokens():
88 if token.cursor.kind == clang.cindex.CursorKind.COMPOUND_STMT:
89 if not in_compound_stmt:
90 in_compound_stmt = True
92 last_comment_line = -1
95 in_compound_stmt = False
98 # tkind = str(token.kind)[str(token.kind).index('.')+1:]
99 # ckind = str(token.cursor.kind)[str(token.cursor.kind).index('.')+1:]
105 extent = token.extent
106 line_start = extent.start.line
107 line_end = extent.end.line
109 if token.kind == clang.cindex.TokenKind.PUNCTUATION and token.spelling == '{':
112 elif token.kind == clang.cindex.TokenKind.COMMENT and (last_comment_line == -1 or (line_start == last_comment_line+1 and line_end-line_start == 0)):
113 #print Colt("%s %s:%s = %s" % (indent, ckind, tkind, token.spelling)).green()
114 last_comment_line = line_end
115 new_comment = refactor_comment(token.spelling)
117 for comment_line in new_comment:
119 Colt("%s [%d-%d]" % (indent, line_start, line_end)).green() +
120 Colt(comment_line).cyan()
123 # multiline comments are parsed in one go, therefore don't expect subsequent comments
124 if line_end - line_start > 0:
125 expect_comment = False
128 expect_comment = False
131 # print Colt("%s %s:%s = %s" % (indent, ckind, tkind, token.spelling)).yellow()
136 logging.debug( "%s%s(%s)" % (indent, kind, text) )
138 for child_cursor in cursor.get_children():
139 traverse_ast(child_cursor, recursion+1)
141 ## Remove garbage from comments and convert special tags from THtml to Doxygen.
143 # @param comment The original comment
144 def refactor_comment(comment):
146 resingle = r'^/{2,}\s*(.*?)\s*(/{2,})?\s*$'
147 remulti_first = r'^/\*\s*(.*?)\s*\*?\s*$'
148 remulti_last = r'^\s*(.*?)\s*\*/$'
150 new_comment = comment.split('\n')
152 if len(new_comment) == 1:
153 msingle = re.search(resingle, comment)
155 new_comment[0] = msingle.group(1)
159 for i in range(0, len(new_comment)):
161 mmulti = re.search(remulti_first, new_comment[i])
163 new_comment[i] = mmulti.group(1)
164 elif i == len(new_comment)-1:
165 mmulti = re.search(remulti_last, new_comment[i])
167 new_comment[i] = mmulti.group(1)
169 new_comment[i] = new_comment[i].strip()
174 ## The main function.
176 # Return value is the executable's return value.
179 # Setup logging on stderr
180 log_level = logging.WARNING
183 format='%(levelname)-8s %(funcName)-20s %(message)s',
187 # Parse command-line options
189 opts, args = getopt.getopt( argv, 'd', [ 'debug=' ] )
192 log_level = getattr( logging, a.upper(), None )
193 if not isinstance(log_level, int):
194 raise getopt.GetoptError('log level must be one of: DEBUG, INFO, WARNING, ERROR, CRITICAL')
196 log_level = logging.DEBUG
198 assert False, 'Unhandled argument'
199 except getopt.GetoptError as e:
200 logging.fatal('Invalid arguments: %s' % e)
203 logging.getLogger('').setLevel(log_level)
205 # Attempt to load libclang from a list of known locations
206 libclang_locations = [
207 '/usr/lib/llvm-3.5/lib/libclang.so.1',
208 '/usr/lib/libclang.so',
209 '/Library/Developer/CommandLineTools/usr/lib/libclang.dylib'
211 libclang_found = False
213 for lib in libclang_locations:
214 if os.path.isfile(lib):
215 clang.cindex.Config.set_library_file(lib)
216 libclang_found = True
219 if not libclang_found:
220 logging.fatal('Cannot find libclang')
223 # Loop over all files
226 index = clang.cindex.Index.create()
227 translation_unit = index.parse(fn, args=['-x', 'c++'])
228 traverse_ast( translation_unit.cursor )
233 if __name__ == '__main__':
234 sys.exit( main( sys.argv[1:] ) )