use std::fmt;
use cfd16_lib::prelude::*;
#[derive(Debug, Clone, Copy)]
pub(crate) enum SecKind {
Data,
Text,
}
#[derive(Debug, Clone)]
pub struct Location {
pub(crate) file: String,
pub(crate) line: usize,
}
impl fmt::Display for Location {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}:{}", self.file, self.line)
}
}
impl Location {
pub(crate) fn new(file: String, line: usize) -> Self {
Self { file, line }
}
}
#[derive(Debug, Clone)]
pub(crate) struct TextSection {
pub(crate) mode: Mode,
#[allow(dead_code)]
pub(crate) kind: SecKind,
pub(crate) items: Vec<TextItem>,
}
impl TextSection {
pub(crate) fn new(mode: Mode, kind: SecKind) -> Self {
Self {
mode,
kind,
items: vec![],
}
}
}
impl fmt::Display for TextSection {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut output = String::new();
for instr in &self.items {
output = format!("{output}\n{instr}")
}
write!(f, "{output}")
}
}
#[allow(missing_docs)]
#[derive(Debug, Clone)]
pub(crate) enum TextItemKind {
Dir(Directive),
Instr(InstructionBuilder),
String(String),
}
#[derive(Debug, Clone)]
pub(crate) struct TextItem {
pub(crate) kind: TextItemKind,
pub(crate) address: usize,
pub(crate) loc: Location,
}
impl TextItem {
pub(crate) fn new(kind: TextItemKind, addr: &mut isize, loc: Location) -> Self {
let address = *addr;
use TextItemKind::*;
match kind {
Dir(Directive::Space(n)) => (*addr) += n as isize,
Dir(Directive::Word(_)) => (*addr) += 2 as isize,
Instr(_) => (*addr) += 2 as isize,
String(ref s) => (*addr) += (s.len() + 1) as isize,
_ => {}
}
TextItem {
kind,
address: address as usize,
loc,
}
}
}
impl fmt::Display for TextItem {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let textitem = match &self.kind {
TextItemKind::Dir(d) => format!("{}", d),
TextItemKind::Instr(i) => format!("{}", i),
TextItemKind::String(s) => format!(".ascii '{}'", s),
};
write!(f, "{} ({:#08x}): {}", self.loc, self.address, textitem)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Directive {
Space(usize),
Word(u16),
Global(String),
Extern(String),
}
impl fmt::Display for Directive {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use Directive::*;
match self {
Space(n) => write!(f, ".space {}", n),
Word(n) => write!(f, ".word {}", n),
Global(s) => write!(f, ".global {}", s),
Extern(s) => write!(f, ".extern {}", s),
}
}
}