use std::sync::Arc;
use techy::core::node::{NodeBuildError, NodeKind, StagedChildren};
use techy::core::specs::ScopeStack;
use techy::core::token::{SpecialsMatch, SpecialsScanError, StdTokenization, TriggerChars};
use techy::core::{
AllLangFeatures, ClosedVocabulary, FinalizeError, Lang, NodeExtTypes, ParsingState,
StateData,
};
use techy::latexlike::{
builtin_package, default_token_rules, BodyMarker, Event, InvocationSyntaxData,
LatexlikeCallableType, LatexlikeGroupType, LatexlikeLang, MathGroupForm, Mode,
StdEnvironmentSyntax,
};
use techy::serialize::{DeserializableValue, SerializableValue};
use techy::source::SourceSpan;
use crate::lang::driver::FlmDriver;
use crate::lang::ext::{FlmNodeExt, FlmStateExt};
use crate::lang::mint::resolve_element;
use crate::lang::origin::FlmOrigin;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[derive(SerializableValue, DeserializableValue)]
pub enum FlmGroupType {
#[serial(name = "content")]
Content,
#[serial(name = "math")]
Math(MathGroupForm),
#[serial(name = "verbatim")]
Verbatim,
#[serial(name = "opaque-wrapper")]
OpaqueWrapper,
#[serial(name = "paragraph")]
Paragraph,
}
impl FlmGroupType {
pub fn is_opaque_in_any_mode(self) -> bool {
matches!(self, FlmGroupType::Verbatim | FlmGroupType::OpaqueWrapper)
}
}
impl LatexlikeGroupType for FlmGroupType {
fn content_group() -> FlmGroupType {
FlmGroupType::Content
}
fn math_group(form: MathGroupForm) -> FlmGroupType {
FlmGroupType::Math(form)
}
fn verbatim_group() -> FlmGroupType {
FlmGroupType::Verbatim
}
fn math_form(self) -> Option<MathGroupForm> {
match self {
FlmGroupType::Math(form) => Some(form),
_ => None,
}
}
}
impl ClosedVocabulary for FlmGroupType {
const ALL: &'static [FlmGroupType] = &[
FlmGroupType::Content,
FlmGroupType::Math(MathGroupForm::Inline),
FlmGroupType::Math(MathGroupForm::Display),
FlmGroupType::Verbatim,
FlmGroupType::OpaqueWrapper,
FlmGroupType::Paragraph,
];
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[derive(SerializableValue, DeserializableValue)]
pub enum FlmCallableType {
#[serial(name = "macro")]
Macro,
#[serial(name = "environment")]
Environment,
#[serial(name = "specials")]
Specials,
#[serial(name = "placeholder")]
Placeholder,
#[serial(name = "presentation")]
Presentation,
}
impl LatexlikeCallableType for FlmCallableType {
fn macro_callable() -> FlmCallableType {
FlmCallableType::Macro
}
fn environment_callable() -> FlmCallableType {
FlmCallableType::Environment
}
fn specials_callable() -> FlmCallableType {
FlmCallableType::Specials
}
}
impl ClosedVocabulary for FlmCallableType {
const ALL: &'static [FlmCallableType] = &[
FlmCallableType::Macro,
FlmCallableType::Environment,
FlmCallableType::Specials,
FlmCallableType::Placeholder,
FlmCallableType::Presentation,
];
}
#[derive(Debug, Clone, Copy)]
pub struct FlmNodeExts;
impl NodeExtTypes for FlmNodeExts {
type NodeExt = FlmNodeExt;
type ArgumentExt = ();
type SlotExt = BodyMarker;
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Flm;
impl Lang for Flm {
type Features = AllLangFeatures;
type GroupTypeId = FlmGroupType;
type CallableTypeId = FlmCallableType;
type ModeId = Mode;
type StateExt = FlmStateExt;
type Event = Event;
type SessionExt = ();
type SourceOrigin = FlmOrigin;
type Tokenization = StdTokenization;
type NodeExts = FlmNodeExts;
type InvocationSyntax = InvocationSyntaxData<StdEnvironmentSyntax<Flm>>;
type Driver = FlmDriver;
fn initial_state_data() -> Result<StateData<Self>, FinalizeError> {
let mut scopes = ScopeStack::new();
scopes.push(builtin_package());
Ok(StateData {
rules: default_token_rules(),
scopes,
mode: Mode::Text,
ext: FlmStateExt::default(),
})
}
fn finalize_transition(
new: &mut StateData<Self>,
prev: &ParsingState<Self>,
events: &[Event],
) -> Result<(), FinalizeError> {
let _ = (new, prev);
if events.iter().any(|event| matches!(event, Event::ExitMathContext)) {
return Err(FinalizeError::new(
"the ExitMathContext event needs the enclosing-state stack: derive \
through a parse context, where the driver lowers it",
));
}
Ok(())
}
fn scan_specials(
state: &ParsingState<Self>,
content: &str,
pos: usize,
) -> Result<Option<SpecialsMatch<Self>>, SpecialsScanError> {
state.scopes().scan_specials(state, content, pos)
}
fn specials_trigger_chars(data: &StateData<Self>) -> TriggerChars {
data.scopes.specials_trigger_chars()
}
fn make_node_ext(
kind: &NodeKind<Self>,
_span: &SourceSpan<FlmOrigin>,
state: &Arc<ParsingState<Self>>,
_children: StagedChildren<'_, Self>,
) -> Result<FlmNodeExt, NodeBuildError> {
match resolve_element(kind, state.ext()) {
Ok(element) => Ok(FlmNodeExt::new(element)),
Err(error) => Err(NodeBuildError::ExtMintFailed { detail: error.to_string() }),
}
}
}
impl LatexlikeLang for Flm {}
#[cfg(test)]
mod tests {
use super::*;
use techy::core::ParsingStateDelta;
#[test]
fn the_vocabularies_play_the_preset_roles() {
assert_eq!(FlmGroupType::content_group(), FlmGroupType::Content);
assert_eq!(FlmGroupType::verbatim_group(), FlmGroupType::Verbatim);
assert!(FlmGroupType::Math(MathGroupForm::Display).is_math());
assert!(!FlmGroupType::Paragraph.is_math());
assert!(FlmCallableType::Macro.is_macro());
assert!(!FlmCallableType::Placeholder.is_specials());
}
#[test]
fn the_seed_is_finalize_coherent() {
let seed = ParsingState::<Flm>::lang_initial().expect("seed state");
let rederived = seed.derived(&ParsingStateDelta::new()).unwrap();
assert_eq!(seed.rules(), rederived.rules());
assert_eq!(seed.mode(), rederived.mode());
assert_eq!(seed.scopes().provider_names().collect::<Vec<_>>(), ["_builtin"]);
}
#[test]
fn an_exit_math_event_is_refused_out_of_parse() {
let seed = ParsingState::<Flm>::lang_initial().expect("seed state");
assert!(seed.derived(&ParsingStateDelta::new().event(Event::ExitMathContext)).is_err());
}
}