| 1 |
//! An example of using `peg` with `codespan_reporting`. |
| 2 |
//! |
| 3 |
//! To run this example, execute the following command from the top level of |
| 4 |
//! this repository: |
| 5 |
//! |
| 6 |
//! ```sh |
| 7 |
//! cargo run --example peg_calculator |
| 8 |
//! ``` |
| 9 |
|
| 10 |
use codespan_reporting::diagnostic::{Diagnostic, Label}; |
| 11 |
use codespan_reporting::files::SimpleFile; |
| 12 |
use codespan_reporting::term; |
| 13 |
use codespan_reporting::term::termcolor::{ColorChoice, StandardStream}; |
| 14 |
use rustyline::error::ReadlineError; |
| 15 |
use rustyline::Editor; |
| 16 |
|
| 17 |
#[allow(clippy::redundant_closure_call)] |
| 18 |
peg::parser! { |
| 19 |
grammar arithmetic() for str { |
| 20 |
rule number() -> i64 |
| 21 |
= n:$(['0'..='9']+) { n.parse().unwrap() } |
| 22 |
|
| 23 |
pub rule calculate() -> i64 = precedence!{ |
| 24 |
x:(@) "+" y:@ { x + y } |
| 25 |
x:(@) "-" y:@ { x - y } |
| 26 |
"-" v:@ { - v } |
| 27 |
-- |
| 28 |
x:(@) "*" y:@ { x * y } |
| 29 |
x:(@) "/" y:@ { x / y } |
| 30 |
-- |
| 31 |
x:@ "^" y:(@) { i64::pow(x, y as u32) } |
| 32 |
v:@ "!" { (1..v+1).product() } |
| 33 |
-- |
| 34 |
"(" v:calculate() ")" { v } |
| 35 |
n:number() { n } |
| 36 |
} |
| 37 |
} |
| 38 |
} |
| 39 |
|
| 40 |
fn main() -> anyhow::Result<()> { |
| 41 |
let writer = StandardStream::stderr(ColorChoice::Always); |
| 42 |
let config = codespan_reporting::term::Config::default(); |
| 43 |
let mut editor = Editor::<()>::new(); |
| 44 |
|
| 45 |
loop { |
| 46 |
let line = match editor.readline("> ") { |
| 47 |
Ok(line) => line, |
| 48 |
Err(ReadlineError::Interrupted) | Err(ReadlineError::Eof) => return Ok(()), |
| 49 |
Err(error) => return Err(error.into()), |
| 50 |
}; |
| 51 |
|
| 52 |
match arithmetic::calculate(&line) { |
| 53 |
Ok(number) => println!("{}", number), |
| 54 |
Err(error) => { |
| 55 |
let file = SimpleFile::new("<repl>", line); |
| 56 |
|
| 57 |
let start = error.location.offset; |
| 58 |
let diagnostic = Diagnostic::error() |
| 59 |
.with_message("parse error") |
| 60 |
.with_labels(vec![ |
| 61 |
Label::primary((), start..start).with_message("parse error") |
| 62 |
]) |
| 63 |
.with_notes(vec![format!("expected: {}", error.expected)]); |
| 64 |
|
| 65 |
term::emit(&mut writer.lock(), &config, &file, &diagnostic)?; |
| 66 |
} |
| 67 |
} |
| 68 |
} |
| 69 |
} |