Skip to content
This repository has been archived by the owner on Aug 18, 2018. It is now read-only.

Commit

Permalink
adding ecma visitr
Browse files Browse the repository at this point in the history
git-svn-id: svn+ssh://rubyforge.org/var/svn/johnson/trunk@98 54575175-8111-4fdf-a583-07ff49f40e23
  • Loading branch information
aaronp committed Mar 31, 2008
1 parent afc18d7 commit 597bdcf
Show file tree
Hide file tree
Showing 5 changed files with 84 additions and 0 deletions.
4 changes: 4 additions & 0 deletions lib/johnson/nodes/node.rb
Expand Up @@ -41,6 +41,10 @@ def initialize(line, column, value)
def to_sexp
SexpVisitor.new.accept(self)
end

def to_ecma
EcmaVisitor.new.accept(self)
end
end
SINGLE_NODES.each { |se| const_set(se.to_sym, Class.new(Node)) }
end
Expand Down
1 change: 1 addition & 0 deletions lib/johnson/visitors.rb
@@ -1 +1,2 @@
require 'johnson/visitors/sexp_visitor'
require 'johnson/visitors/ecma_visitor'
71 changes: 71 additions & 0 deletions lib/johnson/visitors/ecma_visitor.rb
@@ -0,0 +1,71 @@
module Johnson
module Visitors
class EcmaVisitor
def initialize
@depth = 0
end

def visit_SourceElements(o)
(@depth == 0 ? '' : '{') +
o.value.map { |x| "#{indent}#{x.accept(self)}" }.join("\n") +
(@depth == 0 ? '' : '}')
end

%w{ Name Number Regexp String }.each do |type|
define_method(:"visit_#{type}") do |o|
o.value
end
end

{
'OpEqual' => '=',
'StrictNotEqual' => '!==',
'StrictEqual' => '===',
'Or' => '||',
'OpURShift' => '>>>',
'OpURShiftEqual' => '>>>=',
'OpSubtract' => '-',
'OpSubtractEqual' => '-=',
'OpRShift' => '>>',
'OpRShiftEqual' => '>>=',
'OpMultiply' => '*',
'OpMultiplyEqual' => '*=',
'OpMod' => '%',
'OpModEqual' => '%=',
'OpLShift' => '<<',
'OpLShiftEqual' => '<<=',
'OpDivide' => '/',
'OpDivideEqual' => '/=',
'OpBitXor' => '^',
'OpBitXorEqual' => '^=',
'OpBitOr' => '|',
'OpBitOrEqual' => '|=',
'OpBitAnd' => '&',
'OpBitAndEqual' => '&=',
'OpAdd' => '+',
'OpAddEqual' => '+=',
'NotEqual' => '!=',
'LessThan' => '<',
'LessThanOrEqual' => '<=',
'GreaterThan' => '>',
'GreaterThanOrEqual' => '>=',
'And' => '&&',
'InstanceOf' => 'instanceof',
'Equal' => '==',
}.each do |type,op|
define_method(:"visit_#{type}") do |o|
"#{o.left && o.left.accept(self)}" \
" #{op} " \
"#{o.right && o.right.accept(self)}"
end
end

def accept(target)
target.accept(self)
end

private
def indent; ' ' * @depth * 2; end
end
end
end
4 changes: 4 additions & 0 deletions test/helper.rb
Expand Up @@ -37,5 +37,9 @@ def setup
def assert_sexp(expected, actual)
assert_equal(expected, actual.to_sexp)
end

def assert_ecma(expected, actual)
assert_equal(expected, actual.to_ecma)
end
end
end
4 changes: 4 additions & 0 deletions test/johnson/nodes/binary_node_test.rb
Expand Up @@ -51,6 +51,10 @@ class BinaryNodeTest < Johnson::NodeTestCase
)
end
end

define_method(:"test_#{op}_to_ecma") do
assert_ecma("i #{sym} 10", @parser.parse("i #{sym} 10"))
end
end
{
:and => '&&',
Expand Down

0 comments on commit 597bdcf

Please sign in to comment.