Permalink
Browse files

Add support for class and module nodes

  • Loading branch information...
1 parent f854785 commit e0498c2233ec887829bc06994cea54ff840d26d0 @dkubb dkubb committed Apr 12, 2012
Showing with 61 additions and 2 deletions.
  1. +5 −2 lib/to_source/core_ext/node.rb
  2. +36 −0 lib/to_source/visitor.rb
  3. +20 −0 test/to_source/visitor_test.rb
@@ -9,8 +9,11 @@ class Node
#
# Returns nothing.
def lazy_visit(visitor, parent=nil, indent=false)
- args = [self.node_name, self, parent]
- args.push true if indent
+ name = node_name
+ name = "#{name}_def" if %w[ class module ].include?(name)
+
+ args = [name, self, parent]
+ args << true if indent
visitor.__send__ *args
end
View
@@ -17,6 +17,42 @@ def current_indentation
' ' * @indentation
end
+ def class_def(node, parent)
+ emit "class %s" % node.name.name
+
+ superclass = node.superclass
+ unless superclass.is_a?(Rubinius::AST::NilLiteral)
+ emit " < %s" % superclass.name
+ end
+
+ node.body.lazy_visit self, node, true
+
+ emit "\n"
+ emit "end"
+ end
+
+ def module_def(node, parent)
+ emit "module %s" % node.name.name
+
+ node.body.lazy_visit self, node, true
+
+ emit "\n"
+ emit "end"
+ end
+
+ def empty_body(*)
+ # do nothing
+ end
+
+ def class_scope(node, parent, indent)
+ emit "\n"
+ @indentation += 1 if indent
+ node.body.lazy_visit self, node, indent
+ ensure
+ @indentation -= 1 if indent
+ end
+ alias module_scope class_scope
+
def local_variable_assignment(node, parent)
emit "%s = " % node.name
node.value.lazy_visit self, node
@@ -15,6 +15,26 @@ def assert_converts(expected, code)
assert_equal expected, visit(code)
end
+ def test_class
+ assert_source "class TestClass\nend"
+ end
+
+ def test_class_with_superclass
+ assert_source "class TestClass < Object\nend"
+ end
+
+ def test_class_with_body
+ assert_source "class TestClass\n 1\nend"
+ end
+
+ def test_module
+ assert_source "module TestModule\nend"
+ end
+
+ def test_module_with_body
+ assert_source "module TestModule\n 1\nend"
+ end
+
def test_local_assignment
assert_source "foo = 1"
end

0 comments on commit e0498c2

Please sign in to comment.