|
|
|
@ -10,10 +10,17 @@ import ( |
|
|
|
|
|
|
|
|
|
// 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 |
|
|
|
|
program := make(hal.Program) |
|
|
|
|
for index, line := range input { |
|
|
|
|
program[index], err = parseInstruction(line) |
|
|
|
|
args := strings.Split(line, " ") |
|
|
|
|
if len(args) == 0 { |
|
|
|
|
continue |
|
|
|
|
} |
|
|
|
|
lineNumber, err := strconv.ParseInt(args[0], 10, 64) |
|
|
|
|
if err != nil { |
|
|
|
|
return nil, fmt.Errorf("invalid line number at file line %d: %s", index, args[0]) |
|
|
|
|
} |
|
|
|
|
program[lineNumber], err = parseInstruction(args[1:]) |
|
|
|
|
if err != nil { |
|
|
|
|
return nil, fmt.Errorf("error while parsing line %d: %v", index+1, err) |
|
|
|
|
} |
|
|
|
@ -21,10 +28,9 @@ func ParseProgram(input []string) (hal.Program, error) { |
|
|
|
|
return program, nil |
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
func parseInstruction(input string) (*hal.ProgrammedInstruction, error) { |
|
|
|
|
args := strings.Split(input, " ") |
|
|
|
|
func parseInstruction(args []string) (*hal.ProgrammedInstruction, error) { |
|
|
|
|
if len(args) != 0 && len(args) != 1 { |
|
|
|
|
return nil, fmt.Errorf("malformated instruction '%s'", input) |
|
|
|
|
return nil, fmt.Errorf("invalid instruction args count (count = %d)", len(args)) |
|
|
|
|
} |
|
|
|
|
instruction := hal.FindInstructionByName(args[0]) |
|
|
|
|
if instruction == nil { |
|
|
|
@ -36,7 +42,7 @@ func parseInstruction(input string) (*hal.ProgrammedInstruction, error) { |
|
|
|
|
if len(args) == 1 { |
|
|
|
|
operand, err := strconv.ParseFloat(args[1], 64) |
|
|
|
|
if err != nil { |
|
|
|
|
return nil, fmt.Errorf("error while parsing operand for instruction '%s': %v", input, err) |
|
|
|
|
return nil, fmt.Errorf("error while parsing operand for instruction '%s': %v", args[0], err) |
|
|
|
|
} |
|
|
|
|
if instruction.ExecuteWithOperand == nil { |
|
|
|
|
return nil, fmt.Errorf("instruction '%s' has no operand, got operand %d", instruction.Name, operand) |
|
|
|
|