patch method

void patch(
  1. String keywordFound, {
  2. bool alsoBreak = false,
  3. int reservingLines = 0,
})

Call this method when we've found an 'end' keyword, and want to patch up any jumps that were waiting for that. Patch the matching backpatch (and any after it) to the current code end.

Implementation

void patch(
  String keywordFound, {
  bool alsoBreak = false,
  int reservingLines = 0,
}) {
  final target = ValNumber((code.length + reservingLines).toDouble());
  bool done = false;

  for (int idx = backpatches.length - 1; idx >= 0 && !done; idx--) {
    final bp = backpatches[idx];
    bool patchIt = false;

    if (bp.waitingFor == keywordFound) {
      patchIt = true;
      done = true;
    } else if (bp.waitingFor == "break") {
      // Not the expected keyword, but "break"; this is always OK,
      // but we may or may not patch it depending on the call.
      patchIt = alsoBreak;
    } else {
      // Not the expected patch, and not "break"; we have a mismatched block start/end.
      throw CompilerException(
          "'$keywordFound' skips expected '${bp.waitingFor}'");
    }

    if (patchIt) {
      code[bp.lineNum].rhsA = target;
      backpatches.removeAt(idx);
    }
  }

  // Make sure we found one...
  if (!done) {
    throw CompilerException("'$keywordFound' without matching block starter");
  }
}