java.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  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.java.files", default="*.java",
  26. help="Enumerates filename extensions to match Java files [default: %default]")
  27. def configure(self, options):
  28. self.files = options.__dict__['std.code.java.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 = JavaCodeParser().run(data)
  43. self.notify_children(data, is_updated)
  44. return count_mismatched_brackets
  45. class JavaCodeParser(object):
  46. regex_cpp = re.compile(r'''
  47. //(?=\n|\r|\r\n) # Match Java style comments (empty comment line)
  48. | //.*?(?=\n|\r|\r\n) # Match Java 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. | (?P<fn_name>([_$a-zA-Z][_$a-zA-Z0-9]*))\s*[(] # Match function
  58. # NOTE: Java may include $ in the name
  59. # LIMITATION: if there are comments after function name
  60. # and before '(', it is not detected
  61. | ((?P<block_type>class|interface) # Match class or namespace
  62. (?P<block_name>(\s+[_$a-zA-Z][_$a-zA-Z0-9]*)))
  63. # NOTE: noname instances are impossible in Java
  64. # LIMITATION: if there are comments between keyword and name,
  65. # it is not detected
  66. | [{};] # Match block start/end and statement separator
  67. # NOTE: C++ parser includes processing of <> and :
  68. # to handle template definitions, it is easier in Java
  69. | ((?:\n|\r|\r\n)\s*(?:\n|\r|\r\n)) # Match double empty line
  70. ''',
  71. re.DOTALL | re.MULTILINE | re.VERBOSE
  72. )
  73. regex_ln = re.compile(r'(\n)|(\r)|(\r\n)')
  74. def run(self, data):
  75. self.__init__() # Go to initial state if it is called twice
  76. return self.parse(data)
  77. def finalize_block(self, text, block, block_end):
  78. space_match = re.match('^\s*', text[block['start']:block_end], re.MULTILINE)
  79. block['start'] += space_match.end() # trim spaces at the beginning
  80. block['end'] = block_end
  81. start_pos = block['start']
  82. crc32 = 0
  83. for child in block['children']:
  84. # exclude children
  85. crc32 = binascii.crc32(text[start_pos:child['start']], crc32)
  86. start_pos = child['end']
  87. block['checksum'] = binascii.crc32(text[start_pos:block['end']], crc32) & 0xffffffff # to match python 3
  88. def add_lines_data(self, text, blocks):
  89. def add_lines_data_rec(self, text, blocks):
  90. for each in blocks:
  91. # add line begin
  92. self.total_current += len(self.regex_ln.findall(text, self.total_last_pos, each['start']))
  93. each['line_begin'] = self.total_current
  94. self.total_last_pos = each['start']
  95. # process enclosed
  96. add_lines_data_rec(self, text, each['children'])
  97. # add line end
  98. self.total_current += len(self.regex_ln.findall(text, self.total_last_pos, each['end']))
  99. each['line_end'] = self.total_current
  100. self.total_last_pos = each['end']
  101. self.total_last_pos = 0
  102. self.total_current = 1
  103. add_lines_data_rec(self, text, blocks)
  104. def add_regions(self, data, blocks):
  105. # Note: data.add_region() internals depend on special ordering of regions
  106. # in order to identify enclosed regions efficiently
  107. def add_regions_rec(self, data, blocks):
  108. def get_type_id(data, named_type):
  109. if named_type == "function":
  110. return data.get_region_types().FUNCTION
  111. elif named_type == "class":
  112. return data.get_region_types().CLASS
  113. elif named_type == "interface":
  114. return data.get_region_types().INTERFACE
  115. elif named_type == "__global__":
  116. return data.get_region_types().GLOBAL
  117. else:
  118. assert(False)
  119. for each in blocks:
  120. data.add_region(each['name'], each['start'], each['end'],
  121. each['line_begin'], each['line_end'], each['cursor'],
  122. get_type_id(data, each['type']), each['checksum'])
  123. add_regions_rec(self, data, each['children'])
  124. add_regions_rec(self, data, blocks)
  125. def parse(self, data):
  126. def reset_next_block(start):
  127. return {'name':'', 'start':start, 'cursor':0, 'type':''}
  128. count_mismatched_brackets = 0
  129. text = data.get_content()
  130. indent_current = 0;
  131. blocks = [{'name':'__global__', 'start':0, 'cursor':0, 'type':'__global__', 'indent_start':indent_current, 'children':[]}]
  132. curblk = 0
  133. next_block = reset_next_block(0)
  134. cursor_last_pos = 0
  135. cursor_current = 1
  136. for m in re.finditer(self.regex_cpp, text):
  137. # Comment
  138. if text[m.start()] == '/':
  139. data.add_marker(m.start(), m.end(), data.get_marker_types().COMMENT)
  140. if text[m.start():m.end()].startswith("//\n"):
  141. print text[m.start():m.end()]
  142. # String
  143. elif text[m.start()] == '"' or text[m.start()] == '\'':
  144. data.add_marker(m.start() + 1, m.end() - 1, data.get_marker_types().STRING)
  145. # Statement end
  146. elif text[m.start()] == ';':
  147. # Reset next block name and start
  148. next_block['name'] = ""
  149. next_block['start'] = m.end() # potential region start
  150. # Double end line
  151. elif text[m.start()] == '\n' or text[m.start()] == '\r':
  152. # Reset next block start, if has not been named yet
  153. if next_block['name'] == "":
  154. next_block['start'] = m.end() # potential region start
  155. # Block start...
  156. elif text[m.start()] == '{':
  157. # shift indent right
  158. indent_current += 1
  159. # ... if name detected previously
  160. if next_block['name'] != '': # - Start of enclosed block
  161. blocks.append({'name':next_block['name'],
  162. 'start':next_block['start'],
  163. 'cursor':next_block['cursor'],
  164. 'type':next_block['type'],
  165. 'indent_start':indent_current,
  166. 'children':[]})
  167. next_block = reset_next_block(m.end())
  168. curblk += 1
  169. # ... reset next block start, otherwise
  170. else: # - unknown type of block start
  171. next_block['start'] = m.end() # potential region start
  172. # Block end...
  173. elif text[m.start()] == '}':
  174. # ... if indent level matches the start
  175. if blocks[curblk]['indent_start'] == indent_current:
  176. next_block = reset_next_block(m.end())
  177. if curblk == 0:
  178. logging.warning("Non-matching closing bracket '}' detected: " + data.get_path() + ":" +
  179. str(cursor_current + len(self.regex_ln.findall(text, cursor_last_pos, m.start()))))
  180. count_mismatched_brackets += 1
  181. continue
  182. self.finalize_block(text, blocks[curblk], m.end())
  183. assert(blocks[curblk]['type'] != '__global__')
  184. curblk -= 1
  185. assert(curblk >= 0)
  186. blocks[curblk]['children'].append(blocks.pop())
  187. # shift indent left
  188. indent_current -= 1
  189. if indent_current < 0:
  190. logging.warning("Non-matching closing bracket '}' detected")
  191. count_mismatched_brackets += 1
  192. indent_current = 0
  193. # Potential class, interface
  194. elif m.group('block_type') != None:
  195. if next_block['name'] == "":
  196. # - 'name'
  197. next_block['name'] = m.group('block_name').strip()
  198. # - 'cursor'
  199. cursor_current += len(self.regex_ln.findall(text, cursor_last_pos, m.start('block_name')))
  200. cursor_last_pos = m.start('block_name')
  201. next_block['cursor'] = cursor_current
  202. # - 'type'
  203. next_block['type'] = m.group('block_type').strip()
  204. # - 'start' detected earlier
  205. # Potential function name detected...
  206. elif m.group('fn_name') != None:
  207. # ... if outside of a function
  208. # (do not detect functions enclosed directly in a function, i.e. without classes)
  209. # ... and other name before has not been matched
  210. if blocks[curblk]['type'] != 'function' and (next_block['name'] == ""):
  211. # - 'name'
  212. next_block['name'] = m.group('fn_name').strip()
  213. # - 'cursor'
  214. cursor_current += len(self.regex_ln.findall(text, cursor_last_pos, m.start('fn_name')))
  215. cursor_last_pos = m.start('fn_name')
  216. # NOTE: cursor could be collected together with line_begin, line_end,
  217. # but we keep it here separately for easier debugging of file parsing problems
  218. next_block['cursor'] = cursor_current
  219. # - 'type'
  220. next_block['type'] = 'function'
  221. # - 'start' detected earlier
  222. else:
  223. assert(len("Unknown match by regular expression") == 0)
  224. while indent_current > 0:
  225. # log all
  226. logging.warning("Non-matching opening bracket '{' detected")
  227. count_mismatched_brackets += 1
  228. indent_current -= 1
  229. for (ind, each) in enumerate(blocks):
  230. each = each # used
  231. block = blocks[len(blocks) - 1 - ind]
  232. self.finalize_block(text, block, len(text))
  233. self.add_lines_data(text, blocks)
  234. self.add_regions(data, blocks)
  235. return count_mismatched_brackets