pag_compiler/lib.rs
1// Copyright (c) 2023 Paguroidea Developers
2//
3// Licensed under the Apache License, Version 2.0
4// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT
5// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6// option. All files in the project carrying such notice may not be copied,
7// modified, or distributed except according to those terms.
8//! The compiler of Paguroidea. Designed for build scripts.
9use std::path::Path;
10
11use syn::File;
12
13/// Compile the grammar file at `input` to the parser source code
14/// at `output`.
15/// This function is designed to be used in `build.rs`. It will panic and
16/// output the reasons if any error occurs.
17pub fn compile<I: AsRef<Path>, O: AsRef<Path>>(input: I, output: O) {
18 use std::io::Write;
19 let data = std::fs::read_to_string(input.as_ref()).unwrap();
20 match pag_parser::generate_parser(&data) {
21 Ok(tokens) => {
22 let tree: File = syn::parse2(tokens).unwrap();
23 let prettified = prettyplease::unparse(&tree);
24 let mut file = std::fs::File::create(output.as_ref()).unwrap();
25 write!(
26 file,
27 "// This file is @generated by Paguroidea.\n\n{}",
28 prettified
29 )
30 .unwrap();
31 file.flush().unwrap();
32 }
33 Err(errs) => {
34 errs.report_stderr(&format!("{}", input.as_ref().display()), &data)
35 .unwrap();
36 panic!("failed to compile parser")
37 }
38 }
39}