Permalink
Browse files

add exception_class and exception_variable for rescue node

  • Loading branch information...
1 parent 101b77e commit 570b1192e5e8af8351518b8f16ab426627c4f261 @flyerhzm committed Nov 2, 2012
Showing with 64 additions and 0 deletions.
  1. +44 −0 lib/code_analyzer/sexp.rb
  2. +20 −0 spec/code_analyzer/sexp_spec.rb
@@ -525,6 +525,50 @@ def statements
stmts
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.
#
# s(:hash,
@@ -420,6 +420,26 @@ def show
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
it "should get value for hash node" do
node = parse_content("{first_name: 'Richard', last_name: 'Huang'}").grep_node(sexp_type: :hash)

0 comments on commit 570b119

Please sign in to comment.