pag-compiler 0.1.0-alpha.1

Parser-lexer fusion generator (compiler interface)
Documentation
// Copyright (c) 2023 Paguroidea Developers
//
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. All files in the project carrying such notice may not be copied,
// modified, or distributed except according to those terms.
//! The compiler of Paguroidea. Designed for build scripts.
use std::path::Path;

use syn::File;

/// Compile the grammar file at `input` to the parser source code
/// at `output`.
/// This function is designed to be used in `build.rs`. It will panic and
/// output the reasons if any error occurs.
pub fn compile<I: AsRef<Path>, O: AsRef<Path>>(input: I, output: O) {
    use std::io::Write;
    let data = std::fs::read_to_string(input.as_ref()).unwrap();
    match pag_parser::generate_parser(&data) {
        Ok(tokens) => {
            let tree: File = syn::parse2(tokens).unwrap();
            let prettified = prettyplease::unparse(&tree);
            let mut file = std::fs::File::create(output.as_ref()).unwrap();
            write!(
                file,
                "// This file is @generated by Paguroidea.\n\n{}",
                prettified
            )
            .unwrap();
            file.flush().unwrap();
        }
        Err(errs) => {
            errs.report_stderr(&format!("{}", input.as_ref().display()), &data)
                .unwrap();
            panic!("failed to compile parser")
        }
    }
}