cpp.py 16 KB

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