Ensure all examples compile (#1604)

* docs: Remove unused example

* docs: Ensure all examples compile

Co-authored-by: Ed Page <eopage@gmail.com>
This commit is contained in:
Geoffroy Couprie 2022-12-30 16:29:22 +01:00 committed by GitHub
parent b66ff43eff
commit 9cff115667
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 78 additions and 91 deletions

View File

@ -104,11 +104,21 @@ name = "reborrow_fold"
name = "fnmut" name = "fnmut"
required-features = ["alloc"] required-features = ["alloc"]
[[example]]
name = "custom_error"
required-features = ["alloc"]
path = "examples/custom_error.rs"
[[example]] [[example]]
name = "json" name = "json"
required-features = ["alloc"] required-features = ["alloc"]
path = "examples/json.rs" path = "examples/json.rs"
[[example]]
name = "json_iterator"
required-features = ["alloc"]
path = "examples/json_iterator.rs"
[[example]] [[example]]
name = "iterator" name = "iterator"
path = "examples/iterator.rs" path = "examples/iterator.rs"

View File

@ -21,10 +21,12 @@ impl<I> ParseError<I> for CustomError<I> {
} }
} }
fn parse(input: &str) -> IResult<&str, &str, CustomError<&str>> { pub fn parse(_input: &str) -> IResult<&str, &str, CustomError<&str>> {
Err(Error(CustomError::MyError)) Err(Error(CustomError::MyError))
} }
fn main() {}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::parse; use super::parse;

View File

