cpp.py 16 KB

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