use std::fmt;
use std::sync::Arc;
use techy::core::constructs::{
scan_argument_noise, stage_pre_space, ArgumentParser, ChildStateSpec, ConstructParserResult,
GroupChildState, InvocationChildState, MissingMandatoryArgument, ParseContext,
ParsedArgumentNodes,
};
use techy::core::node::ContentNodes;
use techy::core::specs::ArgumentSpec;
use techy::core::token::{TokenEdge, TokenKind};
use crate::lang::flm::{Flm, FlmGroupType};
#[derive(Default)]
pub struct FlmCharsGroupArgumentParser;
impl FlmCharsGroupArgumentParser {
pub fn new() -> FlmCharsGroupArgumentParser {
FlmCharsGroupArgumentParser
}
}
impl fmt::Debug for FlmCharsGroupArgumentParser {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("FlmCharsGroupArgumentParser").finish()
}
}
impl ArgumentParser<Flm> for FlmCharsGroupArgumentParser {
fn parse_argument(
&self,
cx: &mut ParseContext<'_, '_, Flm>,
spec: &ArgumentSpec<Flm>,
) -> ConstructParserResult<Flm, Option<ParsedArgumentNodes<Flm>>> {
let mut noise = scan_argument_noise(cx)?;
let open = noise.next.clone().and_then(|next| match cx.tokens.token_kind(&next) {
TokenKind::GroupOpen { rule, .. } if rule.group_type == FlmGroupType::Content => {
let rule = Arc::clone(rule);
Some((next, rule))
}
_ => None,
});
let Some((open, rule)) = open else {
let at = match noise.next.as_ref() {
Some(token) => cx.tokens.source_span_of(token),
None => cx.here(),
};
cx.recover(MissingMandatoryArgument::new(spec.name.as_deref().map(String::from)), at)?;
noise.rewind(cx);
return Ok(None);
};
let outer = Arc::clone(&cx.state);
let delta = outer.ext().restricted_interior.chars_group_delta(&outer, FlmGroupType::Content);
let contents_state = cx.derive_state(&delta)?;
stage_pre_space(cx, &mut noise.nodes, &open)?;
cx.tokens.move_to(&open, TokenEdge::EndPastPostSpace);
let child_states = ChildStateSpec {
group: GroupChildState::Fixed(outer),
invocation: InvocationChildState::Inherit,
};
let (id, _after_effect) = cx.parse_group(contents_state, &open, rule, child_states, None)?;
let child_count =
cx.staged_nodes().get(id).map_or(0, |view| view.children().len() as u32);
noise.nodes.push(id);
Ok(Some(ParsedArgumentNodes::new(
noise.nodes,
ContentNodes::InChildrenOf(id, 0..child_count),
(),
)))
}
fn can_match_empty(&self) -> bool {
false
}
}