1use std::{error, fmt, path::PathBuf};
2
3use cfd16_lib::InstructionError;
4
5use crate::text::Location;
6
7#[derive(Debug, Clone)]
9pub struct AssemblerError {
10 pub loc: Option<Location>,
12
13 pub kind: AssemErrorKind,
15}
16
17impl AssemblerError {
18 pub(crate) fn new(loc: Option<Location>, kind: AssemErrorKind) -> Self {
19 Self { loc, kind }
20 }
21
22 pub(crate) fn included(loc: Option<Location>, suberr: AssemblerError) -> Self {
24 Self {
25 loc,
26 kind: AssemErrorKind::IncludedError(suberr.to_string()),
27 }
28 }
29}
30
31impl fmt::Display for AssemblerError {
32 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
33 if let Some(l) = &self.loc {
34 write!(f, "Error ({}): {}", l, self.kind)
35 } else {
36 write!(f, "Error: {}", self.kind)
37 }
38 }
39}
40
41impl error::Error for AssemblerError {}
42
43#[derive(Debug, Clone, PartialEq, Eq)]
45pub enum AssemErrorKind {
46 FileRead(PathBuf),
47 NoSuchSymbolFound(String),
48 IncludedError(String),
49 IncludePathInvalid,
50 InvalidLabel,
51 InvalidMnemonic(String),
52 InvalidInstruction(InstructionError),
53 InvalidArgument(String),
54 NoLabelBeforeDotLabel(String),
55 NoSuchBinaryFormat,
56 NonExecableInstr,
57 ElfNotYetSupported,
58 UnalignedInstruction,
59 StringNotAscii,
60}
61
62impl fmt::Display for AssemErrorKind {
63 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64 match self {
65 Self::FileRead(p) => write!(f, "Could not read file '{}'.", p.display()),
66 Self::NoSuchSymbolFound(s) => write!(f, "No such symbol could be found '{}'.", s),
67 Self::IncludedError(s) => write!(f, "Error from included file...\n{s}"),
68 Self::IncludePathInvalid => write!(
69 f,
70 "The provided path for the include directive cannot be read."
71 ),
72 Self::InvalidLabel => write!(f, "Invalid label."),
73 Self::InvalidMnemonic(m) => write!(f, "'{}' is not a valid mnemonic.", m),
74 Self::InvalidInstruction(i) => write!(f, "{}", i),
75 Self::InvalidArgument(a) => write!(f, "Argument '{}' is invalid.", a),
76 Self::NoLabelBeforeDotLabel(l) => write!(f, "No label before dot label '{}'.", l),
77 Self::NoSuchBinaryFormat => write!(f, "The binary format provided does not exist."),
78 Self::NonExecableInstr => write!(
79 f,
80 "The instruction is not executable for this section type."
81 ),
82 Self::ElfNotYetSupported => write!(f, "The ELF format cannot currently be assembled."),
83 Self::UnalignedInstruction => {
84 write!(f, "The instruction must be aligned to a word-boundary.")
85 }
86 Self::StringNotAscii => write!(f, "The string contains non-ascii characters."),
87 }
88 }
89}