use std::{error, fmt, path::PathBuf};
use cfd16_lib::InstructionError;
use crate::text::Location;
#[derive(Debug, Clone)]
pub struct AssemblerError {
pub loc: Option<Location>,
pub kind: AssemErrorKind,
}
impl AssemblerError {
pub(crate) fn new(loc: Option<Location>, kind: AssemErrorKind) -> Self {
Self { loc, kind }
}
pub(crate) fn included(loc: Option<Location>, suberr: AssemblerError) -> Self {
Self {
loc,
kind: AssemErrorKind::IncludedError(suberr.to_string()),
}
}
}
impl fmt::Display for AssemblerError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if let Some(l) = &self.loc {
write!(f, "Error ({}): {}", l, self.kind)
} else {
write!(f, "Error: {}", self.kind)
}
}
}
impl error::Error for AssemblerError {}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AssemErrorKind {
FileRead(PathBuf),
NoSuchSymbolFound(String),
IncludedError(String),
IncludePathInvalid,
InvalidLabel,
InvalidMnemonic(String),
InvalidInstruction(InstructionError),
InvalidArgument(String),
NoLabelBeforeDotLabel(String),
NoSuchBinaryFormat,
NonExecableInstr,
ElfNotYetSupported,
UnalignedInstruction,
StringNotAscii,
}
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::IncludedError(s) => write!(f, "Error from included file...\n{s}"),
Self::IncludePathInvalid => write!(
f,
"The provided path for the include directive cannot be read."
),
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."),
Self::UnalignedInstruction => {
write!(f, "The instruction must be aligned to a word-boundary.")
}
Self::StringNotAscii => write!(f, "The string contains non-ascii characters."),
}
}
}