// Generated by CoffeeScript 1.6.2
(function() {
  var Lexer, child_process, compile, ext, fork, formatSourcePosition, fs, helpers, lexer, loadFile, parser, patchStackTrace, patched, path, sourcemap, vm, _i, _len, _ref,
    __hasProp = {}.hasOwnProperty;

  fs = require('fs');

  vm = require('vm');

  path = require('path');

  child_process = require('child_process');

  Lexer = require('./lexer').Lexer;

  parser = require('./parser').parser;

  helpers = require('./helpers');

  sourcemap = require('./sourcemap');

  exports.VERSION = '1.6.2';

  exports.helpers = helpers;

  exports.compile = compile = function(code, options) {
    var answer, currentColumn, currentLine, fragment, fragments, header, js, merge, newLines, sourceMap, _i, _len;

    if (options == null) {
      options = {};
    }
    merge = exports.helpers.merge;
    if (options.sourceMap) {
      sourceMap = new sourcemap.SourceMap();
    }
    fragments = (parser.parse(lexer.tokenize(code, options))).compileToFragments(options);
    currentLine = 0;
    if (options.header || options.inline) {
      currentLine += 1;
    }
    currentColumn = 0;
    js = "";
    for (_i = 0, _len = fragments.length; _i < _len; _i++) {
      fragment = fragments[_i];
      if (sourceMap) {
        if (fragment.locationData) {
          sourceMap.addMapping([fragment.locationData.first_line, fragment.locationData.first_column], [currentLine, currentColumn], {
            noReplace: true
          });
        }
        newLines = helpers.count(fragment.code, "\n");
        currentLine += newLines;
        currentColumn = fragment.code.length - (newLines ? fragment.code.lastIndexOf("\n") : 0);
      }
      js += fragment.code;
    }
    if (options.header) {
      header = "Generated by CoffeeScript " + this.VERSION;
      js = "// " + header + "\n" + js;
    }
    if (options.sourceMap) {
      answer = {
        js: js
      };
      if (sourceMap) {
        answer.sourceMap = sourceMap;
        answer.v3SourceMap = sourcemap.generateV3SourceMap(sourceMap, options, code);
      }
      return answer;
    } else {
      return js;
    }
  };

  exports.tokens = function(code, options) {
    return lexer.tokenize(code, options);
  };

  exports.nodes = function(source, options) {
    if (typeof source === 'string') {
      return parser.parse(lexer.tokenize(source, options));
    } else {
      return parser.parse(source);
    }
  };

  exports.run = function(code, options) {
    var answer, mainModule, _ref;

    if (options == null) {
      options = {};
    }
    mainModule = require.main;
    if ((_ref = options.sourceMap) == null) {
      options.sourceMap = true;
    }
    mainModule.filename = process.argv[1] = options.filename ? fs.realpathSync(options.filename) : '.';
    mainModule.moduleCache && (mainModule.moduleCache = {});
    mainModule.paths = require('module')._nodeModulePaths(path.dirname(fs.realpathSync(options.filename || '.')));
    if (!helpers.isCoffee(mainModule.filename) || require.extensions) {
      answer = compile(code, options);
      patchStackTrace();
      mainModule._sourceMaps[mainModule.filename] = answer.sourceMap;
      return mainModule._compile(answer.js, mainModule.filename);
    } else {
      return mainModule._compile(code, mainModule.filename);
    }
  };

  exports["eval"] = function(code, options) {
    var Module, Script, js, k, o, r, sandbox, v, _i, _len, _module, _ref, _ref1, _require;

    if (options == null) {
      options = {};
    }
    if (!(code = code.trim())) {
      return;
    }
    Script = vm.Script;
    if (Script) {
      if (options.sandbox != null) {
        if (options.sandbox instanceof Script.createContext().constructor) {
          sandbox = options.sandbox;
        } else {
          sandbox = Script.createContext();
          _ref = options.sandbox;
          for (k in _ref) {
            if (!__hasProp.call(_ref, k)) continue;
            v = _ref[k];
            sandbox[k] = v;
          }
        }
        sandbox.global = sandbox.root = sandbox.GLOBAL = sandbox;
      } else {
        sandbox = global;
      }
      sandbox.__filename = options.filename || 'eval';
      sandbox.__dirname = path.dirname(sandbox.__filename);
      if (!(sandbox !== global || sandbox.module || sandbox.require)) {
        Module = require('module');
        sandbox.module = _module = new Module(options.modulename || 'eval');
        sandbox.require = _require = function(path) {
          return Module._load(path, _module, true);
        };
        _module.filename = sandbox.__filename;
        _ref1 = Object.getOwnPropertyNames(require);
        for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
          r = _ref1[_i];
          if (r !== 'paths') {
            _require[r] = require[r];
          }
        }
        _require.paths = _module.paths = Module._nodeModulePaths(process.cwd());
        _require.resolve = function(request) {
          return Module._resolveFilename(request, _module);
        };
      }
    }
    o = {};
    for (k in options) {
      if (!__hasProp.call(options, k)) continue;
      v = options[k];
      o[k] = v;
    }
    o.bare = true;
    js = compile(code, o);
    if (sandbox === global) {
      return vm.runInThisContext(js);
    } else {
      return vm.runInContext(js, sandbox);
    }
  };

  loadFile = function(module, filename) {
    var raw, stripped;

    raw = fs.readFileSync(filename, 'utf8');
    stripped = raw.charCodeAt(0) === 0xFEFF ? raw.substring(1) : raw;
    return module._compile(compile(stripped, {
      filename: filename,
      literate: helpers.isLiterate(filename)
    }), filename);
  };

  if (require.extensions) {
    _ref = ['.coffee', '.litcoffee', '.coffee.md'];
    for (_i = 0, _len = _ref.length; _i < _len; _i++) {
      ext = _ref[_i];
      require.extensions[ext] = loadFile;
    }
  }

  if (child_process) {
    fork = child_process.fork;
    child_process.fork = function(path, args, options) {
      var execPath;

      if (args == null) {
        args = [];
      }
      if (options == null) {
        options = {};
      }
      execPath = helpers.isCoffee(path) ? 'coffee' : null;
      if (!Array.isArray(args)) {
        args = [];
        options = args || {};
      }
      options.execPath || (options.execPath = execPath);
      return fork(path, args, options);
    };
  }

  lexer = new Lexer;

  parser.lexer = {
    lex: function() {
      var tag, token;

      token = this.tokens[this.pos++];
      if (token) {
        tag = token[0], this.yytext = token[1], this.yylloc = token[2];
        this.yylineno = this.yylloc.first_line;
      } else {
        tag = '';
      }
      return tag;
    },
    setInput: function(tokens) {
      this.tokens = tokens;
      return this.pos = 0;
    },
    upcomingInput: function() {
      return "";
    }
  };

  parser.yy = require('./nodes');

  parser.yy.parseError = function(message, _arg) {
    var token;

    token = _arg.token;
    message = "unexpected " + (token === 1 ? 'end of input' : token);
    return helpers.throwSyntaxError(message, parser.lexer.yylloc);
  };

  patched = false;

  patchStackTrace = function() {
    var mainModule;

    if (patched) {
      return;
    }
    patched = true;
    mainModule = require.main;
    mainModule._sourceMaps = {};
    return Error.prepareStackTrace = function(err, stack) {
      var frame, frames, getSourceMapping, sourceFiles, _ref1;

      sourceFiles = {};
      getSourceMapping = function(filename, line, column) {
        var answer, sourceMap;

        sourceMap = mainModule._sourceMaps[filename];
        if (sourceMap) {
          answer = sourceMap.getSourcePosition([line - 1, column - 1]);
        }
        if (answer) {
          return [answer[0] + 1, answer[1] + 1];
        } else {
          return null;
        }
      };
      frames = (function() {
        var _j, _len1, _results;

        _results = [];
        for (_j = 0, _len1 = stack.length; _j < _len1; _j++) {
          frame = stack[_j];
          if (frame.getFunction() === exports.run) {
            break;
          }
          _results.push("  at " + (formatSourcePosition(frame, getSourceMapping)));
        }
        return _results;
      })();
      return "" + err.name + ": " + ((_ref1 = err.message) != null ? _ref1 : '') + "\n" + (frames.join('\n')) + "\n";
    };
  };

  formatSourcePosition = function(frame, getSourceMapping) {
    var as, column, fileLocation, fileName, functionName, isConstructor, isMethodCall, line, methodName, source, tp, typeName;

    fileName = void 0;
    fileLocation = '';
    if (frame.isNative()) {
      fileLocation = "native";
    } else {
      if (frame.isEval()) {
        fileName = frame.getScriptNameOrSourceURL();
        if (!fileName) {
          fileLocation = "" + (frame.getEvalOrigin()) + ", ";
        }
      } else {
        fileName = frame.getFileName();
      }
      fileName || (fileName = "<anonymous>");
      line = frame.getLineNumber();
      column = frame.getColumnNumber();
      source = getSourceMapping(fileName, line, column);
      fileLocation = source ? "" + fileName + ":" + source[0] + ":" + source[1] + ", <js>:" + line + ":" + column : "" + fileName + ":" + line + ":" + column;
    }
    functionName = frame.getFunctionName();
    isConstructor = frame.isConstructor();
    isMethodCall = !(frame.isToplevel() || isConstructor);
    if (isMethodCall) {
      methodName = frame.getMethodName();
      typeName = frame.getTypeName();
      if (functionName) {
        tp = as = '';
        if (typeName && functionName.indexOf(typeName)) {
          tp = "" + typeName + ".";
        }
        if (methodName && functionName.indexOf("." + methodName) !== functionName.length - methodName.length - 1) {
          as = " [as " + methodName + "]";
        }
        return "" + tp + functionName + as + " (" + fileLocation + ")";
      } else {
        return "" + typeName + "." + (methodName || '<anonymous>') + " (" + fileLocation + ")";
      }
    } else if (isConstructor) {
      return "new " + (functionName || '<anonymous>') + " (" + fileLocation + ")";
    } else if (functionName) {
      return "" + functionName + " (" + fileLocation + ")";
    } else {
      return fileLocation;
    }
  };

}).call(this);
