complexity.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. #
  2. # Metrix++, Copyright 2009-2013, Metrix++ Project
  3. # Link: http://swi.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 core.api
  20. import re
  21. class Plugin(core.api.Plugin, core.api.Child, core.api.IConfigurable):
  22. def declare_configuration(self, parser):
  23. parser.add_option("--std.code.complexity.on", action="store_true", default=False,
  24. help="Enables processing of complexity metrics: cyclomatic by McCabe [default: %default]")
  25. def configure(self, options):
  26. self.is_active = options.__dict__['std.code.complexity.on']
  27. def initialize(self):
  28. if self.is_active == True:
  29. namespace = self.get_plugin_loader().get_database_loader().create_namespace(self.get_name(), support_regions = True)
  30. namespace.add_field('cyclomatic', int)
  31. core.api.subscribe_by_parents_name('std.code.cpp', self, 'callback_cpp')
  32. # cyclomatic complexity pattern
  33. pattern = re.compile(r'''([^0-9A-Za-z_]((if)|(case)|(for)|(while))[^0-9A-Za-z_])|[&][&]|[|][|]|[?]''')
  34. def callback_cpp(self, parent, data):
  35. text = None
  36. for (ind, region) in enumerate(data.iterate_regions(filter_group=data.get_region_types().FUNCTION)):
  37. # cyclomatic complexity
  38. if ind == 0 and region.get_data(self.get_name(), 'cyclomatic') != None:
  39. return # data is available in first from cloned database, skip collection
  40. if text == None: # lazy loading for performance benefits
  41. text = data.get_content(exclude = data.get_marker_types().ALL_EXCEPT_CODE)
  42. count = 0
  43. start_pos = region.get_offset_begin()
  44. for sub_id in region.iterate_subregion_ids():
  45. # exclude sub regions, like enclosed classes
  46. count += len(self.pattern.findall(text, start_pos, data.get_region(sub_id).get_offset_begin()))
  47. start_pos = data.get_region(sub_id).get_offset_end()
  48. count += len(self.pattern.findall(text, start_pos, region.get_offset_end()))
  49. region.set_data(self.get_name(), 'cyclomatic', count)