cfd16_assembler/
error.rs

1use std::{error, fmt, path::PathBuf};
2
3use cfd16_lib::InstructionError;
4
5/// An error that may occur while assembling CFD-16 instructions.
6#[derive(Debug, Clone)]
7pub struct AssemblerError {
8    /// Information about where the error occurred.
9    pub line: Option<usize>,
10
11    /// Kind of error being reported.
12    pub kind: AssemErrorKind,
13}
14
15impl AssemblerError {
16    pub(crate) fn new(line: Option<usize>, kind: AssemErrorKind) -> Self {
17        Self { line, kind }
18    }
19}
20
21impl fmt::Display for AssemblerError {
22    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
23        if let Some(l) = self.line {
24            write!(f, "Error (line {}): {}", l, self.kind)
25        } else {
26            write!(f, "Error: {}", self.kind)
27        }
28    }
29}
30
31impl error::Error for AssemblerError {}
32
33/// A kind of error that can occur during assembly of CFD-16 instructions.
34#[derive(Debug, Clone, PartialEq, Eq)]
35pub enum AssemErrorKind {
36    FileRead(PathBuf),
37    NoSuchSymbolFound(String),
38    InvalidLabel,
39    InvalidMnemonic(String),
40    InvalidInstruction(InstructionError),
41    InvalidArgument(String),
42    NoLabelBeforeDotLabel(String),
43    NoSuchBinaryFormat,
44    NonExecableInstr,
45    ElfNotYetSupported,
46    UnalignedInstruction,
47    StringNotAscii,
48}
49
50impl fmt::Display for AssemErrorKind {
51    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
52        match self {
53            Self::FileRead(p) => write!(f, "Could not read file '{}'.", p.display()),
54            Self::NoSuchSymbolFound(s) => write!(f, "No such symbol could be found '{}'.", s),
55            Self::InvalidLabel => write!(f, "Invalid label."),
56            Self::InvalidMnemonic(m) => write!(f, "'{}' is not a valid mnemonic.", m),
57            Self::InvalidInstruction(i) => write!(f, "{}", i),
58            Self::InvalidArgument(a) => write!(f, "Argument '{}' is invalid.", a),
59            Self::NoLabelBeforeDotLabel(l) => write!(f, "No label before dot label '{}'.", l),
60            Self::NoSuchBinaryFormat => write!(f, "The binary format provided does not exist."),
61            Self::NonExecableInstr => write!(
62                f,
63                "The instruction is not executable for this section type."
64            ),
65            Self::ElfNotYetSupported => write!(f, "The ELF format cannot currently be assembled."),
66            Self::UnalignedInstruction => {
67                write!(f, "The instruction must be aligned to a word-boundary.")
68            }
69            Self::StringNotAscii => write!(f, "The string contains non-ascii characters."),
70        }
71    }
72}