view python/target.py @ 201:d5debbfc0200

Added all 27 core instructions of msp430
author Windel Bouwman
date Thu, 13 Jun 2013 00:07:28 +0200
parents 5e391d9a3381
children f22b431f4113
line wrap: on
line source

from asmnodes import ASymbol, AInstruction
from ppci import CompilerError

"""
  Base classes for defining a target
"""

# Machine code interface:
class Operand:
   """ Single machine operand """
   pass

class Register(Operand):
    def __init__(self, name):
        self.name = name

class Instruction:
    def encode(self):
        raise NotImplementedError('TODO')

class Target:
    def __init__(self, name, desc=''):
        self.name = name
        self.desc = desc
        self.registers = []
        self.instructions = []

    def instruction(self, cls):
        """ Decorator function that registers an instruction to this target """
        self.instructions.append(cls)
        return cls

    def mapOperand(self, operand):
        """ Try to map an operand to a target type """
        if type(operand) is ASymbol:
            # Try to map to register:
            regs = {}
            for r in self.registers:
                regs[r.name] = r
            if operand.name in regs:
                return regs[operand.name]
        raise CompilerError('Cannot map {0}'.format(operand))

    def mapInstruction(self, vi):
        """ Map ast tree to real instruction for this target """

        # map to real operands:
        rops = tuple(map(self.mapOperand, vi.operands))
        optypes = tuple(map(type, rops))

        # look for a suitable instruction
        for ic in self.instructions:
            if ic.mnemonic == vi.opcode and ic.operands == optypes:
                ri = ic(*rops)
                return ri
        raise CompilerError('No suitable instruction found for "{0}"'.format(vi))