Permalink
Browse files

Add typeof and fix a few bugs

  • Loading branch information...
1 parent ce7f684 commit 65b18b22e4ce17fe37988e8f83bbfda133f47211 @wycats wycats committed Sep 6, 2011
Showing with 83 additions and 4 deletions.
  1. +26 −1 lib/sparta/compilers/compiler.rb
  2. +28 −2 lib/sparta/runtime/object.rb
  3. +1 −1 spec/literals_spec.rb
  4. +28 −0 spec/typeof_spec.rb
@@ -43,7 +43,14 @@ def visit_SourceElementsNode(o)
end
def visit_VarDeclNode(o)
- o.value.accept(self)
+ set_line(o)
+
+ if o.value
+ o.value.accept(self)
+ else
+ g.push_undef
+ end
+
s.set_local o.name
end
@@ -297,6 +304,24 @@ def visit_NewExprNode(o)
g.send :with_constructor, 1
end
+ def visit_TypeOfNode(o)
+ set_line(o)
+
+ if o.value.is_a?(RKelly::Nodes::DotAccessorNode)
+ g.push_const :Utils
+ o.value.value.accept(self)
+ g.push_literal o.value.accessor.to_sym
+ g.send :typeof, 2
+ elsif o.value.is_a?(RKelly::Nodes::FunctionExprNode)
+ g.push_literal "function"
+ else
+ g.push_const :Utils
+ g.push_nil
+ o.value.accept(self)
+ g.send :typeof, 2
+ end
+ end
+
protected
def set_line(o)
@@ -18,6 +18,32 @@ def self.brackets(object, name)
object.send(name)
end
end
+
+ def self.typeof(resolve, name)
+ if resolve == undefined
+ "undefined"
+ else
+ val = resolve ? resolve.get(name) : name
+
+ # TODO: Deal with host objects
+ case val
+ when undefined
+ "undefined"
+ when nil
+ "object"
+ when TrueClass, FalseClass
+ "boolean"
+ when Numeric
+ "number"
+ when String
+ "string"
+ when Function
+ "function"
+ else
+ "object"
+ end
+ end
+ end
end
# Object protocol:
@@ -57,8 +83,8 @@ def inspect
end
def get(name)
- if value = self[name]
- value
+ if self.key?(name)
+ self[name]
elsif proto = prototype
proto.get(name)
else
View
@@ -23,6 +23,6 @@
end
it "understands undefined" do
- e("undefined").should == undefined
+ e("x = undefined; x").should == undefined
end
end
View
@@ -0,0 +1,28 @@
+require "spec_helper"
+
+describe "typeof operator" do
+ it "returns 'undefined' for undefined values" do
+ e("typeof undefined").should == "undefined"
+ e("typeof noSuchValueHere").should == "undefined"
+ e("x = undefined; typeof x").should == "undefined"
+ e("x = {}; typeof x.y").should == "undefined"
+ e("var x; typeof x.y").should == "undefined"
+ end
+
+ map = {
+ "null" => "object",
+ "true" => "boolean",
+ "false" => "boolean",
+ "'string'" => "string",
+ "(function() {})" => "function",
+ "{}" => "object"
+ }
+
+ map.each do |value, type|
+ it "returns '#{type}' for #{value} values" do
+ e("typeof #{value}").should == type
+ e("x = #{value}; typeof x").should == type
+ e("x = { y: #{value} }; typeof x.y").should == type
+ end
+ end
+end

0 comments on commit 65b18b2

Please sign in to comment.