plum

#treesitter#compiler#wasm

git clone https://git.pyrossh.dev/plum

A statically typed, imperative programming language inspired by rust, python


plum-core/src/formatter.rs
0a830c8 1
// plum-core/src/formatter.rs
7bbcc54 2
use std::io::Cursor;
7bbcc54 3
7bbcc54 4
use topiary_core::{formatter, Language, Operation, TopiaryQuery};
7bbcc54 5
7bbcc54 6
const FORMAT_QUERY: &str =
7bbcc54 7
    include_str!("../../tooling/tree-sitter-plum/queries/plum/format.scm");
7bbcc54 8
0a830c8 9
#[derive(Debug)]
0a830c8 10
pub enum FormatterError {
7bbcc54 11
    TopiaryCoreError(topiary_core::FormatterError),
0a830c8 12
}
0a830c8 13
0a830c8 14
impl std::fmt::Display for FormatterError {
0a830c8 15
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
0a830c8 16
        match self {
7bbcc54 17
            FormatterError::TopiaryCoreError(e) => write!(f, "Topiary error: {e}"),
7bbcc54 18
        }
7bbcc54 19
    }
7bbcc54 20
}
7bbcc54 21
7bbcc54 22
impl std::error::Error for FormatterError {
7bbcc54 23
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
7bbcc54 24
        match self {
7bbcc54 25
            FormatterError::TopiaryCoreError(e) => Some(e),
0a830c8 26
        }
0a830c8 27
    }
0a830c8 28
}
0a830c8 29
7bbcc54 30
impl From<topiary_core::FormatterError> for FormatterError {
7bbcc54 31
    fn from(e: topiary_core::FormatterError) -> Self {
7bbcc54 32
        FormatterError::TopiaryCoreError(e)
7bbcc54 33
    }
7bbcc54 34
}
0a830c8 35
3d6f280 36
pub fn formatSource(source: &str) -> Result<String, FormatterError> {
3d6f280 37
    formatSourceWithOpts(source, false)
62ecfff 38
}
62ecfff 39
3d6f280 40
pub fn formatSourceWithOpts(source: &str, skip_idempotence: bool) -> Result<String, FormatterError> {
7bbcc54 41
    let ts_language: tree_sitter::Language = tree_sitter_plum::LANGUAGE.into();
7bbcc54 42
    let facade_grammar: topiary_tree_sitter_facade::Language = ts_language.into();
7bbcc54 43
    let query = TopiaryQuery::new(&facade_grammar, FORMAT_QUERY)?;
7bbcc54 44
    let language = Language {
7bbcc54 45
        name: "plum".to_owned(),
7bbcc54 46
        query,
7bbcc54 47
        grammar: facade_grammar,
7bbcc54 48
        indent: None,
7bbcc54 49
    };
7bbcc54 50
    let mut input = Cursor::new(source.as_bytes());
7bbcc54 51
    let mut output = Vec::new();
7bbcc54 52
    formatter(
7bbcc54 53
        &mut input,
7bbcc54 54
        &mut output,
7bbcc54 55
        &language,
7bbcc54 56
        Operation::Format {
62ecfff 57
            skip_idempotence,
7bbcc54 58
            tolerate_parsing_errors: false,
7bbcc54 59
        },
7bbcc54 60
    )?;
7bbcc54 61
    Ok(String::from_utf8(output).expect("Topiary output is valid UTF-8"))
0a830c8 62
}