Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use ast-grep in compiler #15

Open
zlfn opened this issue Dec 13, 2024 · 0 comments
Open

Use ast-grep in compiler #15

zlfn opened this issue Dec 13, 2024 · 0 comments
Labels
enhancement New feature or request

Comments

@zlfn
Copy link
Owner

zlfn commented Dec 13, 2024

For now, we are parsing and replace code manually with tree-sitter.

It's not a big problem, but it's hard to add new transpile layers.

fn parse_call_expression_attributes(code: &mut String, code_bytes: &[u8]) {
    let mut parser = tree_sitter::Parser::new();
    parser.set_language(&tree_sitter_c::LANGUAGE.into()).unwrap();

    let tree = parser.parse(code_bytes, None).unwrap();
    let query = Query::new(&tree_sitter_c::LANGUAGE.into(), "(call_expression(identifier)@a)").unwrap();
    let mut cursor = QueryCursor::new();

    let mut diff: i32 = 0;

    for qm in cursor.matches(&query, tree.root_node(), code_bytes) {
        let identifier_node = qm.captures[0].node;
        let identifier = identifier_node.utf8_text(&code_bytes).unwrap();

        let start = identifier.find("_AC_");
        let start = match start {
            None => continue,
            Some(start) => start
        };

        let mut identifier = String::from(identifier);
        identifier.replace_range(start.., "");

        code.replace_range(
            ((identifier_node.start_byte() as i32) + diff) as usize..
            ((identifier_node.end_byte() as i32) + diff) as usize, 
            &identifier);
        diff += identifier.len() as i32 - identifier_node.byte_range().len() as i32;
    }
}

If you look at this code, you can see that the code is very long compared to what it actually do, and it's hard to figure out what it's doing.

It can solved by structual replacement with ast-grep.

@zlfn zlfn added the enhancement New feature or request label Dec 13, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

1 participant