Permalink
Browse files

Added the ability to serialize ASTs using the Marshal module.

  • Loading branch information...
1 parent 137a42a commit a5349c5e334329523cdaf0b81a78001bfc96cd0b @chriswailes committed Jul 28, 2012
Showing with 25 additions and 1 deletion.
  1. +0 −1 TODO
  2. +17 −0 lib/rltk/ast.rb
  3. +8 −0 test/tc_ast.rb
View
@@ -12,7 +12,6 @@ lexer.rb:
ast.rb:
Add the ability to traverse the AST in pre-order, post-order, or topological-order.
- Add ability to serialize/dump an AST to any IO object.
tokens.rb:
View
@@ -272,6 +272,23 @@ def delete_note(key, recursive = true)
@notes.delete(key)
end
+ # This method is a simple wrapper around Marshal.dump, and is used
+ # to serialize an AST. You can use Marshal.load to reconstruct a
+ # serialized AST.
+ #
+ # @param [nil, IO, String] dest Where the serialized version of the AST will end up. If nil, this method will return the AST as a string.
+ # @param [Fixnum] limit Recursion depth. If -1 is specified there is no limit on the recursion depth.
+ #
+ # @return [void, String] String if *dest* is nil, void otherwise.
+ def dump(dest = nil, limit = -1)
+ case dest
+ when nil then Marshal.dump(self, limit)
+ when String then File.open(dest, 'w') { |f| Marshal.dump(self, f, limit) }
+ when IO then Marshal.dump(self, dest, limit)
+ else raise TypeError, "AST#dump expects nil, a String, or an IO object for the dest parameter."
+ end
+ end
+
# An iterator over the node's children.
#
# @return [void]
View
@@ -57,6 +57,14 @@ def test_children
assert_equal(node.children, expected_children.reverse)
end
+ def test_dump
+ tree0_string = @tree0.dump
+
+ reloaded_tree = Marshal.load(tree0_string)
+
+ assert_equal(@tree0, reloaded_tree)
+ end
+
def test_equal
assert_equal(@tree0, @tree1)
assert_not_equal(@tree0, @tree2)

0 comments on commit a5349c5

Please sign in to comment.