diff options
Diffstat (limited to 'src/parser')
| -rw-r--r-- | src/parser/conversion.rs | 198 | ||||
| -rw-r--r-- | src/parser/conversion/block.rs | 230 | ||||
| -rw-r--r-- | src/parser/conversion/inline.rs | 56 | ||||
| -rw-r--r-- | src/parser/pair_ext_parse.rs | 12 | ||||
| -rw-r--r-- | src/parser/tests.rs | 184 | 
5 files changed, 340 insertions, 340 deletions
| diff --git a/src/parser/conversion.rs b/src/parser/conversion.rs index 50a7fb2..5154f40 100644 --- a/src/parser/conversion.rs +++ b/src/parser/conversion.rs @@ -5,96 +5,96 @@ use failure::Error;  use pest::iterators::Pairs;  use crate::document_tree::{ -    HasChildren, -    elements as e, -    element_categories as c, +	HasChildren, +	elements as e, +	element_categories as c,  };  use super::pest_rst::Rule;  fn ssubel_to_section_unchecked_mut(ssubel: &mut c::StructuralSubElement) -> &mut e::Section { -    match ssubel { -        c::StructuralSubElement::SubStructure(ref mut b) => match **b { -            c::SubStructure::Section(ref mut s) => s, -            _ => unreachable!(), -        }, -        _ => unreachable!(), -    } +	match ssubel { +		c::StructuralSubElement::SubStructure(ref mut b) => match **b { +			c::SubStructure::Section(ref mut s) => s, +			_ => unreachable!(), +		}, +		_ => unreachable!(), +	}  }  fn get_level<'tl>(toplevel: &'tl mut Vec<c::StructuralSubElement>, section_idxs: &[Option<usize>]) -> &'tl mut Vec<c::StructuralSubElement> { -    let mut level = toplevel; -    for maybe_i in section_idxs { -        if let Some(i) = *maybe_i { -            level = ssubel_to_section_unchecked_mut(&mut level[i]).children_mut(); -        } -    } -    level +	let mut level = toplevel; +	for maybe_i in section_idxs { +		if let Some(i) = *maybe_i { +			level = ssubel_to_section_unchecked_mut(&mut level[i]).children_mut(); +		} +	} +	level  }  pub fn convert_document(pairs: Pairs<Rule>) -> Result<e::Document, Error> { -    use self::block::TitleOrSsubel::*; -     -    let mut toplevel: Vec<c::StructuralSubElement> = vec![]; -    // The kinds of section titles encountered. -    // `section_idx[x]` has the kind `kinds[x]`, but `kinds` can be longer -    let mut kinds: Vec<block::TitleKind> = vec![]; -    // Recursive indices into the tree, pointing at the active sections. -    // `None`s indicate skipped section levels: -    // toplevel[section_idxs.flatten()[0]].children[section_idxs.flatten()[1]]... -    let mut section_idxs: Vec<Option<usize>> = vec![]; -     -    for pair in pairs { -        if let Some(ssubel) = block::convert_ssubel(pair)? { match ssubel { -            Title(title, kind) => { -                match kinds.iter().position(|k| k == &kind) { -                    // Idx points to the level we want to add, -                    // so idx-1 needs to be the last valid index. -                    Some(idx) => { -                        // If idx < len: Remove found section and all below -                        section_idxs.truncate(idx); -                        // If idx > len: Add None for skipped levels -                        // TODO: test skipped levels -                        while section_idxs.len() < idx { section_idxs.push(None) } -                    }, -                    None => kinds.push(kind), -                } -                let super_level = get_level(&mut toplevel, §ion_idxs); -                super_level.push(e::Section::with_children(vec![title.into()]).into()); -                section_idxs.push(Some(super_level.len() - 1)); -            }, -            Ssubel(elem) => get_level(&mut toplevel, §ion_idxs).push(elem), -        }} -    } -    Ok(e::Document::with_children(toplevel)) +	use self::block::TitleOrSsubel::*; +	 +	let mut toplevel: Vec<c::StructuralSubElement> = vec![]; +	// The kinds of section titles encountered. +	// `section_idx[x]` has the kind `kinds[x]`, but `kinds` can be longer +	let mut kinds: Vec<block::TitleKind> = vec![]; +	// Recursive indices into the tree, pointing at the active sections. +	// `None`s indicate skipped section levels: +	// toplevel[section_idxs.flatten()[0]].children[section_idxs.flatten()[1]]... +	let mut section_idxs: Vec<Option<usize>> = vec![]; +	 +	for pair in pairs { +		if let Some(ssubel) = block::convert_ssubel(pair)? { match ssubel { +			Title(title, kind) => { +				match kinds.iter().position(|k| k == &kind) { +					// Idx points to the level we want to add, +					// so idx-1 needs to be the last valid index. +					Some(idx) => { +						// If idx < len: Remove found section and all below +						section_idxs.truncate(idx); +						// If idx > len: Add None for skipped levels +						// TODO: test skipped levels +						while section_idxs.len() < idx { section_idxs.push(None) } +					}, +					None => kinds.push(kind), +				} +				let super_level = get_level(&mut toplevel, §ion_idxs); +				super_level.push(e::Section::with_children(vec![title.into()]).into()); +				section_idxs.push(Some(super_level.len() - 1)); +			}, +			Ssubel(elem) => get_level(&mut toplevel, §ion_idxs).push(elem), +		}} +	} +	Ok(e::Document::with_children(toplevel))  }  #[cfg(test)]  mod tests { -    use crate::{ -        parser::parse, -        document_tree::{ -            elements as e, -            element_categories as c, -            HasChildren, -        } -    }; -     -    fn ssubel_to_section(ssubel: &c::StructuralSubElement) -> &e::Section { -        match ssubel { -            c::StructuralSubElement::SubStructure(ref b) => match **b { -                c::SubStructure::Section(ref s) => s, -                ref c => panic!("Expected section, not {:?}", c), -            }, -            ref c => panic!("Expected SubStructure, not {:?}", c), -        } -    } -     -    const SECTIONS: &str = "\ +	use crate::{ +		parser::parse, +		document_tree::{ +			elements as e, +			element_categories as c, +			HasChildren, +		} +	}; +	 +	fn ssubel_to_section(ssubel: &c::StructuralSubElement) -> &e::Section { +		match ssubel { +			c::StructuralSubElement::SubStructure(ref b) => match **b { +				c::SubStructure::Section(ref s) => s, +				ref c => panic!("Expected section, not {:?}", c), +			}, +			ref c => panic!("Expected SubStructure, not {:?}", c), +		} +	} +	 +	const SECTIONS: &str = "\  Intro before first section title  Level 1 @@ -113,32 +113,32 @@ L1 again  L3 again, skipping L2  =====================  "; -     -    #[test] -    fn convert_skipped_section() { -        let doctree = parse(SECTIONS).unwrap(); -        let lvl0 = doctree.children(); -        assert_eq!(lvl0.len(), 3, "Should be a paragraph and 2 sections: {:?}", lvl0); -         -        assert_eq!(lvl0[0], e::Paragraph::with_children(vec![ -            "Intro before first section title".to_owned().into() -        ]).into(), "The intro text should fit"); -         -        let lvl1a = ssubel_to_section(&lvl0[1]).children(); -        assert_eq!(lvl1a.len(), 2, "The 1st lvl1 section should have (a title and) a single lvl2 section as child: {:?}", lvl1a); -        //TODO: test title lvl1a[0] -        let lvl2  = ssubel_to_section(&lvl1a[1]).children(); -        assert_eq!(lvl2.len(), 2, "The lvl2 section should have (a title and) a single lvl3 section as child: {:?}", lvl2); -        //TODO: test title lvl2[0] -        let lvl3a = ssubel_to_section(&lvl2[1]).children(); -        assert_eq!(lvl3a.len(), 1, "The 1st lvl3 section should just a title: {:?}", lvl3a); -        //TODO: test title lvl3a[0] -         -        let lvl1b = ssubel_to_section(&lvl0[2]).children(); -        assert_eq!(lvl1b.len(), 2, "The 2nd lvl1 section should have (a title and) a single lvl2 section as child: {:?}", lvl1b); -        //TODO: test title lvl1b[0] -        let lvl3b = ssubel_to_section(&lvl1b[1]).children(); -        assert_eq!(lvl3b.len(), 1, "The 2nd lvl3 section should have just a title: {:?}", lvl3b); -        //TODO: test title lvl3b[0] -    } +	 +	#[test] +	fn convert_skipped_section() { +		let doctree = parse(SECTIONS).unwrap(); +		let lvl0 = doctree.children(); +		assert_eq!(lvl0.len(), 3, "Should be a paragraph and 2 sections: {:?}", lvl0); +		 +		assert_eq!(lvl0[0], e::Paragraph::with_children(vec![ +			"Intro before first section title".to_owned().into() +		]).into(), "The intro text should fit"); +		 +		let lvl1a = ssubel_to_section(&lvl0[1]).children(); +		assert_eq!(lvl1a.len(), 2, "The 1st lvl1 section should have (a title and) a single lvl2 section as child: {:?}", lvl1a); +		//TODO: test title lvl1a[0] +		let lvl2  = ssubel_to_section(&lvl1a[1]).children(); +		assert_eq!(lvl2.len(), 2, "The lvl2 section should have (a title and) a single lvl3 section as child: {:?}", lvl2); +		//TODO: test title lvl2[0] +		let lvl3a = ssubel_to_section(&lvl2[1]).children(); +		assert_eq!(lvl3a.len(), 1, "The 1st lvl3 section should just a title: {:?}", lvl3a); +		//TODO: test title lvl3a[0] +		 +		let lvl1b = ssubel_to_section(&lvl0[2]).children(); +		assert_eq!(lvl1b.len(), 2, "The 2nd lvl1 section should have (a title and) a single lvl2 section as child: {:?}", lvl1b); +		//TODO: test title lvl1b[0] +		let lvl3b = ssubel_to_section(&lvl1b[1]).children(); +		assert_eq!(lvl3b.len(), 1, "The 2nd lvl3 section should have just a title: {:?}", lvl3b); +		//TODO: test title lvl3b[0] +	}  } diff --git a/src/parser/conversion/block.rs b/src/parser/conversion/block.rs index 9abd1e4..714b410 100644 --- a/src/parser/conversion/block.rs +++ b/src/parser/conversion/block.rs @@ -2,15 +2,15 @@ use failure::{Error,bail};  use pest::iterators::Pair;  use crate::document_tree::{ -    Element,HasChildren,ExtraAttributes, -    elements as e, -    element_categories as c, -    extra_attributes as a, +	Element,HasChildren,ExtraAttributes, +	elements as e, +	element_categories as c, +	extra_attributes as a,  };  use crate::parser::{ -    pest_rst::Rule, -    pair_ext_parse::PairExt, +	pest_rst::Rule, +	pair_ext_parse::PairExt,  };  use super::inline::convert_inline; @@ -19,141 +19,141 @@ use super::inline::convert_inline;  pub(super) enum TitleKind { Double(char), Single(char) }  pub(super) enum TitleOrSsubel { -    Title(e::Title, TitleKind), -    Ssubel(c::StructuralSubElement), +	Title(e::Title, TitleKind), +	Ssubel(c::StructuralSubElement),  }  pub(super) fn convert_ssubel(pair: Pair<Rule>) -> Result<Option<TitleOrSsubel>, Error> { -    use self::TitleOrSsubel::*; -    Ok(Some(match pair.as_rule() { -        Rule::title            => { let (t, k) = convert_title(pair); Title(t, k) }, -        Rule::paragraph        => Ssubel(convert_paragraph(pair)?.into()), -        Rule::target           => Ssubel(convert_target(pair)?.into()), -        Rule::substitution_def => Ssubel(convert_substitution_def(pair)?.into()), -        Rule::admonition_gen   => Ssubel(convert_admonition_gen(pair)?.into()), -        Rule::image            => Ssubel(convert_image::<e::Image>(pair)?.into()), -        Rule::EOI              => return Ok(None), -        rule => panic!("unknown rule {:?}", rule), -    })) +	use self::TitleOrSsubel::*; +	Ok(Some(match pair.as_rule() { +		Rule::title            => { let (t, k) = convert_title(pair); Title(t, k) }, +		Rule::paragraph        => Ssubel(convert_paragraph(pair)?.into()), +		Rule::target           => Ssubel(convert_target(pair)?.into()), +		Rule::substitution_def => Ssubel(convert_substitution_def(pair)?.into()), +		Rule::admonition_gen   => Ssubel(convert_admonition_gen(pair)?.into()), +		Rule::image            => Ssubel(convert_image::<e::Image>(pair)?.into()), +		Rule::EOI              => return Ok(None), +		rule => panic!("unknown rule {:?}", rule), +	}))  }  fn convert_title(pair: Pair<Rule>) -> (e::Title, TitleKind) { -    let mut title: Option<&str> = None; -    let mut adornment_char: Option<char> = None; -    // title_double or title_single. Extract kind before consuming -    let inner_pair = pair.into_inner().next().unwrap(); -    let kind = inner_pair.as_rule(); -    for p in inner_pair.into_inner() { -        match p.as_rule() { -            Rule::line => title = Some(p.as_str()),  // TODO: can contain other stuff? -            Rule::adornments => adornment_char = Some(p.as_str().chars().next().expect("Empty adornment?")), -            rule => unimplemented!("Unexpected rule in title: {:?}", rule), -        }; -    } -    // now we encountered one line of text and one of adornments -    // TODO: emit error if the adornment line is too short (has to match title length) -    let elem = e::Title::with_children(vec![ -        title.expect("No text in title").into() -    ]); -    let title_kind = match kind { -        Rule::title_double => TitleKind::Double(adornment_char.unwrap()), -        Rule::title_single => TitleKind::Single(adornment_char.unwrap()), -        _ => unreachable!(), -    }; -    (elem, title_kind) +	let mut title: Option<&str> = None; +	let mut adornment_char: Option<char> = None; +	// title_double or title_single. Extract kind before consuming +	let inner_pair = pair.into_inner().next().unwrap(); +	let kind = inner_pair.as_rule(); +	for p in inner_pair.into_inner() { +		match p.as_rule() { +			Rule::line => title = Some(p.as_str()),  // TODO: can contain other stuff? +			Rule::adornments => adornment_char = Some(p.as_str().chars().next().expect("Empty adornment?")), +			rule => unimplemented!("Unexpected rule in title: {:?}", rule), +		}; +	} +	// now we encountered one line of text and one of adornments +	// TODO: emit error if the adornment line is too short (has to match title length) +	let elem = e::Title::with_children(vec![ +		title.expect("No text in title").into() +	]); +	let title_kind = match kind { +		Rule::title_double => TitleKind::Double(adornment_char.unwrap()), +		Rule::title_single => TitleKind::Single(adornment_char.unwrap()), +		_ => unreachable!(), +	}; +	(elem, title_kind)  }  fn convert_paragraph(pair: Pair<Rule>) -> Result<e::Paragraph, Error> { -    let children = pair.into_inner().map(convert_inline).collect::<Result<_,_>>()?; -    Ok(e::Paragraph::with_children(children)) +	let children = pair.into_inner().map(convert_inline).collect::<Result<_,_>>()?; +	Ok(e::Paragraph::with_children(children))  }  fn convert_target(pair: Pair<Rule>) -> Result<e::Target, Error> { -    let mut attrs = a::Target { -        anonymous: false, -        ..Default::default() -    }; -    for p in pair.into_inner() { -        match p.as_rule() { -            Rule::target_name_uq | Rule::target_name_qu => { -                attrs.refid = Some(p.as_str().into()); -                attrs.refname.push(p.as_str().into()); -            }, -            Rule::link_target => attrs.refuri = Some(p.parse()?), -            rule => panic!("Unexpected rule in target: {:?}", rule), -        } -    } -    Ok(e::Target::new(Default::default(), attrs)) +	let mut attrs = a::Target { +		anonymous: false, +		..Default::default() +	}; +	for p in pair.into_inner() { +		match p.as_rule() { +			Rule::target_name_uq | Rule::target_name_qu => { +				attrs.refid = Some(p.as_str().into()); +				attrs.refname.push(p.as_str().into()); +			}, +			Rule::link_target => attrs.refuri = Some(p.parse()?), +			rule => panic!("Unexpected rule in target: {:?}", rule), +		} +	} +	Ok(e::Target::new(Default::default(), attrs))  }  fn convert_substitution_def(pair: Pair<Rule>) -> Result<e::SubstitutionDefinition, Error> { -    let mut pairs = pair.into_inner(); -    let name = pairs.next().unwrap().as_str();  // Rule::substitution_name -    let inner_pair = pairs.next().unwrap(); -    let inner: c::TextOrInlineElement = match inner_pair.as_rule() { -        Rule::image => convert_image::<e::ImageInline>(inner_pair)?.into(), -        rule => panic!("Unknown substitution rule {:?}", rule), -    }; -    let mut subst_def = e::SubstitutionDefinition::with_children(vec![inner]); -    subst_def.names_mut().push(name.into()); -    Ok(subst_def) +	let mut pairs = pair.into_inner(); +	let name = pairs.next().unwrap().as_str();  // Rule::substitution_name +	let inner_pair = pairs.next().unwrap(); +	let inner: c::TextOrInlineElement = match inner_pair.as_rule() { +		Rule::image => convert_image::<e::ImageInline>(inner_pair)?.into(), +		rule => panic!("Unknown substitution rule {:?}", rule), +	}; +	let mut subst_def = e::SubstitutionDefinition::with_children(vec![inner]); +	subst_def.names_mut().push(name.into()); +	Ok(subst_def)  }  fn convert_image<I>(pair: Pair<Rule>) -> Result<I, Error> where I: Element + ExtraAttributes<a::Image> { -    let mut pairs = pair.into_inner(); -    let mut image = I::with_extra(a::Image::new( -        pairs.next().unwrap().parse()?,  // line -    )); -    if let Some(opt_block) = pairs.next() {  // image_opt_block -        let options = opt_block.into_inner(); -        for opt in options { -            let mut opt_iter = opt.into_inner(); -            let opt_name = opt_iter.next().unwrap(); -            let opt_val = opt_iter.next().unwrap(); -            match opt_name.as_str() { -                "class"  => image.classes_mut().push(opt_val.as_str().to_owned()), -                "name"   => image.names_mut().push(opt_val.as_str().into()), -                "alt"    => image.extra_mut().alt    = Some(opt_val.as_str().to_owned()), -                "height" => image.extra_mut().height = Some(opt_val.parse()?), -                "width"  => image.extra_mut().width  = Some(opt_val.parse()?), -                "scale"  => image.extra_mut().scale  = Some(parse_scale(&opt_val)?), -                "align"  => image.extra_mut().align  = Some(opt_val.parse()?), -                "target" => image.extra_mut().target = Some(opt_val.parse()?), -                name => bail!("Unknown Image option {}", name), -            } -        } -    } -    Ok(image) +	let mut pairs = pair.into_inner(); +	let mut image = I::with_extra(a::Image::new( +		pairs.next().unwrap().parse()?,  // line +	)); +	if let Some(opt_block) = pairs.next() {  // image_opt_block +		let options = opt_block.into_inner(); +		for opt in options { +			let mut opt_iter = opt.into_inner(); +			let opt_name = opt_iter.next().unwrap(); +			let opt_val = opt_iter.next().unwrap(); +			match opt_name.as_str() { +				"class"  => image.classes_mut().push(opt_val.as_str().to_owned()), +				"name"   => image.names_mut().push(opt_val.as_str().into()), +				"alt"    => image.extra_mut().alt    = Some(opt_val.as_str().to_owned()), +				"height" => image.extra_mut().height = Some(opt_val.parse()?), +				"width"  => image.extra_mut().width  = Some(opt_val.parse()?), +				"scale"  => image.extra_mut().scale  = Some(parse_scale(&opt_val)?), +				"align"  => image.extra_mut().align  = Some(opt_val.parse()?), +				"target" => image.extra_mut().target = Some(opt_val.parse()?), +				name => bail!("Unknown Image option {}", name), +			} +		} +	} +	Ok(image)  }  fn parse_scale(pair: &Pair<Rule>) -> Result<u8, Error> { -    let input = if pair.as_str().chars().rev().next() == Some('%') { &pair.as_str()[..pair.as_str().len()-1] } else { pair.as_str() }; -    use pest::error::{Error,ErrorVariant}; -    Ok(input.parse().map_err(|e: std::num::ParseIntError| { -        let var: ErrorVariant<Rule> = ErrorVariant::CustomError { message: e.to_string() }; -        Error::new_from_span(var, pair.as_span()) -    })?) +	let input = if pair.as_str().chars().rev().next() == Some('%') { &pair.as_str()[..pair.as_str().len()-1] } else { pair.as_str() }; +	use pest::error::{Error,ErrorVariant}; +	Ok(input.parse().map_err(|e: std::num::ParseIntError| { +		let var: ErrorVariant<Rule> = ErrorVariant::CustomError { message: e.to_string() }; +		Error::new_from_span(var, pair.as_span()) +	})?)  }  fn convert_admonition_gen(pair: Pair<Rule>) -> Result<c::BodyElement, Error> { -    let mut iter = pair.into_inner(); -    let typ = iter.next().unwrap().as_str(); -    // TODO: in reality it contains body elements. -    let children: Vec<c::BodyElement> = iter.map(|p| e::Paragraph::with_children(vec![p.as_str().into()]).into()).collect(); -    Ok(match typ { -        "attention" => e::Attention::with_children(children).into(), -        "hint"      =>      e::Hint::with_children(children).into(), -        "note"      =>      e::Note::with_children(children).into(), -        "caution"   =>   e::Caution::with_children(children).into(), -        "danger"    =>    e::Danger::with_children(children).into(), -        "error"     =>     e::Error::with_children(children).into(), -        "important" => e::Important::with_children(children).into(), -        "tip"       =>       e::Tip::with_children(children).into(), -        "warning"   =>   e::Warning::with_children(children).into(), -        typ         => panic!("Unknown admontion type {}!", typ), -    }) +	let mut iter = pair.into_inner(); +	let typ = iter.next().unwrap().as_str(); +	// TODO: in reality it contains body elements. +	let children: Vec<c::BodyElement> = iter.map(|p| e::Paragraph::with_children(vec![p.as_str().into()]).into()).collect(); +	Ok(match typ { +		"attention" => e::Attention::with_children(children).into(), +		"hint"      =>      e::Hint::with_children(children).into(), +		"note"      =>      e::Note::with_children(children).into(), +		"caution"   =>   e::Caution::with_children(children).into(), +		"danger"    =>    e::Danger::with_children(children).into(), +		"error"     =>     e::Error::with_children(children).into(), +		"important" => e::Important::with_children(children).into(), +		"tip"       =>       e::Tip::with_children(children).into(), +		"warning"   =>   e::Warning::with_children(children).into(), +		typ         => panic!("Unknown admontion type {}!", typ), +	})  } diff --git a/src/parser/conversion/inline.rs b/src/parser/conversion/inline.rs index 8e4ce1f..c30b71d 100644 --- a/src/parser/conversion/inline.rs +++ b/src/parser/conversion/inline.rs @@ -2,43 +2,43 @@ use failure::Error;  use pest::iterators::Pair;  use crate::document_tree::{ -    ExtraAttributes, -    elements as e, -    element_categories as c, -    extra_attributes as a, +	ExtraAttributes, +	elements as e, +	element_categories as c, +	extra_attributes as a,  };  use crate::parser::{ -    pest_rst::Rule, +	pest_rst::Rule,  //    pair_ext_parse::PairExt,  };  pub fn convert_inline(pair: Pair<Rule>) -> Result<c::TextOrInlineElement, Error> { -    Ok(match pair.as_rule() { -        Rule::str       => pair.as_str().into(), -        Rule::reference => convert_reference(pair)?.into(), -        rule => unimplemented!("unknown rule {:?}", rule), -    }) +	Ok(match pair.as_rule() { +		Rule::str       => pair.as_str().into(), +		Rule::reference => convert_reference(pair)?.into(), +		rule => unimplemented!("unknown rule {:?}", rule), +	})  }  fn convert_reference(pair: Pair<Rule>) -> Result<e::Reference, Error> { -    let name; -    let refuri = None; -    let refid; -    let refname = vec![]; -    let concrete = pair.into_inner().next().unwrap(); -    match concrete.as_rule() { -        Rule::reference_target => { -            let rt_inner = concrete.into_inner().next().unwrap(); // reference_target_uq or target_name_qu -            refid = Some(rt_inner.as_str().into()); -            name  = Some(rt_inner.as_str().into()); -        }, -        Rule::reference_explicit => unimplemented!("explicit reference"), -        Rule::reference_auto => unimplemented!("auto reference"), -        _ => unreachable!(), -    }; -    Ok(e::Reference::with_extra( -        a::Reference { name, refuri, refid, refname } -    )) +	let name; +	let refuri = None; +	let refid; +	let refname = vec![]; +	let concrete = pair.into_inner().next().unwrap(); +	match concrete.as_rule() { +		Rule::reference_target => { +			let rt_inner = concrete.into_inner().next().unwrap(); // reference_target_uq or target_name_qu +			refid = Some(rt_inner.as_str().into()); +			name  = Some(rt_inner.as_str().into()); +		}, +		Rule::reference_explicit => unimplemented!("explicit reference"), +		Rule::reference_auto => unimplemented!("auto reference"), +		_ => unreachable!(), +	}; +	Ok(e::Reference::with_extra( +		a::Reference { name, refuri, refid, refname } +	))  } diff --git a/src/parser/pair_ext_parse.rs b/src/parser/pair_ext_parse.rs index c7d2d45..a04b3dd 100644 --- a/src/parser/pair_ext_parse.rs +++ b/src/parser/pair_ext_parse.rs @@ -6,16 +6,16 @@ use pest::error::{Error,ErrorVariant};  pub trait PairExt<R> where R: pest::RuleType { -    fn parse<T, E>(&self) -> Result<T, Error<R>> where T: FromStr<Err = E>, E: ToString; +	fn parse<T, E>(&self) -> Result<T, Error<R>> where T: FromStr<Err = E>, E: ToString;  }  impl<'l, R> PairExt<R> for Pair<'l, R> where R: pest::RuleType { -    fn parse<T, E>(&self) -> Result<T, Error<R>> where T: FromStr<Err = E>, E: ToString { -        self.as_str().parse().map_err(|e| to_parse_error(self.as_span(), &e)) -    } +	fn parse<T, E>(&self) -> Result<T, Error<R>> where T: FromStr<Err = E>, E: ToString { +		self.as_str().parse().map_err(|e| to_parse_error(self.as_span(), &e)) +	}  }  pub(crate) fn to_parse_error<E, R>(span: Span, e: &E) -> Error<R> where E: ToString, R: pest::RuleType { -    let var: ErrorVariant<R> = ErrorVariant::CustomError { message: e.to_string() }; -    Error::new_from_span(var, span) +	let var: ErrorVariant<R> = ErrorVariant::CustomError { message: e.to_string() }; +	Error::new_from_span(var, span)  } diff --git a/src/parser/tests.rs b/src/parser/tests.rs index 76af915..b2ee623 100644 --- a/src/parser/tests.rs +++ b/src/parser/tests.rs @@ -4,84 +4,84 @@ use super::pest_rst::{RstParser, Rule};  #[test]  fn plain() { -    parses_to! { -        parser: RstParser, -        input: "line\n", -        rule: Rule::paragraph, -        tokens: [ -            paragraph(0, 4, [ -                str(0, 4) -            ]) -        ] -    }; +	parses_to! { +		parser: RstParser, +		input: "line\n", +		rule: Rule::paragraph, +		tokens: [ +			paragraph(0, 4, [ +				str(0, 4) +			]) +		] +	};  }  #[test]  fn title() { -    parses_to! { -        parser: RstParser, -        input: "\ +	parses_to! { +		parser: RstParser, +		input: "\  Title  =====  ", -        rule: Rule::title, -        tokens: [ -            title(0, 12, [ title_single(0, 12, [ -                line(0, 6, [ str(0, 5) ]), -                adornments(6, 11), -            ]) ]) -        ] -    }; +		rule: Rule::title, +		tokens: [ +			title(0, 12, [ title_single(0, 12, [ +				line(0, 6, [ str(0, 5) ]), +				adornments(6, 11), +			]) ]) +		] +	};  }  #[test]  fn title_overline() { -    parses_to! { -        parser: RstParser, -        input: "\ +	parses_to! { +		parser: RstParser, +		input: "\  -----  Title  -----  ", -        rule: Rule::title, -        tokens: [ -            title(0, 17, [ title_double(0, 17, [ -                adornments(0, 5), -                line(6, 12, [ str(6, 11) ]), -            ]) ]) -        ] -    }; +		rule: Rule::title, +		tokens: [ +			title(0, 17, [ title_double(0, 17, [ +				adornments(0, 5), +				line(6, 12, [ str(6, 11) ]), +			]) ]) +		] +	};  }  #[allow(clippy::cyclomatic_complexity)]  #[test]  fn two_targets() { -    parses_to! { -        parser: RstParser, -        input: "\ +	parses_to! { +		parser: RstParser, +		input: "\  .. _a: http://example.com  .. _`b_`: https://example.org  ", -        rule: Rule::document, -        tokens: [ -            target(0, 26, [ -                target_name_uq(4, 5), -                link_target(7, 25), -            ]), -            target(26, 56, [ -                target_name_qu(31, 33), -                link_target(36, 55), -            ]), -        ] -    }; +		rule: Rule::document, +		tokens: [ +			target(0, 26, [ +				target_name_uq(4, 5), +				link_target(7, 25), +			]), +			target(26, 56, [ +				target_name_qu(31, 33), +				link_target(36, 55), +			]), +		] +	};  }  #[allow(clippy::cyclomatic_complexity)]  #[test]  fn admonitions() { -    parses_to! { -        parser: RstParser, -        input: "\ +	parses_to! { +		parser: RstParser, +		input: "\  .. note::     Just next line  .. admonition:: In line title @@ -90,22 +90,22 @@ fn admonitions() {  .. danger:: Just this line  ", -        rule: Rule::document, -        tokens: [ -            admonition_gen(0, 27, [ -                admonition_type(3, 7), -                paragraph(13, 27, [ str(13, 27) ]), -            ]), -            admonition(28, 71, [ -                line(43, 58, [ str(43, 57) ]), -                paragraph(62, 71, [ str(62, 71) ]), -            ]), -            admonition_gen(73, 100, [ -                admonition_type(76, 82), -                line(84, 100, [ str(84, 99) ]), -            ]), -        ] -    }; +		rule: Rule::document, +		tokens: [ +			admonition_gen(0, 27, [ +				admonition_type(3, 7), +				paragraph(13, 27, [ str(13, 27) ]), +			]), +			admonition(28, 71, [ +				line(43, 58, [ str(43, 57) ]), +				paragraph(62, 71, [ str(62, 71) ]), +			]), +			admonition_gen(73, 100, [ +				admonition_type(76, 82), +				line(84, 100, [ str(84, 99) ]), +			]), +		] +	};  }  // TODO: test substitutions @@ -114,9 +114,9 @@ fn admonitions() {  #[allow(clippy::cyclomatic_complexity)]  #[test]  fn nested_lists() { -    parses_to! { -        parser: RstParser, -        input: "\ +	parses_to! { +		parser: RstParser, +		input: "\  paragraph  -  item 1 @@ -128,27 +128,27 @@ paragraph     - nested item 2     - nested item 3  ", -        rule: Rule::document, -        tokens: [ -            paragraph(0, 9, [ str(0, 9) ]), -            bullet_list(11, 131, [ -                bullet_item(11, 21, [ -                    line(14, 21, [ str(14, 20) ]), -                ]), -                bullet_item(21, 131, [ -                    line(24, 31, [ str(24, 30) ]), -                    paragraph(34, 74, [ -                        str(34, 43), -                        str(47, 58), -                        str(62, 73), -                    ]), -                    bullet_list(77, 131, [ -                        bullet_item( 77,  93, [ line( 79,  93, [str( 79,  92)]) ]), -                        bullet_item( 96, 112, [ line( 98, 112, [str( 98, 111)]) ]), -                        bullet_item(115, 131, [ line(117, 131, [str(117, 130)]) ]), -                    ]), -                ]), -            ]), -        ] -    } +		rule: Rule::document, +		tokens: [ +			paragraph(0, 9, [ str(0, 9) ]), +			bullet_list(11, 131, [ +				bullet_item(11, 21, [ +					line(14, 21, [ str(14, 20) ]), +				]), +				bullet_item(21, 131, [ +					line(24, 31, [ str(24, 30) ]), +					paragraph(34, 74, [ +						str(34, 43), +						str(47, 58), +						str(62, 73), +					]), +					bullet_list(77, 131, [ +						bullet_item( 77,  93, [ line( 79,  93, [str( 79,  92)]) ]), +						bullet_item( 96, 112, [ line( 98, 112, [str( 98, 111)]) ]), +						bullet_item(115, 131, [ line(117, 131, [str(117, 130)]) ]), +					]), +				]), +			]), +		] +	}  } | 