@ -4,23 +4,17 @@ use nom::{
branch::alt, branch::alt,
bytes::complete::{escaped, tag, take_while}, bytes::complete::{escaped, tag, take_while},
character::complete::{alphanumeric1 as alphanumeric, char, one_of}, character::complete::{alphanumeric1 as alphanumeric, char, one_of},
combinator::{map, opt, cut}, combinator::{cut, map},
error::{context, ErrorKind, ParseError}, error::{context, ParseError},
error::{VerboseError, VerboseErrorKind}, multi::separated_list0,
multi::separated_list,
number::complete::double, number::complete::double,
sequence::{delimited, preceded, separated_pair, terminated}, sequence::{preceded, separated_pair, terminated},
Err, IResult, Offset, IResult,
}; };
use std::collections::HashMap; use std::collections::HashMap;
use std::str;
use std::cell::Cell; use std::cell::Cell;
use std::str;
struct Cursor<'a> {
inner: &'a str,
offset: usize,
}
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct JsonValue<'a, 'b> { pub struct JsonValue<'a, 'b> {
@ -28,7 +22,7 @@ pub struct JsonValue<'a, 'b> {
pub offset: &'b Cell<usize>, pub offset: &'b Cell<usize>,
} }
impl<'a, 'b:'a> JsonValue<'a, 'b> { impl<'a, 'b: 'a> JsonValue<'a, 'b> {
pub fn new(input: &'a str, offset: &'b Cell<usize>) -> JsonValue<'a, 'b> { pub fn new(input: &'a str, offset: &'b Cell<usize>) -> JsonValue<'a, 'b> {
JsonValue { input, offset } JsonValue { input, offset }
} }
@ -49,7 +43,7 @@ impl<'a, 'b:'a> JsonValue<'a, 'b> {
self.offset(i); self.offset(i);
println!("-> {}", s); println!("-> {}", s);
Some(s) Some(s)
}, }
_ => None, _ => None,
} }
} }
@ -61,27 +55,27 @@ impl<'a, 'b:'a> JsonValue<'a, 'b> {
self.offset(i); self.offset(i);
println!("-> {}", o); println!("-> {}", o);
Some(o) Some(o)
}, }
_ => None, _ => None,
} }
} }
pub fn number(&self) -> Option<f64> { pub fn number(&self) -> Option<f64> {
println!("number()"); println!("number()");
match double::<_,()>(self.data()) { match double::<_, ()>(self.data()) {
Ok((i, o)) => { Ok((i, o)) => {
self.offset(i); self.offset(i);
println!("-> {}", o); println!("-> {}", o);
Some(o) Some(o)
}, }
_ => None, _ => None,
} }
} }
pub fn array(&self) -> Option<impl Iterator<Item=JsonValue<'a, 'b>>> { pub fn array(&self) -> Option<impl Iterator<Item = JsonValue<'a, 'b>>> {
println!("array()"); println!("array()");
match tag::<_,_,()>("[")(self.data()) { match tag::<_, _, ()>("[")(self.data()) {
Err(_) => None, Err(_) => None,
Ok((i, _)) => { Ok((i, _)) => {
println!("["); println!("[");
@ -92,7 +86,7 @@ impl<'a, 'b:'a> JsonValue<'a, 'b> {
let v = self.clone(); let v = self.clone();
Some(std::iter::from_fn(move|| { Some(std::iter::from_fn(move || {
if done { if done {
return None; return None;
} }
@ -103,30 +97,29 @@ impl<'a, 'b:'a> JsonValue<'a, 'b> {
match value(v.data()) { match value(v.data()) {
Ok((i, _)) => { Ok((i, _)) => {
v.offset(i); v.offset(i);
}, }
Err(_) => {}, Err(_) => {}
} }
} }
match tag::<_, _, ()>("]")(v.data()) {
match tag::<_,_,()>("]")(v.data()) {
Ok((i, _)) => { Ok((i, _)) => {
println!("]"); println!("]");
v.offset(i); v.offset(i);
done = true; done = true;
return None; return None;
}, }
Err(_) => {} Err(_) => {}
}; };
if first { if first {
first = false; first = false;
} else { } else {
match tag::<_,_,()>(",")(v.data()) { match tag::<_, _, ()>(",")(v.data()) {
Ok((i, _)) => { Ok((i, _)) => {
println!(","); println!(",");
v.offset(i); v.offset(i);
}, }
Err(_) => { Err(_) => {
done = true; done = true;
return None; return None;
@ -137,15 +130,14 @@ impl<'a, 'b:'a> JsonValue<'a, 'b> {
println!("-> {}", v.data()); println!("-> {}", v.data());
previous = v.offset.get(); previous = v.offset.get();
Some(v.clone()) Some(v.clone())
})) }))
} }
} }
} }
pub fn object(&self) -> Option<impl Iterator<Item=(&'a str, JsonValue<'a, 'b>)>> { pub fn object(&self) -> Option<impl Iterator<Item = (&'a str, JsonValue<'a, 'b>)>> {
println!("object()"); println!("object()");
match tag::<_,_,()>("{")(self.data()) { match tag::<_, _, ()>("{")(self.data()) {
Err(_) => None, Err(_) => None,
Ok((i, _)) => { Ok((i, _)) => {
self.offset(i); self.offset(i);
@ -158,7 +150,7 @@ impl<'a, 'b:'a> JsonValue<'a, 'b> {
let v = self.clone(); let v = self.clone();
Some(std::iter::from_fn(move|| { Some(std::iter::from_fn(move || {
if done { if done {
return None; return None;
} }
@ -169,29 +161,29 @@ impl<'a, 'b:'a> JsonValue<'a, 'b> {
match value(v.data()) { match value(v.data()) {
Ok((i, _)) => { Ok((i, _)) => {
v.offset(i); v.offset(i);
}, }
Err(_) => {}, Err(_) => {}
} }
} }
match tag::<_,_,()>("}")(v.data()) { match tag::<_, _, ()>("}")(v.data()) {
Ok((i, _)) => { Ok((i, _)) => {
println!("}}"); println!("}}");
v.offset(i); v.offset(i);
done = true; done = true;
return None; return None;
}, }
Err(_) => {} Err(_) => {}
}; };
if first { if first {
first = false; first = false;
} else { } else {
match tag::<_,_,()>(",")(v.data()) { match tag::<_, _, ()>(",")(v.data()) {
Ok((i, _)) => { Ok((i, _)) => {
println!(","); println!(",");
v.offset(i); v.offset(i);
}, }
Err(_) => { Err(_) => {
done = true; done = true;
return None; return None;
@ -203,7 +195,7 @@ impl<'a, 'b:'a> JsonValue<'a, 'b> {
Ok((i, key)) => { Ok((i, key)) => {
v.offset(i); v.offset(i);
match tag::<_,_,()>(":")(v.data()) { match tag::<_, _, ()>(":")(v.data()) {
Err(_) => None, Err(_) => None,
Ok((i, _)) => { Ok((i, _)) => {
v.offset(i); v.offset(i);
@ -214,10 +206,9 @@ impl<'a, 'b:'a> JsonValue<'a, 'b> {
Some((key, v.clone())) Some((key, v.clone()))
} }
} }
}, }
_ => None, _ => None,
} }
})) }))
} }
} }
@ -235,47 +226,44 @@ fn parse_str<'a, E: ParseError<&'a str>>(i: &'a str) -> IResult<&'a str, &'a str
} }
fn string<'a>(i: &'a str) -> IResult<&'a str, &'a str> { fn string<'a>(i: &'a str) -> IResult<&'a str, &'a str> {
context("string", context(
preceded( "string",
char('\"'), preceded(char('\"'), cut(terminated(parse_str, char('\"')))),
cut(terminated( )(i)
parse_str,
char('\"')
))))(i)
} }
fn boolean<'a>(input: &'a str) -> IResult<&'a str, bool> { fn boolean<'a>(input: &'a str) -> IResult<&'a str, bool> {
alt(( alt((map(tag("false"), |_| false), map(tag("true"), |_| true)))(input)
map(tag("false"), |_| false),
map(tag("true"), |_| true)
))(input)
} }
fn array<'a>(i: &'a str) -> IResult<&'a str, ()> { fn array<'a>(i: &'a str) -> IResult<&'a str, ()> {
context( context(
"array", "array",
preceded(char('['), preceded(
cut(terminated( char('['),
map(separated_list(preceded(sp, char(',')), value), |_| ()), cut(terminated(
preceded(sp, char(']')))) map(separated_list0(preceded(sp, char(',')), value), |_| ()),
))(i) preceded(sp, char(']')),
)),
),
)(i)
} }
fn key_value<'a>(i: &'a str) -> IResult<&'a str, (&'a str, ())> { fn key_value<'a>(i: &'a str) -> IResult<&'a str, (&'a str, ())> {
separated_pair(preceded(sp, string), cut(preceded(sp, char(':'))), value)(i) separated_pair(preceded(sp, string), cut(preceded(sp, char(':'))), value)(i)
} }
fn hash<'a>(i: &'a str) -> IResult<&'a str, ()> { fn hash<'a>(i: &'a str) -> IResult<&'a str, ()> {
context( context(
"map", "map",
preceded(char('{'), preceded(
cut(terminated( char('{'),
map( cut(terminated(
separated_list(preceded(sp, char(',')), key_value), map(separated_list0(preceded(sp, char(',')), key_value), |_| ()),
|_| ()), preceded(sp, char('}')),
preceded(sp, char('}')), )),
)) ),
))(i) )(i)
} }
fn value<'a>(i: &'a str) -> IResult<&'a str, ()> { fn value<'a>(i: &'a str) -> IResult<&'a str, ()> {
@ -314,13 +302,17 @@ fn main() {
let parser = JsonValue::new(data, &offset); let parser = JsonValue::new(data, &offset);
if let Some(o) = parser.object() { if let Some(o) = parser.object() {
let s: HashMap<&str, &str> = o.filter(|(k,_)| *k == "users" ) let s: HashMap<&str, &str> = o
.filter_map(|(_, v)| v.object()).flatten() .filter(|(k, _)| *k == "users")
.filter_map(|(user, v)| v.object().map(|o| (user, o))) .filter_map(|(_, v)| v.object())
.map(|(user, o)| { .flatten()
o.filter(|(k,_)| *k == "city" ) .filter_map(|(user, v)| v.object().map(|o| (user, o)))
.filter_map(move |(_, v)| v.string().map(|s| (user, s))) .map(|(user, o)| {
}).flatten().collect(); o.filter(|(k, _)| *k == "city")
.filter_map(move |(_, v)| v.string().map(|s| (user, s)))
})
.flatten()
.collect();
println!("res = {:?}", s); println!("res = {:?}", s);
} }

View File

@ -1,17 +0,0 @@
#[macro_use]
extern crate nom;
use nom::{character::complete::digit0, number::complete::be_u32};
named!(first<u32>, flat_map!(digit0, parse_to!(u32)));
named!(second<u32>, call!(be_u32));
named!(parser<u32>, alt!(first | second));
fn main() {
let data = b"1234;";
let res = parser(&data[..]);
println!("res: {:?}", res);
}