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 Diff line number Diff line
@@ -18,9 +18,10 @@ module JsDuck
      # Parses JavaScript source code with RKelly, turns RKelly AST
      # into Esprima AST, and associate comments with syntax nodes.
      def parse
        ast = RKelly::Parser.new.parse(@input)
        parser = RKelly::Parser.new
        ast = parser.parse(@input)
        unless ast
          raise "Invalid JavaScript syntax"
          raise syntax_error(parser)
        end

        ast = ADAPTER.adapt(ast)
@@ -28,6 +29,18 @@ module JsDuck
        ast["range"] = [0, @input.length-1]
        return Js::Associator.new(@input).associate(ast)
      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
+11 −3
Original line number Diff line number Diff line
@@ -7,11 +7,19 @@ describe JsDuck::Js::Parser do
  end

  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
        parse("if ( x } alert('Hello');")
        parse("if ( x \n } alert('Hello');")
      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