use std::sync::Arc;
use techy::core::node::{NodeRef, NodeTree};
use crate::core::lowering::{
DefaultMark, Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringDecl, LoweringRule,
chars_at_lowering,
};
use crate::core::plan::PlanCx;
use crate::core::registry::{BuildError, FeatureBuilder, FeatureInfo, FlmFeature};
use crate::core::run::RewriteCx;
use crate::core::stage::{Needs, RewriteDecl, RewriteError, RewriteStage, TreesTable};
use crate::lang::input::{is_placing, REFERENCE_ARGUMENT};
use crate::stdlib::backends::pres::SubtreePayload;
use crate::lang::mint::{ArgDef, ArgStdKind, ElementDef, SyntaxDef};
use crate::lang::rewrites::input::{SpliceFailure, splice};
use crate::lang::{Flm, FlmDiagnostics};
use crate::model::addr::TreeId;
use crate::model::aspects::{ApartFromText, BlockRole, BlockRoleAspect, ContentRef};
use crate::model::element::ElementSpec;
use crate::model::names::{ElementName, FeatureName, Name};
use crate::core::data::table::TableName;
use crate::stdlib::VALIDATED;
use crate::stdlib::backends::pres::{self, DroppedPayload};
use crate::stdlib::features::blocks::STRUCTURED;
use crate::stdlib::features::userdefs::{ALWAYS_EXPANDED, EXPANDED};
pub const FEATURE: &str = "input";
pub const ELEMENT: &str = "flm.input";
pub const SPLICE: &str = "flm.input.splice";
pub const SPLICED: TableName<TreesTable> = TableName::new("flm.input.spliced");
pub const RULE: &str = "flm.input.lower.default";
pub const PATH_ARG_ROLE: &str = "flm.input.path";
#[derive(Debug, Clone, Copy)]
struct InputText;
impl ApartFromText for InputText {
fn apart_from_text(&self, _node: &NodeRef<'_, Flm>) -> Vec<ContentRef> {
vec![ContentRef::ArgumentNamed(REFERENCE_ARGUMENT.to_string())]
}
}
#[derive(Debug, Clone, Copy)]
struct InputBlockRole;
impl BlockRoleAspect for InputBlockRole {
fn block_role(&self, node: &NodeRef<'_, Flm>) -> BlockRole {
if is_placing(node) { BlockRole::Block } else { BlockRole::DEFAULT }
}
}
fn element() -> Arc<ElementSpec> {
Arc::new(
ElementSpec::new(ELEMENT)
.docs(
"`\\input{file}`: the content of another file, brought in where the command \
is written.",
)
.with::<dyn BlockRoleAspect>(Arc::new(InputBlockRole))
.with::<dyn ApartFromText>(Arc::new(InputText)),
)
}
struct SpliceStage;
impl RewriteStage for SpliceStage {
fn decl(&self) -> RewriteDecl {
RewriteDecl::new(SPLICE, SPLICED.name()).docs(
"Replaces every `\\input` whose file was brought in by the file's content, in place \
of the command among its sibling nodes. Publishes the trees as \
`flm.input.spliced`; runs before the expansion of user definitions and before \
block structure.",
)
}
fn needs(&self, cx: &PlanCx<'_>) -> Needs {
let mut needs = Needs::new();
for later in [ALWAYS_EXPANDED.name(), EXPANDED.name(), STRUCTURED.name()] {
if cx.registry().cap_id(later).is_some() {
needs = needs.before(later);
}
}
needs
}
fn rewrite(
&self,
_tree_id: TreeId,
tree: &Arc<NodeTree<Flm>>,
cx: &RewriteCx<'_>,
_diags: &mut FlmDiagnostics,
) -> Result<Arc<NodeTree<Flm>>, RewriteError> {
splice(tree, cx.registry().lang().guard()).map_err(|failure| match failure {
SpliceFailure::NestingTooDeep(diagnostic) => RewriteError::NestingTooDeep(diagnostic),
SpliceFailure::Failed(diagnostic) | SpliceFailure::WorkerThread(diagnostic) => {
RewriteError::Failed(diagnostic)
}
})
}
}
#[derive(Debug, Default, Clone, Copy)]
pub struct InputRule;
impl Lower for InputRule {
fn lower(
&self,
node: NodeRef<'_, Flm>,
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
) -> Result<Lowering, LowerError> {
if is_placing(&node) {
if let Some(tree) = lw.placement() {
let subtree = lw.pres_with(cx, &ElementName::from(pres::SUBTREE), SubtreePayload { tree }, Vec::new())?;
return Ok(Lowering::Emit(vec![subtree]));
}
}
let reference = match node.argument_content_nodes_named(REFERENCE_ARGUMENT) {
Ok(Some(content)) => chars_at_lowering(content.iter())?.unwrap_or_default(),
_ => String::new(),
};
let mark = DroppedPayload {
condition: Name::from(ELEMENT),
detail: format!("\\input{{{reference}}}"),
};
let dropped = lw.pres_with(cx, &ElementName::from(pres::DROPPED), mark, Vec::new())?;
Ok(Lowering::Emit(vec![dropped]))
}
}
pub fn rule() -> LoweringRule {
LoweringRule::new(
RULE,
ELEMENT,
LoweringDecl::new().produces(pres::SUBTREE).produces(pres::DROPPED),
Arc::new(InputRule),
DefaultMark::Everywhere,
)
.docs(
"an `\\input` that places a heading input's tree lowers to a `flm.pres.subtree` node \
that gives the tree; one whose file was not brought in, to a `flm.pres.dropped` mark \
that gives the reference",
)
}
#[derive(Debug, Default, Clone, Copy)]
pub struct Input;
impl FlmFeature for Input {
fn info(&self) -> FeatureInfo {
FeatureInfo::new(FEATURE, "Included files").docs(
"`\\input{file}`: the content of another file, parsed where the command is written \
and put in place of the command by the rewrite `flm.input.splice`, which \
publishes `flm.input.spliced`.",
)
}
fn register(&self, b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
let owner: FeatureName = b.feature().clone();
b.argument_role(
PATH_ARG_ROLE,
"A reference to another file, usually its path, whose content is read in where \
the command is written.",
)?;
b.element(
ElementDef::new(
owner,
["input"],
SyntaxDef::Inclusion {
args: vec![ArgDef::named(REFERENCE_ARGUMENT, ArgStdKind::CharsGroup)
.docs(
"The reference to the file, as plain characters; the embedding \
program's input resolver finds the file it refers to.",
)
.role(PATH_ARG_ROLE)],
},
element(),
)
.docs("Brings in the content of another file where the command is written."),
)?;
b.element_type_text(
ELEMENT,
"The content of another file, brought in where the command that names the file is \
written.",
)?;
b.rewrite_stage(Arc::new(SpliceStage))?;
b.collection_member(VALIDATED, SPLICED.name())?;
b.lowering_rule(rule())?;
Ok(())
}
}
pub fn feature() -> Arc<dyn FlmFeature> {
Arc::new(Input)
}