Stop calculating cyclomatic complexity for methods which have Macro conditions (#99)

This commit is contained in:
Vitalii Elenhaupt 2019-03-31 20:27:20 +03:00 committed by GitHub
parent a0da393429
commit c95ea297bd
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 36 additions and 2 deletions

View file

@ -18,6 +18,32 @@ module Ameba::AST
visitor.count.should eq 1
end
it "is 1 if there is Macro::For" do
code = %(
def initialize()
{% for c in ALL_NODES %}
true || false
{% end %}
end
)
node = Crystal::Parser.new(code).parse
visitor = CountingVisitor.new node
visitor.count.should eq 1
end
it "is 1 if there is Macro::If" do
code = %(
def initialize()
{% if foo.bar? %}
true || false
{% end %}
end
)
node = Crystal::Parser.new(code).parse
visitor = CountingVisitor.new node
visitor.count.should eq 1
end
{% for pair in [
{code: "if true; end", description: "conditional"},
{code: "while true; end", description: "while loop"},

View file

@ -1,10 +1,12 @@
module Ameba::AST
# AST Visitor that counts occurrences of certain keywords
class CountingVisitor < Crystal::Visitor
@complexity = 1
DEFAULT_COMPLEXITY = 1
getter macro_condition = false
# Creates a new counting visitor
def initialize(@scope : Crystal::ASTNode)
@complexity = DEFAULT_COMPLEXITY
end
# :nodoc:
@ -24,8 +26,14 @@ module Ameba::AST
{% for node in %i(if while until rescue when or and) %}
# :nodoc:
def visit(node : Crystal::{{ node.id.capitalize }})
@complexity += 1
@complexity += 1 unless macro_condition
end
{% end %}
def visit(node : Crystal::MacroIf | Crystal::MacroFor)
@macro_condition = true
@complexity = DEFAULT_COMPLEXITY
false
end
end
end