use std::any::Any;
use std::fmt;
use std::sync::Arc;
use techy::core::constructs::{
parse_declared_arguments, ChildStateSpec, ConstructParser, ConstructParserResult, Invocation,
ParseContext, PlainCharsError, StopSpec,
};
use techy::core::node::{
BuildId, ChildRegion, ContentNodes, NodeKind, NodeRef, ParsedArguments, ParsedSlot,
ParsedSlots, SlotRole,
};
use techy::core::specs::{ArgumentSpec, CallableSpec};
use techy::core::token::TokenEdge;
use techy::core::{ParseDriver, ParsingState, ParsingStateDelta};
use techy::error::{DiagnosticInfo, ParseError};
use techy::latexlike::BodyMarker;
use techy::serialize::SerializableObject;
use techy::source::SourceSpan;
use crate::lang::flm::Flm;
use crate::lang::mint::specs::FlmCallable;
use crate::lang::origin::{FlmOrigin, FlmSource, FlmSpan};
use crate::lang::rules::FlmParsing;
pub const REFERENCE_ARGUMENT: &str = "reference";
pub const ATTACHED_SLOT: &str = "attached";
pub const PLACED_SLOT: &str = "placed";
pub const DEPTH_LIMIT: usize = 32;
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct IncludedFile {
pub name: String,
pub text: String,
pub first_line: usize,
pub parsing: Option<FlmParsing>,
pub problems: Vec<IncludedFileProblem>,
pub heading: Option<InputHeading>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct InputHeading {
pub command: String,
pub title: String,
pub title_at: Option<(usize, usize)>,
pub label: Option<String>,
pub numbered: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IncludedFileProblem {
pub line: usize,
pub column: usize,
pub message: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InputError {
pub message: String,
}
impl InputError {
pub fn new(message: impl Into<String>) -> InputError {
InputError { message: message.into() }
}
}
impl fmt::Display for InputError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.message)
}
}
impl std::error::Error for InputError {}
pub trait InputResolver: Send + Sync {
fn resolve(
&self,
reference: &str,
including: Option<&str>,
parsing: &FlmParsing,
) -> Result<IncludedFile, InputError>;
}
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(
id = "flm.input.reference-not-plain",
message = "Invalid argument to ‘\\input’, expected plain text only"
)]
pub struct InputReferenceNotPlain;
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(
id = "flm.input.unavailable",
message = "Cannot process ‘\\input{{{reference}}}’: No input source resolver configured for this document"
)]
pub struct InputUnavailable {
pub reference: String,
}
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(
id = "flm.input.unreadable",
message = "Source input ‘{reference}’ nonexistent or unreadable: {detail}"
)]
pub struct InputUnreadable {
pub reference: String,
pub detail: String,
}
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(
id = "flm.input.includes-itself",
message = "Refusing recursive inclusion of ‘{file}’"
)]
pub struct InputIncludesItself {
pub file: String,
}
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(
id = "flm.input.too-deep",
message = "Input depth limit ({limit} levels) reached while processing inclusion of ‘{file}’"
)]
pub struct InputTooDeep {
pub limit: usize,
pub file: String,
}
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(
id = "flm.input.in-definition",
message = "‘\\input’ must not appear in the template or default argument values of a \
user-defined command or environment"
)]
pub struct InputInDefinition;
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(id = "flm.input.front-matter", message = "{message}")]
pub struct IncludedFrontMatterProblem {
pub message: String,
}
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(
id = "flm.input.placed-twice",
message = "Duplicate heading-mode inclusion of ‘{file}’"
)]
pub struct InputPlacedTwice {
pub file: String,
}
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(
id = "flm.input.heading-outside-document",
message = "Heading-mode inclusion of ‘{file}’ is only possible in a whole document"
)]
pub struct InputHeadingOutsideDocument {
pub file: String,
}
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(
id = "flm.input.placement-lost",
message = "Misconfigured input processing: The node of a heading-mode ‘\\input’ for ‘{file}’ was not found in the final document tree"
)]
pub struct InputPlacementLost {
pub file: String,
}
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(
id = "flm.input.heading-command",
message = "Invalid heading command ‘\\{command}’ configured for heading-mode input of ‘{file}’"
)]
pub struct InputHeadingCommandInvalid {
pub file: String,
pub command: String,
}
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(
id = "flm.input.heading-label",
message = "Invalid label ‘{label}’ specified in heading-mode inclusion of ‘{file}’"
)]
pub struct InputHeadingLabelInvalid {
pub file: String,
pub label: String,
}
#[derive(Debug, Clone)]
pub(crate) struct PlacedInput {
pub(crate) site: FlmSpan,
pub(crate) name: String,
pub(crate) source: Arc<FlmSource>,
pub(crate) heading: InputHeading,
pub(crate) state: Arc<ParsingState<Flm>>,
}
#[derive(Debug, Default)]
pub(crate) struct Placements {
records: std::sync::Mutex<Vec<PlacedInput>>,
}
impl Placements {
fn lock(&self) -> std::sync::MutexGuard<'_, Vec<PlacedInput>> {
self.records.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
}
pub(crate) fn len(&self) -> usize {
self.lock().len()
}
pub(crate) fn range(&self, from: usize, to: usize) -> Vec<PlacedInput> {
self.lock().get(from..to).map(<[PlacedInput]>::to_vec).unwrap_or_default()
}
fn record(&self, placed: PlacedInput) -> bool {
let mut records = self.lock();
if records.iter().any(|known| known.name == placed.name) {
return false;
}
records.push(placed);
true
}
}
pub(crate) fn heading_source(placed: &PlacedInput) -> Arc<FlmSource> {
let heading = &placed.heading;
let star = if heading.numbered { "" } else { "*" };
let mut text = format!("\\{}{star}\n{{{}}}", heading.command, heading.title);
if let Some(label) = &heading.label {
text.push_str(&format!("\\label{{{label}}}"));
}
text.push('\n');
let (line, column) = match heading.title_at {
Some((line, column)) => (line.saturating_sub(1), column.saturating_sub(1)),
None => (1, 1),
};
let source = FlmSource::resolved(text, placed.name.as_str(), placed.site.clone())
.with_origin(FlmOrigin::new(placed.name.clone()))
.with_line_column_number_offsets(line, column);
Arc::new(source)
}
fn is_command_name(state: &ParsingState<Flm>, name: &str) -> bool {
!name.is_empty()
&& state
.rules()
.command_rules()
.iter()
.any(|rule| rule.escape_char == '\\' && name.chars().all(|c| rule.name_chars.contains(c)))
}
pub(crate) struct PlacedRoot {
pub(crate) heading: Arc<FlmSource>,
}
impl ConstructParser<Flm> for PlacedRoot {
type Output = BuildId;
fn parse(
&mut self,
cx: &mut ParseContext<'_, '_, Flm>,
) -> ConstructParserResult<Flm, (BuildId, Option<Box<ParsingStateDelta<Flm>>>)> {
let entry = Arc::clone(&cx.state);
let source = Arc::clone(cx.here().source());
let driver = cx.driver;
let mut parser = driver
.make_nodes_parser(StopSpec::none(), ChildStateSpec::inherit())
.map_err(|error| cx.attach_hook_frames(error))?;
let mut nodes = cx.parse_attached_source(Arc::clone(&self.heading), Arc::clone(&entry), &mut *parser)?.nodes;
nodes.extend(cx.parse_attached_source(Arc::clone(&source), Arc::clone(&entry), &mut *parser)?.nodes);
let whole = SourceSpan::entire(&source);
let root = cx
.stage_node(NodeKind::list(), whole.clone(), entry, nodes)
.map_err(|error| cx.implementation_error(error, whole))?;
Ok((root, None))
}
}
#[derive(Debug)]
pub struct InputSpec {
arguments: Vec<Arc<ArgumentSpec<Flm>>>,
}
impl InputSpec {
pub fn new(arguments: Vec<Arc<ArgumentSpec<Flm>>>) -> Result<InputSpec, String> {
if arguments.iter().any(|argument| argument.name.as_deref() == Some(REFERENCE_ARGUMENT)) {
return Ok(InputSpec { arguments });
}
let names: Vec<String> = arguments
.iter()
.map(|argument| argument.name.as_deref().map_or_else(|| String::from("<unnamed>"), |n| format!("‘{n}’")))
.collect();
Err(if names.is_empty() {
String::from("no argument declared")
} else {
format!("declared arguments: {}", names.join(", "))
})
}
}
impl SerializableObject<Flm> for InputSpec {}
impl CallableSpec<Flm> for InputSpec {
fn arguments(&self) -> &[Arc<ArgumentSpec<Flm>>] {
&self.arguments
}
fn make_invocation_parser<'a>(
&'a self,
invocation: Invocation<'a, Flm>,
) -> Result<Box<dyn ConstructParser<Flm, Output = BuildId> + 'a>, ParseError<FlmOrigin>> {
Ok(Box::new(InputParser { invocation }))
}
}
pub fn is_input(node: &NodeRef<'_, Flm>) -> bool {
let Some(spec) = node.spec() else { return false };
(&**spec as &dyn Any)
.downcast_ref::<FlmCallable>()
.is_some_and(|callable| (&**callable.syntax() as &dyn Any).is::<InputSpec>())
}
pub fn is_placing(node: &NodeRef<'_, Flm>) -> bool {
is_input(node) && node.slot_content_nodes_named(PLACED_SLOT).is_ok()
}
pub fn attached_content<'t>(node: &NodeRef<'t, Flm>) -> Option<Vec<NodeRef<'t, Flm>>> {
if !is_input(node) {
return None;
}
node.slot_content_nodes_named(ATTACHED_SLOT).ok().map(|nodes| nodes.iter().collect())
}
struct InputParser<'a> {
invocation: Invocation<'a, Flm>,
}
impl ConstructParser<Flm> for InputParser<'_> {
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 = cx.tokens.source_span_between(token, TokenEdge::Start, TokenEdge::End);
let (mut children, arguments) = parse_declared_arguments(cx, self.invocation.spec, &name)?;
let end = cx.tokens.position_here();
let at = cx.source_span_within(&cx.tokens.position_at(token, TokenEdge::Start), &end)?;
let reference_argument = arguments
.iter()
.find(|argument| argument.name() == Some(REFERENCE_ARGUMENT))
.ok_or_else(|| {
cx.implementation_error("an inclusion macro without a reference argument", at.clone())
})?;
let reference = match cx.argument_content_as_plain_chars(reference_argument, &children) {
Ok(text) => text,
Err(PlainCharsError::NotPlainCharacters { .. }) => {
cx.recover(InputReferenceNotPlain, at.clone())?;
None
}
Err(error) => return Err(cx.implementation_error(error.to_string(), at.clone())),
};
let attached = match reference {
Some(reference) => attach(cx, &reference, &at)?,
None => Attached::Nothing,
};
let slots = match attached {
Attached::Placed => {
let offset = children.len() as u32;
ParsedSlots::new(vec![ParsedSlot::new(
ChildRegion::new(offset..offset, ContentNodes::InRegion(0..0)),
PLACED_SLOT,
SlotRole::Hidden,
BodyMarker::not_body(),
)])
}
Attached::Content(nodes) => {
let offset = children.len() as u32;
let count = nodes.len() as u32;
children.extend(nodes);
ParsedSlots::new(vec![ParsedSlot::new(
ChildRegion::new(offset..offset + count, ContentNodes::InRegion(0..count)),
ATTACHED_SLOT,
SlotRole::Attached,
BodyMarker::not_body(),
)])
}
Attached::Nothing => ParsedSlots::empty(),
};
let id = cx.stage_invocation(
&self.invocation,
ParsedArguments::from(arguments),
slots,
children,
Some(&end),
)?;
Ok((id, None))
}
}
enum Attached {
Content(Vec<BuildId>),
Placed,
Nothing,
}
fn attach(
cx: &mut ParseContext<'_, '_, Flm>,
reference: &str,
at: &FlmSpan,
) -> ConstructParserResult<Flm, Attached> {
let including = at.source().origin();
if including.is_definition() {
cx.recover(InputInDefinition, at.clone())?;
return Ok(Attached::Nothing);
}
let driver = cx.driver;
let Some(resolver) = driver.input_resolver() else {
cx.recover(InputUnavailable { reference: reference.to_string() }, at.clone())?;
return Ok(Attached::Nothing);
};
let in_force = Arc::clone(&cx.state.ext().parsing);
let file = match resolver.resolve(reference, including.canonical_path(), &in_force) {
Ok(file) => file,
Err(error) => {
let condition =
InputUnreadable { reference: reference.to_string(), detail: error.message };
cx.recover(condition, at.clone())?;
return Ok(Attached::Nothing);
}
};
let mut depth = 0;
for source in at.source().including_sources() {
if source.origin().canonical_path() == Some(file.name.as_str()) {
cx.recover(InputIncludesItself { file: file.name.clone() }, at.clone())?;
return Ok(Attached::Nothing);
}
depth += 1;
}
if depth > DEPTH_LIMIT {
cx.recover(InputTooDeep { limit: DEPTH_LIMIT, file: file.name.clone() }, at.clone())?;
return Ok(Attached::Nothing);
}
for problem in &file.problems {
let place = FlmSource::resolved(String::new(), reference, at.clone())
.with_origin(FlmOrigin::new(file.name.clone()))
.with_line_column_number_offsets(problem.line, problem.column);
let condition = IncludedFrontMatterProblem { message: problem.message.clone() };
cx.recover(condition, SourceSpan::new(&Arc::new(place), 0..0))?;
}
let source = FlmSource::resolved(file.text, reference, at.clone())
.with_origin(FlmOrigin::new(file.name.clone()))
.with_line_column_number_offsets(file.first_line.max(1), 1);
let name = file.name;
let state: Arc<ParsingState<Flm>> = match file.parsing {
Some(parsing) => {
let ext = cx.state.ext().clone().with_parsing(parsing.clone());
cx.derive_state(&parsing.state_delta().ext(ext))?
}
None => Arc::clone(&cx.state),
};
let source = Arc::new(source);
if let Some(mut heading) = file.heading {
let Some(placements) = driver.placements() else {
cx.recover(InputHeadingOutsideDocument { file: name }, at.clone())?;
return Ok(Attached::Nothing);
};
if !is_command_name(&cx.state, &heading.command) {
cx.recover(InputHeadingCommandInvalid { file: name, command: heading.command }, at.clone())?;
return Ok(Attached::Nothing);
}
if let Some(label) = heading.label.take_if(|label| label.contains(['{', '}'])) {
cx.recover(InputHeadingLabelInvalid { file: name.clone(), label }, at.clone())?;
}
let placed = PlacedInput { site: at.clone(), name: name.clone(), source, heading, state };
if placements.record(placed) {
return Ok(Attached::Placed);
}
cx.recover(InputPlacedTwice { file: name }, at.clone())?;
return Ok(Attached::Nothing);
}
let mut parser = driver
.make_nodes_parser(StopSpec::none(), ChildStateSpec::inherit())
.map_err(|error| cx.attach_hook_frames(error))?;
let outcome = cx.parse_attached_source(source, state, &mut *parser)?;
Ok(Attached::Content(outcome.nodes))
}