Commit aba71287 authored by Rene Saarsoo's avatar Rene Saarsoo
Browse files

Switch JsDuck::Esprima over to ExecJS.

ExecJS will select the available JavaScript runtime.
parent 5f1d46b4
Loading
Loading
Loading
Loading
+9 −7
Original line number Diff line number Diff line
require 'v8'
require 'execjs'
require 'json'
require 'singleton'

module JsDuck

  # Runs Esprima.js through V8.
  # Runs Esprima.js through execjs (this will select any available
  # JavaScript runtime - preferably therubyracer on MRI and JScript
  # on Windows).
  #
  # Initialized as singleton to avoid loading the esprima.js more
  # than once - otherwise performace will severely suffer.
@@ -12,17 +14,17 @@ module JsDuck
    include Singleton

    def initialize
      @v8 = V8::Context.new
      esprima = File.dirname(File.dirname(File.dirname(File.expand_path(__FILE__))))+"/esprima/esprima.js";
      @v8.load(esprima)
      esprima_path = File.dirname(File.dirname(File.dirname(File.expand_path(__FILE__))))+"/esprima/esprima.js";
      esprima = IO.read(esprima_path)
      helper = "function runEsprima(js) { return JSON.stringify(esprima.parse(js, {comment: true, range: true, raw: true})); }"
      @context = ExecJS.compile(esprima + "\n\n" + helper)
    end

    # Parses JavaScript source code using Esprima.js
    #
    # Returns the resulting AST
    def parse(input)
      @v8['js'] = input
      json = @v8.eval("JSON.stringify(esprima.parse(js, {comment: true, range: true, raw: true}))")
      json = @context.call("runEsprima", input)
      return JSON.parse(json, :max_nesting => false)
    end