organic/src/parser/org_macro.rs
2023-07-14 00:20:32 -04:00

79 lines
2.6 KiB
Rust

use nom::bytes::complete::tag;
use nom::character::complete::anychar;
use nom::combinator::not;
use nom::combinator::opt;
use nom::combinator::peek;
use nom::combinator::verify;
use nom::multi::many0;
use nom::multi::separated_list0;
use super::Context;
use crate::error::Res;
use crate::parser::object::OrgMacro;
use crate::parser::parser_with_context::parser_with_context;
use crate::parser::util::exit_matcher_parser;
use crate::parser::util::get_consumed;
#[tracing::instrument(ret, level = "debug")]
pub fn org_macro<'r, 's>(context: Context<'r, 's>, input: &'s str) -> Res<&'s str, OrgMacro<'s>> {
let (remaining, _) = tag("{{{")(input)?;
let (remaining, macro_name) = org_macro_name(context, remaining)?;
let (remaining, macro_args) = opt(parser_with_context!(org_macro_args)(context))(remaining)?;
let (remaining, _) = tag("}}}")(remaining)?;
let source = get_consumed(input, remaining);
Ok((
remaining,
OrgMacro {
source,
macro_name,
macro_args: macro_args.unwrap_or_else(|| Vec::with_capacity(0)),
},
))
}
#[tracing::instrument(ret, level = "debug")]
fn org_macro_name<'r, 's>(context: Context<'r, 's>, input: &'s str) -> Res<&'s str, &'s str> {
let (remaining, _) = verify(anychar, |c| c.is_alphabetic())(input)?;
let (remaining, _) = many0(verify(anychar, |c| {
c.is_alphanumeric() || *c == '-' || *c == '_'
}))(remaining)?;
let source = get_consumed(input, remaining);
Ok((remaining, source))
}
#[tracing::instrument(ret, level = "debug")]
fn org_macro_args<'r, 's>(context: Context<'r, 's>, input: &'s str) -> Res<&'s str, Vec<&'s str>> {
let (remaining, _) = tag("(")(input)?;
let (remaining, args) =
separated_list0(tag(","), parser_with_context!(org_macro_arg)(context))(remaining)?;
let (remaining, _) = tag(")")(remaining)?;
Ok((remaining, args))
}
#[tracing::instrument(ret, level = "debug")]
fn org_macro_arg<'r, 's>(context: Context<'r, 's>, input: &'s str) -> Res<&'s str, &'s str> {
let mut remaining = input;
let mut escaping: bool = false;
loop {
not(parser_with_context!(exit_matcher_parser)(context))(remaining)?;
not(peek(tag("}}}")))(remaining)?;
let (new_remaining, next_char) = anychar(remaining)?;
if escaping {
remaining = new_remaining;
escaping = false;
continue;
}
if next_char == '\\' {
escaping = true;
}
if next_char == ',' || next_char == ')' {
break;
}
remaining = new_remaining;
}
let source = get_consumed(input, remaining);
Ok((remaining, source))
}