Format processing instructions
for slight improved readability.
@param {Array<Instruction>} pis
@returns {Array<object>}
437898
function formatjson(pis) {
	return pis.map(function(pi) {
		var newpi = {};
		newpi[pi.tag] = pi.att;
		return newpi;
	});
}
218224
function process_raw(token) {
	var token = escapeRegex(token);
	return {
		type: "raw",
		piece: token + "/",
		last: token + "/?"
	};
}
1187331
function(s) {
                //TODO: validate array length
		//TODO: return unwanted subset as new Px object

                var counts = this.valCounts(),
                multipliers = [];

                _.each(s, function(d, i) {
                    if (d[0] === '*') {
                        s[i] = _.range(0, counts[i] - 1);
                    }
                });

                for (var i = 0, l = counts.length; i < l - 1; i++) {
                    multipliers[i] = _.reduce(counts.slice(i+1), function(a, b) { return a * b; });
                }
                multipliers.push(1);

                for (var j = 0, k = s.length; j < k; j++) {
                    
                    // drop the values
                    this.metadata.VALUES[this.variables()[j]] = 
                        _.filter(this.metadata.VALUES[this.variables()[j]], function(e, m) {
                            return _.indexOf(s[j], m) !== -1;
                        });
                }

                var keepIdxs = [];
                var pattern = function pattern(c,m,w,p) {
                    if (c.length > 1) {
                        p = typeof p !== 'undefined' ? p : 1;
                        var count = c.pop(),
                            multiple = m.pop(),
                            want = w.pop();

                        var patt = _.flatten(_.map(_.range(0, count), function(d) { 
                            return _.include(want, d) ? p : _arrayOfZeroes(multiple);
                        }));

                        pattern(c, m, w, patt);
                    }
                    keepIdxs.push(_.flatten(p));
                };
                pattern(counts,multipliers,s);
                keepIdxs = keepIdxs[0];

                var indices = [];
                _.each(s[0], function(d) {
                    var start = d * multipliers[0];
                    var end = start + multipliers[0];
                    indices.push(_.filter(_.range(start, end), function(d, i) {return keepIdxs[i] === 1;}));
                });
                indices = _.flatten(indices);
                this.data = _.filter(this.data, function(d, i) {return _.indexOf(indices, i) !== -1;});
            }
1059768
function parseInput(str, idx) {
  var raw = String(str || '');
  var sliced = raw.slice(0, idx);
  var sections = sliced.split('|');
  var prefix = sections.slice(0, sections.length - 1) || [];
  prefix.push('');
  prefix = prefix.join('|');
  var suffix = getSuffix(raw.slice(idx));
  var context = sections[sections.length - 1];
  return {
    raw: raw,
    prefix: prefix,
    suffix: suffix,
    context: context
  };
}
399367
function format(param, data, cb) {
    const time = util.formatTime(new Date());
    const outArray = data.toString().replace(/^\s+|\s+$/g, '').split(/\s+/);
    let outValueArray = [];
    for (let i = 0; i < outArray.length; i++) {
        if ((!isNaN(outArray[i]))) {
            outValueArray.push(outArray[i]);
        }
    }
    const ps = {};
    ps.time = time;
    ps.serverId = param.serverId;
    ps.serverType = ps.serverId.split('-')[0];
    ps.pid = param.pid;
    const pid = ps.pid;
    ps.cpuAvg = outValueArray[1];
    ps.memAvg = outValueArray[2];
    ps.vsz = outValueArray[3];
    ps.rss = outValueArray[4];
    outValueArray = [];
    if (process.platform === 'darwin') {
        ps.usr = 0;
        ps.sys = 0;
        ps.gue = 0;
        cb(null, ps);
        return;
    }
    exec(`pidstat -p ${pid}`, (err, output) => {
        if (err) {
            console.error('the command pidstat failed! ', err.stack);
            return;
        }
        const _outArray = output.toString().replace(/^\s+|\s+$/g, '').split(/\s+/);
        for (let i = 0; i < _outArray.length; i++) {
            if ((!isNaN(_outArray[i]))) {
                outValueArray.push(_outArray[i]);
            }
        }
        ps.usr = outValueArray[1];
        ps.sys = outValueArray[2];
        ps.gue = outValueArray[3];

        cb(null, ps);
    });
}
1239939
function formatInputOptions(inputOptions) {
  var result = [];

  if (typeof Map !== 'undefined' && inputOptions instanceof Map) {
    inputOptions.forEach(function (value, key) {
      result.push([key, value]);
    });
  } else {
    Object.keys(inputOptions).forEach(function (key) {
      result.push([key, inputOptions[key]]);
    });
  }

  return result;
}
464175
function (printArray, format, preProcessor, settings) {
  format = format || ''
  preProcessor = preProcessor || []
  settings = settings || defaultSettings

  const INDENT = emptyString(settings.indent)
  const ROW_SPACER = emptyString(settings.rowSpace)

  const headings = getAllKeys(printArray)
  const maxLength = getMaxLength(headings, printArray)
  const maxLengths = Object.keys(maxLength).reduce((s, k) => s + maxLength[k], 0)

  // print headline
  const headline = []
  const seperator = []

  _.forEach(headings, function (header, i) {
    headline.push(toLength(header, maxLength[header], 'c'))
    seperator.push(new Array(maxLength[header] + 1).join('-'))
  })

  console.log(INDENT + seperator.join(ROW_SPACER))
  console.log(INDENT + headline.join(ROW_SPACER))
  console.log(INDENT + seperator.join(ROW_SPACER))

  // print rows
  _.forEach(printArray, function (row) {
    const line = []

    if (row === null || typeof row === 'string') {
      if (row === null || row === '') {
        return console.log('')
      }
      return console.log(chalk.grey.bold(toLength(row || '', maxLengths, 'l')))
    }

    _.forEach(headings, function (header, i) {
      let str = row[header] || ''

      if (_.isFunction(preProcessor[i])) {
        str = preProcessor[i](str) || str
      }

      line.push(toLength(str, maxLength[header], format.substr(i, 1)))
    })
    console.log(INDENT + line.join(ROW_SPACER))
  })
}
728800
def parse_pi_content(content)
      params = {}
      content.scan(CONTENT_PATTERN) do |name, quote, value|
        params[name] = value
      end
      params
    end
668725
def _check_for_pi_nodes(self, list, inheader):
        '''
        '''
        list = list[:]
        while list:
            elt = list.pop()
            t = elt.nodeType
            if t == _Node.PROCESSING_INSTRUCTION_NODE:
                raise ParseException('Found processing instruction "<?' + \
                        elt.nodeName + '...>"',
                        inheader, elt.parentNode, self.dom)
            elif t == _Node.DOCUMENT_TYPE_NODE:
                raise ParseException('Found DTD', inheader,
                        elt.parentNode, self.dom)
            list += _children(elt)
523272
function processOtherSpecifier() {
                    const leftBrace = sourceCode.getFirstToken(node, 1)
                    const rightBrace = sourceCode.getLastToken(
                        node,
                        hasSemi ? 3 : 2
                    )
                    setOffsetToToken(leftBrace, 0, importToken)
                    processNodeList(node.specifiers, leftBrace, rightBrace, 1)
                    tokens.push(
                        sourceCode.getLastToken(node, hasSemi ? 2 : 1), // from
                        sourceCode.getLastToken(node, hasSemi ? 1 : 0) // "foo"
                    )
                }
576836
function(pis) {
			if (pis) {
				var optional = [];
				var required = [];
				if (pis.reduce(function(hasinput, pi) {
					var keys = Object.keys(pi);
					var name = keys[0];
					var atts = pi[name];
					if (name === "input") {
						var list = atts.required === false ? optional : required;
						list.push(gui.Object.lookup(atts.type));
						return true;
					}
					return hasinput;
				}, false)) {
					this.$input = new edb.InputPlugin();
					this.$input.add(required, this, true);
					this.$input.add(optional, this, false);
				}
			}
		}
