Skip to content

Commit

Permalink
Report line number for JavaScript syntax errors.
Browse files Browse the repository at this point in the history
A hacky solution for start as the RKelly::Parser doesn't allow
public access to the token at which it stopped.

Improvement of #415
  • Loading branch information
nene committed Jul 29, 2013
1 parent 91ef4ba commit d311d9a
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 5 deletions.
17 changes: 15 additions & 2 deletions lib/jsduck/js/parser.rb
Original file line number Diff line number Diff line change
Expand Up @@ -18,16 +18,29 @@ 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)
# Adjust Program node range
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
Expand Down
14 changes: 11 additions & 3 deletions spec/js_parser_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit d311d9a

Please sign in to comment.