/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is Source Code Map.
 *
 * The Initial Developer of the Original Code is
 * Alexander J. Vincent <ajvincent@gmail.com>.
 * Portions created by the Initial Developer are Copyright (C) 2006
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

// Component metadata.  Please change all the values in this section.

var componentName = "Source Code Map, JavaScript";
var contractId    = "@verbosio.mozdev.org/source-map;1?contentType=application/javascript";
var componentId   = Components.ID("{8e6555e3-1db3-43ea-bfe1-24eda3c992fc}");

// Utility function.
function ERROR_FAILURE() {
  throw Components.results.NS_ERROR_FAILURE;
}

// Utility function.
function NOT_IMPLEMENTED() {
  throw Components.results.NS_ERROR_NOT_IMPLEMENTED;
}

function ERROR_ABORT() {
  throw Components.results.NS_ERROR_ABORT;
}

const SOURCE_MAP_STATE_CLEAR            = 0;
const SOURCE_MAP_STATE_FRAGMENT_OPEN    = 1;
const SOURCE_MAP_STATE_HAS_FRAGMENT     = 2;
const SOURCE_MAP_STATE_SYNTAX_ERROR_REQ = 3;

var C_i = Components.interfaces;

const xeISourceMap                = C_i.xeISourceMap;
const nsIScriptError              = C_i.nsIScriptError;
const nsIProgrammingLanguage      = C_i.nsIProgrammingLanguage;
const nsISecurityCheckedComponent = C_i.nsISecurityCheckedComponent;
const nsIClassInfo                = C_i.nsIClassInfo;
const nsIComponentRegistrar       = C_i.nsIComponentRegistrar;
const nsIFactory                  = C_i.nsIFactory;
const nsIModule                   = C_i.nsIModule;
const nsISupports                 = C_i.nsISupports;

C_i = null;

