bloodyroots
Version:
Recursive descent parser
1,411 lines (1,235 loc) • 43.7 kB
JavaScript
;(function(e,t,n){function i(n,s){if(!t[n]){if(!e[n]){var o=typeof require=="function"&&require;if(!s&&o)return o(n,!0);if(r)return r(n,!0);throw new Error("Cannot find module '"+n+"'")}var u=t[n]={exports:{}};e[n][0].call(u.exports,function(t){var r=e[n][1][t];return i(r?r:t)},u,u.exports)}return t[n].exports}var r=typeof require=="function"&&require;for(var s=0;s<n.length;s++)i(n[s]);return i})({1:[function(require,module,exports){
var events = require('events');
exports.isArray = isArray;
exports.isDate = function(obj){return Object.prototype.toString.call(obj) === '[object Date]'};
exports.isRegExp = function(obj){return Object.prototype.toString.call(obj) === '[object RegExp]'};
exports.print = function () {};
exports.puts = function () {};
exports.debug = function() {};
exports.inspect = function(obj, showHidden, depth, colors) {
var seen = [];
var stylize = function(str, styleType) {
// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
var styles =
{ 'bold' : [1, 22],
'italic' : [3, 23],
'underline' : [4, 24],
'inverse' : [7, 27],
'white' : [37, 39],
'grey' : [90, 39],
'black' : [30, 39],
'blue' : [34, 39],
'cyan' : [36, 39],
'green' : [32, 39],
'magenta' : [35, 39],
'red' : [31, 39],
'yellow' : [33, 39] };
var style =
{ 'special': 'cyan',
'number': 'blue',
'boolean': 'yellow',
'undefined': 'grey',
'null': 'bold',
'string': 'green',
'date': 'magenta',
// "name": intentionally not styling
'regexp': 'red' }[styleType];
if (style) {
return '\033[' + styles[style][0] + 'm' + str +
'\033[' + styles[style][1] + 'm';
} else {
return str;
}
};
if (! colors) {
stylize = function(str, styleType) { return str; };
}
function format(value, recurseTimes) {
// Provide a hook for user-specified inspect functions.
// Check that value is an object with an inspect function on it
if (value && typeof value.inspect === 'function' &&
// Filter out the util module, it's inspect function is special
value !== exports &&
// Also filter out any prototype objects using the circular check.
!(value.constructor && value.constructor.prototype === value)) {
return value.inspect(recurseTimes);
}
// Primitive types cannot have properties
switch (typeof value) {
case 'undefined':
return stylize('undefined', 'undefined');
case 'string':
var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
.replace(/'/g, "\\'")
.replace(/\\"/g, '"') + '\'';
return stylize(simple, 'string');
case 'number':
return stylize('' + value, 'number');
case 'boolean':
return stylize('' + value, 'boolean');
}
// For some reason typeof null is "object", so special case here.
if (value === null) {
return stylize('null', 'null');
}
// Look up the keys of the object.
var visible_keys = Object_keys(value);
var keys = showHidden ? Object_getOwnPropertyNames(value) : visible_keys;
// Functions without properties can be shortcutted.
if (typeof value === 'function' && keys.length === 0) {
if (isRegExp(value)) {
return stylize('' + value, 'regexp');
} else {
var name = value.name ? ': ' + value.name : '';
return stylize('[Function' + name + ']', 'special');
}
}
// Dates without properties can be shortcutted
if (isDate(value) && keys.length === 0) {
return stylize(value.toUTCString(), 'date');
}
var base, type, braces;
// Determine the object type
if (isArray(value)) {
type = 'Array';
braces = ['[', ']'];
} else {
type = 'Object';
braces = ['{', '}'];
}
// Make functions say that they are functions
if (typeof value === 'function') {
var n = value.name ? ': ' + value.name : '';
base = (isRegExp(value)) ? ' ' + value : ' [Function' + n + ']';
} else {
base = '';
}
// Make dates with properties first say the date
if (isDate(value)) {
base = ' ' + value.toUTCString();
}
if (keys.length === 0) {
return braces[0] + base + braces[1];
}
if (recurseTimes < 0) {
if (isRegExp(value)) {
return stylize('' + value, 'regexp');
} else {
return stylize('[Object]', 'special');
}
}
seen.push(value);
var output = keys.map(function(key) {
var name, str;
if (value.__lookupGetter__) {
if (value.__lookupGetter__(key)) {
if (value.__lookupSetter__(key)) {
str = stylize('[Getter/Setter]', 'special');
} else {
str = stylize('[Getter]', 'special');
}
} else {
if (value.__lookupSetter__(key)) {
str = stylize('[Setter]', 'special');
}
}
}
if (visible_keys.indexOf(key) < 0) {
name = '[' + key + ']';
}
if (!str) {
if (seen.indexOf(value[key]) < 0) {
if (recurseTimes === null) {
str = format(value[key]);
} else {
str = format(value[key], recurseTimes - 1);
}
if (str.indexOf('\n') > -1) {
if (isArray(value)) {
str = str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n').substr(2);
} else {
str = '\n' + str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n');
}
}
} else {
str = stylize('[Circular]', 'special');
}
}
if (typeof name === 'undefined') {
if (type === 'Array' && key.match(/^\d+$/)) {
return str;
}
name = JSON.stringify('' + key);
if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
name = name.substr(1, name.length - 2);
name = stylize(name, 'name');
} else {
name = name.replace(/'/g, "\\'")
.replace(/\\"/g, '"')
.replace(/(^"|"$)/g, "'");
name = stylize(name, 'string');
}
}
return name + ': ' + str;
});
seen.pop();
var numLinesEst = 0;
var length = output.reduce(function(prev, cur) {
numLinesEst++;
if (cur.indexOf('\n') >= 0) numLinesEst++;
return prev + cur.length + 1;
}, 0);
if (length > 50) {
output = braces[0] +
(base === '' ? '' : base + '\n ') +
' ' +
output.join(',\n ') +
' ' +
braces[1];
} else {
output = braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
}
return output;
}
return format(obj, (typeof depth === 'undefined' ? 2 : depth));
};
function isArray(ar) {
return ar instanceof Array ||
Array.isArray(ar) ||
(ar && ar !== Object.prototype && isArray(ar.__proto__));
}
function isRegExp(re) {
return re instanceof RegExp ||
(typeof re === 'object' && Object.prototype.toString.call(re) === '[object RegExp]');
}
function isDate(d) {
if (d instanceof Date) return true;
if (typeof d !== 'object') return false;
var properties = Date.prototype && Object_getOwnPropertyNames(Date.prototype);
var proto = d.__proto__ && Object_getOwnPropertyNames(d.__proto__);
return JSON.stringify(proto) === JSON.stringify(properties);
}
function pad(n) {
return n < 10 ? '0' + n.toString(10) : n.toString(10);
}
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
'Oct', 'Nov', 'Dec'];
// 26 Feb 16:19:34
function timestamp() {
var d = new Date();
var time = [pad(d.getHours()),
pad(d.getMinutes()),
pad(d.getSeconds())].join(':');
return [d.getDate(), months[d.getMonth()], time].join(' ');
}
exports.log = function (msg) {};
exports.pump = null;
var Object_keys = Object.keys || function (obj) {
var res = [];
for (var key in obj) res.push(key);
return res;
};
var Object_getOwnPropertyNames = Object.getOwnPropertyNames || function (obj) {
var res = [];
for (var key in obj) {
if (Object.hasOwnProperty.call(obj, key)) res.push(key);
}
return res;
};
var Object_create = Object.create || function (prototype, properties) {
// from es5-shim
var object;
if (prototype === null) {
object = { '__proto__' : null };
}
else {
if (typeof prototype !== 'object') {
throw new TypeError(
'typeof prototype[' + (typeof prototype) + '] != \'object\''
);
}
var Type = function () {};
Type.prototype = prototype;
object = new Type();
object.__proto__ = prototype;
}
if (typeof properties !== 'undefined' && Object.defineProperties) {
Object.defineProperties(object, properties);
}
return object;
};
exports.inherits = function(ctor, superCtor) {
ctor.super_ = superCtor;
ctor.prototype = Object_create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
};
var formatRegExp = /%[sdj%]/g;
exports.format = function(f) {
if (typeof f !== 'string') {
var objects = [];
for (var i = 0; i < arguments.length; i++) {
objects.push(exports.inspect(arguments[i]));
}
return objects.join(' ');
}
var i = 1;
var args = arguments;
var len = args.length;
var str = String(f).replace(formatRegExp, function(x) {
if (x === '%%') return '%';
if (i >= len) return x;
switch (x) {
case '%s': return String(args[i++]);
case '%d': return Number(args[i++]);
case '%j': return JSON.stringify(args[i++]);
default:
return x;
}
});
for(var x = args[i]; i < len; x = args[++i]){
if (x === null || typeof x !== 'object') {
str += ' ' + x;
} else {
str += ' ' + exports.inspect(x);
}
}
return str;
};
},{"events":2}],3:[function(require,module,exports){
// shim for using process in browser
var process = module.exports = {};
process.nextTick = (function () {
var canSetImmediate = typeof window !== 'undefined'
&& window.setImmediate;
var canPost = typeof window !== 'undefined'
&& window.postMessage && window.addEventListener
;
if (canSetImmediate) {
return function (f) { return window.setImmediate(f) };
}
if (canPost) {
var queue = [];
window.addEventListener('message', function (ev) {
if (ev.source === window && ev.data === 'process-tick') {
ev.stopPropagation();
if (queue.length > 0) {
var fn = queue.shift();
fn();
}
}
}, true);
return function nextTick(fn) {
queue.push(fn);
window.postMessage('process-tick', '*');
};
}
return function nextTick(fn) {
setTimeout(fn, 0);
};
})();
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.binding = function (name) {
throw new Error('process.binding is not supported');
}
// TODO(shtylman)
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
},{}],2:[function(require,module,exports){
(function(process){if (!process.EventEmitter) process.EventEmitter = function () {};
var EventEmitter = exports.EventEmitter = process.EventEmitter;
var isArray = typeof Array.isArray === 'function'
? Array.isArray
: function (xs) {
return Object.prototype.toString.call(xs) === '[object Array]'
}
;
function indexOf (xs, x) {
if (xs.indexOf) return xs.indexOf(x);
for (var i = 0; i < xs.length; i++) {
if (x === xs[i]) return i;
}
return -1;
}
// By default EventEmitters will print a warning if more than
// 10 listeners are added to it. This is a useful default which
// helps finding memory leaks.
//
// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
var defaultMaxListeners = 10;
EventEmitter.prototype.setMaxListeners = function(n) {
if (!this._events) this._events = {};
this._events.maxListeners = n;
};
EventEmitter.prototype.emit = function(type) {
// If there is no 'error' event listener then throw.
if (type === 'error') {
if (!this._events || !this._events.error ||
(isArray(this._events.error) && !this._events.error.length))
{
if (arguments[1] instanceof Error) {
throw arguments[1]; // Unhandled 'error' event
} else {
throw new Error("Uncaught, unspecified 'error' event.");
}
return false;
}
}
if (!this._events) return false;
var handler = this._events[type];
if (!handler) return false;
if (typeof handler == 'function') {
switch (arguments.length) {
// fast cases
case 1:
handler.call(this);
break;
case 2:
handler.call(this, arguments[1]);
break;
case 3:
handler.call(this, arguments[1], arguments[2]);
break;
// slower
default:
var args = Array.prototype.slice.call(arguments, 1);
handler.apply(this, args);
}
return true;
} else if (isArray(handler)) {
var args = Array.prototype.slice.call(arguments, 1);
var listeners = handler.slice();
for (var i = 0, l = listeners.length; i < l; i++) {
listeners[i].apply(this, args);
}
return true;
} else {
return false;
}
};
// EventEmitter is defined in src/node_events.cc
// EventEmitter.prototype.emit() is also defined there.
EventEmitter.prototype.addListener = function(type, listener) {
if ('function' !== typeof listener) {
throw new Error('addListener only takes instances of Function');
}
if (!this._events) this._events = {};
// To avoid recursion in the case that type == "newListeners"! Before
// adding it to the listeners, first emit "newListeners".
this.emit('newListener', type, listener);
if (!this._events[type]) {
// Optimize the case of one listener. Don't need the extra array object.
this._events[type] = listener;
} else if (isArray(this._events[type])) {
// Check for listener leak
if (!this._events[type].warned) {
var m;
if (this._events.maxListeners !== undefined) {
m = this._events.maxListeners;
} else {
m = defaultMaxListeners;
}
if (m && m > 0 && this._events[type].length > m) {
this._events[type].warned = true;
console.error('(node) warning: possible EventEmitter memory ' +
'leak detected. %d listeners added. ' +
'Use emitter.setMaxListeners() to increase limit.',
this._events[type].length);
console.trace();
}
}
// If we've already got an array, just append.
this._events[type].push(listener);
} else {
// Adding the second element, need to change to array.
this._events[type] = [this._events[type], listener];
}
return this;
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.once = function(type, listener) {
var self = this;
self.on(type, function g() {
self.removeListener(type, g);
listener.apply(this, arguments);
});
return this;
};
EventEmitter.prototype.removeListener = function(type, listener) {
if ('function' !== typeof listener) {
throw new Error('removeListener only takes instances of Function');
}
// does not use listeners(), so no side effect of creating _events[type]
if (!this._events || !this._events[type]) return this;
var list = this._events[type];
if (isArray(list)) {
var i = indexOf(list, listener);
if (i < 0) return this;
list.splice(i, 1);
if (list.length == 0)
delete this._events[type];
} else if (this._events[type] === listener) {
delete this._events[type];
}
return this;
};
EventEmitter.prototype.removeAllListeners = function(type) {
if (arguments.length === 0) {
this._events = {};
return this;
}
// does not use listeners(), so no side effect of creating _events[type]
if (type && this._events && this._events[type]) this._events[type] = null;
return this;
};
EventEmitter.prototype.listeners = function(type) {
if (!this._events) this._events = {};
if (!this._events[type]) this._events[type] = [];
if (!isArray(this._events[type])) {
this._events[type] = [this._events[type]];
}
return this._events[type];
};
})(require("__browserify_process"))
},{"__browserify_process":3}],4:[function(require,module,exports){
// Generated by CoffeeScript 1.6.2
(function() {
var Parser, inspect, inspect_orig, re_quote, typeIsArray,
__slice = [].slice;
re_quote = require('regexp-quote');
inspect_orig = require('util').inspect;
inspect = function(x) {
return inspect_orig(x, false, null);
};
require('sprintf.js');
typeIsArray = Array.isArray || function(value) {
return {}.toString.call(value) === '[object Array]';
};
Parser = (function() {
function Parser() {}
Parser.define_production = function(alpha_s, beta) {
return this.prototype[alpha_s] = function(vdata, idx) {
return beta.op.call(this, vdata, idx);
};
};
Parser.define_grammar_operation = function(name, op_f) {
return this[name] = function() {
var args;
args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
return {
name: name,
op: op_f != null ? op_f.apply(this, args) : this['match_' + name].apply(this, args)
};
};
};
Parser.define_grammar_operation('at_least_one', function(beta, suffix) {
return this.match_range(beta, 1, void 0, true, suffix);
});
Parser.define_grammar_operation('alternation');
Parser.define_grammar_operation('range');
Parser.define_grammar_operation('re', function(re_str, match_name) {
return this.match_re(RegExp('^(?:' + re_str + ')'), match_name);
});
Parser.define_grammar_operation('seq');
Parser.define_grammar_operation('transform', function(f, beta) {
return this.op_transform(f, beta);
});
Parser.define_grammar_operation('v');
Parser.define_grammar_operation('var_re');
Parser.define_grammar_operation('zero_or_more', function(beta, suffix) {
return this.match_range(beta, 0, void 0, true, suffix);
});
Parser.define_grammar_operation('zero_or_one', function(beta, suffix) {
return this.match_range(beta, 0, 1, true, suffix);
});
Parser.backref = function(ref) {
return function(vdata) {
var m;
m = /^([^\[]*)\[([0-9]*)\]/.exec(ref);
return [(vdata[m[1]] || [])[m[2]]];
};
};
Parser.prototype.debug_log = function(f) {
var data, idx, name, outcome, _ref;
if (this.constructor.debug) {
_ref = f.call(this), name = _ref[0], idx = _ref[1], outcome = _ref[2], data = _ref[3];
return '%-15s %3s %-25s %-8s %s\n'.printf(name, idx, this.string_abbrev(idx, 25), outcome || '', data || '');
}
};
Parser.match_alternation = function() {
var args, beta_seq, suffix;
args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
if (typeIsArray(args[0])) {
beta_seq = args[0], suffix = args[1];
} else {
beta_seq = args;
}
return function(vdata, idx) {
var beta, i, m, m2, _i, _len;
this.debug_log(function() {
var beta;
return [
'alternation', idx, 'begin', 'alternation=%s%s'.sprintf((function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = beta_seq.length; _i < _len; _i++) {
beta = beta_seq[_i];
_results.push(beta.name);
}
return _results;
})(), (suffix != null ? ' suffix=' + suffix.name : ' no-suffix'))
];
});
i = 0;
for (_i = 0, _len = beta_seq.length; _i < _len; _i++) {
beta = beta_seq[_i];
this.debug_log(function() {
return ['alternation', idx, 'i=' + i, beta.name];
});
m = beta.op.call(this, vdata, idx);
if (m != null) {
if (suffix != null) {
m2 = suffix.op.call(this, vdata, idx + m[0]);
if (m2 != null) {
this.debug_log(function() {
return ['alternation', idx + m[0] + m2[0], 'success', 'count=' + (i + 1)];
});
return [
m[0] + m2[0], {
pos: idx,
length: m[0] + m2[0],
type: 'seq',
seq: [m[1], m2[1]]
}
];
}
} else {
this.debug_log(function() {
return ['alternation', idx + m[0], 'success', 'count=%d'.sprintf(i + 1)];
});
return m;
}
}
i++;
}
this.debug_log(function() {
return ['alternation', idx, 'fail'];
});
};
};
Parser.match_range = function(beta, min, max, greedy, suffix) {
if (min == null) {
min = 0;
}
if (greedy == null) {
greedy = true;
}
if (greedy) {
return this._match_greedy_range(beta, min, max, suffix);
} else {
return this._match_nongreedy_range(beta, min, max, suffix);
}
};
Parser._match_greedy_range = function(beta, min, max, suffix) {
return function(vdata, idx) {
var match_indices, result, state,
_this = this;
if (!(state = this._match_range_to_min(beta, min, max, true, vdata, idx))) {
return;
}
match_indices = [state.progress];
this._match_range_from_min(beta, max, vdata, idx, state, function() {
match_indices.push(state.progress);
return false;
});
while (match_indices.length) {
state.progress = match_indices.pop();
this.debug_log(function() {
return ['range', idx + state.progress, 'i=' + state.count, 'greedy backtracking'];
});
if (result = this._match_range_suffix(suffix, vdata, idx, state)) {
return result;
}
state.work.pop();
state.count--;
}
this.debug_log(function() {
return ['range', idx + state.progress, 'fail', 'greedy backtracking'];
});
};
};
Parser._match_nongreedy_range = function(beta, min, max, suffix) {
return function(vdata, idx) {
var state,
_this = this;
if (!(state = this._match_range_to_min(beta, min, max, false, vdata, idx))) {
return;
}
return this._match_range_suffix(suffix, vdata, idx, state) || this._match_range_from_min(beta, max, vdata, idx, state, function() {
return _this._match_range_suffix(suffix, vdata, idx, state);
}) || (this.debug_log(function() {
return ['range', idx + state.progress, 'fail', '>=min non-greedy'];
}), void 0);
};
};
Parser.prototype._match_range_to_min = function(beta, min, max, greedy, vdata, idx) {
var m, state;
this.debug_log(function() {
return ['range', idx, 'begin', '%s min=%s max=%s %s %s'.sprintf(beta.name, min, (max != null ? max : ''), (greedy ? 'greedy' : 'non-greedy'), (typeof suffix !== "undefined" && suffix !== null ? 'suffix=' + suffix.name : 'no-suffix'))];
});
if ((max != null) && min > max) {
this.debug_log(function() {
return ['re', idx, 'fail', 'min > max'];
});
return;
}
state = {
count: 0,
progress: 0,
work: [],
greedy: greedy
};
while (state.count < min) {
this.debug_log(function() {
return ['range', idx + state.progress, 'i=' + state.count, '<min'];
});
m = beta.op.call(this, vdata, idx + state.progress);
if (m == null) {
this.debug_log(function() {
return ['range', idx + state.progress, 'fail', '<min matches'];
});
return;
}
state.progress += m[0];
state.work.push(m[1]);
state.count++;
}
return state;
};
Parser.prototype._match_range_from_min = function(beta, max, vdata, idx, state, func) {
var m, output;
while ((max == null) || state.count < max) {
this.debug_log(function() {
return ['range', idx + state.progress, 'i=' + state.count, '>=min %s'.sprintf(state.greedy ? 'greedy' : 'non-greedy')];
});
m = beta.op.call(this, vdata, idx + state.progress);
if (m == null) {
break;
}
state.progress += m[0];
state.work.push(m[1]);
state.count++;
if (output = func()) {
return output;
}
}
};
Parser.prototype._match_range_suffix = function(suffix, vdata, idx, state) {
var m;
if (suffix != null) {
if ((m = suffix.op.call(this, vdata, idx + state.progress)) != null) {
state.progress += m[0];
state.work.push(m[1]);
this.debug_log(function() {
return ['range', idx + state.progress, 'success', 'count=%d %s'.sprintf(state.count, (state.greedy ? 'greedy' : 'non-greedy'))];
});
return [
state.progress, {
pos: idx,
length: state.progress,
type: 'seq',
seq: state.work
}
];
} else {
}
} else {
this.debug_log(function() {
return ['range', idx + state.progress, 'success', 'count=%d %s'.sprintf(state.count, (state.greedy ? 'greedy' : 'non-greedy trivial'))];
});
return [
state.progress, {
pos: idx,
length: state.progress,
type: 'seq',
seq: state.work
}
];
}
};
Parser.match_re = function(rre, match_name) {
return function(vdata, idx) {
var m;
m = rre.exec(this.str.substr(idx));
if (m) {
this.debug_log(function() {
return ['re', idx, 'success', this.strip_quotes(inspect(rre.source))];
});
if (match_name != null) {
vdata[match_name] = m.slice(0);
}
return [
m[0].length, {
pos: idx,
length: m[0].length,
type: 're',
match: m[0],
groups: m.slice(0)
}
];
} else {
this.debug_log(function() {
return ['re', idx, 'fail', this.strip_quotes(inspect(rre.source))];
});
}
};
};
Parser.match_seq = function() {
var beta_seq;
beta_seq = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
return function(vdata, idx) {
var beta, i, m, progress, work, _i, _len;
this.debug_log(function() {
var beta;
return [
'seq', idx, 'begin', (function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = beta_seq.length; _i < _len; _i++) {
beta = beta_seq[_i];
_results.push(beta.name);
}
return _results;
})()
];
});
progress = 0;
work = [];
i = 0;
for (_i = 0, _len = beta_seq.length; _i < _len; _i++) {
beta = beta_seq[_i];
this.debug_log(function() {
return ['seq', idx + progress, 'i=' + i, beta.name];
});
m = beta.op.call(this, vdata, idx + progress);
if (m == null) {
this.debug_log(function() {
return ['seq', idx + progress, 'fail'];
});
return;
}
progress += m[0];
work.push(m[1]);
i++;
}
this.debug_log(function() {
return ['seq', idx + progress, 'success'];
});
return [
progress, {
pos: idx,
length: progress,
type: 'seq',
seq: work
}
];
};
};
Parser.match_v = function(alpha_s, argf) {
return function(vdata, idx) {
var m, new_vdata;
this.debug_log(function() {
return ['v', idx, 'begin', alpha_s];
});
new_vdata = {};
if (argf != null) {
new_vdata.arg = argf.call(this, vdata);
}
m = this.vcache(alpha_s, idx, new_vdata);
this.debug_log(function() {
return ['v', idx + (m != null ? m[0] : 0), (m != null ? 'success' : 'fail'), alpha_s];
});
return m;
};
};
Parser.match_var_re = function(re_str, match_name) {
var self;
self = this;
return function(vdata, idx) {
return self.match_re(RegExp('^(?:' + this.replace_backreferences(re_str, vdata) + ')'), match_name).call(this, vdata, idx);
};
};
Parser.op_transform = function(f, beta) {
return function(vdata, idx) {
var m, tm;
this.debug_log(function() {
return ['transform', idx, 'begin', beta.name];
});
m = beta.op.call(this, vdata, idx);
if (m == null) {
this.debug_log(function() {
return ['transform', idx, 'fail', beta.name];
});
return;
}
tm = f.call(this, m[1], vdata, idx);
if (tm == null) {
this.debug_log(function() {
return ['transform', idx + m[0], 'fail', 'transform'];
});
return;
}
this.debug_log(function() {
return ['transform', idx + m[0], 'success'];
});
return [m[0], tm];
};
};
Parser.prototype.parse = function(str) {
var doc;
this.str = str;
this.v_cache = {};
this.debug_log(function() {
return ['parse', 0, 'begin'];
});
doc = this.Document({}, 0);
if (doc == null) {
this.debug_log(function() {
return ['parse', 0, 'fail'];
});
return;
}
this.debug_log(function() {
return ['parse', doc[0], 'success'];
});
return doc[1];
};
Parser.prototype.replace_backreferences = function(re_str, vdata) {
var m, mstr, work;
work = re_str;
while (m = /\\=([^\[]+)\[([0-9]+)\]/.exec(work)) {
mstr = (vdata[m[1]] || [])[m[2]];
if (mstr == null) {
mstr = '';
}
work = work.substr(0, m.index) + re_quote(mstr) + work.substr(m.index + m[0].length);
}
return work;
};
Parser.prototype.string_abbrev = function(start, n) {
var istr;
istr = this.str.substr(start);
istr = this.strip_quotes(inspect(istr));
if (istr.length > n) {
return istr.substr(0, n - 3) + '...';
} else {
return istr;
}
};
Parser.prototype.strip_quotes = function(str) {
var m;
m = /^'(.*)'$/.exec(str);
if (m) {
return m[1];
} else {
return str;
}
};
Parser.prototype.vcache = function(alpha_s, idx, vdata) {
var cache_key;
cache_key = [alpha_s, idx, JSON.stringify(vdata)].join('#');
if (this.v_cache.hasOwnProperty(cache_key)) {
this.debug_log(function() {
return ['vcache', idx, 'cached'];
});
return this.v_cache[cache_key];
} else {
return this.v_cache[cache_key] = this[alpha_s](vdata, idx);
}
};
return Parser;
})();
exports.Parser = Parser;
}).call(this);
},{"util":1,"regexp-quote":5,"sprintf.js":6}],5:[function(require,module,exports){
module.exports = function (string) {
return string.replace(/[-\\^$*+?.()|[\]{}]/g, "\\$&")
}
},{}],6:[function(require,module,exports){
(function(process,global){/**
* Copyright (c) 2010 Jakob Westhoff
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the 'Software'), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
;
var sprintf = function( format ) {
// Check for format definition
if ( typeof format !== 'string' ) {
return 'sprintf: The first argument needs to be a string.';
}
var args = [''];
var k;
//var util = require('util');
// If the second arg is an array and there are no more arguments
// re-assign pre-set in the array to args[] from arguments[1]
if (arguments.length === 2 && '[object Array]' === toString.call(arguments[1])) {
// arguments is an array-like object, not an array
for (k=0; k<arguments[1].length; ++k) {
args[k+1] = arguments[1][k];
}
} else {
// arguments is an array-like object, not an array
for (k=0; k<arguments.length; ++k) {
args[k] = arguments[k];
}
}
/**
* Define the regex to match a formating string
* The regex consists of the following parts:
* percent sign to indicate the start
* (optional) sign specifier
* (optional) padding specifier
* (optional) alignment specifier
* (optional) width specifier
* (optional) precision specifier
* type specifier:
* % - literal percent sign
* b - binary number
* c - ASCII character represented by the given value
* d - signed decimal number
* f - floating point value
* o - octal number
* s - string
* x - hexadecimal number (lowercase characters)
* X - hexadecimal number (uppercase characters)
*/
var r = new RegExp( /%(\+)?([0 ]|'(.))?(-)?([0-9]+)?(\.([0-9]+))?([%bcdfjosStxX])/g );
/**
* Each format string is splitted into the following parts:
* 0: Full format string
* 1: sign specifier (+)
* 2: padding specifier (0/<space>/'<any char>)
* 3: if the padding character starts with a ' this will be the real
* padding character
* 4: alignment specifier
* 5: width specifier
* 6: precision specifier including the dot
* 7: precision specifier without the dot
* 8: type specifier
*/
var parts = [];
var paramIndex = 1;
var part;
while ( ( part = r.exec( format ) ) ) {
// Check if an input value has been provided, for the current
// format string, if not break out of the loop.
if ( paramIndex >= args.length ) {
break;
}
var pIdx = parts.length;
parts[pIdx] = {
/* beginning of the part in the string */
begin: part.index,
/* end of the part in the string */
end: part.index + part[0].length,
/* force sign */
sign: ( part[1] === '+' ),
/* is the given data negative */
negative: ( parseInt( args[paramIndex], 10 ) < 0 ) ? true : false,
/* padding character (default: <space>) */
padding: ( part[2] === undefined ) ?
( ' ' ) : /* default */
( ( part[2].substring( 0, 1 ) === '\'' ) ?
( part[3] ) : /* use special char */
( part[2] ) /* use normal <space> or zero */
),
/* should the output be aligned left?*/
alignLeft: ( part[4] === '-' ),
/* width specifier (number or false) */
width: ( part[5] !== undefined ) ? part[5] : false,
/* precision specifier (number or false) */
precision: ( part[7] !== undefined ) ? part[7] : false,
/* type specifier */
type: part[8],
/* the given data associated with this part converted to a string */
//data: ( part[8] != '%' ) ? String ( args[paramIndex++] ) : false
};
var data;
switch(part[8]) {
case '%':
data = false;
break;
case 'j':
data = JSON.stringify(args[paramIndex]);
break;
default:
data = String (args[paramIndex]);
break;
}
parts[pIdx].data = data;
paramIndex++;
}
var newString = '';
var start = 0;
// Generate our new formated string
for( var i=0; i<parts.length; ++i ) {
// Add first unformated string part
newString += format.substring( start, parts[i].begin );
// Mark the new string start
start = parts[i].end;
if (typeof parts[i].data === 'undefined') {
parts[i].data = 'undefined';
}
// Create the appropriate preformat substitution
// This substitution is only the correct type conversion. All the
// different options and flags haven't been applied to it at this
// point
var preSubstitution = '';
switch ( parts[i].type ) {
case '%':
preSubstitution = '%';
break;
case 'b':
preSubstitution = Math.abs( parseInt( parts[i].data, 10 ) ).toString( 2 );
break;
case 'c':
preSubstitution = String.fromCharCode( Math.abs( parseInt( parts[i].data, 10 ) ) );
break;
case 'd':
preSubstitution = String( Math.abs( parseInt( parts[i].data, 10 ) ) );
break;
case 'f':
preSubstitution = ( parts[i].precision === false ) ?
( String( ( Math.abs( parseFloat( parts[i].data ) ) ) ) ) :
( Math.abs( parseFloat( parts[i].data ) ).toFixed( parts[i].precision ) );
break;
case 'o':
preSubstitution = Math.abs( parseInt( parts[i].data, 10 ) ).toString( 8 );
break;
case 'j':
// Cut if precision is defined
preSubstitution = parts[i].data.substring( 0, parts[i].precision ?
parts[i].precision : parts[i].data.length);
break;
case 's':
// Cut if precision is defined
preSubstitution = parts[i].data.substring( 0, parts[i].precision ?
parts[i].precision : parts[i].data.length);
break;
case 'S':
// Cut if precision is defined
preSubstitution = parts[i].data.substring( 0, parts[i].precision ?
parts[i].precision : parts[i].data.length).toUpperCase();
break;
case 't':
// Cut if precision is defined
preSubstitution = parts[i].data.substring( 0, parts[i].precision ?
parts[i].precision : parts[i].data.length).toLowerCase();
break;
case 'x':
preSubstitution = Math.abs( parseInt( parts[i].data, 10 ) ).toString( 16 ).toLowerCase();
break;
case 'X':
preSubstitution = Math.abs( parseInt( parts[i].data, 10 ) ).toString( 16 ).toUpperCase();
break;
default:
preSubstitution = '?%'+parts[i].type+'?';
break;
}
// The % character is a special type and does not need further processing
if ( parts[i].type === '%' ) {
newString += preSubstitution;
continue;
}
// Modify the preSubstitution by taking sign, padding and width
// into account
// Pad the string based on the given width
if ( parts[i].width !== false ) {
// Padding needed?
if ( parts[i].width > preSubstitution.length )
{
var origLength = preSubstitution.length;
for( var j = 0; j < parts[i].width - origLength; ++j )
{
preSubstitution = ( parts[i].alignLeft === true ) ?
( preSubstitution + parts[i].padding ) :
( parts[i].padding + preSubstitution );
}
}
}
// Add a sign symbol if neccessary or enforced, but only if we are
// not handling a string
if ( parts[i].type === 'b' ||
parts[i].type === 'd' ||
parts[i].type === 'o' ||
parts[i].type === 'f' ||
parts[i].type === 'x' ||
parts[i].type === 'X' ) {
if ( parts[i].negative === true ) {
preSubstitution = '-' + preSubstitution;
}
else if ( parts[i].sign === true ) {
preSubstitution = '+' + preSubstitution;
}
}
// Add the substitution to the new string
newString += preSubstitution;
}
// Add the last part of the given format string, which may still be there
newString += format.substring( start, format.length );
return newString;
};
// Register the new sprintf function as a global function, as well as a
// method to the String object. If not already defined.
global.sprintf = sprintf;
// a printf method on the String prototype
String.prototype.printf = function() {
var newArguments = Array.prototype.slice.call( arguments );
newArguments.unshift( String( this ) );
var text = sprintf.apply( undefined, newArguments );
process.stdout.write(text);
return text;
};
// a sprintf method on the String prototype
String.prototype.sprintf = function() {
var newArguments = Array.prototype.slice.call( arguments );
//var util = require('util');
//console.log('newArguments: '+util.inspect(newArguments));
newArguments.unshift( String( this ) );
//console.log('newArguments: '+util.inspect(newArguments));
return sprintf.apply( undefined, newArguments );
};
})(require("__browserify_process"),window)
},{"__browserify_process":3}]},{},[4])
;