pub mod latex;
use std::sync::Arc;
use techy::core::node::NodeRef;
use crate::model::aspects::{BlockRole, BlockRoleAspect, FixedBlockRole};
use crate::model::element::{ElementSpec, element_value};
use crate::core::lowering::{
DefaultMark, Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringDecl, LoweringRule,
};
use crate::model::names::{ElementName, FeatureName, Name};
use crate::core::registry::{BuildError, FeatureBuilder, FeatureInfo, FlmFeature};
use crate::lang::mint::{ArgDef, ArgStdKind, BodyDef, ElementDef, SyntaxDef};
use crate::lang::text::is_space;
use crate::lang::{Flm, FlmGroupType};
use crate::stdlib::backends::lowering::{copy_subtree_verbatim, stage_verbatim_content};
use crate::stdlib::backends::pres::{
self, VerbatimDisplay, VerbatimKind, VerbatimPayload, plain_text,
};
pub const FEATURE: &str = "verbatim";
pub const MACRO: &str = "flm.verbatim.macro";
pub const ENVIRONMENT: &str = "flm.verbatim.environment";
pub const MACRO_RULE: &str = "flm.verbatim.macro.lower.default";
pub const ENVIRONMENT_RULE: &str = "flm.verbatim.environment.lower.default";
pub const CONTENT_ARG: &str = "content";
pub const LANG_ARG: &str = "lang";
pub const MACROS: [(&str, VerbatimKind, bool); 3] = [
("verbtext", VerbatimKind::Text, false),
("verbcode", VerbatimKind::Code, true),
("verba", VerbatimKind::Identifier, true),
];
pub const ENVIRONMENTS: [(&str, VerbatimKind, bool, bool); 2] = [
("verbatimtext", VerbatimKind::Text, false, false),
("verbatimcode", VerbatimKind::Code, true, true),
];
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VerbatimCallable {
pub name: Name,
pub kind: VerbatimKind,
pub lang_arg: bool,
pub block: bool,
}
fn macro_element(name: &str, kind: VerbatimKind, lang_arg: bool) -> Arc<ElementSpec> {
Arc::new(
ElementSpec::new(MACRO)
.docs(format!("`\\{name}`: inline verbatim content of kind `{kind}`."))
.with::<dyn BlockRoleAspect>(Arc::new(FixedBlockRole(BlockRole::DEFAULT)))
.with_value(Arc::new(VerbatimCallable {
name: Name::from(name),
kind,
lang_arg,
block: false,
})),
)
}
fn environment_element(
name: &str,
kind: VerbatimKind,
lang_arg: bool,
block: bool,
) -> Arc<ElementSpec> {
let role = if block { BlockRole::Block } else { BlockRole::DEFAULT };
Arc::new(
ElementSpec::new(ENVIRONMENT)
.docs(format!(
"`\\begin{{{name}}}…\\end{{{name}}}`: verbatim content of kind `{kind}`."
))
.with::<dyn BlockRoleAspect>(Arc::new(FixedBlockRole(role)))
.with_value(Arc::new(VerbatimCallable {
name: Name::from(name),
kind,
lang_arg,
block,
})),
)
}
fn macro_args(lang_arg: bool) -> Vec<ArgDef> {
let mut args = Vec::new();
if lang_arg {
args.push(language_argument());
}
args.push(
ArgDef::named(CONTENT_ARG, ArgStdKind::Verbatim { delimiters: None }).docs(
"The content, shown exactly as written. The first character after the command \
opens the region, and its partner closes it (`}` for `{`, `]` for `[`, `>` for \
`<`, `)` for `(`, nested pairs counted; the same character for any other).",
),
);
args
}
fn language_argument() -> ArgDef {
ArgDef::optional(LANG_ARG).docs(
"The programming language the content is written in. A backend that highlights \
syntax may use it; the text backend does not print it.",
)
}
pub(super) fn language_of(node: &NodeRef<'_, Flm>) -> Option<String> {
let content = node.argument_content_nodes_named(LANG_ARG).ok()??;
let text = plain_text(content.iter()).trim_matches(is_space).to_string();
(!text.is_empty()).then_some(text)
}
fn kind_and_display(
node: &NodeRef<'_, Flm>,
) -> Result<(VerbatimKind, VerbatimDisplay), LowerError> {
let value = element_value::<VerbatimCallable>(node)
.ok_or_else(|| LowerError::structure("a verbatim node without its value"))?;
let display =
if value.block { VerbatimDisplay::Block } else { VerbatimDisplay::Inline };
Ok((value.kind, display))
}
#[derive(Debug, Default)]
pub struct MacroRule;
impl Lower for MacroRule {
fn lower(
&self,
node: NodeRef<'_, Flm>,
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
) -> Result<Lowering, LowerError> {
let (kind, display) = kind_and_display(&node)?;
let lang = language_of(&node);
let body = match node.argument_content_nodes_named(CONTENT_ARG) {
Ok(Some(content)) => stage_verbatim_content(&node, content, cx, lw)?,
_ => Vec::new(),
};
let payload = VerbatimPayload { kind, display, lang };
let verbatim = lw.pres_with(cx, &ElementName::from(pres::VERBATIM), payload, body)?;
Ok(Lowering::Emit(vec![verbatim]))
}
}
#[derive(Debug, Default)]
pub struct EnvironmentRule;
impl Lower for EnvironmentRule {
fn lower(
&self,
node: NodeRef<'_, Flm>,
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
) -> Result<Lowering, LowerError> {
let (kind, display) = kind_and_display(&node)?;
let lang = language_of(&node);
let mut body = Vec::new();
if let Some(content) = node.body() {
for child in content.iter() {
if child.group_type() == Some(FlmGroupType::Verbatim) {
body.extend(stage_verbatim_content(&node, child.children(), cx, lw)?);
} else {
body.push(copy_subtree_verbatim(cx, child)?);
}
}
}
let payload = VerbatimPayload { kind, display, lang };
let verbatim = lw.pres_with(cx, &ElementName::from(pres::VERBATIM), payload, body)?;
Ok(Lowering::Emit(vec![verbatim]))
}
}
#[derive(Debug, Default, Clone, Copy)]
pub struct Verbatim;
impl FlmFeature for Verbatim {
fn info(&self) -> FeatureInfo {
FeatureInfo::new(FEATURE, "Verbatim content").docs(
"Content shown exactly as written: the macros `\\verbtext`, `\\verbcode` and \
`\\verba` and the environments `verbatimtext` and `verbatimcode`, each lowered to \
a `flm.pres.verbatim` node that carries its verbatim kind and its language.",
)
}
fn register(&self, b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
let owner: FeatureName = b.feature().clone();
for (name, kind, lang_arg) in MACROS {
b.element(
ElementDef::new(
owner.clone(),
[name],
SyntaxDef::Macro { args: macro_args(lang_arg) },
macro_element(name, kind, lang_arg),
)
.docs(format!(
"Shows inline content of the verbatim kind `{kind}` exactly as written, \
between a delimiter character and its partner."
)),
)?;
}
for (name, kind, lang_arg, block) in ENVIRONMENTS {
let args = if lang_arg { vec![language_argument()] } else { Vec::new() };
b.element(
ElementDef::new(
owner.clone(),
[name],
SyntaxDef::Environment { args, body: BodyDef::new().verbatim() },
environment_element(name, kind, lang_arg, block),
)
.docs(format!(
"Shows its body, content of the verbatim kind `{kind}`, exactly as written, \
{}.",
if block { "as a block of its own" } else { "inline" }
)),
)?;
}
b.element_type_text(
MACRO,
"Inline content shown exactly as written, written with a macro between a delimiter \
character and its partner; its verbatim kind (text, code or identifier) says what \
the content is.",
)?;
b.element_type_text(
ENVIRONMENT,
"Content shown exactly as written, written as the body of an environment; its \
verbatim kind (text or code) says what the content is.",
)?;
b.lowering_rule(
LoweringRule::new(
MACRO_RULE,
MACRO,
LoweringDecl::new().produces(pres::VERBATIM),
Arc::new(MacroRule),
DefaultMark::Everywhere,
)
.docs(
"a verbatim macro lowers to an inline `flm.pres.verbatim` node carrying its \
verbatim kind and language, over the characters of its content argument",
),
)?;
b.lowering_rule(
LoweringRule::new(
ENVIRONMENT_RULE,
ENVIRONMENT,
LoweringDecl::new().produces(pres::VERBATIM),
Arc::new(EnvironmentRule),
DefaultMark::Everywhere,
)
.docs(
"a verbatim environment lowers to a `flm.pres.verbatim` node carrying its \
verbatim kind, display and language, over the characters of its body",
),
)?;
latex::register(b)?;
Ok(())
}
}
pub fn feature() -> Arc<dyn FlmFeature> {
Arc::new(Verbatim)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_declared_callables_are_pythons_five() {
let macros: Vec<&str> = MACROS.iter().map(|(name, _, _)| *name).collect();
assert_eq!(macros, ["verbtext", "verbcode", "verba"]);
let environments: Vec<&str> = ENVIRONMENTS.iter().map(|(name, _, _, _)| *name).collect();
assert_eq!(environments, ["verbatimtext", "verbatimcode"]);
}
#[test]
fn only_the_code_environment_is_a_block() {
let element = environment_element("verbatimcode", VerbatimKind::Code, true, true);
assert_eq!(element.name, ENVIRONMENT);
let value = element.value_as::<VerbatimCallable>().expect("valued");
assert!(value.block);
let text = environment_element("verbatimtext", VerbatimKind::Text, false, false);
assert!(!text.value_as::<VerbatimCallable>().expect("valued").block);
}
#[test]
fn a_macro_takes_its_language_argument_before_its_content() {
let named: Vec<Option<String>> =
macro_args(true).iter().map(|arg| arg.name.clone()).collect();
assert_eq!(named, [Some(String::from(LANG_ARG)), Some(String::from(CONTENT_ARG))]);
let plain: Vec<Option<String>> =
macro_args(false).iter().map(|arg| arg.name.clone()).collect();
assert_eq!(plain, [Some(String::from(CONTENT_ARG))]);
}
}