Read line number from file

master
Jonas Franz 5 years ago
parent 41bb7cf2d5
commit 2d3900728f
Signed by: JonasFranzDEV
GPG Key ID: 7293A220B7C38080
  1. 0
      example.hal
  2. 2
      hal/module.go
  3. 20
      parser/program_parser.go

@ -2,7 +2,7 @@ package hal
import "fmt"
type Program []*ProgrammedInstruction
type Program map[int64]*ProgrammedInstruction
type Module struct {
Accumulator float64

@ -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)

Loading…
Cancel
Save