use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use std::sync::Arc;
use techy::core::constructs::{
parse_declared_arguments, ConstructParser, ConstructParserResult, Invocation, ParseContext,
};
use techy::core::node::{
BuildId, CallableData, ContentNodes, NodeBuildError, NodeId, NodeKind, NodeRef, NodeSlice,
NodeTree, ParsedArgument, ParsedArguments, ParsedSlots,
};
use techy::core::specs::{
ArgumentSpec, CallableQuery, CallableSpec, CallableSyntax, Package, ProviderError,
SpecsProvider,
};
use techy::core::token::{CommandOverrides, CommandRule, TokenEdge, TokenKind, TokenRulesOverrides};
use techy::core::{DeriveError, FrameRole, ParsingState, ParsingStateDelta};
use techy::error::{Diagnostic, HookFailed, ParseError, Severity};
use techy::latexlike::{argument_specs_named, InvocationSyntaxData, Mode};
use techy::serialize::SerializableObject;
use techy::source::{Source, SourceSpan, TextContent};
use crate::model::doc::FragmentLayout;
use crate::model::element::ElementSpec;
use crate::lang::build::BuiltLang;
use crate::lang::ext::{TemplateCommandRule, TemplateInteriorRules, RestrictedInterior};
use crate::lang::flm::{Flm, FlmCallableType};
use crate::lang::mint::{mint_packages, ArgDef, ArgStdKind, ElementDef, MintError, SyntaxDef};
use crate::lang::origin::{FlmDiagnostic, FlmOrigin, FlmSource, FlmSpan};
use crate::lang::parse::{parse_fragment_with_state, ParseOptions};
use crate::lang::rewrites::userdefs::diagnostics::{
BadDefinition, BadPlaceholder, DefinitionProblem, PlaceholderProblem,
};
use crate::lang::text::is_space;
pub const PLACEHOLDER_ESCAPE: char = '#';
pub const BODY_REFERENCE: &str = "body";
pub const TEMPLATE_PACKAGE_NAME: &str = "_userdefs.template";
pub const PLACEHOLDER_PROVIDER_NAME: &str = "_userdefs.placeholder";
pub const CONDITIONAL_ELEMENT: &str = "flm.userdefs.conditional";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ConditionalTest {
NoValue,
Value,
Boolean,
Blank,
NotBlank,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Branches {
True,
False,
Both,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Conditional {
pub test: ConditionalTest,
pub branches: Branches,
}
impl Conditional {
pub const ALL: [(&'static str, Conditional); 14] = [
("IfNoValueT", Conditional { test: ConditionalTest::NoValue, branches: Branches::True }),
("IfNoValueF", Conditional { test: ConditionalTest::NoValue, branches: Branches::False }),
("IfNoValueTF", Conditional { test: ConditionalTest::NoValue, branches: Branches::Both }),
("IfValueT", Conditional { test: ConditionalTest::Value, branches: Branches::True }),
("IfValueF", Conditional { test: ConditionalTest::Value, branches: Branches::False }),
("IfValueTF", Conditional { test: ConditionalTest::Value, branches: Branches::Both }),
("IfBooleanT", Conditional { test: ConditionalTest::Boolean, branches: Branches::True }),
("IfBooleanF", Conditional { test: ConditionalTest::Boolean, branches: Branches::False }),
("IfBooleanTF", Conditional { test: ConditionalTest::Boolean, branches: Branches::Both }),
("IfProvidedT", Conditional { test: ConditionalTest::Boolean, branches: Branches::True }),
("IfProvidedF", Conditional { test: ConditionalTest::Boolean, branches: Branches::False }),
("IfProvidedTF", Conditional { test: ConditionalTest::Boolean, branches: Branches::Both }),
("ifblank", Conditional { test: ConditionalTest::Blank, branches: Branches::Both }),
("notblank", Conditional { test: ConditionalTest::NotBlank, branches: Branches::Both }),
];
pub fn argument_count(&self) -> usize {
match self.branches {
Branches::True | Branches::False => 2,
Branches::Both => 3,
}
}
pub fn branch_index(&self, holds: bool) -> Option<usize> {
match (self.branches, holds) {
(Branches::True, true) | (Branches::False, false) | (Branches::Both, true) => Some(1),
(Branches::Both, false) => Some(2),
(Branches::True, false) | (Branches::False, true) => None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum PlaceholderTarget {
Argument(usize),
Body,
Extra(String),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PlaceholderRef {
pub written: String,
pub target: PlaceholderTarget,
pub substitution: bool,
}
pub(crate) fn substitution_of<'t>(node: &NodeRef<'t, Flm>) -> Option<NodeSlice<'t, Flm>> {
let provided = node
.arguments()
.and_then(|arguments| arguments.get(0))
.is_some_and(ParsedArgument::is_provided);
if provided {
node.argument_content_nodes(0)
} else {
None
}
}
pub(crate) fn substitution_text_of(nodes: &NodeSlice<'_, Flm>) -> String {
nodes.source_text().map(|text| text.trim().to_string()).unwrap_or_default()
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ExtraPlaceholder {
pub name: String,
pub substitution: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct PlaceholderVocabulary {
pub arity: usize,
pub names: Vec<Option<String>>,
pub body: bool,
pub extras: Vec<ExtraPlaceholder>,
}
impl PlaceholderVocabulary {
pub fn new(arity: usize) -> PlaceholderVocabulary {
PlaceholderVocabulary { arity, names: vec![None; arity], body: false, extras: Vec::new() }
}
pub fn names(mut self, names: Vec<Option<String>>) -> PlaceholderVocabulary {
self.names = names;
self
}
pub fn with_body(mut self) -> PlaceholderVocabulary {
self.body = true;
self
}
pub fn extra(mut self, name: impl Into<String>, substitution: bool) -> PlaceholderVocabulary {
self.extras.push(ExtraPlaceholder { name: name.into(), substitution });
self
}
pub fn index_of(&self, name: &str) -> Option<usize> {
self.names.iter().position(|declared| declared.as_deref() == Some(name))
}
pub fn resolve(
&self,
written: &str,
substitution: bool,
offset: usize,
) -> Result<PlaceholderTarget, PlaceholderProblem> {
if let Some(extra) = self.extras.iter().find(|extra| extra.name == written) {
if substitution && !extra.substitution {
return Err(PlaceholderProblem::SubstitutionNotAccepted);
}
return Ok(PlaceholderTarget::Extra(written.to_string()));
}
if written == BODY_REFERENCE {
if !self.body {
return Err(PlaceholderProblem::NoBody);
}
if substitution {
return Err(PlaceholderProblem::SubstitutionNotAccepted);
}
return Ok(PlaceholderTarget::Body);
}
if let Some(index) = self.index_of(written) {
if substitution {
return Err(PlaceholderProblem::SubstitutionNotAccepted);
}
return Ok(PlaceholderTarget::Argument(index));
}
if !written.is_empty() && written.bytes().all(|byte| byte.is_ascii_digit()) {
let referable = self.arity.saturating_sub(offset);
let out_of_range = || PlaceholderProblem::OutOfRange { arity: referable };
let number: usize = written.parse().map_err(|_| out_of_range())?;
if number < 1 || number > referable {
return Err(out_of_range());
}
if substitution {
return Err(PlaceholderProblem::SubstitutionNotAccepted);
}
return Ok(PlaceholderTarget::Argument(number - 1 + offset));
}
Err(PlaceholderProblem::UnknownName)
}
}
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),
}
}
pub struct PlaceholderSpec {
arguments: Vec<Arc<ArgumentSpec<Flm>>>,
}
impl PlaceholderSpec {
pub fn new() -> PlaceholderSpec {
let codes = [("o", "substitution"), ("m", "reference")];
let specs = argument_specs_named::<Flm, _, _, _>(codes)
.expect("the placeholder argument codes are constants of this module");
PlaceholderSpec { arguments: specs }
}
}
impl Default for PlaceholderSpec {
fn default() -> PlaceholderSpec {
PlaceholderSpec::new()
}
}
impl fmt::Debug for PlaceholderSpec {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("PlaceholderSpec").finish()
}
}
impl SerializableObject<Flm> for PlaceholderSpec {}
impl CallableSpec<Flm> for PlaceholderSpec {
fn arguments(&self) -> &[Arc<ArgumentSpec<Flm>>] {
&self.arguments
}
fn requires_content(&self) -> bool {
true
}
fn make_invocation_parser<'a>(
&'a self,
invocation: Invocation<'a, Flm>,
) -> Result<Box<dyn ConstructParser<Flm, Output = BuildId> + 'a>, ParseError<FlmOrigin>> {
Ok(Box::new(PlaceholderParser { invocation }))
}
fn stack_frame_title(&self, role: FrameRole, name: &str) -> String {
match role {
FrameRole::Argument { index } => {
format!("argument {} of placeholder beginning ‘{}’", index + 1, name)
}
_ => format!("placeholder beginning ‘{name}’"),
}
}
}
fn without_placeholder_escape(state: &ParsingState<Flm>) -> ParsingStateDelta<Flm> {
let commands: Vec<Arc<CommandRule>> = state
.rules()
.command_rules()
.iter()
.filter(|rule| rule.escape_char != PLACEHOLDER_ESCAPE)
.cloned()
.collect();
ParsingStateDelta::new().rules(TokenRulesOverrides {
commands: CommandOverrides { enabled: Some(true), rules: Some(commands) },
..TokenRulesOverrides::default()
})
}
fn staged_reference_text(
cx: &ParseContext<'_, '_, Flm>,
children: &[BuildId],
argument: &ParsedArgument<Flm>,
) -> String {
let Some(region) = &argument.region else {
return String::new();
};
let Some((range, content)) = region.staged() else {
return String::new();
};
let staged = cx.staged_nodes();
let ids: Vec<BuildId> = match content {
ContentNodes::InRegion(inner) => children
.get(range.start as usize..range.end as usize)
.and_then(|region| region.get(inner.start as usize..inner.end as usize))
.map(<[BuildId]>::to_vec)
.unwrap_or_default(),
ContentNodes::InChildrenOf(parent, inner) => staged
.get(*parent)
.and_then(|view| view.children().get(inner.start as usize..inner.end as usize))
.map(<[BuildId]>::to_vec)
.unwrap_or_default(),
};
let mut text = String::new();
let mut all_text = true;
for id in &ids {
match staged.get(*id) {
Some(view) => match view.kind() {
NodeKind::Chars { content } => text.push_str(content.resolve(view.span().source())),
_ => {
all_text = false;
break;
}
},
None => {
all_text = false;
break;
}
}
}
if !all_text {
text.clear();
if let (Some(first), Some(last)) = (ids.first(), ids.last()) {
if let (Some(first), Some(last)) = (staged.get(*first), staged.get(*last)) {
let source = first.span().source();
if Arc::ptr_eq(source, last.span().source()) {
let range = first.span().start()..last.span().end();
if let Some(covered) = source.content().get(range) {
text.push_str(covered);
}
}
}
}
}
text.trim_matches(is_space).to_string()
}
fn stage_placeholder(
cx: &mut ParseContext<'_, '_, Flm>,
invocation: &Invocation<'_, Flm>,
reference: &str,
arguments: ParsedArguments<Flm>,
children: Vec<BuildId>,
span: FlmSpan,
) -> ConstructParserResult<Flm, BuildId> {
let data = CallableData {
callable_type: FlmCallableType::Placeholder,
name: reference.into(),
spec: Arc::clone(invocation.spec),
arguments,
slots: ParsedSlots::empty(),
invocation_syntax: InvocationSyntaxData::Specials,
};
let state = Arc::clone(&cx.state);
cx.stage_node(NodeKind::callable(data), span.clone(), state, children)
.map_err(|error| staging_error(cx, error, span))
}
pub struct PlaceholderParser<'a> {
invocation: Invocation<'a, Flm>,
}
impl PlaceholderParser<'_> {
fn stage_escape(
&self,
cx: &mut ParseContext<'_, '_, Flm>,
span: FlmSpan,
) -> ConstructParserResult<Flm, BuildId> {
let kind = NodeKind::chars(TextContent::from(String::from(PLACEHOLDER_ESCAPE)));
let state = Arc::clone(&cx.state);
cx.stage_node(kind, span.clone(), state, Vec::new())
.map_err(|error| staging_error(cx, error, span))
}
fn parse_bracketed(
&self,
cx: &mut ParseContext<'_, '_, Flm>,
) -> ConstructParserResult<Flm, BuildId> {
let token = self.invocation.token;
cx.tokens.move_to(token, TokenEdge::Start);
let plain = cx.derive_state(&without_placeholder_escape(&cx.state))?;
let Some(escape) = cx.probe_token(&plain)? else {
let here = cx.here();
return Err(cx.implementation_error(
"the placeholder escape could not be re-read as a character",
here,
));
};
match cx.tokens.token_kind(&escape) {
TokenKind::Char(c) if c == PLACEHOLDER_ESCAPE => {}
other => {
let span = cx.tokens.source_span_of(&escape);
return Err(cx.implementation_error(
format!("expected the placeholder escape, found a {} token", other.as_str()),
span,
));
}
}
let start = cx.tokens.position_at(&escape, TokenEdge::Start);
let name = cx.tokens.source_span_of(&escape);
cx.tokens.move_to(&escape, TokenEdge::EndPastPostSpace);
let (children, arguments) = parse_declared_arguments(cx, self.invocation.spec, &name)?;
let reference = arguments
.get(1)
.map(|argument| staged_reference_text(cx, &children, argument))
.unwrap_or_default();
let end = cx.tokens.position_here();
let span = cx.source_span_within(&start, &end)?;
stage_placeholder(
cx,
&self.invocation,
&reference,
ParsedArguments::from(arguments),
children,
span,
)
}
fn parse_raw_name(
&self,
cx: &mut ParseContext<'_, '_, Flm>,
) -> ConstructParserResult<Flm, BuildId> {
let token = self.invocation.token;
let state = Arc::clone(&cx.state);
let start = cx.tokens.position_at(token, TokenEdge::Start);
let mut name = String::new();
let end = loop {
let Some(next) = cx.probe_token(&state)? else {
break cx.tokens.position_here();
};
let closes = match cx.tokens.token_kind(&next) {
TokenKind::Char('}') => true,
TokenKind::GroupClose { delim } => delim == "}",
TokenKind::Char(c) => {
name.push(c);
cx.tokens.move_to(&next, TokenEdge::EndPastPostSpace);
continue;
}
_ => break cx.tokens.position_here(),
};
if closes {
let end = cx.tokens.position_at(&next, TokenEdge::EndPastPostSpace);
cx.tokens.move_to(&next, TokenEdge::EndPastPostSpace);
break end;
}
break cx.tokens.position_here();
};
let span = cx.source_span_within(&start, &end)?;
stage_placeholder(
cx,
&self.invocation,
name.trim_matches(is_space),
ParsedArguments::empty(),
Vec::new(),
span,
)
}
}
impl fmt::Debug for PlaceholderParser<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("PlaceholderParser").field("invocation", &self.invocation).finish()
}
}
impl ConstructParser<Flm> for PlaceholderParser<'_> {
type Output = BuildId;
fn parse(
&mut self,
cx: &mut ParseContext<'_, '_, Flm>,
) -> ConstructParserResult<Flm, (BuildId, Option<Box<ParsingStateDelta<Flm>>>)> {
let token = self.invocation.token;
let name: String = match cx.tokens.token_kind(token) {
TokenKind::Command { name, .. } => name.to_string(),
other => {
let span = cx.tokens.source_span_of(token);
return Err(cx.implementation_error(
format!("a placeholder was dispatched from a {} token", other.as_str()),
span,
));
}
};
let span = cx.tokens.source_span_of(token);
let id = if name.chars().all(|c| c == PLACEHOLDER_ESCAPE) && !name.is_empty() {
self.stage_escape(cx, span)?
} else if (name == "{" || name == "[") && cx.state.rules().groups_enabled() {
self.parse_bracketed(cx)?
} else if name == "{" {
self.parse_raw_name(cx)?
} else {
stage_placeholder(
cx,
&self.invocation,
&name,
ParsedArguments::empty(),
Vec::new(),
span,
)?
};
Ok((id, None))
}
}
pub struct PlaceholderProvider {
spec: Arc<dyn CallableSpec<Flm>>,
}
impl PlaceholderProvider {
pub fn new() -> PlaceholderProvider {
PlaceholderProvider { spec: Arc::new(PlaceholderSpec::new()) }
}
pub fn spec(&self) -> &Arc<dyn CallableSpec<Flm>> {
&self.spec
}
}
impl Default for PlaceholderProvider {
fn default() -> PlaceholderProvider {
PlaceholderProvider::new()
}
}
impl fmt::Debug for PlaceholderProvider {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("PlaceholderProvider").finish()
}
}
impl SerializableObject<Flm> for PlaceholderProvider {}
impl SpecsProvider<Flm> for PlaceholderProvider {
fn name(&self) -> &str {
PLACEHOLDER_PROVIDER_NAME
}
fn retrieve_spec(
&self,
query: &CallableQuery<'_, Flm>,
_state: &ParsingState<Flm>,
) -> Result<Option<Arc<dyn CallableSpec<Flm>>>, ProviderError> {
let placeholder_escape = matches!(
query.syntax,
CallableSyntax::Command { escape_char } if escape_char == PLACEHOLDER_ESCAPE
);
if query.callable_type == FlmCallableType::Macro && placeholder_escape {
Ok(Some(Arc::clone(&self.spec)))
} else {
Ok(None)
}
}
}
fn template_declarations() -> Vec<ElementDef> {
let mut defs = Vec::with_capacity(Conditional::ALL.len());
for (name, conditional) in Conditional::ALL {
let element = Arc::new(
ElementSpec::new(CONDITIONAL_ELEMENT)
.docs(format!("the conditional `\\{name}` of the template language"))
.with_value(Arc::new(conditional)),
);
let args = vec![ArgDef::new(ArgStdKind::Mandatory); conditional.argument_count()];
defs.push(
ElementDef::new(TEMPLATE_PACKAGE_NAME, [name], SyntaxDef::Macro { args }, element)
.modes([Mode::Text, Mode::Math]),
);
}
defs
}
pub struct TemplateLanguage {
package: Arc<Package<Flm>>,
provider: Arc<PlaceholderProvider>,
}
impl TemplateLanguage {
pub fn new(lang: &BuiltLang) -> Result<TemplateLanguage, Vec<MintError>> {
let defs = template_declarations();
let minted = mint_packages(&defs, &[], &[], &[], &BTreeSet::new(), &[], lang.structural());
if !minted.errors.is_empty() {
return Err(minted.errors);
}
let Some(package) = minted.packages.into_iter().next() else {
return Err(Vec::new());
};
Ok(TemplateLanguage { package, provider: Arc::new(PlaceholderProvider::new()) })
}
pub fn package(&self) -> &Arc<Package<Flm>> {
&self.package
}
pub fn provider(&self) -> &Arc<PlaceholderProvider> {
&self.provider
}
#[allow(clippy::result_large_err)]
pub fn state(
&self,
lang: &BuiltLang,
mode: Mode,
) -> Result<Arc<ParsingState<Flm>>, DeriveError<Flm>> {
let base = lang.initial_state();
let mut commands: Vec<Arc<CommandRule>> = base.rules().command_rules().to_vec();
commands.push(Arc::new(CommandRule {
escape_char: PLACEHOLDER_ESCAPE,
name_chars: String::new(),
}));
let rules = TokenRulesOverrides {
commands: CommandOverrides { enabled: Some(true), rules: Some(commands) },
..TokenRulesOverrides::default()
};
let policy = RestrictedInterior::Template(TemplateInteriorRules {
commands: vec![TemplateCommandRule {
escape_char: PLACEHOLDER_ESCAPE,
name_chars: String::new(),
}],
specials: false,
});
let ext = lang.initial_state().ext().clone().with_restricted_interior(policy);
let package: Arc<dyn SpecsProvider<Flm>> = self.package.clone();
let provider: Arc<dyn SpecsProvider<Flm>> = self.provider.clone();
let delta = ParsingStateDelta::new()
.rules(rules)
.ext(ext)
.push_provider(package)
.push_provider(provider)
.mode(mode);
lang.derive_state(&delta)
}
}
impl fmt::Debug for TemplateLanguage {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("TemplateLanguage").field("package", &self.package.name()).finish()
}
}
#[derive(Debug, Clone)]
pub struct TemplateSpec<'a> {
pub text: &'a str,
pub mode: Mode,
pub vocabulary: &'a PlaceholderVocabulary,
pub offset: usize,
pub definition: &'a str,
pub label: &'a str,
pub origin_label: &'a str,
pub user_definition: bool,
}
pub struct CompiledTemplate {
text: String,
source: Arc<FlmSource>,
tree: Arc<NodeTree<Flm>>,
mode: Mode,
definition: String,
label: String,
placeholders: BTreeMap<NodeId, PlaceholderRef>,
diagnostics: Vec<FlmDiagnostic>,
}
impl CompiledTemplate {
pub fn text(&self) -> &str {
&self.text
}
pub fn source(&self) -> &Arc<FlmSource> {
&self.source
}
pub fn tree(&self) -> &Arc<NodeTree<Flm>> {
&self.tree
}
pub fn mode(&self) -> Mode {
self.mode
}
pub fn definition(&self) -> &str {
&self.definition
}
pub fn label(&self) -> &str {
&self.label
}
pub fn placeholder(&self, node: NodeId) -> Option<&PlaceholderRef> {
self.placeholders.get(&node)
}
pub fn placeholders(&self) -> impl Iterator<Item = (NodeId, &PlaceholderRef)> + '_ {
self.placeholders.iter().map(|(id, reference)| (*id, reference))
}
pub fn substitution_text(&self, node: NodeId) -> Option<String> {
if !self.placeholders.contains_key(&node) {
return None;
}
let content = substitution_of(&self.tree.get(node)?)?;
Some(substitution_text_of(&content))
}
pub fn diagnostics(&self) -> &[FlmDiagnostic] {
&self.diagnostics
}
}
impl fmt::Debug for CompiledTemplate {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("CompiledTemplate")
.field("text", &self.text)
.field("mode", &self.mode)
.field("definition", &self.definition)
.field("placeholders", &self.placeholders)
.finish()
}
}
fn source_start(source: &Arc<FlmSource>) -> FlmSpan {
SourceSpan::new(source, 0..0)
}
pub fn minting_diagnostics(definition: &str, errors: &[MintError]) -> Vec<FlmDiagnostic> {
let origin = FlmOrigin::synthetic(format!("declaration of {definition}"));
let source: Arc<FlmSource> = Arc::new(Source::new(String::new()).with_origin(origin));
let errors = if errors.is_empty() {
vec![String::from("its declarations produced no package and reported no error")]
} else {
errors.iter().map(ToString::to_string).collect()
};
errors
.into_iter()
.map(|detail| {
Diagnostic::error(
BadDefinition::new(definition, DefinitionProblem::Minting { detail }),
source_start(&source),
)
})
.collect()
}
pub fn compile_template(
spec: &TemplateSpec<'_>,
lang: &BuiltLang,
) -> Result<CompiledTemplate, Vec<FlmDiagnostic>> {
let language = TemplateLanguage::new(lang)
.map_err(|errors| minting_diagnostics(spec.definition, &errors))?;
compile_template_with(spec, lang, &language)
}
fn mode_name(mode: Mode) -> String {
format!("{mode:?}").to_ascii_lowercase()
}
pub fn compile_template_with(
spec: &TemplateSpec<'_>,
lang: &BuiltLang,
language: &TemplateLanguage,
) -> Result<CompiledTemplate, Vec<FlmDiagnostic>> {
let label = format!("{} ({} mode)", spec.origin_label, mode_name(spec.mode));
let origin =
if spec.user_definition { FlmOrigin::definition(label) } else { FlmOrigin::synthetic(label) };
let source: Arc<FlmSource> = Arc::new(Source::new(spec.text.to_string()).with_origin(origin));
let failed = |detail: String| {
vec![Diagnostic::error(
BadDefinition::new(spec.definition, DefinitionProblem::ParseFailed { detail }),
source_start(&source),
)]
};
let state = language.state(lang, spec.mode).map_err(|error| failed(error.to_string()))?;
let standard = match spec.mode {
Mode::Text => Arc::clone(&state),
_ => language.state(lang, Mode::Text).map_err(|error| failed(error.to_string()))?,
};
let options = ParseOptions { standard_state: Some(standard), ..ParseOptions::default() };
let fragment = parse_fragment_with_state(
lang,
Arc::clone(&source),
FragmentLayout::default(),
&options,
state,
)
.map_err(|error| failed(error.to_string()))?;
let mut diagnostics: Vec<FlmDiagnostic> = fragment.diags().iter().cloned().collect();
let tree = fragment.tree().materialize();
let mut placeholders = BTreeMap::new();
for node in tree.root().descendants() {
if node.callable_type() != Some(FlmCallableType::Placeholder) {
continue;
}
let written = node.name().unwrap_or("").to_string();
let substitution = node
.arguments()
.and_then(|arguments| arguments.get(0))
.is_some_and(ParsedArgument::is_provided);
match spec.vocabulary.resolve(&written, substitution, spec.offset) {
Ok(target) => {
placeholders.insert(node.id(), PlaceholderRef { written, target, substitution });
}
Err(problem) => diagnostics.push(Diagnostic::error(
BadPlaceholder::new(spec.definition, written, problem),
node.span().clone(),
)),
}
}
if diagnostics.iter().any(|diagnostic| diagnostic.severity() == Severity::Error) {
return Err(diagnostics);
}
Ok(CompiledTemplate {
text: spec.text.to_string(),
source,
tree: Arc::new(tree),
mode: spec.mode,
definition: spec.definition.to_string(),
label: spec.label.to_string(),
placeholders,
diagnostics,
})
}
pub fn compile_in_modes<T>(
modes: impl IntoIterator<Item = Mode>,
mut compile: impl FnMut(Mode, &mut Vec<FlmDiagnostic>) -> Option<T>,
) -> (Vec<(Mode, T)>, Vec<FlmDiagnostic>) {
let mut kept = Vec::new();
let mut kept_diagnostics = Vec::new();
let mut failed_diagnostics = Vec::new();
for mode in modes {
let mut found = Vec::new();
match compile(mode, &mut found) {
Some(compiled) => {
kept.push((mode, compiled));
kept_diagnostics.extend(found);
}
None => failed_diagnostics.extend(found),
}
}
if kept.is_empty() {
(kept, failed_diagnostics)
} else {
(kept, kept_diagnostics)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_conditional_selects_the_branch_its_test_answers() {
let tf = Conditional { test: ConditionalTest::Value, branches: Branches::Both };
assert_eq!(tf.branch_index(true), Some(1));
assert_eq!(tf.branch_index(false), Some(2));
let t = Conditional { test: ConditionalTest::Value, branches: Branches::True };
assert_eq!(t.branch_index(false), None);
assert_eq!(t.argument_count(), 2);
}
#[test]
fn the_vocabulary_resolves_a_number_under_the_offset() {
let vocabulary = PlaceholderVocabulary::new(3);
assert_eq!(vocabulary.resolve("1", false, 1), Ok(PlaceholderTarget::Argument(1)));
assert_eq!(vocabulary.resolve("2", false, 1), Ok(PlaceholderTarget::Argument(2)));
assert_eq!(
vocabulary.resolve("3", false, 1),
Err(PlaceholderProblem::OutOfRange { arity: 2 })
);
assert_eq!(
vocabulary.resolve("0", false, 0),
Err(PlaceholderProblem::OutOfRange { arity: 3 })
);
}
#[test]
fn a_named_reference_ignores_the_offset() {
let vocabulary =
PlaceholderVocabulary::new(2).names(vec![Some(String::from("a")), Some("b".into())]);
assert_eq!(vocabulary.resolve("a", false, 1), Ok(PlaceholderTarget::Argument(0)));
assert_eq!(vocabulary.resolve("1", false, 1), Ok(PlaceholderTarget::Argument(1)));
}
#[test]
fn the_vocabulary_answers_a_hook_name_before_an_argument_name() {
let vocabulary = PlaceholderVocabulary::new(1)
.names(vec![Some(String::from("x"))])
.extra("x", true);
assert_eq!(
vocabulary.resolve("x", true, 0),
Ok(PlaceholderTarget::Extra(String::from("x")))
);
}
#[test]
fn the_vocabulary_refuses_a_substitution_on_a_base_reference() {
let vocabulary = PlaceholderVocabulary::new(1).with_body();
assert_eq!(
vocabulary.resolve("1", true, 0),
Err(PlaceholderProblem::SubstitutionNotAccepted)
);
assert_eq!(
vocabulary.resolve(BODY_REFERENCE, true, 0),
Err(PlaceholderProblem::SubstitutionNotAccepted)
);
assert_eq!(vocabulary.resolve(BODY_REFERENCE, false, 0), Ok(PlaceholderTarget::Body));
}
#[test]
fn the_vocabulary_reports_an_unknown_name_and_a_missing_body() {
let vocabulary = PlaceholderVocabulary::new(0);
assert_eq!(vocabulary.resolve("nope", false, 0), Err(PlaceholderProblem::UnknownName));
assert_eq!(vocabulary.resolve(BODY_REFERENCE, false, 0), Err(PlaceholderProblem::NoBody));
}
}