Skip to content

Commit

Permalink
Refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
sthiele committed Aug 26, 2022
1 parent 05beb51 commit 6470802
Show file tree
Hide file tree
Showing 3 changed files with 560 additions and 476 deletions.
83 changes: 83 additions & 0 deletions src/bin/clingofmt.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
use anyhow::{Context, Result};
use clap::Parser;
use clingofmt::pass_one;
use log::error;
use std::fs;
use std::{
io::{self, Write},
path::PathBuf,
};

/// Format clingo code
#[derive(Parser, Debug)]
#[clap(version, author)]
struct Opt {
/// Input file in clingo format
#[clap(name = "FILE", parse(from_os_str))]
file: PathBuf,

/// Enable debug output
#[clap(long)]
debug: bool,
}

pub enum Reader<'a> {
File(io::BufReader<fs::File>),
Stdin(io::StdinLock<'a>),
}
impl<'a> io::Read for Reader<'a> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
match self {
Self::File(reader) => reader.read(buf),
Self::Stdin(guard) => guard.read(buf),
}
}
}
impl<'a> io::BufRead for Reader<'a> {
fn fill_buf(&mut self) -> io::Result<&[u8]> {
match self {
Self::File(reader) => reader.fill_buf(),
Self::Stdin(guard) => guard.fill_buf(),
}
}
fn consume(&mut self, amt: usize) {
match self {
Self::File(reader) => reader.consume(amt),
Self::Stdin(guard) => guard.consume(amt),
}
}
}

fn main() {
stderrlog::new()
.module(module_path!())
.verbosity(3)
.init()
.unwrap();
if let Err(err) = run() {
error!("{:?}", err);
std::process::exit(1);
}
}

fn run() -> Result<()> {
let opt = Opt::parse();

let path = opt.file.to_str().unwrap();
let source_code =
fs::read(path).with_context(|| format!("Error reading source file {}", path))?;

let mut parser = tree_sitter::Parser::new();
parser
.set_language(tree_sitter_clingo::language())
.expect("Error loading clingo grammar");
let tree = parser.parse(&source_code, None).unwrap();

let mut buf = Vec::new();
pass_one(&tree, &source_code, &mut buf, opt.debug)?;

let mut out = std::io::stdout();
let buf_str = std::str::from_utf8(&buf)?;
write!(out, "{buf_str}")?;
Ok(())
}
Loading

0 comments on commit 6470802

Please sign in to comment.