compile method Null safety

Status compile()

Compiles the source code into instructions.

Implementation

Status compile() {
  var program = <Instruction>[];
  var stack = <int>[];
  for (var i = 0; i < source.length; i++) {
    final c = source[i];

    switch (c) {
      case '>':
        program.add(Instruction(Operator.increasePointer));
        break;
      case '<':
        program.add(Instruction(Operator.decreasePointer));
        break;
      case '+':
        program.add(Instruction(Operator.increaseValue));
        break;
      case '-':
        program.add(Instruction(Operator.decreaseValue));
        break;
      case '.':
        program.add(Instruction(Operator.output));
        break;
      case ',':
        program.add(Instruction(Operator.input));
        break;
      case '[':
        stack.add(program.length);
        program.add(Instruction(Operator.jumpForward));
        break;
      case ']':
        if (stack.isEmpty) {
          return Status.failed;
        }
        final jumpIndex = stack.removeLast();
        program[jumpIndex].operand = program.length;
        program.add(Instruction(Operator.jumpBack, operand: jumpIndex));
        break;
      default:
        break;
    }
  }

  program.add(Instruction(Operator.end));
  _program = program;
  return Status.success;
}