importProgram method Null safety

void importProgram(
  1. String listing
)

Implementation

void importProgram(String listing) {
  final Map<String, ProgramInstruction<OT>> pdToInstruction;
  {
    final allInstructions = getAllInstructions();
    pdToInstruction = <String, ProgramInstruction<OT>>{
      for (final v in allInstructions) _canonicalizePD(v.programDisplay): v
    };
    assert(allInstructions.length == pdToInstruction.length);
  }
  final lines = listing.split('\n');
  final program = List<ProgramInstruction<OT>>.empty(growable: true);
  int lineNumber = 0;
  for (final line in lines) {
    lineNumber++;
    var rest = line.trim();
    if (rest.isEmpty || rest.startsWith('#')) {
      continue;
    }
    int pos = rest.indexOf(' ');
    if (pos == -1) {
      throw Exception('Error at line $lineNumber:  Line number not found');
    }
    final instructionNumber = int.tryParse(rest.substring(0, pos));
    if (instructionNumber == null) {
      throw Exception('No instruction number on line $lineNumber: $line');
    }
    rest = rest.substring(pos).trim();
    if (rest.substring(0, 1) != '{') {
      throw Exception('Error at line $lineNumber: '
          'Line doesn\'t have " {" after number: $line');
    }
    rest = rest.substring(1);
    pos = rest.indexOf('}');
    if (pos == -1) {
      throw Exception(
          'Syntax error at line $lineNumber: "}" not found: $line');
    }
    rest = _canonicalizePD(rest.substring(0, pos));
    if (rest.isEmpty) {
      if (program.isNotEmpty || instructionNumber != 0) {
        throw Exception(
            'Unexpected empty instruction at line $lineNumber: $line');
      }
    } else if (instructionNumber != program.length + 1) {
      throw Exception(
          'Unexpected instruction number at line $lineNumber: $line');
    } else {
      final instr = pdToInstruction[rest];
      if (instr == null) {
        throw Exception(
            'Instruction "$rest" not found at line $lineNumber: $line');
      }
      program.add(instr);
    }
  }
  final int len =
      program.fold(0, (n, instr) => n + (instr.isExtended ? 2 : 1));
  if (len > memory.policy.maxProgramBytes) {
    throw Exception('Insufficient space for $len byte program');
  }
  suspendedProgram?.abort();
  suspendedProgram = null;
  reset();
  for (final instr in program) {
    insert(instr);
  }
  currentLine = 0;
}