484659
function generateTS(ast, options) {
  // These only indent non-empty lines to avoid trailing whitespace.
  function indent2(code) {
    return code.replace(/^(.+)$/gm, "  $1");
  }

  function indent10(code) {
    return code.replace(/^(.+)$/gm, "          $1");
  }

  function generateTables() {
    if (options.optimize === "size") {
      return [
        "const peg$consts = [",
        indent2(ast.consts.join(",\n")),
        "];",
        "",
        "const peg$bytecode = [",
        indent2(ast.rules.map(rule =>
          "peg$decode(\"" +
          js.stringEscape(rule.bytecode.map(
            b => String.fromCharCode(b + 32)
          ).join("")) +
          "\")"
        ).join(",\n")),
        "];"
      ].join("\n");
    } else {
      return ast.consts.map((c, i) => "const peg$c" + i + " = " + c + ";").join("\n");
    }
  }

  function generateRuleHeader(ruleNameCode, ruleIndexCode) {
    let parts = [];

    parts.push("");

    if (options.trace) {
      parts.push([
        "peg$tracer.trace({",
        "  type: \"rule.enter\",",
        "  rule: " + ruleNameCode + ",",
        "  location: peg$computeLocation(startPos, startPos)",
        "});",
        ""
      ].join("\n"));
    }

    if (options.cache) {
      parts.push([
        "const key = peg$currPos * " + ast.rules.length + " + " + ruleIndexCode + ";",
        "const cached: ICached = peg$resultsCache[key];",
        "",
        "if (cached) {",
        "  peg$currPos = cached.nextPos;",
        ""
      ].join("\n"));

      if (options.trace) {
        parts.push([
          "if (cached.result !== peg$FAILED) {",
          "  peg$tracer.trace({",
          "    type: \"rule.match\",",
          "    rule: " + ruleNameCode + ",",
          "    result: cached.result,",
          "    location: peg$computeLocation(startPos, peg$currPos)",
          "  });",
          "} else {",
          "  peg$tracer.trace({",
          "    type: \"rule.fail\",",
          "    rule: " + ruleNameCode + ",",
          "    location: peg$computeLocation(startPos, startPos)",
          "  });",
          "}",
          ""
        ].join("\n"));
      }

      parts.push([
        "  return cached.result;",
        "}",
        ""
      ].join("\n"));
    }

    return parts.join("\n");
  }

  function generateRuleFooter(ruleNameCode, resultCode) {
    let parts = [];

    if (options.cache) {
      parts.push([
        "",
        "peg$resultsCache[key] = { nextPos: peg$currPos, result: " + resultCode + " };"
      ].join("\n"));
    }

    if (options.trace) {
      parts.push([
        "",
        "if (" + resultCode + " !== peg$FAILED) {",
        "  peg$tracer.trace({",
        "    type: \"rule.match\",",
        "    rule: " + ruleNameCode + ",",
        "    result: " + resultCode + ",",
        "    location: peg$computeLocation(startPos, peg$currPos)",
        "  });",
        "} else {",
        "  peg$tracer.trace({",
        "    type: \"rule.fail\",",
        "    rule: " + ruleNameCode + ",",
        "    location: peg$computeLocation(startPos, startPos)",
        "  });",
        "}"
      ].join("\n"));
    }

    parts.push([
      "",
      "return " + resultCode + ";"
    ].join("\n"));

    return parts.join("\n");
  }

  function generateInterpreter() {
    let parts = [];

    function generateCondition(cond, argsLength) {
      let baseLength = argsLength + 3;
      let thenLengthCode = "bc[ip + " + (baseLength - 2) + "]";
      let elseLengthCode = "bc[ip + " + (baseLength - 1) + "]";

      return [
        "ends.push(end);",
        "ips.push(ip + " + baseLength + " + " + thenLengthCode + " + " + elseLengthCode + ");",
        "",
        "if (" + cond + ") {",
        "  end = ip + " + baseLength + " + " + thenLengthCode + ";",
        "  ip += " + baseLength + ";",
        "} else {",
        "  end = ip + " + baseLength + " + " + thenLengthCode + " + " + elseLengthCode + ";",
        "  ip += " + baseLength + " + " + thenLengthCode + ";",
        "}",
        "",
        "break;"
      ].join("\n");
    }

    function generateLoop(cond) {
      let baseLength = 2;
      let bodyLengthCode = "bc[ip + " + (baseLength - 1) + "]";

      return [
        "if (" + cond + ") {",
        "  ends.push(end);",
        "  ips.push(ip);",
        "",
        "  end = ip + " + baseLength + " + " + bodyLengthCode + ";",
        "  ip += " + baseLength + ";",
        "} else {",
        "  ip += " + baseLength + " + " + bodyLengthCode + ";",
        "}",
        "",
        "break;"
      ].join("\n");
    }

    function generateCall() {
      let baseLength = 4;
      let paramsLengthCode = "bc[ip + " + (baseLength - 1) + "]";

      return [
        "params = bc.slice(ip + " + baseLength + ", ip + " + baseLength + " + " + paramsLengthCode + ")",
        "  .map(function(p) { return stack[stack.length - 1 - p]; });",
        "",
        "stack.splice(",
        "  stack.length - bc[ip + 2],",
        "  bc[ip + 2],",
        "  peg$consts[bc[ip + 1]].apply(null, params)",
        ");",
        "",
        "ip += " + baseLength + " + " + paramsLengthCode + ";",
        "break;"
      ].join("\n");
    }

    parts.push([
      "function peg$decode(s: string): number {",
      "  return s.split(\"\").map((ch) => { return ch.charCodeAt(0) - 32; });",
      "}",
      "",
      "function peg$parseRule(index) {"
    ].join("\n"));

    if (options.trace) {
      parts.push([
        "  let bc = peg$bytecode[index];",
        "  let ip = 0;",
        "  let ips = [];",
        "  let end = bc.length;",
        "  let ends = [];",
        "  let stack = [];",
        "  let startPos = peg$currPos;",
        "  let params;"
      ].join("\n"));
    } else {
      parts.push([
        "  let bc = peg$bytecode[index];",
        "  let ip = 0;",
        "  let ips = [];",
        "  let end = bc.length;",
        "  let ends = [];",
        "  let stack = [];",
        "  let params;"
      ].join("\n"));
    }

    parts.push(indent2(generateRuleHeader("peg$ruleNames[index]", "index")));

    parts.push([
      // The point of the outer loop and the |ips| & |ends| stacks is to avoid
      // recursive calls for interpreting parts of bytecode. In other words, we
      // implement the |interpret| operation of the abstract machine without
      // function calls. Such calls would likely slow the parser down and more
      // importantly cause stack overflows for complex grammars.
      "  while (true) {",
      "    while (ip < end) {",
      "      switch (bc[ip]) {",
      "        case " + op.PUSH + ":", // PUSH c
      "          stack.push(peg$consts[bc[ip + 1]]);",
      "          ip += 2;",
      "          break;",
      "",
      "        case " + op.PUSH_UNDEFINED + ":", // PUSH_UNDEFINED
      "          stack.push(undefined);",
      "          ip++;",
      "          break;",
      "",
      "        case " + op.PUSH_NULL + ":", // PUSH_NULL
      "          stack.push(null);",
      "          ip++;",
      "          break;",
      "",
      "        case " + op.PUSH_FAILED + ":", // PUSH_FAILED
      "          stack.push(peg$FAILED);",
      "          ip++;",
      "          break;",
      "",
      "        case " + op.PUSH_EMPTY_ARRAY + ":", // PUSH_EMPTY_ARRAY
      "          stack.push([]);",
      "          ip++;",
      "          break;",
      "",
      "        case " + op.PUSH_CURR_POS + ":", // PUSH_CURR_POS
      "          stack.push(peg$currPos);",
      "          ip++;",
      "          break;",
      "",
      "        case " + op.POP + ":", // POP
      "          stack.pop();",
      "          ip++;",
      "          break;",
      "",
      "        case " + op.POP_CURR_POS + ":", // POP_CURR_POS
      "          peg$currPos = stack.pop();",
      "          ip++;",
      "          break;",
      "",
      "        case " + op.POP_N + ":", // POP_N n
      "          stack.length -= bc[ip + 1];",
      "          ip += 2;",
      "          break;",
      "",
      "        case " + op.NIP + ":", // NIP
      "          stack.splice(-2, 1);",
      "          ip++;",
      "          break;",
      "",
      "        case " + op.APPEND + ":", // APPEND
      "          stack[stack.length - 2].push(stack.pop());",
      "          ip++;",
      "          break;",
      "",
      "        case " + op.WRAP + ":", // WRAP n
      "          stack.push(stack.splice(stack.length - bc[ip + 1], bc[ip + 1]));",
      "          ip += 2;",
      "          break;",
      "",
      "        case " + op.TEXT + ":", // TEXT
      "          stack.push(input.substring(stack.pop(), peg$currPos));",
      "          ip++;",
      "          break;",
      "",
      "        case " + op.IF + ":", // IF t, f
      indent10(generateCondition("stack[stack.length - 1]", 0)),
      "",
      "        case " + op.IF_ERROR + ":", // IF_ERROR t, f
      indent10(generateCondition(
        "stack[stack.length - 1] === peg$FAILED",
        0
      )),
      "",
      "        case " + op.IF_NOT_ERROR + ":", // IF_NOT_ERROR t, f
      indent10(
        generateCondition("stack[stack.length - 1] !== peg$FAILED",
          0
        )),
      "",
      "        case " + op.WHILE_NOT_ERROR + ":", // WHILE_NOT_ERROR b
      indent10(generateLoop("stack[stack.length - 1] !== peg$FAILED")),
      "",
      "        case " + op.MATCH_ANY + ":", // MATCH_ANY a, f, ...
      indent10(generateCondition("input.length > peg$currPos", 0)),
      "",
      "        case " + op.MATCH_STRING + ":", // MATCH_STRING s, a, f, ...
      indent10(generateCondition(
        "input.substr(peg$currPos, peg$consts[bc[ip + 1]].length) === peg$consts[bc[ip + 1]]",
        1
      )),
      "",
      "        case " + op.MATCH_STRING_IC + ":", // MATCH_STRING_IC s, a, f, ...
      indent10(generateCondition(
        "input.substr(peg$currPos, peg$consts[bc[ip + 1]].length).toLowerCase() === peg$consts[bc[ip + 1]]",
        1
      )),
      "",
      "        case " + op.MATCH_REGEXP + ":", // MATCH_REGEXP r, a, f, ...
      indent10(generateCondition(
        "peg$consts[bc[ip + 1]].test(input.charAt(peg$currPos))",
        1
      )),
      "",
      "        case " + op.ACCEPT_N + ":", // ACCEPT_N n
      "          stack.push(input.substr(peg$currPos, bc[ip + 1]));",
      "          peg$currPos += bc[ip + 1];",
      "          ip += 2;",
      "          break;",
      "",
      "        case " + op.ACCEPT_STRING + ":", // ACCEPT_STRING s
      "          stack.push(peg$consts[bc[ip + 1]]);",
      "          peg$currPos += peg$consts[bc[ip + 1]].length;",
      "          ip += 2;",
      "          break;",
      "",
      "        case " + op.FAIL + ":", // FAIL e
      "          stack.push(peg$FAILED);",
      "          if (peg$silentFails === 0) {",
      "            peg$fail(peg$consts[bc[ip + 1]]);",
      "          }",
      "          ip += 2;",
      "          break;",
      "",
      "        case " + op.LOAD_SAVED_POS + ":", // LOAD_SAVED_POS p
      "          peg$savedPos = stack[stack.length - 1 - bc[ip + 1]];",
      "          ip += 2;",
      "          break;",
      "",
      "        case " + op.UPDATE_SAVED_POS + ":", // UPDATE_SAVED_POS
      "          peg$savedPos = peg$currPos;",
      "          ip++;",
      "          break;",
      "",
      "        case " + op.CALL + ":", // CALL f, n, pc, p1, p2, ..., pN
      indent10(generateCall()),
      "",
      "        case " + op.RULE + ":", // RULE r
      "          stack.push(peg$parseRule(bc[ip + 1]));",
      "          ip += 2;",
      "          break;",
      "",
      "        case " + op.SILENT_FAILS_ON + ":", // SILENT_FAILS_ON
      "          peg$silentFails++;",
      "          ip++;",
      "          break;",
      "",
      "        case " + op.SILENT_FAILS_OFF + ":", // SILENT_FAILS_OFF
      "          peg$silentFails--;",
      "          ip++;",
      "          break;",
      "",
      "        default:",
      "          throw new Error(\"Invalid opcode: \" + bc[ip] + \".\");",
      "      }",
      "    }",
      "",
      "    if (ends.length > 0) {",
      "      end = ends.pop();",
      "      ip = ips.pop();",
      "    } else {",
      "      break;",
      "    }",
      "  }"
    ].join("\n"));

    parts.push(indent2(generateRuleFooter("peg$ruleNames[index]", "stack[0]")));
    parts.push("}");

    return parts.join("\n");
  }

  function generateRuleFunction(rule) {
    let parts = [];
    let stackVars = [];
    let code;

    function c(i) {
      return "peg$c" + i;
    } // |consts[i]| of the abstract machine
    function s(i) {
      return "s" + i;
    } // |stack[i]| of the abstract machine

    let stack = {
      sp: -1,
      maxSp: -1,

      push(exprCode) {
        let code = s(++this.sp) + " = " + exprCode + ";";

        if (this.sp > this.maxSp) {
          this.maxSp = this.sp;
        }

        return code;
      },

      pop(n) {
        if (n === undefined) {
          return s(this.sp--);
        } else {
          let values = Array(n);

          for (let i = 0; i < n; i++) {
            values[i] = s(this.sp - n + 1 + i);
          }

          this.sp -= n;

          return values;
        }
      },

      top() {
        return s(this.sp);
      },

      index(i) {
        return s(this.sp - i);
      }
    };

    function compile(bc) {
      let ip = 0;
      let end = bc.length;
      let parts = [];
      let value;

      function compileCondition(cond, argCount) {
        let baseLength = argCount + 3;
        let thenLength = bc[ip + baseLength - 2];
        let elseLength = bc[ip + baseLength - 1];
        let baseSp = stack.sp;
        let thenCode, elseCode, thenSp, elseSp;

        ip += baseLength;
        thenCode = compile(bc.slice(ip, ip + thenLength));
        thenSp = stack.sp;
        ip += thenLength;

        if (elseLength > 0) {
          stack.sp = baseSp;
          elseCode = compile(bc.slice(ip, ip + elseLength));
          elseSp = stack.sp;
          ip += elseLength;

          if (thenSp !== elseSp) {
            throw new Error(
              "Branches of a condition must move the stack pointer in the same way."
            );
          }
        }

        parts.push("if (" + cond + ") {");
        parts.push(indent2(thenCode));
        if (elseLength > 0) {
          parts.push("} else {");
          parts.push(indent2(elseCode));
        }
        parts.push("}");
      }

      function compileLoop(cond) {
        let baseLength = 2;
        let bodyLength = bc[ip + baseLength - 1];
        let baseSp = stack.sp;
        let bodyCode, bodySp;

        ip += baseLength;
        bodyCode = compile(bc.slice(ip, ip + bodyLength));
        bodySp = stack.sp;
        ip += bodyLength;

        if (bodySp !== baseSp) {
          throw new Error("Body of a loop can't move the stack pointer.");
        }

        parts.push("while (" + cond + ") {");
        parts.push(indent2(bodyCode));
        parts.push("}");
      }

      function compileCall() {
        let baseLength = 4;
        let paramsLength = bc[ip + baseLength - 1];

        let value = c(bc[ip + 1]) + "(" +
          bc.slice(ip + baseLength, ip + baseLength + paramsLength).map(
            p => stack.index(p)
          ).join(", ") +
          ")";
        stack.pop(bc[ip + 2]);
        parts.push(stack.push(value));
        ip += baseLength + paramsLength;
      }

      while (ip < end) {
        switch (bc[ip]) {
          case op.PUSH: // PUSH c
            parts.push(stack.push(c(bc[ip + 1])));
            ip += 2;
            break;

          case op.PUSH_CURR_POS: // PUSH_CURR_POS
            parts.push(stack.push("peg$currPos"));
            ip++;
            break;

          case op.PUSH_UNDEFINED: // PUSH_UNDEFINED
            parts.push(stack.push("undefined"));
            ip++;
            break;

          case op.PUSH_NULL: // PUSH_NULL
            parts.push(stack.push("null"));
            ip++;
            break;

          case op.PUSH_FAILED: // PUSH_FAILED
            parts.push(stack.push("peg$FAILED"));
            ip++;
            break;

          case op.PUSH_EMPTY_ARRAY: // PUSH_EMPTY_ARRAY
            parts.push(stack.push("[]"));
            ip++;
            break;

          case op.POP: // POP
            stack.pop();
            ip++;
            break;

          case op.POP_CURR_POS: // POP_CURR_POS
            parts.push("peg$currPos = " + stack.pop() + ";");
            ip++;
            break;

          case op.POP_N: // POP_N n
            stack.pop(bc[ip + 1]);
            ip += 2;
            break;

          case op.NIP: // NIP
            value = stack.pop();
            stack.pop();
            parts.push(stack.push(value));
            ip++;
            break;

          case op.APPEND: // APPEND
            value = stack.pop();
            parts.push(stack.top() + ".push(" + value + ");");
            ip++;
            break;

          case op.WRAP: // WRAP n
            parts.push(
              stack.push("[" + stack.pop(bc[ip + 1]).join(", ") + "]")
            );
            ip += 2;
            break;

          case op.TEXT: // TEXT
            parts.push(
              stack.push("input.substring(" + stack.pop() + ", peg$currPos)")
            );
            ip++;
            break;

          case op.IF: // IF t, f
            compileCondition(stack.top(), 0);
            break;

          case op.IF_ERROR: // IF_ERROR t, f
            compileCondition(stack.top() + " === peg$FAILED", 0);
            break;

          case op.IF_NOT_ERROR: // IF_NOT_ERROR t, f
            compileCondition(stack.top() + " !== peg$FAILED", 0);
            break;

          case op.WHILE_NOT_ERROR: // WHILE_NOT_ERROR b
            compileLoop(stack.top() + " !== peg$FAILED", 0);
            break;

          case op.MATCH_ANY: // MATCH_ANY a, f, ...
            compileCondition("input.length > peg$currPos", 0);
            break;

          case op.MATCH_STRING: // MATCH_STRING s, a, f, ...
            compileCondition(
              eval(ast.consts[bc[ip + 1]]).length > 1 ?
              "input.substr(peg$currPos, " +
              eval(ast.consts[bc[ip + 1]]).length +
              ") === " +
              c(bc[ip + 1]) :
              "input.charCodeAt(peg$currPos) === " +
              eval(ast.consts[bc[ip + 1]]).charCodeAt(0),
              1
            );
            break;

          case op.MATCH_STRING_IC: // MATCH_STRING_IC s, a, f, ...
            compileCondition(
              "input.substr(peg$currPos, " +
              eval(ast.consts[bc[ip + 1]]).length +
              ").toLowerCase() === " +
              c(bc[ip + 1]),
              1
            );
            break;

          case op.MATCH_REGEXP: // MATCH_REGEXP r, a, f, ...
            compileCondition(
              c(bc[ip + 1]) + ".test(input.charAt(peg$currPos))",
              1
            );
            break;

          case op.ACCEPT_N: // ACCEPT_N n
            parts.push(stack.push(
              bc[ip + 1] > 1 ?
              "input.substr(peg$currPos, " + bc[ip + 1] + ")" :
              "input.charAt(peg$currPos)"
            ));
            parts.push(
              bc[ip + 1] > 1 ?
              "peg$currPos += " + bc[ip + 1] + ";" :
              "peg$currPos++;"
            );
            ip += 2;
            break;

          case op.ACCEPT_STRING: // ACCEPT_STRING s
            parts.push(stack.push(c(bc[ip + 1])));
            parts.push(
              eval(ast.consts[bc[ip + 1]]).length > 1 ?
              "peg$currPos += " + eval(ast.consts[bc[ip + 1]]).length + ";" :
              "peg$currPos++;"
            );
            ip += 2;
            break;

          case op.FAIL: // FAIL e
            parts.push(stack.push("peg$FAILED"));
            parts.push("if (peg$silentFails === 0) { peg$fail(" + c(bc[ip + 1]) + "); }");
            ip += 2;
            break;

          case op.LOAD_SAVED_POS: // LOAD_SAVED_POS p
            parts.push("peg$savedPos = " + stack.index(bc[ip + 1]) + ";");
            ip += 2;
            break;

          case op.UPDATE_SAVED_POS: // UPDATE_SAVED_POS
            parts.push("peg$savedPos = peg$currPos;");
            ip++;
            break;

          case op.CALL: // CALL f, n, pc, p1, p2, ..., pN
            compileCall();
            break;

          case op.RULE: // RULE r
            parts.push(stack.push("peg$parse" + ast.rules[bc[ip + 1]].name + "()"));
            ip += 2;
            break;

          case op.SILENT_FAILS_ON: // SILENT_FAILS_ON
            parts.push("peg$silentFails++;");
            ip++;
            break;

          case op.SILENT_FAILS_OFF: // SILENT_FAILS_OFF
            parts.push("peg$silentFails--;");
            ip++;
            break;

          default:
            throw new Error("Invalid opcode: " + bc[ip] + ".");
        }
      }

      return parts.join("\n");
    }

    code = compile(rule.bytecode);

    const outputType = (options && options.returnTypes && options.returnTypes[rule.name]) ?
                       options.returnTypes[rule.name] : "any";
    
    parts.push("function peg$parse" + rule.name + "(): " + outputType +" {");

    if (options.trace) {
      parts.push("  const startPos = peg$currPos;");
    }

    for (let i = 0; i <= stack.maxSp; i++) {
      stackVars[i] = s(i);
    }

    parts.push("  let " + stackVars.join(", ") + ";");

    parts.push(indent2(generateRuleHeader(
      "\"" + js.stringEscape(rule.name) + "\"",
      asts.indexOfRule(ast, rule.name)
    )));
    parts.push(indent2(code));
    parts.push(indent2(generateRuleFooter(
      "\"" + js.stringEscape(rule.name) + "\"",
      s(0)
    )));

    parts.push("}");

    return parts.join("\n");
  }

  function generateToplevel() {
    let parts = [];

    if (options.tspegjs.customHeader) {
      parts.push(options.tspegjs.customHeader);
    }
    parts.push([
      "export interface IFilePosition {",
      "  offset: number;",
      "  line: number;",
      "  column: number;",
      "}",
      "",
      "export interface IFileRange {",
      "  start: IFilePosition;",
      "  end: IFilePosition;",
      "}",
      "",
      "export interface ILiteralExpectation {",
      "  type: \"literal\";",
      "  text: string;",
      "  ignoreCase: boolean;",
      "}",
      "",
      "export interface IClassParts extends Array<string | IClassParts> {}",
      "",
      "export interface IClassExpectation {",
      "  type: \"class\";",
      "  parts: IClassParts;",
      "  inverted: boolean;",
      "  ignoreCase: boolean;",
      "}",
      "",
      "export interface IAnyExpectation {",
      "  type: \"any\";",
      "}",
      "",
      "export interface IEndExpectation {",
      "  type: \"end\";",
      "}",
      "",
      "export interface IOtherExpectation {",
      "  type: \"other\";",
      "  description: string;",
      "}",
      "",
      "export type Expectation = ILiteralExpectation | IClassExpectation | IAnyExpectation | IEndExpectation | IOtherExpectation;",
      "",
      "export class SyntaxError extends Error {",
      "  public static buildMessage(expected: Expectation[], found: string | null) {",
      "    function hex(ch: string): string {",
      "      return ch.charCodeAt(0).toString(16).toUpperCase();",
      "    }",
      "",
      "    function literalEscape(s: string): string {",
      "      return s",
      "        .replace(/\\\\/g, \"\\\\\\\\\")", // backslash
      "        .replace(/\"/g,  \"\\\\\\\"\")", // closing double quote
      "        .replace(/\\0/g, \"\\\\0\")", // null
      "        .replace(/\\t/g, \"\\\\t\")", // horizontal tab
      "        .replace(/\\n/g, \"\\\\n\")", // line feed
      "        .replace(/\\r/g, \"\\\\r\")", // carriage return
      "        .replace(/[\\x00-\\x0F]/g,            (ch) => \"\\\\x0\" + hex(ch) )",
      "        .replace(/[\\x10-\\x1F\\x7F-\\x9F]/g, (ch) => \"\\\\x\"  + hex(ch) );",
      "    }",
      "",
      "    function classEscape(s: string): string {",
      "      return s",
      "        .replace(/\\\\/g, \"\\\\\\\\\")", // backslash
      "        .replace(/\\]/g, \"\\\\]\")", // closing bracket
      "        .replace(/\\^/g, \"\\\\^\")", // caret
      "        .replace(/-/g,  \"\\\\-\")", // dash
      "        .replace(/\\0/g, \"\\\\0\")", // null
      "        .replace(/\\t/g, \"\\\\t\")", // horizontal tab
      "        .replace(/\\n/g, \"\\\\n\")", // line feed
      "        .replace(/\\r/g, \"\\\\r\")", // carriage return
      "        .replace(/[\\x00-\\x0F]/g,            (ch) => \"\\\\x0\" + hex(ch) )",
      "        .replace(/[\\x10-\\x1F\\x7F-\\x9F]/g, (ch) => \"\\\\x\"  + hex(ch) );",
      "    }",
      "",
      "    function describeExpectation(expectation: Expectation) {",
      "      switch (expectation.type) {",
      "        case \"literal\":",
      "          return \"\\\"\" + literalEscape(expectation.text) + \"\\\"\";",
      "        case \"class\":",
      "          const escapedParts = expectation.parts.map((part) => {",
      "            return Array.isArray(part)",
      "              ? classEscape(part[0] as string) + \"-\" + classEscape(part[1] as string)",
      "              : classEscape(part);",
      "          });",
      "",
      "          return \"[\" + (expectation.inverted ? \"^\" : \"\") + escapedParts + \"]\";",
      "        case \"any\":",
      "          return \"any character\";",
      "        case \"end\":",
      "          return \"end of input\";",
      "        case \"other\":",
      "          return expectation.description;",
      "      }",
      "    }",
      "",
      "    function describeExpected(expected1: Expectation[]) {",
      "      const descriptions = expected1.map(describeExpectation);",
      "      let i;",
      "      let j;",
      "",
      "      descriptions.sort();",
      "",
      "      if (descriptions.length > 0) {",
      "        for (i = 1, j = 1; i < descriptions.length; i++) {",
      "          if (descriptions[i - 1] !== descriptions[i]) {",
      "            descriptions[j] = descriptions[i];",
      "            j++;",
      "          }",
      "        }",
      "        descriptions.length = j;",
      "      }",
      "",
      "      switch (descriptions.length) {",
      "        case 1:",
      "          return descriptions[0];",
      "",
      "        case 2:",
      "          return descriptions[0] + \" or \" + descriptions[1];",
      "",
      "        default:",
      "          return descriptions.slice(0, -1).join(\", \")",
      "            + \", or \"",
      "            + descriptions[descriptions.length - 1];",
      "      }",
      "    }",
      "",
      "    function describeFound(found1: string | null) {",
      "      return found1 ? \"\\\"\" + literalEscape(found1) + \"\\\"\" : \"end of input\";",
      "    }",
      "",
      "    return \"Expected \" + describeExpected(expected) + \" but \" + describeFound(found) + \" found.\";",
      "  }",
      "",
      "  public message: string;",
      "  public expected: Expectation[];",
      "  public found: string | null;",
      "  public location: IFileRange;",
      "  public name: string;",
      "",
      "  constructor(message: string, expected: Expectation[], found: string | null, location: IFileRange) {",
      "    super();",
      "    this.message = message;",
      "    this.expected = expected;",
      "    this.found = found;",
      "    this.location = location;",
      "    this.name = \"SyntaxError\";",
      "",
      "    if (typeof (Error as any).captureStackTrace === \"function\") {",
      "      (Error as any).captureStackTrace(this, SyntaxError);",
      "    }",
      "  }",
      "}",
      ""
    ].join("\n"));

    if (options.trace) {
      parts.push([
        "export interface ITraceEvent {",
        "  type: string;",
        "  rule: string;",
        "  result?: any;",
        "  location: IFileRange;",
        "}",
        "",
        "export class DefaultTracer {",
        "  private indentLevel: number;",
        "",
        "  constructor() {",
        "    this.indentLevel = 0;",
        "  }",
        "",
        "  public trace(event: ITraceEvent) {",
        "    const that = this;",
        "",
        "    function log(evt: ITraceEvent) {",
        "      function repeat(text: string, n: number) {",
        "         let result = \"\", i;",
        "",
        "         for (i = 0; i < n; i++) {",
        "           result += text;",
        "         }",
        "",
        "         return result;",
        "      }",
        "",
        "      function pad(text: string, length: number) {",
        "        return text + repeat(\" \", length - text.length);",
        "      }",
        "",
        "      if (typeof console === \"object\") {", // IE 8-10
        "        console.log(",
        "          evt.location.start.line + \":\" + evt.location.start.column + \"-\"",
        "            + evt.location.end.line + \":\" + evt.location.end.column + \" \"",
        "            + pad(evt.type, 10) + \" \"",
        "            + repeat(\"  \", that.indentLevel) + evt.rule",
        "        );",
        "      }",
        "    }",
        "",
        "    switch (event.type) {",
        "      case \"rule.enter\":",
        "        log(event);",
        "        this.indentLevel++;",
        "        break;",
        "",
        "      case \"rule.match\":",
        "        this.indentLevel--;",
        "        log(event);",
        "        break;",
        "",
        "      case \"rule.fail\":",
        "        this.indentLevel--;",
        "        log(event);",
        "        break;",
        "",
        "      default:",
        "        throw new Error(\"Invalid event type: \" + event.type + \".\");",
        "    }",
        "  }",
        "}",
        ""
      ].join("\n"));
    }

    if (options.cache) {
      parts.push([
        "export interface ICached {",
        "  nextPos: number;",
        "  result: any;",
        "}",
        "",
      ].join("\n"));
    }

    parts.push([
      "function peg$parse(input: string, options?: IParseOptions) {",
      "  options = options !== undefined ? options : {};",
      "",
      "  const peg$FAILED = {};",
      ""
    ].join("\n"));

    if (options.optimize === "size") {
      let startRuleIndices = "{ " +
        options.allowedStartRules.map(
          r => r + ": " + asts.indexOfRule(ast, r)
        ).join(", ") +
        " }";
      let startRuleIndex = asts.indexOfRule(ast, options.allowedStartRules[0]);

      parts.push([
        "  const peg$startRuleIndices = " + startRuleIndices + ";",
        "  const peg$startRuleIndex = " + startRuleIndex + ";"
      ].join("\n"));
    } else {
      let startRuleFunctions = "{ " +
        options.allowedStartRules.map(
          r => r + ": peg$parse" + r
        ).join(", ") +
        " }";
      let startRuleFunction = "peg$parse" + options.allowedStartRules[0];

      parts.push([
        "  const peg$startRuleFunctions: {[id: string]: any} = " + startRuleFunctions + ";",
        "  let peg$startRuleFunction: () => any = " + startRuleFunction + ";"
      ].join("\n"));
    }

    parts.push("");

    parts.push(indent2(generateTables()));

    parts.push([
      "",
      "  let peg$currPos = 0;",
      "  let peg$savedPos = 0;",
      "  const peg$posDetailsCache = [{ line: 1, column: 1 }];",
      "  let peg$maxFailPos = 0;",
      "  let peg$maxFailExpected: any[] = [];",
      "  let peg$silentFails = 0;", // 0 = report failures, > 0 = silence failures
      ""
    ].join("\n"));

    if (options.cache) {
      parts.push([
        "  const peg$resultsCache: {[id: number]: ICached} = {};",
        ""
      ].join("\n"));
    }

    if (options.trace) {
      if (options.optimize === "size") {
        let ruleNames = "[" +
          ast.rules.map(
            r => "\"" + js.stringEscape(r.name) + "\""
          ).join(", ") +
          "]";

        parts.push([
          "  let peg$ruleNames = " + ruleNames + ";",
          ""
        ].join("\n"));
      }

      parts.push([
        "  const peg$tracer = \"tracer\" in options ? options.tracer : new DefaultTracer();",
        ""
      ].join("\n"));
    }

    parts.push([
      "  let peg$result;",
      ""
    ].join("\n"));

    if (options.optimize === "size") {
      parts.push([
        "  if (options.startRule !== undefined) {",
        "    if (!(options.startRule in peg$startRuleIndices)) {",
        "      throw new Error(\"Can't start parsing from rule \\\"\" + options.startRule + \"\\\".\");",
        "    }",
        "",
        "    peg$startRuleIndex = peg$startRuleIndices[options.startRule];",
        "  }"
      ].join("\n"));
    } else {
      parts.push([
        "  if (options.startRule !== undefined) {",
        "    if (!(options.startRule in peg$startRuleFunctions)) {",
        "      throw new Error(\"Can't start parsing from rule \\\"\" + options.startRule + \"\\\".\");",
        "    }",
        "",
        "    peg$startRuleFunction = peg$startRuleFunctions[options.startRule];",
        "  }"
      ].join("\n"));
    }

    parts.push([
      "",
      "  function text(): string {",
      "    return input.substring(peg$savedPos, peg$currPos);",
      "  }",
      "",
      "  function location(): IFileRange {",
      "    return peg$computeLocation(peg$savedPos, peg$currPos);",
      "  }",
      "",
      "  function expected(description: string, location1?: IFileRange) {",
      "    location1 = location1 !== undefined",
      "      ? location1",
      "      : peg$computeLocation(peg$savedPos, peg$currPos);",
      "",
      "    throw peg$buildStructuredError(",
      "      [peg$otherExpectation(description)],",
      "      input.substring(peg$savedPos, peg$currPos),",
      "      location1",
      "    );",
      "  }",
      "",
      "  function error(message: string, location1?: IFileRange) {",
      "    location1 = location1 !== undefined",
      "      ? location1",
      "      : peg$computeLocation(peg$savedPos, peg$currPos);",
      "",
      "    throw peg$buildSimpleError(message, location1);",
      "  }",
      "",
      "  function peg$literalExpectation(text1: string, ignoreCase: boolean): ILiteralExpectation {",
      "    return { type: \"literal\", text: text1, ignoreCase: ignoreCase };",
      "  }",
      "",
      "  function peg$classExpectation(parts: IClassParts, inverted: boolean, ignoreCase: boolean): IClassExpectation {",
      "    return { type: \"class\", parts: parts, inverted: inverted, ignoreCase: ignoreCase };",
      "  }",
      "",
      "  function peg$anyExpectation(): IAnyExpectation {",
      "    return { type: \"any\" };",
      "  }",
      "",
      "  function peg$endExpectation(): IEndExpectation {",
      "    return { type: \"end\" };",
      "  }",
      "",
      "  function peg$otherExpectation(description: string): IOtherExpectation {",
      "    return { type: \"other\", description: description };",
      "  }",
      "",
      "  function peg$computePosDetails(pos: number) {",
      "    let details = peg$posDetailsCache[pos];",
      "    let p;",
      "",
      "    if (details) {",
      "      return details;",
      "    } else {",
      "      p = pos - 1;",
      "      while (!peg$posDetailsCache[p]) {",
      "        p--;",
      "      }",
      "",
      "      details = peg$posDetailsCache[p];",
      "      details = {",
      "        line: details.line,",
      "        column: details.column",
      "      };",
      "",
      "      while (p < pos) {",
      "        if (input.charCodeAt(p) === 10) {",
      "          details.line++;",
      "          details.column = 1;",
      "        } else {",
      "          details.column++;",
      "        }",
      "",
      "        p++;",
      "      }",
      "",
      "      peg$posDetailsCache[pos] = details;",
      "",
      "      return details;",
      "    }",
      "  }",
      "",
      "  function peg$computeLocation(startPos: number, endPos: number): IFileRange {",
      "    const startPosDetails = peg$computePosDetails(startPos);",
      "    const endPosDetails = peg$computePosDetails(endPos);",
      "",
      "    return {",
      "      start: {",
      "        offset: startPos,",
      "        line: startPosDetails.line,",
      "        column: startPosDetails.column",
      "      },",
      "      end: {",
      "        offset: endPos,",
      "        line: endPosDetails.line,",
      "        column: endPosDetails.column",
      "      }",
      "    };",
      "  }",
      "",
      "  function peg$fail(expected1: Expectation) {",
      "    if (peg$currPos < peg$maxFailPos) { return; }",
      "",
      "    if (peg$currPos > peg$maxFailPos) {",
      "      peg$maxFailPos = peg$currPos;",
      "      peg$maxFailExpected = [];",
      "    }",
      "",
      "    peg$maxFailExpected.push(expected1);",
      "  }",
      "",
      "  function peg$buildSimpleError(message: string, location1: IFileRange) {",
      "    return new SyntaxError(message, [], \"\", location1);",
      "  }",
      "",
      "  function peg$buildStructuredError(expected1: Expectation[], found: string | null, location1: IFileRange) {",
      "    return new SyntaxError(",
      "      SyntaxError.buildMessage(expected1, found),",
      "      expected1,",
      "      found,",
      "      location1",
      "    );",
      "  }",
      ""
    ].join("\n"));

    if (options.optimize === "size") {
      parts.push(indent2(generateInterpreter()));
      parts.push("");
    } else {
      ast.rules.forEach(rule => {
        parts.push(indent2(generateRuleFunction(rule)));
        parts.push("");
      });
    }

    if (ast.initializer) {
      parts.push(indent2(ast.initializer.code));
      parts.push("");
    }

    if (options.optimize === "size") {
      parts.push("  peg$result = peg$parseRule(peg$startRuleIndex);");
    } else {
      parts.push("  peg$result = peg$startRuleFunction();");
    }

    parts.push([
      "",
      "  if (peg$result !== peg$FAILED && peg$currPos === input.length) {",
      "    return peg$result;",
      "  } else {",
      "    if (peg$result !== peg$FAILED && peg$currPos < input.length) {",
      "      peg$fail(peg$endExpectation());",
      "    }",
      "",
      "    throw peg$buildStructuredError(",
      "      peg$maxFailExpected,",
      "      peg$maxFailPos < input.length ? input.charAt(peg$maxFailPos) : null,",
      "      peg$maxFailPos < input.length",
      "        ? peg$computeLocation(peg$maxFailPos, peg$maxFailPos + 1)",
      "        : peg$computeLocation(peg$maxFailPos, peg$maxFailPos)",
      "    );",
      "  }",
      "}"
    ].join("\n"));

    return parts.join("\n");
  }

  function generateWrapper(toplevelCode) {
    function generateGeneratedByComment() {
      let res = [];
      if (!options.tspegjs.noTslint) {
        if (options.tspegjs.tslintIgnores) {
          // apply user custom exclusions
          res = res.concat(
            options.tspegjs.tslintIgnores
                .split(",")
                .map((rule) => "// tslint:disable:" + rule)
          );
        } else {
          // apply default tslint excusions
          res = res.concat([
            "// tslint:disable:only-arrow-functions",
            "// tslint:disable:object-literal-shorthand",
            "// tslint:disable:trailing-comma",
            "// tslint:disable:object-literal-sort-keys",
            "// tslint:disable:one-variable-per-declaration",
            "// tslint:disable:max-line-length",
            "// tslint:disable:no-consecutive-blank-lines",
            "// tslint:disable:align",
            options.trace ? "// tslint:disable:no-console" : ""
          ]); 
        }
      }
      res = res.concat([
        "",
        "// Generated by PEG.js v. " + pegJsVersion + " (ts-pegjs plugin v. " + pluginVersion + " )",
        "//",
        "// https://pegjs.org/   https://github.com/metadevpro/ts-pegjs"
      ]);

      return res.join("\n");
    }

    function generateParserObject() {
      const optionsType = `export interface IParseOptions {
  filename?: string;
  startRule?: string;
  tracer?: any;
  [key: string]: any;
}`;
      const parseFunctionType = "export type ParseFunction = (input: string, options?: IParseOptions) => any;";
      const parseExport = "export const parse: ParseFunction = peg$parse;";

      return options.trace ?
        [
          optionsType,
          parseFunctionType,
          parseExport,
          ""
          // "{",
          // "  SyntaxError: peg$SyntaxError,",
          // "  DefaultTracer: peg$DefaultTracer,",
          // "  parse: peg$parse",
          // "}"
        ].join("\n") :
        [
          optionsType,
          parseFunctionType,
          parseExport,
          ""
          // "{",
          // "  SyntaxError: peg$SyntaxError,",
          // "  parse: peg$parse",
          // "}"
        ].join("\n");
    }

    function generateParserExports() {
      return options.trace ?
        [
          "{",
          "  SyntaxError as SyntaxError,",
          "  DefaultTracer as DefaultTracer,",
          "  peg$parse as parse",
          "}"
        ].join("\n") :
        [
          "{",
          "  SyntaxError as SyntaxError,",
          "  peg$parse as parse",
          "}"
        ].join("\n");
    }

    let generators = {
      bare() {
        return [
          generateGeneratedByComment(),
          // "(function() {",
          // "  \"use strict\";",
          "",
          toplevelCode,
          "",
          //indent2("return " + generateParserObject() + ";"),
          generateParserObject(),
          //"})()"
        ].join("\n");
      },

      commonjs() {
        let parts = [];
        let dependencyVars = Object.keys(options.dependencies);

        parts.push([
          generateGeneratedByComment(),
          "",
          "\"use strict\";",
          ""
        ].join("\n"));

        if (dependencyVars.length > 0) {
          dependencyVars.forEach(variable => {
            parts.push("let " + variable +
              " = require(\"" +
              js.stringEscape(options.dependencies[variable]) +
              "\");"
            );
          });
          parts.push("");
        }

        parts.push([
          toplevelCode,
          "",
          //"module.exports = " + generateParserObject() + ";",
          generateParserObject(),
          ""
        ].join("\n"));

        return parts.join("\n");
      },

      es() {
        let parts = [];
        let dependencyVars = Object.keys(options.dependencies);

        parts.push(
          generateGeneratedByComment(),
          ""
        );

        if (dependencyVars.length > 0) {
          dependencyVars.forEach(variable => {
            parts.push("import " + variable +
              " from \"" +
              js.stringEscape(options.dependencies[variable]) +
              "\";"
            );
          });
          parts.push("");
        }

        parts.push(
          toplevelCode,
          "",
          "export " + generateParserExports() + ";",
          ""
        );

        return parts.join("\n");
      },

      amd() {
        let dependencyVars = Object.keys(options.dependencies);
        let dependencyIds = dependencyVars.map(v => options.dependencies[v]);
        let dependencies = "[" +
          dependencyIds.map(
            id => "\"" + js.stringEscape(id) + "\""
          ).join(", ") +
          "]";
        let params = dependencyVars.map(v => v + ": any").join(", ");

        return [
          generateGeneratedByComment(),
          "define(" + dependencies + ", function(" + params + ") {",
          "  \"use strict\";",
          "",
          indent2(toplevelCode),
          "",
          indent2("return " + generateParserObject() + ";"),
          "});",
          ""
        ].join("\n");
      },

      globals() {
        return [
          generateGeneratedByComment(),
          "(function(root) {",
          "  \"use strict\";",
          "",
          indent2(toplevelCode),
          "",
          indent2("root." + options.exportVar + " = " + generateParserObject() + ";"),
          "})(this);",
          ""
        ].join("\n");
      },

      umd() {
        let parts = [];
        let dependencyVars = Object.keys(options.dependencies);
        let dependencyIds = dependencyVars.map(v => options.dependencies[v]);
        let dependencies = "[" +
          dependencyIds.map(
            id => "\"" + js.stringEscape(id) + "\""
          ).join(", ") +
          "]";
        let requires = dependencyIds.map(
          id => "require(\"" + js.stringEscape(id) + "\")"
        ).join(", ");
        let params = dependencyVars.map(v => v + ": any").join(", ");

        parts.push([
          generateGeneratedByComment(),
          "(function(root, factory) {",
          "  if (typeof define === \"function\" && define.amd) {",
          "    define(" + dependencies + ", factory);",
          "  } else if (typeof module === \"object\" && module.exports) {",
          "    module.exports = factory(" + requires + ");"
        ].join("\n"));

        if (options.exportVar !== null) {
          parts.push([
            "  } else {",
            "    root." + options.exportVar + " = factory();"
          ].join("\n"));
        }

        parts.push([
          "  }",
          "})(this, function(" + params + ") {",
          "  \"use strict\";",
          "",
          indent2(toplevelCode),
          "",
          indent2("return " + generateParserObject() + ";"),
          "});",
          ""
        ].join("\n"));

        return parts.join("\n");
      }
    };

    return generators[options.format]();
  }

  ast.code = generateWrapper(generateToplevel());
}
647835
function processes(callback) {

  let parsedhead = [];

  function getName(command) {
    command = command || '';
    let result = command.split(' ')[0];
    if (result.substr(-1) === ':') {
      result = result.substr(0, result.length - 1);
    }
    if (result.substr(0, 1) !== '[') {
      let parts = result.split('/');
      if (isNaN(parseInt(parts[parts.length - 1]))) {
        result = parts[parts.length - 1];
      } else {
        result = parts[0];
      }
    }
    return result;
  }

  function parseLine(line) {
    let offset = 0;
    let offset2 = 0;

    function checkColumn(i) {
      offset = offset2;
      offset2 = line.substring(parsedhead[i].to + offset, 1000).indexOf(' ');
    }

    checkColumn(0);
    let pid = parseInt(line.substring(parsedhead[0].from + offset, parsedhead[0].to + offset2));
    checkColumn(1);
    let ppid = parseInt(line.substring(parsedhead[1].from + offset, parsedhead[1].to + offset2));
    checkColumn(2);
    let pcpu = parseFloat(line.substring(parsedhead[2].from + offset, parsedhead[2].to + offset2).replace(/,/g, '.'));
    checkColumn(3);
    let pmem = parseFloat(line.substring(parsedhead[3].from + offset, parsedhead[3].to + offset2).replace(/,/g, '.'));
    checkColumn(4);
    let priority = parseInt(line.substring(parsedhead[4].from + offset, parsedhead[4].to + offset2));
    checkColumn(5);
    let vsz = parseInt(line.substring(parsedhead[5].from + offset, parsedhead[5].to + offset2));
    checkColumn(6);
    let rss = parseInt(line.substring(parsedhead[6].from + offset, parsedhead[6].to + offset2));
    checkColumn(7);
    let nice = parseInt(line.substring(parsedhead[7].from + offset, parsedhead[7].to + offset2)) || 0;
    checkColumn(8);
    let started = parseTimeUnix(line.substring(parsedhead[8].from + offset, parsedhead[8].to + offset2).trim());
    checkColumn(9);
    let state = line.substring(parsedhead[9].from + offset, parsedhead[9].to + offset2).trim();
    state = (state[0] === 'R' ? 'running' : (state[0] === 'S' ? 'sleeping' : (state[0] === 'T' ? 'stopped' : (state[0] === 'W' ? 'paging' : (state[0] === 'X' ? 'dead' : (state[0] === 'Z' ? 'zombie' : ((state[0] === 'D' || state[0] === 'U') ? 'blocked' : 'unknown')))))));
    checkColumn(10);
    let tty = line.substring(parsedhead[10].from + offset, parsedhead[10].to + offset2).trim();
    if (tty === '?' || tty === '??') tty = '';
    checkColumn(11);
    let user = line.substring(parsedhead[11].from + offset, parsedhead[11].to + offset2).trim();
    checkColumn(12);
    let command = line.substring(parsedhead[12].from + offset, parsedhead[12].to + offset2).trim().replace(/\[/g, '').replace(/]/g, '');

    return ({
      pid: pid,
      parentPid: ppid,
      name: _linux ? getName(command) : command,
      pcpu: pcpu,
      pcpuu: 0,
      pcpus: 0,
      pmem: pmem,
      priority: priority,
      mem_vsz: vsz,
      mem_rss: rss,
      nice: nice,
      started: started,
      state: state,
      tty: tty,
      user: user,
      command: command
    });
  }

  function parseProcesses(lines) {
    let result = [];
    if (lines.length > 1) {
      let head = lines[0];
      parsedhead = util.parseHead(head, 8);
      lines.shift();
      lines.forEach(function (line) {
        if (line.trim() !== '') {
          result.push(parseLine(line));
        }
      });
    }
    return result;
  }
  function parseProcesses2(lines) {

    function formatDateTime(time) {
      const month = ('0' + (time.getMonth() + 1).toString()).substr(-2);
      const year = time.getFullYear().toString();
      const day = ('0' + time.getDay().toString()).substr(-2);
      const hours = time.getHours().toString();
      const mins = time.getMinutes().toString();
      const secs = ('0' + time.getSeconds().toString()).substr(-2);

      return (year + '-' + month + '-' + day + ' ' + hours + ':' + mins + ':' + secs);
    }

    let result = [];
    lines.forEach(function (line) {
      if (line.trim() !== '') {
        line = line.trim().replace(/ +/g, ' ').replace(/,+/g, '.');
        const parts = line.split(' ');
        const command = parts.slice(9).join(' ');
        const pmem = parseFloat((1.0 * parseInt(parts[3]) * 1024 / os.totalmem()).toFixed(1));
        const elapsed_parts = parts[5].split(':');
        const started = formatDateTime(new Date(Date.now() - (elapsed_parts.length > 1 ? (elapsed_parts[0] * 60 + elapsed_parts[1]) * 1000 : elapsed_parts[0] * 1000)));

        result.push({
          pid: parseInt(parts[0]),
          parentPid: parseInt(parts[1]),
          name: getName(command),
          pcpu: 0,
          pcpuu: 0,
          pcpus: 0,
          pmem: pmem,
          priority: 0,
          mem_vsz: parseInt(parts[2]),
          mem_rss: parseInt(parts[3]),
          nice: parseInt(parts[4]),
          started: started,
          state: (parts[6] === 'R' ? 'running' : (parts[6] === 'S' ? 'sleeping' : (parts[6] === 'T' ? 'stopped' : (parts[6] === 'W' ? 'paging' : (parts[6] === 'X' ? 'dead' : (parts[6] === 'Z' ? 'zombie' : ((parts[6] === 'D' || parts[6] === 'U') ? 'blocked' : 'unknown'))))))),
          tty: parts[7],
          user: parts[8],
          command: command
        });
      }
    });
    return result;
  }

  return new Promise((resolve) => {
    process.nextTick(() => {
      let result = {
        all: 0,
        running: 0,
        blocked: 0,
        sleeping: 0,
        unknown: 0,
        list: []
      };

      let cmd = '';

      if ((_processes_cpu.ms && Date.now() - _processes_cpu.ms >= 500) || _processes_cpu.ms === 0) {
        if (_linux || _freebsd || _openbsd || _darwin || _sunos) {
          if (_linux) cmd = 'export LC_ALL=C; ps -axo pid:11,ppid:11,pcpu:6,pmem:6,pri:5,vsz:11,rss:11,ni:5,lstart:30,state:5,tty:15,user:20,command; unset LC_ALL';
          if (_freebsd || _openbsd) cmd = 'export LC_ALL=C; ps -axo pid,ppid,pcpu,pmem,pri,vsz,rss,ni,lstart,state,tty,user,command; unset LC_ALL';
          if (_darwin) cmd = 'export LC_ALL=C; ps -acxo pid,ppid,pcpu,pmem,pri,vsz,rss,nice,lstart,state,tty,user,command -r; unset LC_ALL';
          if (_sunos) cmd = 'ps -Ao pid,ppid,pcpu,pmem,pri,vsz,rss,nice,stime,s,tty,user,comm';
          exec(cmd, { maxBuffer: 1024 * 2000 }, function (error, stdout) {
            if (!error) {
              result.list = parseProcesses(stdout.toString().split('\n'));
              result.all = result.list.length;
              result.running = result.list.filter(function (e) {
                return e.state === 'running';
              }).length;
              result.blocked = result.list.filter(function (e) {
                return e.state === 'blocked';
              }).length;
              result.sleeping = result.list.filter(function (e) {
                return e.state === 'sleeping';
              }).length;

              if (_linux) {
                // calc process_cpu - ps is not accurate in linux!
                cmd = 'cat /proc/stat | grep "cpu "';
                for (let i = 0; i < result.list.length; i++) {
                  cmd += (';cat /proc/' + result.list[i].pid + '/stat');
                }
                exec(cmd, { maxBuffer: 1024 * 2000 }, function (error, stdout) {
                  let curr_processes = stdout.toString().split('\n');

                  // first line (all - /proc/stat)
                  let all = parseProcStat(curr_processes.shift());

                  // process
                  let list_new = {};
                  let resultProcess = {};
                  for (let i = 0; i < curr_processes.length; i++) {
                    resultProcess = calcProcStatLinux(curr_processes[i], all, _processes_cpu);

                    if (resultProcess.pid) {

                      // store pcpu in outer array
                      let listPos = result.list.map(function (e) { return e.pid; }).indexOf(resultProcess.pid);
                      if (listPos >= 0) {
                        result.list[listPos].pcpu = resultProcess.pcpuu + resultProcess.pcpus;
                        result.list[listPos].pcpuu = resultProcess.pcpuu;
                        result.list[listPos].pcpus = resultProcess.pcpus;
                      }

                      // save new values
                      list_new[resultProcess.pid] = {
                        pcpuu: resultProcess.pcpuu,
                        pcpus: resultProcess.pcpus,
                        utime: resultProcess.utime,
                        stime: resultProcess.stime,
                        cutime: resultProcess.cutime,
                        cstime: resultProcess.cstime
                      };
                    }
                  }

                  // store old values
                  _processes_cpu.all = all;
                  _processes_cpu.list = list_new;
                  _processes_cpu.ms = Date.now() - _processes_cpu.ms;
                  _processes_cpu.result = result;
                  if (callback) { callback(result); }
                  resolve(result);
                });
              } else {
                if (callback) { callback(result); }
                resolve(result);
              }
            } else {
              cmd = 'ps -o pid,ppid,vsz,rss,nice,etime,stat,tty,user,comm';
              if (_sunos) {
                cmd = 'ps -o pid,ppid,vsz,rss,nice,etime,s,tty,user,comm';
              }
              exec(cmd, { maxBuffer: 1024 * 2000 }, function (error, stdout) {
                if (!error) {
                  let lines = stdout.toString().split('\n');
                  lines.shift();

                  result.list = parseProcesses2(lines);
                  result.all = result.list.length;
                  result.running = result.list.filter(function (e) {
                    return e.state === 'running';
                  }).length;
                  result.blocked = result.list.filter(function (e) {
                    return e.state === 'blocked';
                  }).length;
                  result.sleeping = result.list.filter(function (e) {
                    return e.state === 'sleeping';
                  }).length;
                  if (callback) { callback(result); }
                  resolve(result);
                } else {
                  if (callback) { callback(result); }
                  resolve(result);
                }
              });
            }
          });
        }
        if (_windows) {
          try {
            util.wmic('process get /value').then((stdout, error) => {
              if (!error) {
                let processSections = stdout.split(/\n\s*\n/);
                let procs = [];
                let procStats = [];
                let list_new = {};
                let allcpuu = 0;
                let allcpus = 0;
                for (let i = 0; i < processSections.length; i++) {
                  if (processSections[i].trim() !== '') {
                    let lines = processSections[i].trim().split('\r\n');
                    let pid = parseInt(util.getValue(lines, 'ProcessId', '=', true), 10);
                    let parentPid = parseInt(util.getValue(lines, 'ParentProcessId', '=', true), 10);
                    let statusValue = util.getValue(lines, 'ExecutionState', '=');
                    let name = util.getValue(lines, 'Caption', '=', true);
                    let commandLine = util.getValue(lines, 'CommandLine', '=', true);
                    let utime = parseInt(util.getValue(lines, 'UserModeTime', '=', true), 10);
                    let stime = parseInt(util.getValue(lines, 'KernelModeTime', '=', true), 10);
                    let mem = parseInt(util.getValue(lines, 'WorkingSetSize', '=', true), 10);
                    allcpuu = allcpuu + utime;
                    allcpus = allcpus + stime;
                    result.all++;
                    if (!statusValue) { result.unknown++; }
                    if (statusValue === '3') { result.running++; }
                    if (statusValue === '4' || statusValue === '5') { result.blocked++; }

                    procStats.push({
                      pid: pid,
                      utime: utime,
                      stime: stime,
                      pcpu: 0,
                      pcpuu: 0,
                      pcpus: 0,
                    });
                    procs.push({
                      pid: pid,
                      parentPid: parentPid,
                      name: name,
                      pcpu: 0,
                      pcpuu: 0,
                      pcpus: 0,
                      pmem: mem / os.totalmem() * 100,
                      priority: parseInt(util.getValue(lines, 'Priority', '=', true), 10),
                      mem_vsz: parseInt(util.getValue(lines, 'PageFileUsage', '=', true), 10),
                      mem_rss: Math.floor(parseInt(util.getValue(lines, 'WorkingSetSize', '=', true), 10) / 1024),
                      nice: 0,
                      started: parseTimeWin(util.getValue(lines, 'CreationDate', '=', true)),
                      state: (!statusValue ? _winStatusValues[0] : _winStatusValues[statusValue]),
                      tty: '',
                      user: '',
                      command: commandLine || name
                    });
                  }
                }
                result.sleeping = result.all - result.running - result.blocked - result.unknown;
                result.list = procs;
                for (let i = 0; i < procStats.length; i++) {
                  let resultProcess = calcProcStatWin(procStats[i], allcpuu + allcpus, _processes_cpu);

                  // store pcpu in outer array
                  let listPos = result.list.map(function (e) { return e.pid; }).indexOf(resultProcess.pid);
                  if (listPos >= 0) {
                    result.list[listPos].pcpu = resultProcess.pcpuu + resultProcess.pcpus;
                    result.list[listPos].pcpuu = resultProcess.pcpuu;
                    result.list[listPos].pcpus = resultProcess.pcpus;
                  }

                  // save new values
                  list_new[resultProcess.pid] = {
                    pcpuu: resultProcess.pcpuu,
                    pcpus: resultProcess.pcpus,
                    utime: resultProcess.utime,
                    stime: resultProcess.stime
                  };
                }
                // store old values
                _processes_cpu.all = allcpuu + allcpus;
                _processes_cpu.list = list_new;
                _processes_cpu.ms = Date.now() - _processes_cpu.ms;
                _processes_cpu.result = result;
              }
              if (callback) {
                callback(result);
              }
              resolve(result);
            });
          } catch (e) {
            if (callback) { callback(result); }
            resolve(result);
          }
        }
      } else {
        if (callback) { callback(_processes_cpu.result); }
        resolve(_processes_cpu.result);
      }
    });
  });
}
1089571
function readPESPackets(filter = true, warning = false) {
  var pesBuilder = {};
  var pesMaker = x => {
    if (x.type === 'TSPacket') {
      if (x.payloadUnitStartIndicator === true) {
        if (x.payload.readUIntBE(0, 3) !== 0x000001) {
          if (warning)
            console.log(`Warning: Non PES packet found at payload start indicator for PID ${x.pid}.`);
          return H([x]);
        }
        var pesOptional = x.payload.readUInt16BE(6);
        var pesPacket = {
          type : 'PESPacket',
          pid : x.pid,
          streamID : util.streamIDName[x.payload.readUInt8(3)],
          pesPacketLength : x.payload.readUInt16BE(4),
          scramblingControl : (pesOptional & 0x3000) >>> 12,
          priority : (pesOptional & 0x0800) !== 0,
          dataAlignmentIndicator : (pesOptional & 0x0400) !== 0,
          copyright : (pesOptional & 0x0200) !== 0,
          originalOrCopy : (pesOptional & 0x0100) !== 0,
          ptsDtsIndicator : (pesOptional & 0x00c0) >> 6,
          escrFlag : (pesOptional & 0x0020) !== 0,
          esRateFlag : (pesOptional & 0x0010) !== 0,
          dsmTrickModeFlag : (pesOptional & 0x0008) !== 0,
          additionalCopyInfoFlag : (pesOptional & 0x0004) !== 0,
          crcFlag : (pesOptional & 0x0002) !== 0,
          extensionFlag : (pesOptional & 0x00001) !== 0,
          pesHeaderLength : x.payload.readUInt8(8)
        };
        switch (pesPacket.ptsDtsIndicator) {
        case 2:
          pesPacket.pts = readTimeStamp(x.payload, 9);
          break;
        case 3:
          pesPacket.pts = readTimeStamp(x.payload, 9);
          pesPacket.dts = readTimeStamp(x.payload, 14);
          break;
        default:
          break;
        }
        pesPacket.payloads = [ x.payload.slice(9 + pesPacket.pesHeaderLength) ];
        if (pesBuilder[x.pid]) {
          var finishedPacket = pesBuilder[x.pid];
          pesBuilder[x.pid] = pesPacket;
          return filter ? H([finishedPacket]) : H([x, finishedPacket]);
        } else {
          pesBuilder[x.pid] = pesPacket;
          return filter ? H([]) : H([x]);
        }
      } else { // execute if payloadUnitStartIndicator !== true
        if (pesBuilder[x.pid]) {
          if (x.payload) // Might be a adaptation field only - no payload
            pesBuilder[x.pid].payloads.push(x.payload);
        }
        return filter ? H([]) : H([x]);
      } // payloadUnitStartIndicator === true
    } else {
      return H([x]);
    }  // Is TSPacket
  };
  return H.pipeline(H.flatMap(pesMaker));
}
868908
function seq() {
  var parsers = [].slice.call(arguments);
  var numParsers = parsers.length;
  for (var j = 0; j < numParsers; j += 1) {
    assertParser(parsers[j]);
  }
  return Parsimmon(function(input, i) {
    var result;
    var accum = new Array(numParsers);
    for (var j = 0; j < numParsers; j += 1) {
      result = mergeReplies(parsers[j]._(input, i), result);
      if (!result.status) {
        return result;
      }
      accum[j] = result.value;
      i = result.index;
    }
    return mergeReplies(makeSuccess(i, accum), result);
  });
}
1002365
function formatProperties (properties) {
    const result = {}
    Object.keys(properties).forEach(key => {
      debug('formatProperties: key: ' + key)
      if (properties.hasOwnProperty(key)) {
        result[ key ] = _.clone(properties[ key ])
        result[ key ].type = properties[ key ].type.name
      }
    })
    return result
  }
1326951
function parse(headers) {
    var output = {}, i, p, k, v;
    headers = headers || '';
    headers = headers.replace('\r', '');
    headers = headers.split('\n');
    for(i = 0;i < headers.length;i++) {
      p = headers[i].indexOf(':');
      k = headers[i].substr(0, p);
      v = headers[i].substr(p + 1);
      if(k && v) {
        k = k.replace(/^\s+/, '').replace(/\s+$/, '');
        v = v.replace(/^\s+/, '').replace(/\s+$/, '');
        output[k.toLowerCase()] = v;
      }
    }
    return output;
  }