PageRenderTime 79ms CodeModel.GetById 27ms app.highlight 48ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/coffee-script/coffee-script.js

http://github.com/jashkenas/coffee-script
JavaScript | 403 lines | 373 code | 29 blank | 1 comment | 107 complexity | c0457b352bccd2401e25dce2a09a3480 MD5 | raw file
  1// Generated by CoffeeScript 1.10.0
  2(function() {
  3  var Lexer, SourceMap, base64encode, compile, ext, fn1, formatSourcePosition, fs, getSourceMap, helpers, i, len, lexer, parser, path, ref, sourceMaps, vm, withPrettyErrors,
  4    hasProp = {}.hasOwnProperty,
  5    indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };
  6
  7  fs = require('fs');
  8
  9  vm = require('vm');
 10
 11  path = require('path');
 12
 13  Lexer = require('./lexer').Lexer;
 14
 15  parser = require('./parser').parser;
 16
 17  helpers = require('./helpers');
 18
 19  SourceMap = require('./sourcemap');
 20
 21  exports.VERSION = '1.10.0';
 22
 23  exports.FILE_EXTENSIONS = ['.coffee', '.litcoffee', '.coffee.md'];
 24
 25  exports.helpers = helpers;
 26
 27  base64encode = function(src) {
 28    switch (false) {
 29      case typeof Buffer !== 'function':
 30        return new Buffer(src).toString('base64');
 31      case typeof btoa !== 'function':
 32        return btoa(src);
 33      default:
 34        throw new Error('Unable to base64 encode inline sourcemap.');
 35    }
 36  };
 37
 38  withPrettyErrors = function(fn) {
 39    return function(code, options) {
 40      var err;
 41      if (options == null) {
 42        options = {};
 43      }
 44      try {
 45        return fn.call(this, code, options);
 46      } catch (error) {
 47        err = error;
 48        if (typeof code !== 'string') {
 49          throw err;
 50        }
 51        throw helpers.updateSyntaxError(err, code, options.filename);
 52      }
 53    };
 54  };
 55
 56  exports.compile = compile = withPrettyErrors(function(code, options) {
 57    var currentColumn, currentLine, encoded, extend, fragment, fragments, generateSourceMap, header, i, js, len, map, merge, newLines, ref, sourceMapDataURI, sourceURL, token, tokens, v3SourceMap;
 58    merge = helpers.merge, extend = helpers.extend;
 59    options = extend({}, options);
 60    generateSourceMap = options.sourceMap || options.inlineMap;
 61    if (generateSourceMap) {
 62      map = new SourceMap;
 63    }
 64    tokens = lexer.tokenize(code, options);
 65    options.referencedVars = (function() {
 66      var i, len, results;
 67      results = [];
 68      for (i = 0, len = tokens.length; i < len; i++) {
 69        token = tokens[i];
 70        if (token[0] === 'IDENTIFIER') {
 71          results.push(token[1]);
 72        }
 73      }
 74      return results;
 75    })();
 76    fragments = parser.parse(tokens).compileToFragments(options);
 77    currentLine = 0;
 78    if (options.header) {
 79      currentLine += 1;
 80    }
 81    if (options.shiftLine) {
 82      currentLine += 1;
 83    }
 84    currentColumn = 0;
 85    js = "";
 86    for (i = 0, len = fragments.length; i < len; i++) {
 87      fragment = fragments[i];
 88      if (generateSourceMap) {
 89        if (fragment.locationData && !/^[;\s]*$/.test(fragment.code)) {
 90          map.add([fragment.locationData.first_line, fragment.locationData.first_column], [currentLine, currentColumn], {
 91            noReplace: true
 92          });
 93        }
 94        newLines = helpers.count(fragment.code, "\n");
 95        currentLine += newLines;
 96        if (newLines) {
 97          currentColumn = fragment.code.length - (fragment.code.lastIndexOf("\n") + 1);
 98        } else {
 99          currentColumn += fragment.code.length;
100        }
101      }
102      js += fragment.code;
103    }
104    if (options.header) {
105      header = "Generated by CoffeeScript " + this.VERSION;
106      js = "// " + header + "\n" + js;
107    }
108    if (generateSourceMap) {
109      v3SourceMap = map.generate(options, code);
110    }
111    if (options.inlineMap) {
112      encoded = base64encode(JSON.stringify(v3SourceMap));
113      sourceMapDataURI = "//# sourceMappingURL=data:application/json;base64," + encoded;
114      sourceURL = "//# sourceURL=" + ((ref = options.filename) != null ? ref : 'coffeescript');
115      js = js + "\n" + sourceMapDataURI + "\n" + sourceURL;
116    }
117    if (options.sourceMap) {
118      return {
119        js: js,
120        sourceMap: map,
121        v3SourceMap: JSON.stringify(v3SourceMap, null, 2)
122      };
123    } else {
124      return js;
125    }
126  });
127
128  exports.tokens = withPrettyErrors(function(code, options) {
129    return lexer.tokenize(code, options);
130  });
131
132  exports.nodes = withPrettyErrors(function(source, options) {
133    if (typeof source === 'string') {
134      return parser.parse(lexer.tokenize(source, options));
135    } else {
136      return parser.parse(source);
137    }
138  });
139
140  exports.run = function(code, options) {
141    var answer, dir, mainModule, ref;
142    if (options == null) {
143      options = {};
144    }
145    mainModule = require.main;
146    mainModule.filename = process.argv[1] = options.filename ? fs.realpathSync(options.filename) : '.';
147    mainModule.moduleCache && (mainModule.moduleCache = {});
148    dir = options.filename ? path.dirname(fs.realpathSync(options.filename)) : fs.realpathSync('.');
149    mainModule.paths = require('module')._nodeModulePaths(dir);
150    if (!helpers.isCoffee(mainModule.filename) || require.extensions) {
151      answer = compile(code, options);
152      code = (ref = answer.js) != null ? ref : answer;
153    }
154    return mainModule._compile(code, mainModule.filename);
155  };
156
157  exports["eval"] = function(code, options) {
158    var Module, _module, _require, createContext, i, isContext, js, k, len, o, r, ref, ref1, ref2, ref3, sandbox, v;
159    if (options == null) {
160      options = {};
161    }
162    if (!(code = code.trim())) {
163      return;
164    }
165    createContext = (ref = vm.Script.createContext) != null ? ref : vm.createContext;
166    isContext = (ref1 = vm.isContext) != null ? ref1 : function(ctx) {
167      return options.sandbox instanceof createContext().constructor;
168    };
169    if (createContext) {
170      if (options.sandbox != null) {
171        if (isContext(options.sandbox)) {
172          sandbox = options.sandbox;
173        } else {
174          sandbox = createContext();
175          ref2 = options.sandbox;
176          for (k in ref2) {
177            if (!hasProp.call(ref2, k)) continue;
178            v = ref2[k];
179            sandbox[k] = v;
180          }
181        }
182        sandbox.global = sandbox.root = sandbox.GLOBAL = sandbox;
183      } else {
184        sandbox = global;
185      }
186      sandbox.__filename = options.filename || 'eval';
187      sandbox.__dirname = path.dirname(sandbox.__filename);
188      if (!(sandbox !== global || sandbox.module || sandbox.require)) {
189        Module = require('module');
190        sandbox.module = _module = new Module(options.modulename || 'eval');
191        sandbox.require = _require = function(path) {
192          return Module._load(path, _module, true);
193        };
194        _module.filename = sandbox.__filename;
195        ref3 = Object.getOwnPropertyNames(require);
196        for (i = 0, len = ref3.length; i < len; i++) {
197          r = ref3[i];
198          if (r !== 'paths' && r !== 'arguments' && r !== 'caller') {
199            _require[r] = require[r];
200          }
201        }
202        _require.paths = _module.paths = Module._nodeModulePaths(process.cwd());
203        _require.resolve = function(request) {
204          return Module._resolveFilename(request, _module);
205        };
206      }
207    }
208    o = {};
209    for (k in options) {
210      if (!hasProp.call(options, k)) continue;
211      v = options[k];
212      o[k] = v;
213    }
214    o.bare = true;
215    js = compile(code, o);
216    if (sandbox === global) {
217      return vm.runInThisContext(js);
218    } else {
219      return vm.runInContext(js, sandbox);
220    }
221  };
222
223  exports.register = function() {
224    return require('./register');
225  };
226
227  if (require.extensions) {
228    ref = this.FILE_EXTENSIONS;
229    fn1 = function(ext) {
230      var base;
231      return (base = require.extensions)[ext] != null ? base[ext] : base[ext] = function() {
232        throw new Error("Use CoffeeScript.register() or require the coffee-script/register module to require " + ext + " files.");
233      };
234    };
235    for (i = 0, len = ref.length; i < len; i++) {
236      ext = ref[i];
237      fn1(ext);
238    }
239  }
240
241  exports._compileFile = function(filename, sourceMap, inlineMap) {
242    var answer, err, raw, stripped;
243    if (sourceMap == null) {
244      sourceMap = false;
245    }
246    if (inlineMap == null) {
247      inlineMap = false;
248    }
249    raw = fs.readFileSync(filename, 'utf8');
250    stripped = raw.charCodeAt(0) === 0xFEFF ? raw.substring(1) : raw;
251    try {
252      answer = compile(stripped, {
253        filename: filename,
254        sourceMap: sourceMap,
255        inlineMap: inlineMap,
256        sourceFiles: [filename],
257        literate: helpers.isLiterate(filename)
258      });
259    } catch (error) {
260      err = error;
261      throw helpers.updateSyntaxError(err, stripped, filename);
262    }
263    return answer;
264  };
265
266  lexer = new Lexer;
267
268  parser.lexer = {
269    lex: function() {
270      var tag, token;
271      token = parser.tokens[this.pos++];
272      if (token) {
273        tag = token[0], this.yytext = token[1], this.yylloc = token[2];
274        parser.errorToken = token.origin || token;
275        this.yylineno = this.yylloc.first_line;
276      } else {
277        tag = '';
278      }
279      return tag;
280    },
281    setInput: function(tokens) {
282      parser.tokens = tokens;
283      return this.pos = 0;
284    },
285    upcomingInput: function() {
286      return "";
287    }
288  };
289
290  parser.yy = require('./nodes');
291
292  parser.yy.parseError = function(message, arg) {
293    var errorLoc, errorTag, errorText, errorToken, token, tokens;
294    token = arg.token;
295    errorToken = parser.errorToken, tokens = parser.tokens;
296    errorTag = errorToken[0], errorText = errorToken[1], errorLoc = errorToken[2];
297    errorText = (function() {
298      switch (false) {
299        case errorToken !== tokens[tokens.length - 1]:
300          return 'end of input';
301        case errorTag !== 'INDENT' && errorTag !== 'OUTDENT':
302          return 'indentation';
303        case errorTag !== 'IDENTIFIER' && errorTag !== 'NUMBER' && errorTag !== 'INFINITY' && errorTag !== 'STRING' && errorTag !== 'STRING_START' && errorTag !== 'REGEX' && errorTag !== 'REGEX_START':
304          return errorTag.replace(/_START$/, '').toLowerCase();
305        default:
306          return helpers.nameWhitespaceCharacter(errorText);
307      }
308    })();
309    return helpers.throwSyntaxError("unexpected " + errorText, errorLoc);
310  };
311
312  formatSourcePosition = function(frame, getSourceMapping) {
313    var as, column, fileLocation, fileName, functionName, isConstructor, isMethodCall, line, methodName, source, tp, typeName;
314    fileName = void 0;
315    fileLocation = '';
316    if (frame.isNative()) {
317      fileLocation = "native";
318    } else {
319      if (frame.isEval()) {
320        fileName = frame.getScriptNameOrSourceURL();
321        if (!fileName) {
322          fileLocation = (frame.getEvalOrigin()) + ", ";
323        }
324      } else {
325        fileName = frame.getFileName();
326      }
327      fileName || (fileName = "<anonymous>");
328      line = frame.getLineNumber();
329      column = frame.getColumnNumber();
330      source = getSourceMapping(fileName, line, column);
331      fileLocation = source ? fileName + ":" + source[0] + ":" + source[1] : fileName + ":" + line + ":" + column;
332    }
333    functionName = frame.getFunctionName();
334    isConstructor = frame.isConstructor();
335    isMethodCall = !(frame.isToplevel() || isConstructor);
336    if (isMethodCall) {
337      methodName = frame.getMethodName();
338      typeName = frame.getTypeName();
339      if (functionName) {
340        tp = as = '';
341        if (typeName && functionName.indexOf(typeName)) {
342          tp = typeName + ".";
343        }
344        if (methodName && functionName.indexOf("." + methodName) !== functionName.length - methodName.length - 1) {
345          as = " [as " + methodName + "]";
346        }
347        return "" + tp + functionName + as + " (" + fileLocation + ")";
348      } else {
349        return typeName + "." + (methodName || '<anonymous>') + " (" + fileLocation + ")";
350      }
351    } else if (isConstructor) {
352      return "new " + (functionName || '<anonymous>') + " (" + fileLocation + ")";
353    } else if (functionName) {
354      return functionName + " (" + fileLocation + ")";
355    } else {
356      return fileLocation;
357    }
358  };
359
360  sourceMaps = {};
361
362  getSourceMap = function(filename) {
363    var answer, ref1;
364    if (sourceMaps[filename]) {
365      return sourceMaps[filename];
366    }
367    if (ref1 = path != null ? path.extname(filename) : void 0, indexOf.call(exports.FILE_EXTENSIONS, ref1) < 0) {
368      return;
369    }
370    answer = exports._compileFile(filename, true);
371    return sourceMaps[filename] = answer.sourceMap;
372  };
373
374  Error.prepareStackTrace = function(err, stack) {
375    var frame, frames, getSourceMapping;
376    getSourceMapping = function(filename, line, column) {
377      var answer, sourceMap;
378      sourceMap = getSourceMap(filename);
379      if (sourceMap) {
380        answer = sourceMap.sourceLocation([line - 1, column - 1]);
381      }
382      if (answer) {
383        return [answer[0] + 1, answer[1] + 1];
384      } else {
385        return null;
386      }
387    };
388    frames = (function() {
389      var j, len1, results;
390      results = [];
391      for (j = 0, len1 = stack.length; j < len1; j++) {
392        frame = stack[j];
393        if (frame.getFunction() === exports.run) {
394          break;
395        }
396        results.push("  at " + (formatSourcePosition(frame, getSourceMapping)));
397      }
398      return results;
399    })();
400    return (err.toString()) + "\n" + (frames.join('\n')) + "\n";
401  };
402
403}).call(this);