cs.py 17 KB

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