use std::cell::Cell;
use std::fmt;
use std::sync::Arc;
use techy::core::constructs::{
scan_argument_noise, ArgumentParser, ChildStateSpec, ConstructParserResult,
GroupArgumentParser, OptionalGroupArgumentParser, ParseContext, ParsedArgumentNodes,
StopCause, StopSpec, TokenStopKind,
};
use techy::core::node::{ContentNodes, GroupData, NodeBuildError, NodeKind, NodeRef};
use techy::core::specs::ArgumentSpec;
use techy::core::token::{GroupRule, Token, TokenKind, TokenReader};
use techy::error::{HookFailed, ParseError};
use techy::source::TextContent;
use crate::lang::mint::{DefinitionShape, FlmArgumentParser};
use crate::lang::{Flm, FlmGroupType, FlmOrigin, FlmSpan};
use super::diagnostics::Unterminated;
use super::TEXT_ARG;
const ENVIRONMENT_END: &str = "end";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Form {
Highlight,
Comment,
}
pub fn form_of(node: &NodeRef<'_, Flm>) -> Option<Form> {
let (open, _) = delimiters_of(node)?;
Some(if open == "[" { Form::Comment } else { Form::Highlight })
}
pub(super) fn delimiters_of<'t>(node: &NodeRef<'t, Flm>) -> Option<(&'t str, &'t str)> {
let region = node.arguments()?.get_named(TEXT_ARG)?.region.as_ref()?;
let group = node.tree().get(region.content_parent())?;
group.group_delimiters()
}
pub struct AnnotationParser {
command: String,
end_command: String,
braces: GroupArgumentParser<Flm>,
brackets: OptionalGroupArgumentParser<Flm>,
}
impl AnnotationParser {
pub fn new(command: &str) -> AnnotationParser {
let bracket = Arc::new(GroupRule {
group_type: FlmGroupType::Content,
open: String::from("["),
close: String::from("]"),
});
AnnotationParser {
command: command.to_string(),
end_command: format!("end{command}"),
braces: GroupArgumentParser::new(FlmGroupType::Content).with_expression_fallback(false),
brackets: OptionalGroupArgumentParser::new(bracket),
}
}
fn passage(
&self,
cx: &mut ParseContext<'_, '_, Flm>,
) -> ConstructParserResult<Flm, Option<ParsedArgumentNodes<Flm>>> {
let start = cx.tokens.position_here();
let state = Arc::clone(&cx.state);
let closed = Cell::new(false);
let stops_at = |token: &Token<Flm>, tokens: &dyn TokenReader<'_, Flm>| {
Ok(match tokens.token_kind(token) {
TokenKind::Command { name, .. } if name == self.end_command => {
closed.set(true);
true
}
TokenKind::Command { name, .. } => name == ENVIRONMENT_END,
_ => false,
})
};
let stop = StopSpec::at_token(TokenStopKind::Predicate(&stops_at), false);
let (outcome, _) = cx.parse_nodes(Arc::clone(&state), stop, ChildStateSpec::inherit())?;
let (close, end) = match outcome.stop {
StopCause::TokenCondition { after, .. } if closed.get() => {
let close_start = cx.tokens.position_here();
cx.tokens.move_to_position(&after);
let span = cx.source_span_within(&close_start, &after)?;
(TextContent::Spanned(span.span()), after)
}
StopCause::TokenCondition { .. }
| StopCause::EndOfInput
| StopCause::UnexpectedGroupClose { .. }
| StopCause::NodeCondition => {
let end = cx.tokens.position_here();
let span = cx.source_span_within(&start, &end)?;
cx.recover(
Unterminated { command: self.command.clone(), end_command: self.end_command.clone() },
span,
)?;
(TextContent::empty(), end)
}
};
let group_span = cx.source_span_within(&start, &end)?;
let count = outcome.nodes.len() as u32;
let data = GroupData { group_type: Some(FlmGroupType::Content), open: TextContent::empty(), close };
let group = cx
.stage_node(NodeKind::group(data), group_span.clone(), state, outcome.nodes)
.map_err(|error| staging_error(cx, error, group_span))?;
Ok(Some(ParsedArgumentNodes::new(vec![group], ContentNodes::InChildrenOf(group, 0..count), ())))
}
}
fn staging_error(
cx: &ParseContext<'_, '_, Flm>,
error: NodeBuildError,
span: FlmSpan,
) -> ParseError<FlmOrigin> {
match error {
NodeBuildError::ExtMintFailed { detail } => ParseError::new(HookFailed::new(detail, None), span),
other => cx.implementation_error(other, span),
}
}
impl fmt::Debug for AnnotationParser {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("AnnotationParser").field("command", &self.command).finish()
}
}
impl ArgumentParser<Flm> for AnnotationParser {
fn parse_argument(
&self,
cx: &mut ParseContext<'_, '_, Flm>,
spec: &ArgumentSpec<Flm>,
) -> ConstructParserResult<Flm, Option<ParsedArgumentNodes<Flm>>> {
let noise = scan_argument_noise(cx)?;
let next = noise.next.clone();
noise.rewind(cx);
let braced = next.is_some_and(|token| {
matches!(cx.tokens.token_kind(&token), TokenKind::GroupOpen { rule, .. }
if rule.group_type == FlmGroupType::Content)
});
if braced {
return self.braces.parse_argument(cx, spec);
}
if let Some(comment) = self.brackets.parse_argument(cx, spec)? {
return Ok(Some(comment));
}
self.passage(cx)
}
fn can_match_empty(&self) -> bool {
false
}
}
impl FlmArgumentParser for AnnotationParser {
fn identity(&self) -> Vec<u8> {
format!("flm.annotations.text:{}", self.command).into_bytes()
}
fn definition_shape(&self) -> DefinitionShape {
DefinitionShape::NoShape { token: "annotation" }
}
fn description(&self) -> String {
format!(
"a `{{…}}` highlight, a `[…]` comment, or a highlighted passage up to `\\{}`",
self.end_command
)
}
}