Skip to content

Commit

Permalink
add exception_class and exception_variable for rescue node
Browse files Browse the repository at this point in the history
  • Loading branch information
flyerhzm committed Nov 2, 2012
1 parent 101b77e commit 570b119
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 0 deletions.
44 changes: 44 additions & 0 deletions lib/code_analyzer/sexp.rb
Expand Up @@ -525,6 +525,50 @@ def statements
stmts stmts
end end


# Get expcetion class of rescue node.
#
# s(:rescue,
# s(
# s(:var_ref,
# s(:@const, "CustomException", s(1, 17))
# )
# ),
# nil,
# s(:stmts_add, s(:stmts_new), s(:void_stmt)),
# nil
# )
# => s(s(:var_ref, s(:@const, "CustomException", s(1, 17))))
def exception_classes
if :rescue == sexp_type
if :mrhs_add == self[1].sexp_type
exceptions = Array.new(self[1][2])
arg_nodes = self[1][1][1]
while :args_add == arg_nodes.sexp_type
exceptions.unshift arg_nodes[2]
arg_nodes = arg_nodes[1]
end
exceptions
else
self[1]
end
end
end

# Get exception variable of rescue node.
#
# s(:rescue,
# nil,
# s(:var_field, s(:@ident, "e", s(1, 20))),
# s(:stmts_add, s(:stmts_new), s(:void_stmt)),
# nil
# )
# => s(:var_field, s(:@ident, "e", s(1, 20)))
def exception_variable
if :rescue == sexp_type
self[2]
end
end

# Get hash value node. # Get hash value node.
# #
# s(:hash, # s(:hash,
Expand Down
20 changes: 20 additions & 0 deletions spec/code_analyzer/sexp_spec.rb
Expand Up @@ -420,6 +420,26 @@ def show
end end
end end


describe "exception_classes" do
it "should get exception classes of rescue node" do
node = parse_content("def test; rescue CustomException; end").grep_node(sexp_type: :rescue)
node.exception_classes.first.to_s.should == "CustomException"
end

it "should get exception classes of rescue node for multiple exceptions" do
node = parse_content("def test; rescue StandardError, CustomException; end").grep_node(sexp_type: :rescue)
node.exception_classes.first.to_s.should == "StandardError"
node.exception_classes.last.to_s.should == "CustomException"
end
end

describe "exception_variable" do
it "should get exception class of rescue node" do
node = parse_content("def test; rescue => e; end").grep_node(sexp_type: :rescue)
node.exception_variable.to_s.should == "e"
end
end

describe "hash_value" do describe "hash_value" do
it "should get value for hash node" do it "should get value for hash node" do
node = parse_content("{first_name: 'Richard', last_name: 'Huang'}").grep_node(sexp_type: :hash) node = parse_content("{first_name: 'Richard', last_name: 'Huang'}").grep_node(sexp_type: :hash)
Expand Down

0 comments on commit 570b119

Please sign in to comment.