mod blocks;
mod components;
mod env;
mod flow;
mod layout;
mod origins;
mod params;
mod text;
use crate::cel::{Error, Program, Value, Values};
use crate::context::RenderContext;
use crate::diagnostic::{Code, Diagnostic, Location, Mode, Stage};
use crate::expanded::{self, Content, Origin, Root};
use crate::lines::Lines;
use crate::load::Loaded;
use crate::md::Md;
use crate::resolve::{DocumentId, Renderer, Resolved};
use crate::tree::{self, Move, Node};
use crate::validate::Validated;
use crate::validate::scope::Scope;
pub(crate) use blocks::splice;
use blocks::{Block, finished};
use env::Env;
use std::collections::HashMap;
use std::ops;
use std::rc::Rc;
pub const LIMIT: usize = 100_000;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Options {
pub origins: bool,
pub limit: usize,
pub mode: Mode,
}
impl Default for Options {
fn default() -> Self {
Self {
origins: false,
limit: LIMIT,
mode: Mode::default(),
}
}
}
#[derive(Clone, Debug)]
pub(crate) struct Expanded {
pub(crate) root: Root,
pub(crate) diagnostics: Vec<Diagnostic>,
pub(crate) blocks: Option<Vec<Block>>,
pub(crate) replaced: Option<Replaced>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct Replaced {
pub(crate) nodes: ops::Range<usize>,
pub(crate) inserted: usize,
pub(crate) by: Move,
}
#[derive(Clone, Debug)]
struct Report {
once: Option<(Code, DocumentId, Location)>,
diagnostic: Diagnostic,
}
pub(crate) fn expand(
resolved: &Resolved,
validated: &Validated,
loaded: &Loaded,
context: &RenderContext,
options: &Options,
) -> Expanded {
let mut expander = Expander::new(resolved, validated, loaded, context, options);
let env = Env::document(&expander, resolved.main);
let mut children = Vec::new();
let mut blocks = Vec::new();
for block in &resolved.document(resolved.main).root.children {
let (nodes, given) = expander.block(block, &env);
children.extend(nodes);
blocks.push(given);
}
finished(children, blocks, loaded, None)
}
struct Expander<'r> {
resolved: &'r Resolved,
validated: &'r Validated,
options: &'r Options,
md: HashMap<DocumentId, (Value, Md<'r>)>,
lines: HashMap<DocumentId, Lines<'r>>,
programs: HashMap<String, Result<Rc<Program>, Error>>,
last_heading: u8,
heading_kept: bool,
heading_read: bool,
made: usize,
expanding: Vec<(DocumentId, Location)>,
crossed: Option<usize>,
reports: Vec<Report>,
}
impl<'r> Expander<'r> {
fn new(
resolved: &'r Resolved,
validated: &'r Validated,
loaded: &'r Loaded,
context: &'r RenderContext,
options: &'r Options,
) -> Self {
let md = resolved
.ids()
.map(|id| {
let settings = &resolved.document(id).settings;
let mut md = context.md(settings).data(loaded.data(id));
if id == resolved.main {
md = md.input(&loaded.inputs);
}
(id, (md.into(), context.functions(settings)))
})
.collect();
let lines = resolved
.ids()
.map(|id| (id, resolved.document(id).lines()))
.collect();
Self {
resolved,
validated,
options,
md,
lines,
programs: HashMap::new(),
last_heading: 0,
heading_kept: true,
heading_read: false,
made: 0,
expanding: Vec::new(),
crossed: None,
reports: Vec::new(),
}
}
fn heading_depth(&mut self) -> u8 {
self.heading_read |= self.heading_kept;
self.last_heading
}
fn md(&self, id: DocumentId) -> Value {
self.md[&id].0.clone()
}
fn values(&self, id: DocumentId) -> Values {
Values::default().with("md", self.md(id))
}
fn scope(&self, id: DocumentId) -> Scope<'r> {
Scope::body(self.resolved, id)
}
fn evaluate(&mut self, source: &str, env: &Env) -> Result<Value, Error> {
let program = match self.validated.program(source) {
Some(program) => Rc::clone(program),
None => self
.programs
.entry(source.to_string())
.or_insert_with(|| Program::parse(source).map(Rc::new))
.clone()?,
};
program.evaluate(&env.values, &self.md[&env.document].1)
}
fn report(&mut self, code: Code, env: &Env, at: Location, message: impl Into<String>) {
self.reports.push(Report {
once: Some((code, env.document, at)),
diagnostic: Diagnostic::new(code, at, message)
.in_stage(Stage::Evaluate)
.in_file(self.resolved.file(env.document)),
});
}
fn list(&mut self, nodes: &'r [Node], env: &Env<'r>) -> Vec<expanded::Node> {
let mut out = Vec::new();
for node in nodes {
self.node(node, env, &mut out);
}
text::joined(out)
}
fn inline(&mut self, nodes: &'r [Node], env: &Env<'r>) -> Vec<expanded::Node> {
let mut out = Vec::new();
for node in nodes {
self.node(node, env, &mut out);
}
out
}
fn node(&mut self, node: &'r Node, env: &Env<'r>, out: &mut Vec<expanded::Node>) {
let content = match node {
Node::Yaml(_)
| Node::ComponentDefinition(_)
| Node::ComponentSignature(_)
| Node::ComponentSlot(_) => return,
Node::Interpolation(interpolation) => {
return self.interpolation(interpolation, env, out);
}
Node::ComponentContainer(container) => {
let invocation = components::Invocation::container(node, container);
return self.component(invocation, env, out);
}
Node::ComponentLeaf(leaf) => {
return self.component(components::Invocation::leaf(node, leaf), env, out);
}
Node::ComponentInline(leaf) => {
return self.component(components::Invocation::inline(node, leaf), env, out);
}
Node::Link(link) => return self.link(link, node, env, out),
Node::Image(image) => return self.image(image, node, env, out),
Node::Blockquote(quote) => Content::Blockquote(tree::Blockquote {
children: self.list("e.children, env),
alert: quote.alert,
position: None,
}),
Node::Break(_) => Content::Break(tree::Void::default()),
Node::Code(code) => {
if let Some(name) = self.renderer(code, env) {
let invocation = components::Invocation::code(node, code, name);
return self.component(invocation, env, out);
}
Content::Code(plain_code(code))
}
Node::Definition(definition) => {
Content::Definition(self.definition(definition, node, env))
}
Node::Delete(delete) => Content::Delete(self.parent(&delete.children, env)),
Node::Emphasis(emphasis) => Content::Emphasis(self.parent(&emphasis.children, env)),
Node::FootnoteDefinition(footnote) => {
Content::FootnoteDefinition(tree::FootnoteDefinition {
identifier: footnote.identifier.clone(),
label: footnote.label.clone(),
children: self.list(&footnote.children, env),
position: None,
})
}
Node::FootnoteReference(reference) => Content::FootnoteReference(tree::Reference {
position: None,
..reference.clone()
}),
Node::Heading(heading) => Content::Heading(self.heading(heading, env)),
Node::Html(html) => Content::Html(literal(&html.value)),
Node::ImageReference(image) => Content::ImageReference(tree::ImageReference {
position: None,
..image.clone()
}),
Node::InlineCode(code) => Content::InlineCode(literal(&code.value)),
Node::InlineMath(math) => Content::InlineMath(literal(&math.value)),
Node::LinkReference(link) => Content::LinkReference(tree::LinkReference {
children: self.list(&link.children, env),
reference_type: link.reference_type,
identifier: link.identifier.clone(),
label: link.label.clone(),
position: None,
}),
Node::List(list) => Content::List(tree::List {
ordered: list.ordered,
start: list.start,
spread: list.spread,
children: self.list(&list.children, env),
position: None,
}),
Node::ListItem(item) => Content::ListItem(tree::ListItem {
spread: item.spread,
checked: item.checked,
children: self.list(&item.children, env),
position: None,
}),
Node::Math(math) => Content::Math(tree::Math {
position: None,
..math.clone()
}),
Node::Paragraph(paragraph) => Content::Paragraph(self.parent(¶graph.children, env)),
Node::Strong(strong) => Content::Strong(self.parent(&strong.children, env)),
Node::Table(table) => Content::Table(tree::Table {
align: table.align.clone(),
children: self.list(&table.children, env),
position: None,
}),
Node::TableCell(cell) => Content::TableCell(self.parent(&cell.children, env)),
Node::TableRow(row) => Content::TableRow(self.parent(&row.children, env)),
Node::Text(text) => Content::Text(literal(&text.value)),
Node::ThematicBreak(_) => Content::ThematicBreak(tree::Void::default()),
Node::WikiLink(link) => Content::WikiLink(tree::WikiLink {
position: None,
..link.clone()
}),
};
let made = self.made(content, origins::of(node, env));
out.push(made);
}
fn renderer(&self, code: &tree::Code, env: &Env<'r>) -> Option<&'r str> {
code.info.as_ref()?;
let renderers = &self.resolved.document(env.document).renderers;
match renderers.get(code.lang.as_deref()?)? {
Renderer::Component(name, _) => Some(name),
Renderer::Ambiguous(_) => None,
}
}
fn definition(
&mut self,
definition: &tree::LinkDefinition,
node: &Node,
env: &Env<'r>,
) -> tree::LinkDefinition {
tree::LinkDefinition {
url: self
.checked_url(&definition.url, definition.url_parts.as_deref(), node, env)
.unwrap_or_default(),
url_parts: None,
position: None,
..definition.clone()
}
}
fn parent(&mut self, children: &'r [Node], env: &Env<'r>) -> tree::Parent<expanded::Node> {
tree::Parent {
children: self.list(children, env),
position: None,
}
}
fn heading(
&mut self,
heading: &'r tree::Heading,
env: &Env<'r>,
) -> tree::Heading<expanded::Node> {
let depth = env
.shift
.map_or(heading.depth, |base| (base + heading.depth).min(6));
let children = self.list(&heading.children, env);
self.last_heading = depth;
self.heading_kept = false;
tree::Heading {
depth,
children,
position: None,
}
}
fn made(&mut self, content: Content, origin: Option<Origin>) -> expanded::Node {
self.made += 1;
if self.made > self.options.limit
&& self.crossed.is_none()
&& let Some((id, at)) = self.expanding.last().copied()
{
self.crossed = Some(self.expanding.len());
self.reports.push(Report {
once: None,
diagnostic: Diagnostic::new(
Code::F034,
at,
format!(
"the expanded document would have more than {} nodes; this renders its fallback",
self.options.limit
),
)
.in_stage(Stage::Evaluate)
.in_file(self.resolved.file(id)),
});
}
expanded::Node { content, origin }
}
fn over_limit(&self) -> bool {
self.crossed.is_some()
}
fn expanding<T>(
&mut self,
env: &Env,
at: Location,
expansion: impl FnOnce(&mut Self) -> T,
) -> Option<T> {
if self.over_limit() {
return None;
}
self.expanding.push((env.document, at));
let depth = self.expanding.len();
let result = expansion(self);
self.expanding.pop();
(self.crossed != Some(depth)).then_some(result)
}
}
fn literal(value: &str) -> tree::Literal {
tree::Literal {
value: value.to_string(),
position: None,
}
}
fn plain_code(code: &tree::Code) -> expanded::Code {
expanded::Code {
lang: code.lang.clone(),
meta: code.meta.clone(),
value: code.value.clone(),
component: None,
alt: None,
}
}