Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 26 additions & 1 deletion lib/ast/node.rb
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,32 @@ def to_sexp(indent=0)

sexp
end
alias :inspect :to_sexp

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should become alias :to_s :to_sexp.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

to_s is defined, so i did't want to touch that
figured you can easily do that line if you want it. That change hasn't really got anything to do with the inspect changing.

# Converts `self` to a s-expression ruby string.
# The code return will recreate the node, using the sexp module s()
#
# @param [Integer] indent Base indentation level.
# @return [String]
def inspect(indent=0)
indented = " " * indent
sexp = "#{indented}s(:#{@type}"

first_node_child = children.index do |child|
child.is_a?(Node) || child.is_a?(Array)
end || children.count

children.each_with_index do |child, idx|
if child.is_a?(Node) && idx >= first_node_child
sexp << ",\n#{child.inspect(indent + 1)}"
else
sexp << ", #{child.inspect}"
end
end

sexp << ")"

sexp
end

# @return [AST::Node] self
def to_ast
Expand Down
14 changes: 14 additions & 0 deletions test/test_ast.rb
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,20 @@ class MetaNode < AST::Node
]).to_sexp.should.equal "(a :sym\n (b\n (node 0 1)\n (node 0 1)))"
end

it 'should format inspect correctly' do
AST::Node.new(:a, [ :sym, [ 1, 2 ] ]).inspect.should.equal "s(:a, :sym, [1, 2])"
AST::Node.new(:a, [ :sym,
AST::Node.new(:b, [ @node, @node ])
]).inspect.should.equal "s(:a, :sym,\n s(:b,\n s(:node, 0, 1),\n s(:node, 0, 1)))"
end

it 'should recreate inspect output' do
simple_node = AST::Node.new(:a, [ :sym, [ 1, 2 ] ])
eval(simple_node.inspect).should.equal simple_node
complex_node = s(:a , :sym, s(:b, s(:node, 0, 1), s(:node, 0, 1)))
eval(complex_node.inspect).should.equal complex_node
end

it 'should return self in to_ast' do
@node.to_ast.should.be.identical_to @node
end
Expand Down