use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;
use techy::error::{Diagnostic, DiagnosticInfo, DiagnosticValue, ToDiagnosticValue};
use techy::serialize::SerialValue;
use crate::core::data::store::StageOut;
use crate::core::data::table::{
PieceClass, ProjectCx, SingletonTable, Table, TableHandle, TableName,
};
use crate::core::plan::PlanCx;
use crate::core::registry::{
BuildError, DefContent, DefinitionText, FeatureBuilder, FlmRegistry, StyleDef,
};
use crate::core::run::StageCx;
use crate::core::stage::{Effect, Needs, Scope, Stage, StageDecl};
use crate::lang::{FlmOrigin, nowhere};
use crate::model::names::{CapName, FeatureName, Name};
use super::conventions::{
STYLE_CORE, STYLE_ERRORS, STYLE_HEADINGS, STYLE_LISTS, STYLE_MATH_PASSTHROUGH, STYLE_VERBATIM,
};
use super::emit::NOWHERE_LABEL;
use super::feature::{DefinitionOverride, HtmlRenderOptions};
use super::mathjax::mathjax_script;
use super::stages::{OUTPUT_TABLE, PIECES_TABLE, stage_failed};
pub const RESOLVE_STAGE: &str = "flm.html.resolve-definitions";
pub const DEFINITIONS_TABLE: TableName<ResolvedDefinitions> =
TableName::new("flm.html.definitions");
pub const STYLE_PAGE: &str = "flm.html.style.page";
const STYLESHEETS: [(&str, &str, &str); 7] = [
(
STYLE_CORE,
include_str!("css/core.css"),
"paragraphs, blocks, the display styles of a span, links, images and the three \
decorations",
),
(STYLE_HEADINGS, include_str!("css/headings.css"), "the six heading sizes"),
(
STYLE_VERBATIM,
include_str!("css/verbatim.css"),
"content set character for character, inline and as a block",
),
(
STYLE_MATH_PASSTHROUGH,
include_str!("css/math-passthrough.css"),
"a displayed formula, and content written inside a formula",
),
(
STYLE_LISTS,
include_str!("css/lists.css"),
"lists with their entries and labels, and a run of lines with its alignment",
),
(
STYLE_ERRORS,
include_str!("css/errors.css"),
"what the page shows where the document asked for something that could not be \
produced",
),
(
STYLE_PAGE,
include_str!("css/page.css"),
"the page's own typography and the width the content is held to; required by the \
page this backend assembles and by no element",
),
];
pub fn stylesheets() -> Vec<StyleDef> {
STYLESHEETS
.iter()
.map(|(id, text, docs)| StyleDef {
id: Name::from(*id),
content: vec![DefContent::Inline(String::from(*text))],
docs: String::from(*docs),
})
.collect()
}
pub fn register(b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
for style in stylesheets() {
b.style_def(style)?;
}
b.script_def(mathjax_script())?;
b.table(
DEFINITIONS_TABLE,
"the stylesheets and scripts the page requires, each with how it is delivered",
)?;
b.stage(Arc::new(ResolveDefinitionsStage))?;
Ok(())
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum DefinitionKind {
Style,
Script,
}
impl DefinitionKind {
pub fn as_str(self) -> &'static str {
match self {
DefinitionKind::Style => "style",
DefinitionKind::Script => "script",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolvedDefinition {
pub id: Name,
pub kind: DefinitionKind,
pub owner: FeatureName,
pub delivery: DefinitionOverride,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ResolvedDefinitions {
pub definitions: Vec<ResolvedDefinition>,
}
impl ResolvedDefinitions {
pub fn get(&self, id: &str) -> Option<&ResolvedDefinition> {
self.definitions.iter().find(|definition| definition.id.as_str() == id)
}
pub fn of_kind(&self, kind: DefinitionKind) -> impl Iterator<Item = &ResolvedDefinition> {
self.definitions.iter().filter(move |definition| definition.kind == kind)
}
}
impl Table for ResolvedDefinitions {
fn absorb(&mut self, piece: ResolvedDefinitions) {
if !piece.definitions.is_empty() {
self.definitions = piece.definitions;
}
}
fn project(&self, _cx: &dyn ProjectCx) -> SerialValue {
SerialValue::List(
self.definitions
.iter()
.map(|definition| {
let (provided, parts) = match &definition.delivery {
DefinitionOverride::ProvidedByHost => (true, Vec::new()),
DefinitionOverride::Parts(parts) => (false, parts.clone()),
};
SerialValue::Map(vec![
(String::from("id"), SerialValue::Str(definition.id.to_string())),
(
String::from("kind"),
SerialValue::Str(String::from(definition.kind.as_str())),
),
(String::from("owner"), SerialValue::Str(definition.owner.to_string())),
(String::from("provided_by_host"), SerialValue::Bool(provided)),
(
String::from("parts"),
SerialValue::List(parts.iter().map(project_part).collect()),
),
])
})
.collect(),
)
}
fn piece_class(&self) -> PieceClass {
if self.definitions.is_empty() { PieceClass::Empty } else { PieceClass::DocumentFact }
}
}
impl SingletonTable for ResolvedDefinitions {
const NAME: &'static str = "flm.html.definitions";
}
fn project_part(part: &DefContent) -> SerialValue {
let (key, value) = match part {
DefContent::Inline(text) => ("inline", text.clone()),
DefContent::File(path) => ("file", path.clone()),
DefContent::Url(address) => ("url", address.clone()),
DefContent::Table(table) => ("table", table.to_string()),
};
SerialValue::Map(vec![(String::from(key), SerialValue::Str(value))])
}
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(
id = "flm.html.unknown-requirement",
message = "the HTML page requires the stylesheet or script `{definition}` (for the document's \
content, for the page itself, or through the render option \
`required_definitions`), but no registered feature declares a stylesheet or \
script with that identifier"
)]
pub struct UnknownRequirement {
pub definition: String,
}
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(
id = "flm.html.unknown-definition",
message = "the render option `definitions` lists `{definition}`, but no registered feature \
declares a stylesheet or script with that identifier"
)]
pub struct UnknownDefinition {
pub definition: String,
}
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(
id = "flm.html.definition-part-missing",
message = "the {kind} `{definition}` takes a part from the table `{table}`, but {condition}"
)]
pub struct DefinitionPartMissing {
pub kind: String,
pub definition: String,
pub table: String,
pub condition: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum NotInlinablePart {
File {
path: String,
},
ClosingTag {
tag: String,
at: usize,
},
Table {
table: String,
},
}
impl NotInlinablePart {
pub fn kind(&self) -> &'static str {
match self {
NotInlinablePart::File { .. } => "file",
NotInlinablePart::ClosingTag { .. } => "closing-tag",
NotInlinablePart::Table { .. } => "table",
}
}
}
impl std::fmt::Display for NotInlinablePart {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
NotInlinablePart::File { path } => {
write!(
f,
"the part is the file `{path}`, and this library does not read files; in the \
render option `definitions`, give the file's content as text, or an address \
the page loads, or mark the stylesheet or script as provided by the host's \
own page"
)
}
NotInlinablePart::ClosingTag { tag, at } => write!(
f,
"the part's text contains the closing tag `</{tag}` (in any letter case) at byte \
{at}, which would end the `<{tag}>` element it is written into"
),
NotInlinablePart::Table { table } => write!(
f,
"the part must be the text of the table `{table}`, and only the stage that \
resolves the page's stylesheets and scripts reads that table"
),
}
}
}
impl ToDiagnosticValue for NotInlinablePart {
fn to_diagnostic_value(&self) -> DiagnosticValue {
let mut fields = vec![(String::from("kind"), self.kind().to_diagnostic_value())];
match self {
NotInlinablePart::File { path } => {
fields.push((String::from("path"), path.to_diagnostic_value()));
}
NotInlinablePart::ClosingTag { tag, at } => {
fields.push((String::from("tag"), tag.to_diagnostic_value()));
fields.push((String::from("at"), at.to_diagnostic_value()));
}
NotInlinablePart::Table { table } => {
fields.push((String::from("table"), table.to_diagnostic_value()));
}
}
DiagnosticValue::Map(fields)
}
}
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(
id = "flm.html.definition-not-inlinable",
message = "a part of the stylesheet or script `{definition}` cannot be written into the \
page: {part}"
)]
pub struct DefinitionNotInlinable {
pub definition: String,
pub part: NotInlinablePart,
}
fn part_tables(registry: &FlmRegistry) -> Vec<CapName> {
let parts = registry
.styles()
.iter()
.flat_map(|(_, style)| &style.content)
.chain(registry.scripts().iter().flat_map(|(_, script)| &script.content));
let mut tables: Vec<CapName> = Vec::new();
for part in parts {
if let DefContent::Table(table) = part {
if !tables.contains(table) {
tables.push(table.clone());
}
}
}
tables
}
fn resolve_part(
cx: &StageCx<'_>,
out: &mut StageOut<'_>,
kind: DefinitionKind,
definition: &str,
part: &DefContent,
) -> DefContent {
let DefContent::Table(table) = part else { return part.clone() };
let found = match cx.get(TableHandle::<DefinitionText>::new(table.clone())) {
Ok(found) => found.map(|found| found.text.clone()),
Err(error) => {
stage_failed(out, RESOLVE_STAGE, error);
return DefContent::Inline(String::new());
}
};
let condition = match &found {
None => String::from("no stage wrote that table"),
Some(text) if text.is_empty() => format!("the table `{table}` holds no text"),
Some(_) => String::new(),
};
if !condition.is_empty() {
let kind = match kind {
DefinitionKind::Style => "stylesheet",
DefinitionKind::Script => "script",
};
out.diags.push(Diagnostic::error(
DefinitionPartMissing {
kind: String::from(kind),
definition: definition.to_string(),
table: table.to_string(),
condition,
},
nowhere(FlmOrigin::synthetic(NOWHERE_LABEL)),
));
}
DefContent::Inline(found.unwrap_or_default())
}
fn chosen_registrations<'r>(
registry: &FlmRegistry,
registrations: impl Iterator<Item = (&'r FeatureName, &'r str)>,
) -> BTreeSet<usize> {
let mut chosen: BTreeMap<&str, (Option<usize>, usize)> = BTreeMap::new();
for (index, (owner, id)) in registrations.enumerate() {
let position = registry.feature_position(owner);
match chosen.get(id) {
Some((best, _)) if position <= *best => {}
_ => {
chosen.insert(id, (position, index));
}
}
}
chosen.into_values().map(|(_, index)| index).collect()
}
#[derive(Debug, Default, Clone, Copy)]
pub struct ResolveDefinitionsStage;
impl Stage for ResolveDefinitionsStage {
fn decl(&self) -> StageDecl {
StageDecl::new(RESOLVE_STAGE, Effect::Compute, Scope::Document)
.writes(DEFINITIONS_TABLE)
.docs(
"resolves the stylesheets and scripts that the document's trees and pieces \
required, the ones the host requires, and the host's deliveries, into \
`flm.html.definitions`",
)
}
fn needs(&self, cx: &PlanCx<'_>) -> Needs {
let mut needs =
Needs::new().reads(OUTPUT_TABLE).reads(PIECES_TABLE).option::<HtmlRenderOptions>();
for table in part_tables(cx.registry()) {
needs = needs.reads_opt(TableHandle::<DefinitionText>::new(table));
}
needs
}
fn run(&self, cx: &StageCx<'_>, out: &mut StageOut<'_>) {
let fragments = match cx.get(OUTPUT_TABLE) {
Ok(Some(fragments)) => fragments,
Ok(None) => return,
Err(error) => return stage_failed(out, RESOLVE_STAGE, error),
};
let pieces = match cx.get(PIECES_TABLE) {
Ok(pieces) => pieces,
Err(error) => return stage_failed(out, RESOLVE_STAGE, error),
};
let options = match cx.option::<HtmlRenderOptions>() {
Ok(options) => options,
Err(error) => return stage_failed(out, RESOLVE_STAGE, error),
};
let mut required: BTreeSet<Name> = options.required_definitions.clone();
for fragment in fragments.trees.values() {
required.extend(fragment.requires.iter().cloned());
}
for piece in pieces.iter().flat_map(|pieces| &pieces.pieces) {
required.extend(piece.fragment.requires.iter().cloned());
}
required.insert(Name::from(STYLE_PAGE));
let registry = cx.registry();
let mut declared: BTreeMap<&str, (DefinitionKind, &FeatureName, &Vec<DefContent>)> =
BTreeMap::new();
let mut order: Vec<&str> = Vec::new();
let styles = chosen_registrations(registry, registry.styles().iter().map(|(owner, style)| (owner, style.id.as_str())));
for (index, (owner, style)) in registry.styles().iter().enumerate() {
if styles.contains(&index) {
declared.insert(style.id.as_str(), (DefinitionKind::Style, owner, &style.content));
order.push(style.id.as_str());
}
}
let scripts = chosen_registrations(registry, registry.scripts().iter().map(|(owner, script)| (owner, script.id.as_str())));
for (index, (owner, script)) in registry.scripts().iter().enumerate() {
if scripts.contains(&index) && !declared.contains_key(script.id.as_str()) {
declared
.insert(script.id.as_str(), (DefinitionKind::Script, owner, &script.content));
order.push(script.id.as_str());
}
}
for id in options.definitions.keys() {
if !declared.contains_key(id.as_str()) {
out.diags.push(Diagnostic::warning(
UnknownDefinition { definition: id.to_string() },
nowhere(FlmOrigin::synthetic(NOWHERE_LABEL)),
));
}
}
for id in &required {
if !declared.contains_key(id.as_str()) {
out.diags.push(Diagnostic::error(
UnknownRequirement { definition: id.to_string() },
nowhere(FlmOrigin::synthetic(NOWHERE_LABEL)),
));
}
}
let mut resolved = ResolvedDefinitions::default();
for id in order {
if !required.contains(&Name::from(id)) {
continue;
}
let (kind, owner, content) = &declared[id];
let name = Name::from(id);
let delivery = match options.definitions.get(&name) {
Some(over) => over.clone(),
None => DefinitionOverride::Parts(
content.iter().map(|part| resolve_part(cx, out, *kind, id, part)).collect(),
),
};
resolved.definitions.push(ResolvedDefinition {
id: name,
kind: *kind,
owner: (*owner).clone(),
delivery,
});
}
resolved.definitions.sort_by_key(|definition| definition.kind);
match out.table(DEFINITIONS_TABLE) {
Ok(table) => *table = resolved,
Err(error) => stage_failed(out, RESOLVE_STAGE, error),
}
}
}