Skip to content

Commit

Permalink
Migrate sed to treesitter
Browse files Browse the repository at this point in the history
Co-authored-by: RanolP me@ranolp.dev
  • Loading branch information
zlfn committed Sep 14, 2024
1 parent 87e2938 commit 2707cef
Show file tree
Hide file tree
Showing 7 changed files with 144 additions and 28 deletions.
2 changes: 1 addition & 1 deletion .mise.toml
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
[tools]
rust = "nightly-2024-09-09"
rust = "nightly-2024-02-13"
90 changes: 90 additions & 0 deletions Cargo.lock

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

7 changes: 5 additions & 2 deletions source/src/gbdk.rs → source/src/gbdk/gb.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
pub mod gb {
extern "C" {
pub fn delay(delay: u16);
#[link_name="waitpad __preserves_regs(b, c, h, l)"]
pub fn waitpad(mask: u8) -> u8;
#[link_name="waitpad __preserves_regs(a, b, c, d, e, h, l)"]
pub fn waitpadup();
}
}

pub mod drawing {
use core::ffi::c_char;

pub const GRAPHICS_WIDTH: u8 = 160;
pub const GRAPHICS_HEIGHT: u8 = 144;

Expand All @@ -27,7 +30,7 @@ pub mod drawing {
pub const AND: u8 = 0x03;

extern "C" {
#[link_name="circle __sdcccall(0)"]
#[link_name="circle __sdcccall(0) __preserve_regs(a, b, c)"]
pub fn circle(x: u8, y: u8, radius: u8, style: u8);
#[link_name="color __sdcccall(0)"]
pub fn color(forecolor: u8, backcolor: u8, mode: u8);
Expand Down
1 change: 1 addition & 0 deletions source/src/gbdk/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pub mod gb;
2 changes: 1 addition & 1 deletion source/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
use core::ffi::c_char;

mod gbdk;
use gbdk::drawing::{r#box, circle, color, getpix, gotogxy, gprint, line, plot_point, BLACK, DKGREY, LTGREY, M_FILL, M_NOFILL, SOLID, WHITE, XOR};
use gbdk::gb::drawing::{r#box, circle, color, getpix, gotogxy, gprint, line, plot_point, BLACK, DKGREY, LTGREY, M_FILL, M_NOFILL, SOLID, WHITE, XOR};

fn linetest(x: u8, y: u8, w: u8) {
let w = w as i8;
Expand Down
5 changes: 5 additions & 0 deletions xtask/build-rom/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,8 @@ edition = "2021"
[dependencies]
clap = { version = "4.5.17", features = ["derive"] }
colored = "2.1.0"
tree-sitter = "0.23.0"
tree-sitter-c = "0.23.0"

[build-dependencies]
cc="*"
65 changes: 41 additions & 24 deletions xtask/build-rom/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
use core::str;
use std::{fs, io::{ErrorKind, Write}, process::{self, Command}, str::FromStr};
use std::{fs::{self, File, OpenOptions}, io::{ErrorKind, Write}, process::{self, Command}, str::FromStr};
use clap::Parser;

use colored::Colorize;
use tree_sitter::{self, Query, QueryCursor};

///Build GB ROM from Rust
#[derive(Parser, Debug)]
Expand Down Expand Up @@ -125,18 +126,6 @@ fn main() {
else {
println!("{}", "[rustc] Rust -> LLVM-IR compile succeeded".green());
}

fs::copy("./out/out.ll", "./out/pre.ll").unwrap();
let postprocess_status = llvm_post_process();


if postprocess_status.is_err() {
println!("{}", "[sed] LLVM-IR postprocess for LLVM-CBE failed".red());
process::exit(1);
}
else {
println!("{}", "[sed] LLVM-IR postprocess for LLVM-CBE succeeded".green());
}
}

if build_from <= BuildChain::LLVM {
Expand All @@ -162,7 +151,7 @@ fn main() {
//Command::new("sed 's/uint8_t\\* memset(uint8_t\\*, uint32_t, uint16_t);/inline uint8_t\\* memset(uint8_t\\* dst, uint8_t c, uint16_t sz) {uint8_t \\*p = dst; while (sz--) *p++ = c; return dst; }/g' -i ./out/main.c").status().unwrap();
//Command::new("sed '/__noreturn void rust_begin_unwind(struct l_struct_core_KD__KD_panic_KD__KD_PanicInfo\\* llvm_cbe_info)/{:a;N;/__builtin_unreachable/{N;N;d};/ }/b;ba}' -i ./out/main.c").status().unwrap();
fs::copy("./out/out.c", "./out/pre.c").unwrap();
let postprocess_status = c_post_process();
let postprocess_status = treesitter_process();

if postprocess_status.is_err() {
println!("{}", "[sed] C postprocess for SDCC failed".red());
Expand Down Expand Up @@ -229,19 +218,47 @@ fn main() {
}
}

fn llvm_post_process() -> Result<(), std::io::Error> {
//`or disjoint` -> `or`
let s = Command::new("sed")
.args([
"s/or disjoint/or/g",
"-i", "./out/out.ll",
])
.status()?;
fn treesitter_process() -> Result<(), std::io::Error> {
let mut code = fs::read_to_string("./out/out.c")?;
let code_bytes = code.clone();
let code_bytes = code_bytes.as_bytes();
let mut parser = tree_sitter::Parser::new();
parser.set_language(&tree_sitter_c::LANGUAGE.into()).unwrap();

if !s.success() {
return Err(std::io::Error::new(ErrorKind::NotFound, "sed failed"))
let tree = parser.parse(code_bytes, None).unwrap();
let query = Query::new(&tree_sitter_c::LANGUAGE.into(), "(function_declarator(identifier)@iden)@decl").unwrap();
let mut cursor = QueryCursor::new();

let mut diff: i32 = 0;

for qm in cursor.matches(&query, tree.root_node(), code_bytes) {
let node = qm.captures[1].node;
let identifier = node.utf8_text(&code_bytes).unwrap();
let attributes: Vec<_> = identifier.split("_AC___").collect(); //` __`

if attributes.len() < 2 {
continue;
}

match &attributes[..] {
[] | [_] => {},
[name, attrib @ ..] => {
code.replace_range(((node.start_byte() as i32) + diff) as usize..((node.end_byte() as i32) + diff) as usize, name);
diff += name.len() as i32 - node.byte_range().len() as i32;
let attrib = format!("__{}", attrib.join(" __"));
let attrib = attrib
.replace("_AC_", " ")
.replace("_IC_", "(")
.replace("_JC_", ")")
.replace("_MC_", ",");
println!("{:?}", attrib);
}
}
}

let mut file = File::create("./out/out.c")?;
file.write_all(&code.as_bytes())?;

Ok(())
}

Expand Down

0 comments on commit 2707cef

Please sign in to comment.