use std::sync::Arc;
use techy::core::node::NodeRef;
use crate::lang::{Flm, FlmGroupType};
use crate::lang::mint::{
ArgDef, ArgLayout, BodyDef, BodyLayout, ElementDef, ScopedPackageDef, SyntaxDef, field_element,
};
use crate::model::aspects::{BlockRole, BlockRoleAspect, FixedBlockRole};
use crate::model::element::{ElementSpec, element_value};
use crate::model::names::{FeatureName, Name};
use crate::stdlib::backends::lowering::rules::owning_callable;
use super::config::{QuoteEnvironment, QuoteSection};
use super::{
CONTENT_ARG, INDENT_COMMAND, LINEBREAK_COMMAND, LINES_PACKAGE, QUOTE, SECTION,
sections_package,
};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct QuoteElement {
pub name: String,
pub environment: QuoteEnvironment,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SectionElement {
pub section: QuoteSection,
}
impl BlockRoleAspect for SectionElement {
fn block_role(&self, node: &NodeRef<'_, Flm>) -> BlockRole {
match section_position(node) {
Some(position) if position.quote.environment.holds_blocks() => BlockRole::Block,
_ => BlockRole::DEFAULT,
}
}
}
#[derive(Debug, Clone, Copy)]
pub(super) struct SectionPosition<'t> {
pub(super) section: QuoteSection,
pub(super) quote: &'t QuoteElement,
}
pub(super) fn section_position<'t>(node: &NodeRef<'t, Flm>) -> Option<SectionPosition<'t>> {
let section = element_value::<SectionElement>(node)?.section;
let quote = quote_of_body(node)?;
quote.environment.enables(section).then_some(SectionPosition { section, quote })
}
fn quote_of_body<'t>(node: &NodeRef<'t, Flm>) -> Option<&'t QuoteElement> {
owning_callable(node).and_then(|owner| element_value::<QuoteElement>(&owner))
}
pub(super) fn is_in_quote_body(node: &NodeRef<'_, Flm>) -> bool {
let place = match node.parent() {
Some(parent) if parent.group_type() == Some(FlmGroupType::Paragraph) => parent,
_ => *node,
};
quote_of_body(&place).is_some()
}
fn quote_element(name: &str, environment: &QuoteEnvironment) -> Arc<ElementSpec> {
Arc::new(
ElementSpec::new(QUOTE)
.docs(format!("`{name}`: a quote environment, a quotation set apart from the running text."))
.with::<dyn BlockRoleAspect>(Arc::new(FixedBlockRole(BlockRole::Block)))
.with_value(Arc::new(QuoteElement {
name: name.to_string(),
environment: environment.clone(),
})),
)
}
pub(super) fn environment_def(
owner: &FeatureName,
name: &str,
environment: &QuoteEnvironment,
) -> ElementDef {
let layout = if environment.holds_blocks() { BodyLayout::Blocks } else { BodyLayout::Inline };
let mut body = BodyDef::new().layout(layout);
if !environment.sections.is_empty() {
body = body.scoped(sections_package(name));
}
if environment.bare == Some(QuoteSection::Lines) {
body = body.scoped(LINES_PACKAGE);
}
let commands: Vec<String> =
environment.sections.iter().map(|section| format!("`\\{}`", section.as_str())).collect();
let docs = match (commands.is_empty(), environment.bare) {
(false, _) => format!(
"Writes a quotation set apart from the running text, whose quotation sections are \
written with {}.",
commands.join(", ")
),
(true, Some(kind)) => format!(
"Writes a quotation set apart from the running text, whose content is one {} section.",
kind.as_str()
),
(true, None) => String::from("Writes a quotation set apart from the running text."),
};
ElementDef::new(
owner.clone(),
[name],
SyntaxDef::Environment { args: Vec::new(), body },
quote_element(name, environment),
)
.docs(docs)
}
fn section_element(section: QuoteSection) -> Arc<ElementSpec> {
let value = Arc::new(SectionElement { section });
Arc::new(
ElementSpec::new(SECTION)
.docs(format!("`\\{}{{…}}`: a {} section of a quotation.", section.as_str(), section.as_str()))
.with::<dyn BlockRoleAspect>(Arc::clone(&value) as Arc<dyn BlockRoleAspect>)
.with_value(value),
)
}
fn section_def(owner: &FeatureName, section: QuoteSection, element: &Arc<ElementSpec>) -> ElementDef {
let mut content = ArgDef::mandatory(CONTENT_ARG);
let docs = match section {
QuoteSection::Text => "The quoted passage, one paragraph.",
QuoteSection::Lines => {
content = content.scoped(LINES_PACKAGE);
"The lines, each ended by `\\\\`; `\\indent` at the start of a line indents it by a \
tab."
}
QuoteSection::Attributed => "The attribution: an author, a source.",
QuoteSection::Block => {
content = content.layout(ArgLayout::InlineOrBlocks);
"Paragraphs and blocks; content written on one line is one paragraph."
}
};
let name = section.as_str();
ElementDef::new(
owner.clone(),
[name],
SyntaxDef::Macro { args: vec![content.docs(docs)] },
Arc::clone(element),
)
.docs(match section {
QuoteSection::Text => "Writes a quoted passage, a text section of the quotation around it.",
QuoteSection::Lines => "Writes a lines section of the quotation around it.",
QuoteSection::Attributed => "Writes the attribution of the quotation around it.",
QuoteSection::Block => "Writes a block section of the quotation around it.",
})
}
pub(super) fn sections_packages<'c>(
owner: &FeatureName,
environments: impl IntoIterator<Item = (&'c String, &'c QuoteEnvironment)>,
) -> Vec<ScopedPackageDef> {
let elements: Vec<(QuoteSection, Arc<ElementSpec>)> =
QuoteSection::ALL.into_iter().map(|section| (section, section_element(section))).collect();
environments
.into_iter()
.filter(|(_, environment)| !environment.sections.is_empty())
.map(|(name, environment)| {
let defs = environment
.sections
.iter()
.filter_map(|section| elements.iter().find(|(kind, _)| kind == section))
.map(|(section, element)| section_def(owner, *section, element))
.collect();
ScopedPackageDef {
owner: owner.clone(),
name: Name::from(sections_package(name)),
elements: defs,
docs: format!(
"The quotation-section commands available inside the body of the quote \
environment `{name}`."
),
}
})
.collect()
}
pub(super) fn lines_package(owner: &FeatureName) -> ScopedPackageDef {
let linebreak = ElementDef::new(
owner.clone(),
[LINEBREAK_COMMAND],
SyntaxDef::Macro { args: Vec::new() },
field_element(
"A `\\\\` inside a lines section of a quotation: the end of a line.",
),
)
.docs("Ends a line of the lines section.");
let indent = ElementDef::new(
owner.clone(),
[INDENT_COMMAND],
SyntaxDef::Macro { args: Vec::new() },
field_element(
"An `\\indent` at the start of a line of a lines section of a quotation: one tab of \
indentation for the line.",
),
)
.docs("Indents the line it starts by one tab; written several times, by as many tabs.");
ScopedPackageDef {
owner: owner.clone(),
name: Name::from(LINES_PACKAGE),
elements: vec![linebreak, indent],
docs: String::from(
"The commands available inside a lines section of a quotation: `\\\\`, which ends a \
line, and `\\indent`, which indents the line it starts.",
),
}
}