Class: JsDuck::Js::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/jsduck/js/parser.rb

Overview

A JavaScript parser implementation that uses RKelly and adapts its output to be the same as the old Esprima parser used to produce.

Constant Summary collapse

ADAPTER =
Js::RKellyAdapter.new

Instance Method Summary collapse

Constructor Details

#initialize(input, options = {}) ⇒ Parser

Returns a new instance of Parser.



14
15
16
# File 'lib/jsduck/js/parser.rb', line 14

def initialize(input, options={})
  @input = input
end

Instance Method Details

#parseObject

Parses JavaScript source code with RKelly, turns RKelly AST into Esprima AST, and associate comments with syntax nodes.



20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/jsduck/js/parser.rb', line 20

def parse
  parser = RKelly::Parser.new
  ast = parser.parse(@input)
  unless ast
    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

#syntax_error(parser) ⇒ Object



33
34
35
36
37
38
39
40
# File 'lib/jsduck/js/parser.rb', line 33

def syntax_error(parser)
  token = parser.stopped_at
  if token
    "Invalid JavaScript syntax: Unexpected '#{token.value}' on line #{token.range.from.line}"
  else
    "Invalid JavaScript syntax: Unexpected end of file"
  end
end