Skip to content

Commit

Permalink
driver: Print emitted asm with syntax highlighting
Browse files Browse the repository at this point in the history
  • Loading branch information
mrkajetanp committed Aug 14, 2024
1 parent 5f03150 commit c8bbb10
Show file tree
Hide file tree
Showing 3 changed files with 70 additions and 1 deletion.
31 changes: 31 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,5 @@ strum = { version = "0.26.3", features = ["derive"] }
strum_macros = "0.26.4"
llvm-sys = { version = "180", features = ["prefer-dynamic"], optional = true }
cfg-if = "1.0.0"
synoptic = "2.0.4"
lliw = "0.2.0"
38 changes: 37 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
#![feature(let_chains)]

use display_tree::format_tree;
use lliw::Fg;
use std::fs;
use std::io::{Error, Write};
use std::process::Command;
use strum::EnumIs;
use synoptic;

pub mod ast;
pub mod codegen;
Expand Down Expand Up @@ -138,14 +140,48 @@ impl Driver {
fn emit(&self, code: codegen::Program) -> Result<String, Error> {
let output_path = format!("{}.s", self.name);
let asm = code.emit();
log::debug!("Emitted assembly:\n\n{}", asm);

if log::log_enabled!(log::Level::Debug) {
Driver::print_asm_with_highlight(&asm);
}

let mut file = fs::File::create(&output_path)?;
file.write_all(asm.as_bytes())?;

Ok(output_path)
}

fn print_asm_with_highlight(asm: &str) {
fn colour(name: &str) -> Fg {
match name {
"comment" => Fg::LightBlack,
"digit" => Fg::Purple,
"string" => Fg::Green,
"keyword" => Fg::Yellow,
"function" => Fg::Red,
_ => panic!("unknown token name"),
}
}

let mut highlight = synoptic::from_extension("asm", 4).unwrap();
let highlighted_asm = asm.split('\n').map(|line| line.to_string()).collect();
highlight.run(&highlighted_asm);

for (line_number, line) in highlighted_asm.iter().enumerate() {
// Line returns tokens for the corresponding line
for token in highlight.line(line_number, &line) {
// Tokens can either require highlighting or not require highlighting
match token {
synoptic::TokOpt::Some(text, kind) => {
print!("{}{text}{}", colour(&kind), Fg::Reset)
}
synoptic::TokOpt::None(text) => print!("{text}"),
}
}
println!();
}
}

fn assemble(&self, path: &str) {
let _ = Command::new("gcc")
.args([path, "-masm=intel", "-o", &self.name])
Expand Down

0 comments on commit c8bbb10

Please sign in to comment.