function JSSourceMap() {
  this.clear();
  this.functionCount = 0;
}
JSSourceMap.prototype = {
  // xeISourceMap
  clear: function clear() {
    this.internalSource = "";
    this.mapArray = [];
    this.lineCount = 0;
    this.mapCount = 0;
    this.firstSyntaxError = null;
    this.currentURI = "";
    this.state = SOURCE_MAP_STATE_CLEAR;
  },

  // xeISourceMap
  startFragment: function startFragment(aURIString) {
    switch (this.state) {
      case SOURCE_MAP_STATE_CLEAR:
      case SOURCE_MAP_STATE_HAS_FRAGMENT:
        // Ok!
        break;

      default:
        ERROR_ABORT();
    }

    this.internalSource += "function a" + (this.functionCount++) + " () {\n";
    this.lineCount++;
    this.currentURI = aURIString;

    this.state = SOURCE_MAP_STATE_FRAGMENT_OPEN;
  },

  // xeISourceMap
  endFragment: function endFragment() {
    switch (this.state) {
      case SOURCE_MAP_STATE_FRAGMENT_OPEN:
        // Ok!
        break;

      default:
        ERROR_ABORT();
    }

    this.internalSource += "\n}\n";
    this.lineCount += 2;

    this.state = SOURCE_MAP_STATE_HAS_FRAGMENT;
  },

  // xeISourceMap
  addSource: function addSource(aSourceString, aLineNumber, aColumnNumber) {
    switch (this.state) {
      case SOURCE_MAP_STATE_FRAGMENT_OPEN:
        // Ok!
        break;

      default:
        ERROR_ABORT();
    }

    var sourceLineCount = source.split("\n").length;

    var map = {
      source:             aSourceString,
      sourceLineCount:    sourceLineCount,
      sourceLineNumber:   aLineNumber,
      sourceColumnNumber: aColumnNumber,
      mapLineNumber:      this.lineCount,
      uri:                this.currentURI
    }

    this.mapArray[this.mapCount++] = map;
    this.internalSource += aSourceString + "\n";
    this.lineCount += sourceLineCount;
  },

  // xeISourceMap
  getFirstSyntaxError: function getFirstSyntaxError() {
    switch (this.state) {
      case SOURCE_MAP_STATE_SYNTAX_ERROR_REQ:
        return this.firstSyntaxError;

      case SOURCE_MAP_STATE_CLEAR:
      case SOURCE_MAP_STATE_HAS_FRAGMENT:
        // Ok!
        break;

      default:
        ERROR_ABORT();
    }

    var scriptError = null;

    try {
      var sandboxURL = "http://verbosio.mozdev.org/sandbox?date" + (new Date()) * 1
      sandboxURL += "&salt=" + String(Math.random()).substr(2);
      const sandbox = new Components.utils.Sandbox(sandboxURL);
      var res = Components.utils.evalInSandbox(this.internalSource, sandbox);
    }
    catch (e) {
      if (e.name != "SyntaxError") {
        return null;
      }

       scriptError = Components.classes("@mozilla.org/scripterror;1")
                               .createInstance(nsIScriptError);
      var internalLineNumber = e.lineNumber;
      var sourceLine = this.internalSource.split("\n")[internalLineNumber - 1];

      var realLineNumber = -1;
      var errorURI = null;
      for (var i = 0; i < this.mapArray.length; i++) {
        var map = this.mapArray[i];
        if (internalLineNumber > map.mapLineNumber + map.sourceLineCount) {
          continue;
        }

        realLineNumber = (internalLineNumber - map.mapLineNumber) + map.sourceLineNumber;
        errorURI = map.uri;
        break;
      }

      if (realLineNumber <= 0) {
        ERROR_FAILURE();
      }

      scriptError.init(e.message,
                       errorURI,
                       sourceLine,
                       realLineNumber,
                       0, // We can't get a column number for JS syntax errors.
                       nsIScriptError.errorFlag);
    }

    this.state = SOURCE_MAP_STATE_SYNTAX_ERROR_REQ;
    this.firstSyntaxError = scriptError;
    return scriptError;
  },

  // nsIClassInfo
  getInterfaces: function getInterfaces(aCount) {
    var interfaces = [xeISourceMap,
                      nsIClassInfo];
    aCount.value = interfaces.length;
    return interfaces;
  },

  // nsIClassInfo
  getHelperForLanguage: function getHelperForLanguage(aLanguage) {
    return null;
  },

  // nsIClassInfo
  classDescription: componentName,

  // nsIClassInfo
  classID: componentId,

  // nsIClassInfo
  contractID: contractId,

  // nsIClassInfo
  implementationLanguage: nsIProgrammingLanguage.JAVASCRIPT,

  // nsIClassInfo
  flags: 0,

  // nsISupports
  QueryInterface: function QueryInterface(aIID) {
    if (aIID.equals(xeISourceMap) ||
        aIID.equals(nsIClassInfo) ||
        aIID.equals(nsISupports))
      return this;

    // Discover what interfaces we need
    var i = Components.interfaces;
    var found = false;
    for (var prop in i) {
      if (aIID.equals(i[prop])) {
        found = true;
        dump("QUERYINTERFACE jsSourceMap: " + prop + "\n");
        break;
      }
    }
    if (!found) {
      dump("QUERYINTERFACE jsSourceMap: Unknown\n");
    }

    throw Components.results.NS_ERROR_NO_INTERFACE;
    return null;
  }
};

/* Factories in modules cause leaks according to
   https://bugzilla.mozilla.org/show_bug.cgi?id=168411#c28
 */

var factory = {
  createInstance: function createInstance(outer, iid) {
    if (outer != null)
      throw Components.results.NS_ERROR_NO_AGGREGATION;
    return (new JSSourceMap()).QueryInterface(iid);
  }
};

/* The rest of this code is largely borrowed from "Creating Applications With
 * Mozilla", http://books.mozdev.org, Chapter 8.
 */
var Module = {
  registerSelf: function registerSelf(compMgr, fileSpec, location, type) {
    compReg = compMgr.QueryInterface(nsIComponentRegistrar);

    compReg.registerFactoryLocation(componentId,
                                    componentName,
                                    contractId,
                                    fileSpec,
                                    location,
                                    type );
  },

  getClassObject: function getClassObject(compMgr, aCID, aIID) {
    if (!aCID.equals(componentId)) {
      throw Components.results.NS_ERROR_NO_INTERFACE;
    }
    if (!aIID.equals(nsIFactory)) {
      throw Components.results.NS_ERROR_NOT_IMPLEMENTED;
    }
    return factory;
  },

  canUnload: function canUnload() {
    return true;
  },

  QueryInterface: function QueryInterface(aIID) {
    if (aIID.equals(nsIModule) ||
       (aIID.equals(nsISupports)))
      return this;

    throw Components.results.NS_ERROR_NO_INTERFACE;
    return null;
  }
};

function NSGetModule(compMgr, fileSpec) {
  return Module;
}
