Class: JsDuck::Esprima

Inherits:
Object
  • Object
show all
Includes:
Util::Singleton
Defined in:
lib/jsduck/esprima.rb

Overview

Runs Esprima.js through JavaScript runtime selected by ExecJS. Normally this will be V8 engine within therubyracer gem, but when JSDuck is installed through some other means than rubygems, then one could use any of the runtimes supported by ExecJS. (NodeJS for example.)

Initialized as singleton to avoid loading the esprima.js more than once - otherwise performace will severely suffer.

Instance Method Summary collapse

Methods included from Util::Singleton

included

Constructor Details

#initializeEsprima

Returns a new instance of Esprima.



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/jsduck/esprima.rb', line 18

def initialize
  esprima_path = File.dirname(File.expand_path(__FILE__)) + "/esprima/esprima.js"
  esprima = IO.read(esprima_path)

  # Esprima attempts to assign to window.esprima, but our v8
  # engine has no global window variable defined.  So define our
  # own and then grab esprima out from it again.
  source = <<-EOJS
    if (typeof window === "undefined") {
        var window = {};
    }

    #{esprima}

    var esprima = window.esprima;

    function runEsprima(js) {
      return JSON.stringify(esprima.parse(js, {comment: true, range: true, raw: true}));
    }
  EOJS

  @context = ExecJS.compile(source)
end

Instance Method Details

#parse(input) ⇒ Object

Parses JavaScript source code using Esprima.js

Returns the resulting AST



45
46
47
48
# File 'lib/jsduck/esprima.rb', line 45

def parse(input)
  json = @context.call("runEsprima", input)
  return Util::Json.parse(json, :max_nesting => false)
end