From 2d3900728fdc556b44713b38d6bea059332f2274 Mon Sep 17 00:00:00 2001 From: Jonas Franz Date: Mon, 18 May 2020 20:43:36 +0200 Subject: [PATCH] Read line number from file --- example.hal | 0 hal/module.go | 2 +- parser/program_parser.go | 20 +++++++++++++------- 3 files changed, 14 insertions(+), 8 deletions(-) create mode 100644 example.hal diff --git a/example.hal b/example.hal new file mode 100644 index 0000000..e69de29 diff --git a/hal/module.go b/hal/module.go index e483900..05b6b50 100644 --- a/hal/module.go +++ b/hal/module.go @@ -2,7 +2,7 @@ package hal import "fmt" -type Program []*ProgrammedInstruction +type Program map[int64]*ProgrammedInstruction type Module struct { Accumulator float64 diff --git a/parser/program_parser.go b/parser/program_parser.go index 861c43e..0026c58 100644 --- a/parser/program_parser.go +++ b/parser/program_parser.go @@ -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)