leo/compiler/parser/examples/parser.rs

76 lines
2.4 KiB
Rust
Raw Normal View History

2022-01-21 23:32:09 +03:00
// Copyright (C) 2019-2022 Aleo Systems Inc.
2021-03-10 15:23:46 +03:00
// This file is part of the Leo library.
// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use leo_ast::Ast;
2022-02-16 19:41:32 +03:00
use leo_errors::emitter::Handler;
2022-01-21 23:32:09 +03:00
use leo_span::symbol::create_session_if_not_set_then;
2022-02-23 22:53:21 +03:00
use std::{
fs,
path::{Path, PathBuf},
};
use structopt::StructOpt;
2021-03-10 15:23:46 +03:00
#[derive(Debug, StructOpt)]
#[structopt(name = "leo parser", about = "Parse Leo AST and store it as a JSON")]
struct Opt {
/// Path to the Leo file.
#[structopt(parse(from_os_str))]
input_path: PathBuf,
2022-02-23 22:53:21 +03:00
/// Optional path to the output directory.
#[structopt(parse(from_os_str))]
out_dir_path: Option<PathBuf>,
/// Whether to print result to STDOUT.
#[structopt(short, long)]
2022-02-23 22:53:21 +03:00
print_stdout: bool,
}
fn main() -> Result<(), String> {
2022-02-23 22:53:21 +03:00
let opt = Opt::from_args();
let code = fs::read_to_string(&opt.input_path).expect("failed to open file");
2021-03-10 15:23:46 +03:00
2022-01-21 23:32:09 +03:00
// Parses the Leo file constructing an ast which is then serialized.
let serialized_leo_tree = create_session_if_not_set_then(|_| {
2022-02-16 19:41:32 +03:00
Handler::with(|h| {
2022-03-16 03:15:08 +03:00
let ast = leo_parser::parse_ast(h, opt.input_path.to_str().unwrap(), &code)?;
2022-02-16 19:41:32 +03:00
let json = Ast::to_json_string(&ast)?;
println!("{}", json);
Ok(json)
})
.map_err(|b| b.to_string())
})?;
2021-03-10 15:23:46 +03:00
if opt.print_stdout {
println!("{}", serialized_leo_tree);
2021-03-10 15:23:46 +03:00
}
let out_path = if let Some(out_dir) = opt.out_dir_path {
format!(
2021-03-10 15:23:46 +03:00
"{}/{}.json",
out_dir.as_path().display(),
opt.input_path.file_stem().unwrap().to_str().unwrap()
)
} else {
format!("./{}.json", opt.input_path.file_stem().unwrap().to_str().unwrap())
2021-03-10 15:23:46 +03:00
};
fs::write(Path::new(&out_path), serialized_leo_tree).expect("failed to write output");
2022-02-23 22:53:21 +03:00
2021-03-10 15:23:46 +03:00
Ok(())
}