cs.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  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 core.api
  22. import core.cout
  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.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. core.api.Plugin.initialize(self, properties=[
  32. self.Property('files', ','.join(self.files))
  33. ])
  34. self.get_plugin_loader().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. space_match = re.match('^\s*', text[block['start']:block_end], re.MULTILINE)
  98. block['start'] += space_match.end() # trim spaces at the beginning
  99. block['end'] = block_end
  100. start_pos = block['start']
  101. crc32 = 0
  102. for child in block['children']:
  103. # exclude children
  104. crc32 = binascii.crc32(text[start_pos:child['start']], crc32)
  105. start_pos = child['end']
  106. block['checksum'] = binascii.crc32(text[start_pos:block['end']], crc32) & 0xffffffff # to match python 3
  107. def add_lines_data(self, text, blocks):
  108. def add_lines_data_rec(self, text, blocks):
  109. for each in blocks:
  110. # add line begin
  111. self.total_current += len(self.regex_ln.findall(text, self.total_last_pos, each['start']))
  112. each['line_begin'] = self.total_current
  113. self.total_last_pos = each['start']
  114. # process enclosed
  115. add_lines_data_rec(self, text, each['children'])
  116. # add line end
  117. self.total_current += len(self.regex_ln.findall(text, self.total_last_pos, each['end']))
  118. each['line_end'] = self.total_current
  119. self.total_last_pos = each['end']
  120. self.total_last_pos = 0
  121. self.total_current = 1
  122. add_lines_data_rec(self, text, blocks)
  123. def add_regions(self, data, blocks):
  124. # Note: data.add_region() internals depend on special ordering of regions
  125. # in order to identify enclosed regions efficiently
  126. def add_regions_rec(self, data, blocks):
  127. def get_type_id(data, named_type):
  128. if named_type == "function":
  129. return data.get_region_types().FUNCTION
  130. elif named_type == "class":
  131. return data.get_region_types().CLASS
  132. elif named_type == "struct":
  133. return data.get_region_types().STRUCT
  134. elif named_type == "namespace":
  135. return data.get_region_types().NAMESPACE
  136. elif named_type == "interface":
  137. return data.get_region_types().INTERFACE
  138. elif named_type == "__global__":
  139. return data.get_region_types().GLOBAL
  140. else:
  141. assert(False)
  142. for each in blocks:
  143. data.add_region(each['name'], each['start'], each['end'],
  144. each['line_begin'], each['line_end'], each['cursor'],
  145. get_type_id(data, each['type']), each['checksum'])
  146. add_regions_rec(self, data, each['children'])
  147. add_regions_rec(self, data, blocks)
  148. def parse(self, data):
  149. def reset_next_block(start):
  150. return {'name':'', 'start':start, 'cursor':0, 'type':'', 'inside_attribute':False}
  151. count_mismatched_brackets = 0
  152. text = data.get_content()
  153. indent_current = 0;
  154. blocks = [{'name':'__global__', 'start':0, 'cursor':0, 'type':'__global__', 'indent_start':indent_current, 'children':[]}]
  155. curblk = 0
  156. next_block = reset_next_block(0)
  157. cursor_last_pos = 0
  158. cursor_current = 1
  159. for m in re.finditer(self.regex_cpp, text):
  160. # Comment
  161. if text[m.start()] == '/':
  162. data.add_marker(m.start(), m.end(), data.get_marker_types().COMMENT)
  163. # String
  164. elif text[m.start()] == '"' or text[m.start()] == '\'':
  165. data.add_marker(m.start() + 1, m.end() - 1, data.get_marker_types().STRING)
  166. # Preprocessor (including internal comments)
  167. elif text[m.start()] == ' ' or text[m.start()] == '\t' or text[m.start()] == '#':
  168. data.add_marker(m.start(), m.end(), data.get_marker_types().PREPROCESSOR)
  169. # Statement end
  170. elif text[m.start()] == ';':
  171. # Reset next block name and start
  172. next_block['name'] = ""
  173. next_block['start'] = m.end() # potential region start
  174. # Block openned by '[' bracket...
  175. elif text[m.start()] == '[':
  176. # ... may include attributes, so do not capture function names inside
  177. next_block['inside_attribute'] = True
  178. # Block closed by ']' bracket...
  179. # note: do not care about nesting for simplicity -
  180. # because attribute's statement can not have symbol ']' inside
  181. elif text[m.start()] == ']':
  182. # ... may include attributes, so do not capture function names inside
  183. next_block['inside_attribute'] = False
  184. # Double end line
  185. elif text[m.start()] == '\n' or text[m.start()] == '\r':
  186. # Reset next block start, if has not been named yet
  187. if next_block['name'] == "":
  188. next_block['start'] = m.end() # potential region start
  189. # Block start...
  190. elif text[m.start()] == '{':
  191. # shift indent right
  192. indent_current += 1
  193. # ... if name detected previously
  194. if next_block['name'] != '': # - Start of enclosed block
  195. blocks.append({'name':next_block['name'],
  196. 'start':next_block['start'],
  197. 'cursor':next_block['cursor'],
  198. 'type':next_block['type'],
  199. 'indent_start':indent_current,
  200. 'children':[]})
  201. next_block = reset_next_block(m.end())
  202. curblk += 1
  203. # ... reset next block start, otherwise
  204. else: # - unknown type of block start
  205. next_block['start'] = m.end() # potential region start
  206. # Block end...
  207. elif text[m.start()] == '}':
  208. # ... if indent level matches the start
  209. if blocks[curblk]['indent_start'] == indent_current:
  210. next_block = reset_next_block(m.end())
  211. if curblk == 0:
  212. core.cout.notify(data.get_path(),
  213. cursor_current + len(self.regex_ln.findall(text, cursor_last_pos, m.start())),
  214. core.cout.SEVERITY_WARNING,
  215. "Non-matching closing bracket '}' detected.")
  216. count_mismatched_brackets += 1
  217. continue
  218. self.finalize_block(text, blocks[curblk], m.end())
  219. assert(blocks[curblk]['type'] != '__global__')
  220. curblk -= 1
  221. assert(curblk >= 0)
  222. blocks[curblk]['children'].append(blocks.pop())
  223. # shift indent left
  224. indent_current -= 1
  225. if indent_current < 0:
  226. core.cout.notify(data.get_path(),
  227. cursor_current + len(self.regex_ln.findall(text, cursor_last_pos, m.start())),
  228. core.cout.SEVERITY_WARNING,
  229. "Non-matching closing bracket '}' detected.")
  230. count_mismatched_brackets += 1
  231. indent_current = 0
  232. # Potential namespace, struct, class, interface
  233. elif m.group('block_type') != None:
  234. if next_block['name'] == "":
  235. # - 'name'
  236. next_block['name'] = m.group('block_name').strip()
  237. # - 'cursor'
  238. cursor_current += len(self.regex_ln.findall(text, cursor_last_pos, m.start('block_name')))
  239. cursor_last_pos = m.start('block_name')
  240. next_block['cursor'] = cursor_current
  241. # - 'type'
  242. next_block['type'] = m.group('block_type').strip()
  243. # - 'start' detected earlier
  244. # Potential function name detected...
  245. elif m.group('fn_name') != None:
  246. # ... if outside of a function
  247. # (do not detect functions enclosed directly in a function, i.e. without classes)
  248. # ... and other name before has not been matched
  249. if blocks[curblk]['type'] != 'function' and (next_block['name'] == "") \
  250. and next_block['inside_attribute'] == False:
  251. # - 'name'
  252. next_block['name'] = m.group('fn_name').strip()
  253. # - 'cursor'
  254. cursor_current += len(self.regex_ln.findall(text, cursor_last_pos, m.start('fn_name')))
  255. cursor_last_pos = m.start('fn_name')
  256. # NOTE: cursor could be collected together with line_begin, line_end,
  257. # but we keep it here separately for easier debugging of file parsing problems
  258. next_block['cursor'] = cursor_current
  259. # - 'type'
  260. next_block['type'] = 'function'
  261. # - 'start' detected earlier
  262. else:
  263. assert(len("Unknown match by regular expression") == 0)
  264. while indent_current > 0:
  265. # log all
  266. core.cout.notify(data.get_path(),
  267. cursor_current + len(self.regex_ln.findall(text, cursor_last_pos, len(text))),
  268. core.cout.SEVERITY_WARNING,
  269. "Non-matching opening bracket '{' detected.")
  270. count_mismatched_brackets += 1
  271. indent_current -= 1
  272. for (ind, each) in enumerate(blocks):
  273. each = each # used
  274. block = blocks[len(blocks) - 1 - ind]
  275. self.finalize_block(text, block, len(text))
  276. self.add_lines_data(text, blocks)
  277. self.add_regions(data, blocks)
  278. return count_mismatched_brackets