Skip to content

Instantly share code, notes, and snippets.

@mooz
Created February 1, 2013 13:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mooz/4691338 to your computer and use it in GitHub Desktop.
Save mooz/4691338 to your computer and use it in GitHub Desktop.
Use Reflect API from xpcshell
// Reflect API from xpcshell
var Cc = Components.classes;
var Ci = Components.interfaces;
var Cu = Components.utils;
function openFile(aPath) {
var file = Cc["@mozilla.org/file/local;1"]
.createInstance(Ci.nsILocalFile);
file.initWithPath(aPath);
return file;
}
function readTextFile(aPath, aCharset) {
var file = openFile(aPath);
if (!file.exists())
throw aPath + " not found";
var fileStream = Cc["@mozilla.org/network/file-input-stream;1"]
.createInstance(Ci.nsIFileInputStream);
fileStream.init(file, 1, 0, false);
var converterStream = Cc["@mozilla.org/intl/converter-input-stream;1"]
.createInstance(Ci.nsIConverterInputStream);
if (!aCharset)
aCharset = 'UTF-8';
converterStream.init(fileStream, aCharset, fileStream.available(),
converterStream.DEFAULT_REPLACEMENT_CHARACTER);
var out = {};
converterStream.readString(fileStream.available(), out);
converterStream.close();
fileStream.close();
return out.value;
}
function getSpecialDirectory(prop) {
var dirService = Cc['@mozilla.org/file/directory_service;1']
.getService(Ci.nsIProperties);
return dirService.get(prop, Ci.nsILocalFile);
}
function getFullPathForPWD(relativePath) {
var curDir = getSpecialDirectory("CurWorkD");
curDir.appendRelativePath(filePath);
return curDir.path;
}
function parse(src) {
var reflect = Cu.import("resource://gre/modules/reflect.jsm");
var ast = reflect.Reflect.parse(src, { loc: false });
print(JSON.stringify(ast, null, 2));
}
if (arguments[0]) {
var filePath = arguments[0];
var source = readTextFile(getFullPathForPWD(filePath));
parse(source);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment