cpp.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. #
  2. # Metrix++, Copyright 2009-2013, Metrix++ Project
  3. # Link: http://swi.sourceforge.net
  4. #
  5. # This file is a part of Metrix++ Tool.
  6. #
  7. # Metrix++ is free software: you can redistribute it and/or modify
  8. # it under the terms of the GNU General Public License as published by
  9. # the Free Software Foundation, version 3 of the License.
  10. #
  11. # Metrix++ is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with Metrix++. If not, see <http://www.gnu.org/licenses/>.
  18. #
  19. import fnmatch
  20. import re
  21. import binascii
  22. import logging
  23. import core.api
  24. class Plugin(core.api.Plugin, core.api.Parent, core.api.Child, core.api.IConfigurable, core.api.ICode):
  25. def declare_configuration(self, parser):
  26. parser.add_option("--std.code.cpp.files", default="*.c,*.cpp,*.h,*.hpp",
  27. help="Enumerates filename extensions to match C/C++ files [default: %default]")
  28. def configure(self, options):
  29. self.files = options.__dict__['std.code.cpp.files'].split(',')
  30. def initialize(self):
  31. core.api.subscribe_by_parents_name('core.dir', self)
  32. namespace = self.get_plugin_loader().get_database_loader().create_namespace(self.get_name())
  33. namespace.add_field('files', int)
  34. namespace.add_field('mismatched_brackets', None)
  35. def callback(self, parent, data):
  36. for ext in self.files:
  37. if fnmatch.fnmatch(data.get_path(), ext):
  38. if data.get_data(self.get_name(), 'files') != None:
  39. self.notify_children(data)
  40. return
  41. count_mismatched_brackets = CppCodeParser().run(data)
  42. data.set_data(self.get_name(), 'files', 1)
  43. data.set_data(self.get_name(), 'mismatched_brackets', count_mismatched_brackets)
  44. self.notify_children(data)
  45. break
  46. class CppCodeParser(object):
  47. regex_cpp = re.compile(r'''
  48. /([\\](?:\n|\r|\r\n))*/(?=\n|\r|\r\n) # Match C++ style comments (empty comment line)
  49. | /([\\](?:\n|\r|\r\n))*/.*?[^\\](?=\n|\r|\r\n) # Match C++ style comments
  50. # NOTE: end of line is NOT consumed
  51. # NOTE: ([\\](?:\n|\r|\r\n))* for new line separators,
  52. # Need to support new line separators in expense of efficiency?
  53. | /([\\](?:\n|\r|\r\n))*\*.*?\*([\\](?:\n|\r|\r\n))*/ # Match C style comments
  54. | \'(?:\\.|[^\\\'])*\' # Match quoted strings
  55. | "(?:\\.|[^\\"])*" # Match double quoted strings
  56. | (((?<=\n|\r)|^)[ \t]*[#].*?[^\\](?=\n|\r|\r\n)) # Match preprocessor
  57. # NOTE: end of line is NOT consumed
  58. # NOTE: beginning of line is NOT consumed
  59. | (?P<fn_name>
  60. (operator( # Match C++ operator ...
  61. (\s+[_a-zA-Z][_a-zA-Z0-9]*(\s*\[\s*\])?) # - cast, new and delete operators
  62. | (\s*\[\s*\]) # - operator []
  63. | (\s*\(\s*\)) # - operator ()
  64. | (\s*[+-\\*/=<>!%&^|~,?.]{1,3}) # - other operators (from 1 to 3 symbols)
  65. ))
  66. | ([~]?[_a-zA-Z][_a-zA-Z0-9]*) # ... or function or constructor
  67. )\s*[(] # LIMITATION: if there are comments after function name
  68. # and before '(', it is not detected
  69. # LIMITATION: if there are comments within operator definition,
  70. # if may be not detected
  71. | ((?P<block_type>class|struct|namespace) # Match C++ class or struct
  72. (?P<block_name>((\s+[a-zA-Z_][a-zA-Z0-9_]*)|(?=\s*[{])))) # noname is supported, symbol '{' is not consumed
  73. # LIMITATION: if there are comments between keyword and name,
  74. # it is not detected
  75. | [<>{};:] # Match block start/end, brackets and statement separator
  76. | ((?:\n|\r|\r\n)\s*(?:\n|\r|\r\n)) # Match double empty line
  77. ''',
  78. re.DOTALL | re.MULTILINE | re.VERBOSE
  79. )
  80. regex_ln = re.compile(r'(\n)|(\r)|(\r\n)')
  81. def run(self, data):
  82. self.__init__() # Go to initial state if it is called twice
  83. return self.parse(data)
  84. def finalize_block(self, text, block, block_end):
  85. space_match = re.match('^\s*', text[block['start']:block_end], re.MULTILINE)
  86. block['start'] += space_match.end() # trim spaces at the beginning
  87. block['end'] = block_end
  88. start_pos = block['start']
  89. crc32 = 0
  90. for child in block['children']:
  91. # exclude children
  92. crc32 = binascii.crc32(text[start_pos:child['start']], crc32)
  93. start_pos = child['end']
  94. block['checksum'] = binascii.crc32(text[start_pos:block['end']], crc32) & 0xffffffff # to match python 3
  95. def add_lines_data(self, text, blocks):
  96. def add_lines_data_rec(self, text, blocks):
  97. for each in blocks:
  98. # add line begin
  99. self.total_current += len(self.regex_ln.findall(text, self.total_last_pos, each['start']))
  100. each['line_begin'] = self.total_current
  101. self.total_last_pos = each['start']
  102. # process enclosed
  103. add_lines_data_rec(self, text, each['children'])
  104. # add line end
  105. self.total_current += len(self.regex_ln.findall(text, self.total_last_pos, each['end']))
  106. each['line_end'] = self.total_current
  107. self.total_last_pos = each['end']
  108. self.total_last_pos = 0
  109. self.total_current = 1
  110. add_lines_data_rec(self, text, blocks)
  111. def add_regions(self, data, blocks):
  112. # Note: data.add_region() internals depend on special ordering of regions
  113. # in order to identify enclosed regions efficiently
  114. def add_regions_rec(self, data, blocks):
  115. def get_type_id(data, named_type):
  116. if named_type == "function":
  117. return data.get_region_types().FUNCTION
  118. elif named_type == "class":
  119. return data.get_region_types().CLASS
  120. elif named_type == "struct":
  121. return data.get_region_types().STRUCT
  122. elif named_type == "namespace":
  123. return data.get_region_types().NAMESPACE
  124. elif named_type == "__global__":
  125. return data.get_region_types().GLOBAL
  126. else:
  127. assert(False)
  128. for each in blocks:
  129. data.add_region(each['name'], each['start'], each['end'],
  130. each['line_begin'], each['line_end'], each['cursor'],
  131. get_type_id(data, each['type']), each['checksum'])
  132. add_regions_rec(self, data, each['children'])
  133. add_regions_rec(self, data, blocks)
  134. def parse(self, data):
  135. def reset_next_block(start):
  136. return {'name':'', 'start':start, 'cursor':0, 'type':'', 'confirmed':False}
  137. count_mismatched_brackets = 0
  138. text = data.get_content()
  139. indent_current = 0;
  140. blocks = [{'name':'__global__', 'start':0, 'cursor':0, 'type':'__global__', 'indent_start':indent_current, 'children':[]}]
  141. curblk = 0
  142. next_block = reset_next_block(0)
  143. cursor_last_pos = 0
  144. cursor_current = 1
  145. for m in re.finditer(self.regex_cpp, text):
  146. # Comment
  147. if text[m.start()] == '/':
  148. data.add_marker(m.start(), m.end(), data.get_marker_types().COMMENT)
  149. if text[m.start():m.end()].startswith("//\n"):
  150. print text[m.start():m.end()]
  151. # String
  152. elif text[m.start()] == '"' or text[m.start()] == '\'':
  153. data.add_marker(m.start() + 1, m.end() - 1, data.get_marker_types().STRING)
  154. # Preprocessor (including internal comments)
  155. elif text[m.start()] == ' ' or text[m.start()] == '\t' or text[m.start()] == '#':
  156. data.add_marker(m.start(), m.end(), data.get_marker_types().PREPROCESSOR)
  157. # Statement end
  158. elif text[m.start()] == ';':
  159. # Reset next block name and start
  160. next_block['name'] = ""
  161. next_block['start'] = m.end() # potential region start
  162. # Template argument closing bracket
  163. elif text[m.start()] == '>':
  164. # Reset next block name and start (in order to skip class names in templates), if has not been confirmed before
  165. if next_block['confirmed'] == False and (next_block['type'] == 'class' or next_block['type'] == 'struct'):
  166. next_block['name'] = ""
  167. next_block['start'] = m.end() # potential region start
  168. # Template argument opening bracket or after class inheritance specification
  169. elif text[m.start()] == ':' or text[m.start()] == '<':
  170. # .. if goes after calss definition
  171. if next_block['type'] == 'class' or next_block['type'] == 'struct':
  172. next_block['confirmed'] = True
  173. # Double end line
  174. elif text[m.start()] == '\n' or text[m.start()] == '\r':
  175. # Reset next block start, if has not been named yet
  176. if next_block['name'] == "":
  177. next_block['start'] = m.end() # potential region start
  178. # Block start...
  179. elif text[m.start()] == '{':
  180. # shift indent right
  181. indent_current += 1
  182. # ... if name detected previously
  183. if next_block['name'] != '': # - Start of enclosed block
  184. blocks.append({'name':next_block['name'],
  185. 'start':next_block['start'],
  186. 'cursor':next_block['cursor'],
  187. 'type':next_block['type'],
  188. 'indent_start':indent_current,
  189. 'children':[]})
  190. next_block = reset_next_block(m.end())
  191. curblk += 1
  192. # ... reset next block start, otherwise
  193. else: # - unknown type of block start
  194. next_block['start'] = m.end() # potential region start
  195. # Block end...
  196. elif text[m.start()] == '}':
  197. # ... if indent level matches the start
  198. if blocks[curblk]['indent_start'] == indent_current:
  199. next_block = reset_next_block(m.end())
  200. if curblk == 0:
  201. logging.warning("Non-matching closing bracket '}' detected: " + data.get_path() + ":" +
  202. str(cursor_current + len(self.regex_ln.findall(text, cursor_last_pos, m.start()))))
  203. count_mismatched_brackets += 1
  204. continue
  205. self.finalize_block(text, blocks[curblk], m.end())
  206. assert(blocks[curblk]['type'] != '__global__')
  207. curblk -= 1
  208. assert(curblk >= 0)
  209. blocks[curblk]['children'].append(blocks.pop())
  210. # shift indent left
  211. indent_current -= 1
  212. if indent_current < 0:
  213. logging.warning("Non-matching closing bracket '}' detected")
  214. count_mismatched_brackets += 1
  215. indent_current = 0
  216. # Potential namespace, struct, class
  217. elif text[m.start():m.end()].startswith(('class','struct','namespace')) == True \
  218. and m.group('fn_name') == None: # function name can start with keyword, for example class_id_type()
  219. if next_block['name'] == "":
  220. # - 'name'
  221. next_block['name'] = m.group('block_name').strip()
  222. if next_block['name'] == "":
  223. next_block['name'] = '__noname__'
  224. # - 'cursor'
  225. cursor_current += len(self.regex_ln.findall(text, cursor_last_pos, m.start('block_name')))
  226. cursor_last_pos = m.start('block_name')
  227. next_block['cursor'] = cursor_current
  228. # - 'type'
  229. next_block['type'] = m.group('block_type').strip()
  230. # - 'start' detected earlier
  231. # Potential function name detected...
  232. else:
  233. # ... if outside of a function (do not detect enclosed functions, unless classes are matched)
  234. if blocks[curblk]['type'] != 'function' and (next_block['name'] == "" or next_block['type'] != 'function'):
  235. # - 'name'
  236. next_block['name'] = m.group('fn_name').strip()
  237. # - 'cursor'
  238. cursor_current += len(self.regex_ln.findall(text, cursor_last_pos, m.start('fn_name')))
  239. cursor_last_pos = m.start('fn_name')
  240. # NOTE: cursor could be collected together with line_begin, line_end,
  241. # but we keep it here separately for easier debugging of file parsing problems
  242. next_block['cursor'] = cursor_current
  243. # - 'type'
  244. next_block['type'] = 'function'
  245. # - 'start' detected earlier
  246. while indent_current > 0:
  247. # log all
  248. logging.warning("Non-matching opening bracket '{' detected")
  249. count_mismatched_brackets += 1
  250. indent_current -= 1
  251. for (ind, each) in enumerate(blocks):
  252. each = each # used
  253. block = blocks[len(blocks) - 1 - ind]
  254. self.finalize_block(text, block, len(text))
  255. self.add_lines_data(text, blocks)
  256. self.add_regions(data, blocks)
  257. return count_mismatched_brackets