Commit c8c820aa authored by Rene Saarsoo's avatar Rene Saarsoo
Browse files

Detection of string return values.

parent 08b86793
Loading
Loading
Loading
Loading
+18 −0
Original line number Diff line number Diff line
@@ -75,6 +75,8 @@ module JsDuck
        :this
      elsif boolean?(ast)
        "Boolean"
      elsif string?(ast)
        "String"
      else
        :other
      end
@@ -112,6 +114,22 @@ module JsDuck
      ast["type"] == "Literal" && (ast["value"] == true || ast["value"] == false)
    end

    def string?(ast)
      if string_literal?(ast)
        true
      elsif ast["type"] == "BinaryExpression" && ast["operator"] == "+"
        string?(ast["left"]) || string?(ast["right"])
      elsif ast["type"] == "UnaryExpression" && ast["operator"] == "typeof"
        true
      else
        false
      end
    end

    def string_literal?(ast)
      ast["type"] == "Literal" && ast["value"].is_a?(String)
    end

    def control_flow?(ast)
      CONTROL_FLOW[ast["type"]]
    end
+22 −0
Original line number Diff line number Diff line
@@ -285,4 +285,26 @@ describe "JsDuck::FunctionAst#return_types" do
    end
  end

  describe "returns ['String'] when function body" do
    it "returns a string literal" do
      returns("/** */ function foo() { return 'foo'; }").should == ["String"]
    end

    it "returns a string concatenation" do
      returns("/** */ function foo() { return 'foo' + 'bar'; }").should == ["String"]
    end

    it "returns a string concatenated with number" do
      returns("/** */ function foo() { return 'foo' + 7; }").should == ["String"]
    end

    it "returns a number concatenated with string" do
      returns("/** */ function foo() { return 8 + 'foo'; }").should == ["String"]
    end

    it "returns a typeof expression" do
      returns("/** */ function foo() { return typeof 8; }").should == ["String"]
    end
  end

end