Rust: skeleton trap file emission code

This commit is contained in:
Paolo Tranquilli
2024-08-27 17:50:53 +02:00
parent 927710017e
commit 2a2b79e6df
2 changed files with 54 additions and 1 deletions

View File

@@ -8,7 +8,7 @@ use ra_ap_load_cargo::{load_workspace_at, LoadCargoConfig, ProcMacroServerChoice
mod config;
mod trap;
fn main() -> anyhow::Result<()> {
let cfg = config::Config::extract().context("failed to load configuration")?;

53
rust/src/trap.rs Normal file
View File

@@ -0,0 +1,53 @@
use std::fmt::Formatter;
use std::fs::File;
use std::io::Write;
use std::path::{PathBuf};
#[derive(Debug)]
struct TrapLabel(u64);
impl std::fmt::Display for TrapLabel {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "#{:x}", self.0)
}
}
trait TrapEntry: std::fmt::Display {}
#[derive(Debug)]
struct TrapFile {
label_index: u64,
file: File,
}
impl TrapFile {
pub fn new(path: &PathBuf) -> std::io::Result<TrapFile> {
let file = File::create(path)?;
Ok(TrapFile {
label_index: 0,
file: file,
})
}
pub fn insert_comment(&mut self, comment: &str) -> std::io::Result<()> {
write!(self.file, "/* {comment} */\n")
}
pub fn allocate_label(&mut self) -> std::io::Result<TrapLabel> {
let ret = TrapLabel(self.label_index);
write!(self.file, "{ret}=*\n")?;
self.label_index += 1;
Ok(ret)
}
pub fn allocate_label_for(&mut self, key: &str) -> std::io::Result<TrapLabel> {
let ret = TrapLabel(self.label_index);
write!(self.file, "{ret}=\"{}\"\n", key.replace("\"", "\"\""))?;
self.label_index += 1;
Ok(ret)
}
pub fn emit<T: TrapEntry>(&mut self, entry: T) -> std::io::Result<()> {
write!(self.file, "{entry}\n")
}
}