From d311d9a01709fd94da08a5968c991b35609e4dff Mon Sep 17 00:00:00 2001 From: Rene Saarsoo Date: Mon, 29 Jul 2013 17:25:53 +0300 Subject: [PATCH] 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 --- lib/jsduck/js/parser.rb | 17 +++++++++++++++-- spec/js_parser_spec.rb | 14 +++++++++++--- 2 files changed, 26 insertions(+), 5 deletions(-) diff --git a/lib/jsduck/js/parser.rb b/lib/jsduck/js/parser.rb index c5ad511cf..18d249279 100644 --- a/lib/jsduck/js/parser.rb +++ b/lib/jsduck/js/parser.rb @@ -18,9 +18,10 @@ def initialize(input, options={}) # 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 @@ def parse 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 diff --git a/spec/js_parser_spec.rb b/spec/js_parser_spec.rb index 20eb9dae6..b032a9437 100644 --- a/spec/js_parser_spec.rb +++ b/spec/js_parser_spec.rb @@ -7,11 +7,19 @@ def parse(input) 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