cfd16-assembler 0.7.0

An assembler backend for the CFD-16 ISA.
Documentation
use std::{error, fmt, path::PathBuf};

use cfd16_lib::InstructionError;

/// An error that may occur while assembling CFD-16 instructions.
#[derive(Debug, Clone)]
pub struct AssemblerError {
    /// Information about where the error occurred.
    pub line: Option<usize>,

    /// Kind of error being reported.
    pub kind: AssemErrorKind,
}

impl AssemblerError {
    pub(crate) fn new(line: Option<usize>, kind: AssemErrorKind) -> Self {
        Self { line, kind }
    }
}

impl fmt::Display for AssemblerError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(l) = self.line {
            write!(f, "Error (line {}): {}", l, self.kind)
        } else {
            write!(f, "Error: {}", self.kind)
        }
    }
}

impl error::Error for AssemblerError {}

/// A kind of error that can occur during assembly of CFD-16 instructions.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AssemErrorKind {
    FileRead(PathBuf),
    NoSuchSymbolFound(String),
    InvalidLabel,
    InvalidMnemonic(String),
    InvalidInstruction(InstructionError),
    InvalidArgument(String),
    NoLabelBeforeDotLabel(String),
    NoSuchBinaryFormat,
    NonExecableInstr,
    ElfNotYetSupported,
}

impl fmt::Display for AssemErrorKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::FileRead(p) => write!(f, "Could not read file '{}'.", p.display()),
            Self::NoSuchSymbolFound(s) => write!(f, "No such symbol could be found '{}'.", s),
            Self::InvalidLabel => write!(f, "Invalid label."),
            Self::InvalidMnemonic(m) => write!(f, "'{}' is not a valid mnemonic.", m),
            Self::InvalidInstruction(i) => write!(f, "{}", i),
            Self::InvalidArgument(a) => write!(f, "Argument '{}' is invalid.", a),
            Self::NoLabelBeforeDotLabel(l) => write!(f, "No label before dot label '{}'.", l),
            Self::NoSuchBinaryFormat => write!(f, "The binary format provided does not exist."),
            Self::NonExecableInstr => write!(
                f,
                "The instruction is not executable for this section type."
            ),
            Self::ElfNotYetSupported => write!(f, "The ELF format cannot currently be assembled."),
        }
    }
}