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

Report line number for JavaScript syntax errors.

A hacky solution for start as the RKelly::Parser doesn't allow
public access to the token at which it stopped.

Improvement of #415
parent 91ef4ba3
Loading
Loading
Loading
Loading
+15 −2
Original line number Original line Diff line number Diff line
@@ -18,9 +18,10 @@ module JsDuck
      # Parses JavaScript source code with RKelly, turns RKelly AST
      # Parses JavaScript source code with RKelly, turns RKelly AST
      # into Esprima AST, and associate comments with syntax nodes.
      # into Esprima AST, and associate comments with syntax nodes.
      def parse
      def parse
        ast = RKelly::Parser.new.parse(@input)
        parser = RKelly::Parser.new
        ast = parser.parse(@input)
        unless ast
        unless ast
          raise "Invalid JavaScript syntax"
          raise syntax_error(parser)
        end
        end


        ast = ADAPTER.adapt(ast)
        ast = ADAPTER.adapt(ast)
@@ -28,6 +29,18 @@ module JsDuck
        ast["range"] = [0, @input.length-1]
        ast["range"] = [0, @input.length-1]
        return Js::Associator.new(@input).associate(ast)
        return Js::Associator.new(@input).associate(ast)
      end
      end

      def syntax_error(parser)
        tokens = parser.instance_variable_get(:@tokens)
        position = parser.instance_variable_get(:@position)

        if position < tokens.length
          token = tokens[position-1]
          "Invalid JavaScript syntax: Unexpected '#{token.value}' on line #{token.range.from.line}"
        else
          "Invalid JavaScript syntax: Unexpected end of file"
        end
      end
    end
    end


  end
  end
+11 −3
Original line number Original line Diff line number Diff line
@@ -7,11 +7,19 @@ describe JsDuck::Js::Parser do
  end
  end


  describe "parsing invalid JavaScript" do
  describe "parsing invalid JavaScript" do
    it "causes JS syntax error to be raised" do
    it "causes JS syntax error with line number to be raised" do
      begin
      begin
        parse("if ( x } alert('Hello');")
        parse("if ( x \n } alert('Hello');")
      rescue
      rescue
        $!.to_s.should == "Invalid JavaScript syntax"
        $!.to_s.should == "Invalid JavaScript syntax: Unexpected '}' on line 2"
      end
    end

    it "causes JS syntax error for unexpected end of file to be raised" do
      begin
        parse("if ( x ) alert( ")
      rescue
        $!.to_s.should == "Invalid JavaScript syntax: Unexpected end of file"
      end
      end
    end
    end
  end
  end