cs.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  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.cs.files", default="*.cs",
  26. help="Enumerates filename extensions to match C# files [default: %default]")
  27. def configure(self, options):
  28. self.files = options.__dict__['std.code.cs.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 = CsCodeParser().run(data)
  40. self.notify_children(data, is_updated)
  41. return count_mismatched_brackets
  42. class CsCodeParser(object):
  43. regex_cpp = re.compile(r'''
  44. //(?=\n|\r\n|\r) # Match C# style comments (empty comment line)
  45. | //.*?(?=\n|\r\n|\r) # Match C# style comments
  46. # NOTE: end of line is NOT consumed
  47. # NOTE: it is slightly different in C++
  48. | /\*\*/ # Match C style comments (empty comment line)
  49. # NOTE: it is slightly different in C++
  50. | /\*.*?\*/ # Match C style comments
  51. # NOTE: it is slightly different in C++
  52. | \'(?:\\.|[^\\\'])*\' # Match quoted strings
  53. | "(?:\\.|[^\\"])*" # Match double quoted strings
  54. | (((?<=\n|\r)|^)[ \t]*[#].*?(?=\n|\r\n|\r)) # Match preprocessor
  55. # NOTE: end of line is NOT consumed
  56. # NOTE: beginning of line is NOT consumed
  57. # NOTE: C# does not support backslashing as C++ does
  58. | (?P<fn_name>
  59. (operator( # Match C# operator ...
  60. (\s+[_a-zA-Z][_a-zA-Z0-9]*(\s*\[\s*\])?) # - cast, true, false operators
  61. | (\s*\[\s*\]) # - operator []
  62. | (\s*\(\s*\)) # - operator ()
  63. | (\s*[+-\\*/=<>!%&^|~,?.]{1,3}) # - other operators (from 1 to 3 symbols)
  64. # NOTE: maybe dot and ? should not be in the list...
  65. ))
  66. | (([~]\s*)?[_a-zA-Z][_a-zA-Z0-9]*
  67. ([.][a-zA-Z_][a-zA-Z0-9_]*)*) # ... or function or constructor
  68. # NOTE: C# destructor can have spaces in name after ~
  69. # NOTE: explicit interface implementation method has got a dot
  70. | (?P<prop_setget>get|set) # ... or property setter/getter
  71. )\s*(?(prop_setget)(?=[{])|[(<])
  72. # LIMITATION: if there are comments after function name
  73. # and before '(', it is not detected
  74. # LIMITATION: if there are comments within operator definition,
  75. # if may be not detected
  76. # LIMITATION: if there are comments after set|get keyword,
  77. # if may be not detected
  78. | ((?P<block_type>class|struct|namespace|interface) # Match class or struct or interface or namespace
  79. (?P<block_name>(\s+[a-zA-Z_][a-zA-Z0-9_]*)([.][a-zA-Z_][a-zA-Z0-9_]*)*))
  80. # NOTE: noname instances are impossible in C#
  81. # NOTE: names can have sub-names separated by dots
  82. # LIMITATION: if there are comments between keyword and name,
  83. # it is not detected
  84. | [\[\]{};] # Match block start/end and statement separator
  85. # NOTE: C++ parser includes processing of <> and :
  86. # to handle template definitions, it is easier in C#
  87. | ((?:\n|\r\n|\r)\s*(?:\n|\r\n|\r)) # Match double empty line
  88. ''',
  89. re.DOTALL | re.MULTILINE | re.VERBOSE
  90. )
  91. # \r\n goes before \r in order to consume right number of lines on Unix for Windows files
  92. regex_ln = re.compile(r'(\n)|(\r\n)|(\r)')
  93. def run(self, data):
  94. self.__init__() # Go to initial state if it is called twice
  95. return self.parse(data)
  96. def finalize_block(self, text, block, block_end):
  97. if block['type'] != '__global__':
  98. # do not trim spaces for __global__region
  99. space_match = re.match('^\s*', text[block['start']:block_end], re.MULTILINE)
  100. block['start'] += space_match.end() # trim spaces at the beginning
  101. block['end'] = block_end
  102. start_pos = block['start']
  103. crc32 = 0
  104. for child in block['children']:
  105. # exclude children
  106. crc32 = binascii.crc32(text[start_pos:child['start']], crc32)
  107. start_pos = child['end']
  108. block['checksum'] = binascii.crc32(text[start_pos:block['end']], crc32) & 0xffffffff # to match python 3
  109. def add_lines_data(self, text, blocks):
  110. def add_lines_data_rec(self, text, blocks):
  111. for each in blocks:
  112. # add line begin
  113. self.total_current += len(self.regex_ln.findall(text, self.total_last_pos, each['start']))
  114. each['line_begin'] = self.total_current
  115. self.total_last_pos = each['start']
  116. # process enclosed
  117. add_lines_data_rec(self, text, each['children'])
  118. # add line end
  119. self.total_current += len(self.regex_ln.findall(text, self.total_last_pos, each['end']))
  120. each['line_end'] = self.total_current
  121. self.total_last_pos = each['end']
  122. self.total_last_pos = 0
  123. self.total_current = 1
  124. add_lines_data_rec(self, text, blocks)
  125. def add_regions(self, data, blocks):
  126. # Note: data.add_region() internals depend on special ordering of regions
  127. # in order to identify enclosed regions efficiently
  128. def add_regions_rec(self, data, blocks):
  129. def get_type_id(data, named_type):
  130. if named_type == "function":
  131. return mpp.api.Region.T.FUNCTION
  132. elif named_type == "class":
  133. return mpp.api.Region.T.CLASS
  134. elif named_type == "struct":
  135. return mpp.api.Region.T.STRUCT
  136. elif named_type == "namespace":
  137. return mpp.api.Region.T.NAMESPACE
  138. elif named_type == "interface":
  139. return mpp.api.Region.T.INTERFACE
  140. elif named_type == "__global__":
  141. return mpp.api.Region.T.GLOBAL
  142. else:
  143. assert(False)
  144. for each in blocks:
  145. data.add_region(each['name'], each['start'], each['end'],
  146. each['line_begin'], each['line_end'], each['cursor'],
  147. get_type_id(data, each['type']), each['checksum'])
  148. add_regions_rec(self, data, each['children'])
  149. add_regions_rec(self, data, blocks)
  150. def parse(self, data):
  151. def reset_next_block(start):
  152. return {'name':'', 'start':start, 'cursor':0, 'type':'', 'inside_attribute':False}
  153. count_mismatched_brackets = 0
  154. text = data.get_content()
  155. indent_current = 0;
  156. blocks = [{'name':'__global__', 'start':0, 'cursor':0, 'type':'__global__', 'indent_start':indent_current, 'children':[]}]
  157. curblk = 0
  158. next_block = reset_next_block(0)
  159. cursor_last_pos = 0
  160. cursor_current = 1
  161. for m in re.finditer(self.regex_cpp, text):
  162. # Comment
  163. if text[m.start()] == '/':
  164. data.add_marker(m.start(), m.end(), mpp.api.Marker.T.COMMENT)
  165. # String
  166. elif text[m.start()] == '"' or text[m.start()] == '\'':
  167. data.add_marker(m.start() + 1, m.end() - 1, mpp.api.Marker.T.STRING)
  168. # Preprocessor (including internal comments)
  169. elif text[m.start()] == ' ' or text[m.start()] == '\t' or text[m.start()] == '#':
  170. data.add_marker(m.start(), m.end(), mpp.api.Marker.T.PREPROCESSOR)
  171. # Statement end
  172. elif text[m.start()] == ';':
  173. # Reset next block name and start
  174. next_block['name'] = ""
  175. next_block['start'] = m.end() # potential region start
  176. # Block openned by '[' bracket...
  177. elif text[m.start()] == '[':
  178. # ... may include attributes, so do not capture function names inside
  179. next_block['inside_attribute'] = True
  180. # Block closed by ']' bracket...
  181. # note: do not care about nesting for simplicity -
  182. # because attribute's statement can not have symbol ']' inside
  183. elif text[m.start()] == ']':
  184. # ... may include attributes, so do not capture function names inside
  185. next_block['inside_attribute'] = False
  186. # Double end line
  187. elif text[m.start()] == '\n' or text[m.start()] == '\r':
  188. # Reset next block start, if has not been named yet
  189. if next_block['name'] == "":
  190. next_block['start'] = m.end() # potential region start
  191. # Block start...
  192. elif text[m.start()] == '{':
  193. # shift indent right
  194. indent_current += 1
  195. # ... if name detected previously
  196. if next_block['name'] != '': # - Start of enclosed block
  197. blocks.append({'name':next_block['name'],
  198. 'start':next_block['start'],
  199. 'cursor':next_block['cursor'],
  200. 'type':next_block['type'],
  201. 'indent_start':indent_current,
  202. 'children':[]})
  203. next_block = reset_next_block(m.end())
  204. curblk += 1
  205. # ... reset next block start, otherwise
  206. else: # - unknown type of block start
  207. next_block['start'] = m.end() # potential region start
  208. # Block end...
  209. elif text[m.start()] == '}':
  210. # ... if indent level matches the start
  211. if blocks[curblk]['indent_start'] == indent_current:
  212. next_block = reset_next_block(m.end())
  213. if curblk == 0:
  214. mpp.cout.notify(data.get_path(),
  215. cursor_current + len(self.regex_ln.findall(text, cursor_last_pos, m.start())),
  216. mpp.cout.SEVERITY_WARNING,
  217. "Non-matching closing bracket '}' detected.")
  218. count_mismatched_brackets += 1
  219. continue
  220. self.finalize_block(text, blocks[curblk], m.end())
  221. assert(blocks[curblk]['type'] != '__global__')
  222. curblk -= 1
  223. assert(curblk >= 0)
  224. blocks[curblk]['children'].append(blocks.pop())
  225. # shift indent left
  226. indent_current -= 1
  227. if indent_current < 0:
  228. mpp.cout.notify(data.get_path(),
  229. cursor_current + len(self.regex_ln.findall(text, cursor_last_pos, m.start())),
  230. mpp.cout.SEVERITY_WARNING,
  231. "Non-matching closing bracket '}' detected.")
  232. count_mismatched_brackets += 1
  233. indent_current = 0
  234. # Potential namespace, struct, class, interface
  235. elif m.group('block_type') != None:
  236. if next_block['name'] == "":
  237. # - 'name'
  238. next_block['name'] = m.group('block_name').strip()
  239. # - 'cursor'
  240. cursor_current += len(self.regex_ln.findall(text, cursor_last_pos, m.start('block_name')))
  241. cursor_last_pos = m.start('block_name')
  242. next_block['cursor'] = cursor_current
  243. # - 'type'
  244. next_block['type'] = m.group('block_type').strip()
  245. # - 'start' detected earlier
  246. # Potential function name detected...
  247. elif m.group('fn_name') != None:
  248. # ... if outside of a function
  249. # (do not detect functions enclosed directly in a function, i.e. without classes)
  250. # ... and other name before has not been matched
  251. if blocks[curblk]['type'] != 'function' and (next_block['name'] == "") \
  252. and next_block['inside_attribute'] == False:
  253. # - 'name'
  254. next_block['name'] = m.group('fn_name').strip()
  255. # - 'cursor'
  256. cursor_current += len(self.regex_ln.findall(text, cursor_last_pos, m.start('fn_name')))
  257. cursor_last_pos = m.start('fn_name')
  258. # NOTE: cursor could be collected together with line_begin, line_end,
  259. # but we keep it here separately for easier debugging of file parsing problems
  260. next_block['cursor'] = cursor_current
  261. # - 'type'
  262. next_block['type'] = 'function'
  263. # - 'start' detected earlier
  264. else:
  265. assert(len("Unknown match by regular expression") == 0)
  266. while indent_current > 0:
  267. # log all
  268. mpp.cout.notify(data.get_path(),
  269. cursor_current + len(self.regex_ln.findall(text, cursor_last_pos, len(text))),
  270. mpp.cout.SEVERITY_WARNING,
  271. "Non-matching opening bracket '{' detected.")
  272. count_mismatched_brackets += 1
  273. indent_current -= 1
  274. for (ind, each) in enumerate(blocks):
  275. each = each # used
  276. block = blocks[len(blocks) - 1 - ind]
  277. self.finalize_block(text, block, len(text))
  278. self.add_lines_data(text, blocks)
  279. self.add_regions(data, blocks)
  280. return count_mismatched_brackets