package parser import ( "fmt" "strconv" "strings" "git.jfdev.de/JonasFranzDEV/hal/hal" ) // ParseProgram parses an program by the following specification: LINE_NUMBER INSTRUCTION OPERAND(optional) func ParseProgram(input []string) (hal.Program, error) { program := make(hal.Program, len(input)) var err error for index, line := range input { program[index], err = parseInstruction(line) if err != nil { return nil, fmt.Errorf("error while parsing line %d: %v", index+1, err) } } return program, nil } func parseInstruction(input string) (*hal.ProgrammedInstruction, error) { args := strings.Split(input, " ") if len(args) != 0 && len(args) != 1 { return nil, fmt.Errorf("malformated instruction '%s'", input) } instruction := hal.FindInstructionByName(args[0]) if instruction == nil { return nil, fmt.Errorf("unknown instruction '%s'", args[0]) } programmedInstruction := &hal.ProgrammedInstruction{ Instruction: instruction, } if len(args) == 1 { operand, err := strconv.ParseInt(args[1], 10, 64) if err != nil { return nil, fmt.Errorf("error while parsing operand for instruction '%s': %v", input, err) } if instruction.ExecuteWithOperand == nil { return nil, fmt.Errorf("instruction '%s' has no operand, got operand %d", instruction.Name, operand) } programmedInstruction.Operand = operand } return programmedInstruction, nil }