organic/src/parser/target.rs

71 lines
2.3 KiB
Rust
Raw Normal View History

2023-07-22 05:36:00 +00:00
use nom::bytes::complete::tag;
use nom::character::complete::anychar;
use nom::character::complete::one_of;
use nom::combinator::peek;
use nom::combinator::recognize;
use nom::combinator::verify;
use nom::multi::many_till;
use super::org_source::OrgSource;
2023-09-03 04:05:47 +00:00
use super::util::exit_matcher_parser;
use super::util::maybe_consume_object_trailing_whitespace_if_not_exiting;
2023-09-03 04:05:47 +00:00
use crate::context::parser_with_context;
use crate::context::ContextElement;
use crate::context::ExitClass;
use crate::context::ExitMatcherNode;
use crate::context::RefContext;
2023-07-22 05:36:00 +00:00
use crate::error::CustomError;
use crate::error::MyError;
use crate::error::Res;
use crate::parser::util::get_consumed;
2023-09-03 04:05:47 +00:00
use crate::types::Target;
2023-07-22 05:36:00 +00:00
2023-08-11 00:04:59 +00:00
#[cfg_attr(feature = "tracing", tracing::instrument(ret, level = "debug"))]
2023-09-11 17:13:28 +00:00
pub(crate) fn target<'b, 'g, 'r, 's>(
context: RefContext<'b, 'g, 'r, 's>,
input: OrgSource<'s>,
) -> Res<OrgSource<'s>, Target<'s>> {
2023-07-22 05:36:00 +00:00
let (remaining, _) = tag("<<")(input)?;
let (remaining, _) = peek(verify(anychar, |c| {
!c.is_whitespace() && !"<>\n".contains(*c)
}))(remaining)?;
2023-09-03 04:05:47 +00:00
let parser_context = ContextElement::ExitMatcherNode(ExitMatcherNode {
class: ExitClass::Beta,
exit_matcher: &target_end,
});
let parser_context = context.with_additional_node(&parser_context);
2023-07-22 05:43:17 +00:00
let (remaining, _body) = recognize(many_till(
2023-07-22 05:36:00 +00:00
anychar,
parser_with_context!(exit_matcher_parser)(&parser_context),
))(remaining)?;
let preceding_character = remaining
.get_preceding_character()
2023-07-22 05:36:00 +00:00
.expect("We cannot be at the start of the file because we are inside a target.");
if preceding_character.is_whitespace() {
return Err(nom::Err::Error(CustomError::MyError(MyError(
"Targets cannot end with whitespace.".into(),
2023-07-22 05:36:00 +00:00
))));
}
let (remaining, _) = tag(">>")(remaining)?;
let (remaining, _trailing_whitespace) =
maybe_consume_object_trailing_whitespace_if_not_exiting(context, remaining)?;
2023-07-22 05:36:00 +00:00
let source = get_consumed(input, remaining);
Ok((
remaining,
Target {
source: source.into(),
},
))
2023-07-22 05:36:00 +00:00
}
2023-08-11 00:04:59 +00:00
#[cfg_attr(feature = "tracing", tracing::instrument(ret, level = "debug"))]
fn target_end<'b, 'g, 'r, 's>(
_context: RefContext<'b, 'g, 'r, 's>,
input: OrgSource<'s>,
) -> Res<OrgSource<'s>, OrgSource<'s>> {
2023-07-22 05:36:00 +00:00
recognize(one_of("<>\n"))(input)
}