Skip to content

Instantly share code, notes, and snippets.

@kazimuth
Created January 16, 2017 00:01
Show Gist options
  • Save kazimuth/8f98c1d3c371961dfe2f5c1ac54649f7 to your computer and use it in GitHub Desktop.
Save kazimuth/8f98c1d3c371961dfe2f5c1ac54649f7 to your computer and use it in GitHub Desktop.
peg issue
#![feature(plugin)]
#![plugin(peg_syntax_ext)]
extern crate peg;
#[derive(Debug, PartialEq, PartialOrd)]
pub enum NumericConstant {
U64(u64),
I64(i64),
F64(f64),
}
#[cfg(test)]
mod tests {
use super::number;
use super::NumericConstant::*;
#[test]
fn test_parse_u64s() {
assert_eq!(Ok(U64(0xDEADBEEF)), number::numeric_constant("0XDEADBEEF"));
assert_eq!(Ok(U64(0o10202222)), number::numeric_constant("010202222"));
assert_eq!(Ok(U64(18446744073709551615)), number::numeric_constant("18446744073709551615"));
}
#[test]
fn test_parse_i64s() {
assert_eq!(Ok(I64(-0xDEADBEEF)), number::numeric_constant("-0xDEADBEEF"));
assert_eq!(Ok(I64(-393)), number::numeric_constant("-393"));
assert_eq!(Ok(I64(-9223372036854775807)), number::numeric_constant("-9223372036854775807"));
}
#[test]
fn test_parse_f64s() {
assert_eq!(Ok(F64(37.33e15)), number::numeric_constant("37.33e15"));
assert_eq!(Ok(F64(-933.0)), number::numeric_constant("-933.0"));
}
}
peg! number (r#"
use std::str::FromStr;
use super::NumericConstant;
/// Parse a numeric constant.
pub numeric_constant -> NumericConstant
= lit:(u64literal / i64literal / f64literal / #expected("numeric constant")) {
lit
}
u64literal -> NumericConstant
= header:$("0x" / "0X" / "0" / "") contents:$([a-fA-F0-9]+) {?
match header {
"0x" | "0X" => u64::from_str_radix(contents, 16),
"0" => u64::from_str_radix(contents, 8),
"" => u64::from_str_radix(contents, 10),
_ => unreachable!()
}
.map_err(|e| "u64")
.map(|u| NumericConstant::U64(u))
}
i64literal -> NumericConstant
= "-" header:$("0x" / "0X" / "0" / "") contents:$([a-fA-F0-9]+) {?
match header {
"0x" | "0X" => i64::from_str_radix(contents, 16),
"0" => i64::from_str_radix(contents, 8),
"" => i64::from_str_radix(contents, 10),
_ => unreachable!()
}
.map_err(|e| "i64")
.map(|i| NumericConstant::I64(-i))
}
f64literal -> NumericConstant
= val:$("-"? [0-9]* "."? [0-9]* ([eE][-+]?[0-9]+))? {?
f64::from_str(val)
.map_err(|e| "f64")
.map(|f| NumericConstant::F64(f))
}
"#);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment