Class: Spitewaste::AssemblyParser

Inherits:
Object
  • Object
show all
Defined in:
lib/spitewaste/parsers/assembly.rb

Constant Summary collapse

OperatorError =
Class.new Exception
SyntaxError =
Class.new Exception

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(program, **options) ⇒ AssemblyParser



8
9
10
# File 'lib/spitewaste/parsers/assembly.rb', line 8

def initialize program, **options
  @program = program
end

Instance Attribute Details

#errorObject (readonly)

Returns the value of attribute error.



6
7
8
# File 'lib/spitewaste/parsers/assembly.rb', line 6

def error
  @error
end

#instructionsObject (readonly)

Returns the value of attribute instructions.



6
7
8
# File 'lib/spitewaste/parsers/assembly.rb', line 6

def instructions
  @instructions
end

Instance Method Details

#parseObject



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/spitewaste/parsers/assembly.rb', line 12

def parse
  mnemonics = OPERATORS_M2T.keys
  @instructions = @program.lines.map.with_index(1) { |insn, no|
    op, arg = insn.split

    unless i = mnemonics.index(op = op.to_sym)
      @error = [:unknown, op, [i, 1]]
      raise OperatorError, "unknown operator '#{op}' (line #{no})", []
    end

    bad_arg = -> kind {
      @error = [kind, op, [i, 1]]
      raise SyntaxError, "#{kind} argument for #{op} operator (line #{no})", []
    }

    bad_arg[:missing] if i < 8 && !arg
    bad_arg[:invalid] if i < 8 && !arg[/^-?\d+$/]
    bad_arg[:useless] if i > 7 && arg

    [op, arg && arg.to_i]
  }
end