krz/orgo

Lightning fast org-mode static site generator. fast go org-mode static-site-generator

src/resolve.rs

186 lines · 6882 bytes

10 symbols in this file
  1//! RESOLVE stage (spec §2.1, §4.3): rewrite `LinkTarget`s to final URLs using the
  2//! symbol table, AND record which targets each page consumed.
  3//!
  4//! Critical invariant (spec §4.3, R2): RESOLVE returns the used-target list as a
  5//! first-class side output from v1, even before incrementality consumes it. Throwing
  6//! it away would make renamed-heading invalidation impossible to compute later without
  7//! re-resolving everything.
  8//!
  9//! Resolution rewrites each internal link into an [`crate::model::LinkTarget::External`]
 10//! carrying its final URL, so the renderer needs no symbol-table knowledge. Unresolved
 11//! links are left untouched (the renderer falls back to a best-effort anchor) and
 12//! reported as [`BrokenLink`] warnings (spec §4.3.4).
 13
 14use camino::Utf8Path;
 15
 16use crate::index::{SymbolTable, TargetId};
 17use crate::model::{Document, Element, Link, LinkTarget, Object, Section, TableRow};
 18use crate::util::{normalize_link_path, output_path, output_url};
 19
 20/// A document whose links have been rewritten to concrete URLs.
 21#[derive(Debug, Clone)]
 22pub struct ResolvedDoc {
 23    pub document: Document,
 24}
 25
 26/// A broken internal link — surfaced as a warning, or an error under `--strict` (spec §4.3.4).
 27#[derive(Debug, Clone)]
 28pub struct BrokenLink {
 29    pub target: TargetId,
 30}
 31
 32/// Result of resolving one page. `used_targets` are the "uses" edges (spec §4.3).
 33#[derive(Debug)]
 34pub struct ResolveOutput {
 35    pub resolved: ResolvedDoc,
 36    /// The "uses" edges — MUST be captured from day one (spec §4.3, R2).
 37    pub used_targets: Vec<TargetId>,
 38    pub broken: Vec<BrokenLink>,
 39}
 40
 41/// `resolve(doc, &SymbolTable) -> (ResolvedDoc, Vec<TargetId used>)` (spec §4.3).
 42pub fn resolve(doc: &Document, symbols: &SymbolTable) -> ResolveOutput {
 43    let mut document = doc.clone();
 44    let from = doc.source_path.clone();
 45    // URLs are computed between *output* paths, which `#+SLUG:` can rename.
 46    let from_out = output_path(&from, &doc.keywords);
 47    let mut used = Vec::new();
 48    let mut broken = Vec::new();
 49    let mut cx = Cx {
 50        from: &from,
 51        from_out: &from_out,
 52        symbols,
 53        used: &mut used,
 54        broken: &mut broken,
 55    };
 56    cx.section(&mut document.root);
 57    ResolveOutput {
 58        resolved: ResolvedDoc { document },
 59        used_targets: used,
 60        broken,
 61    }
 62}
 63
 64/// The text a description-less internal link should display once its target becomes a URL.
 65fn human_text(target: &LinkTarget) -> Option<String> {
 66    match target {
 67        LinkTarget::Heading(t) => Some(t.clone()),
 68        LinkTarget::CustomId(id) | LinkTarget::Id(id) => Some(id.clone()),
 69        LinkTarget::File { path, .. } => Some(path.to_string()),
 70        LinkTarget::External(_) => None,
 71    }
 72}
 73
 74struct Cx<'a> {
 75    from: &'a Utf8Path,
 76    from_out: &'a Utf8Path,
 77    symbols: &'a SymbolTable,
 78    used: &'a mut Vec<TargetId>,
 79    broken: &'a mut Vec<BrokenLink>,
 80}
 81
 82impl Cx<'_> {
 83    fn section(&mut self, section: &mut Section) {
 84        if let Some(h) = &mut section.heading {
 85            self.objects(&mut h.title);
 86        }
 87        for el in &mut section.content {
 88            self.element(el);
 89        }
 90        for child in &mut section.children {
 91            self.section(child);
 92        }
 93    }
 94
 95    fn element(&mut self, el: &mut Element) {
 96        match el {
 97            Element::Paragraph(objs) => self.objects(objs),
 98            Element::List(list) => {
 99                for item in &mut list.items {
100                    if let Some(term) = &mut item.term {
101                        self.objects(term);
102                    }
103                    for e in &mut item.content {
104                        self.element(e);
105                    }
106                }
107            }
108            Element::Table(table) => {
109                self.objects(&mut table.caption);
110                for row in &mut table.rows {
111                    if let TableRow::Cells(cells) = row {
112                        for cell in cells {
113                            self.objects(cell);
114                        }
115                    }
116                }
117            }
118            Element::Figure { caption, .. } => self.objects(caption),
119            Element::QuoteBlock(inner)
120            | Element::CenterBlock(inner)
121            | Element::SpecialBlock { content: inner, .. }
122            | Element::Drawer { content: inner, .. }
123            | Element::FootnoteDefinition { content: inner, .. } => {
124                for e in inner {
125                    self.element(e);
126                }
127            }
128            _ => {}
129        }
130    }
131
132    fn objects(&mut self, objs: &mut [Object]) {
133        for obj in objs {
134            match obj {
135                Object::Link(link) => self.link(link),
136                Object::Bold(i)
137                | Object::Italic(i)
138                | Object::Underline(i)
139                | Object::StrikeThrough(i) => self.objects(i),
140                Object::FootnoteRef {
141                    inline: Some(i), ..
142                } => self.objects(i),
143                _ => {}
144            }
145        }
146    }
147
148    fn link(&mut self, link: &mut Link) {
149        if let Some(desc) = &mut link.description {
150            self.objects(desc);
151        }
152        let tid = match &link.target {
153            LinkTarget::External(_) => return,
154            LinkTarget::CustomId(id) => TargetId::CustomId(id.clone()),
155            LinkTarget::Id(id) => TargetId::Id(id.clone()),
156            LinkTarget::Heading(t) => TargetId::Heading(t.clone()),
157            LinkTarget::File { path, .. } => {
158                // Only `.org` files are pages. A link to an asset (an image, a PDF) is
159                // already a correct relative URL in the output tree, since assets are
160                // copied preserving layout — so it is neither resolved nor reported.
161                if path.extension() != Some("org") {
162                    return;
163                }
164                TargetId::File(normalize_link_path(self.from, path))
165            }
166        };
167        match self.symbols.targets.get(&tid) {
168            Some(loc) => {
169                self.used.push(tid.clone());
170                // Preserve the human-readable text before the target becomes a bare URL,
171                // so a description-less `[[*Heading]]` still renders as the heading text.
172                if link.description.is_none() {
173                    if let Some(text) = human_text(&link.target) {
174                        link.description = Some(vec![Object::Text(text)]);
175                    }
176                }
177                let url = output_url(self.from_out, &loc.output_path, loc.anchor.as_deref());
178                link.target = LinkTarget::External(url);
179            }
180            None => {
181                self.broken.push(BrokenLink { target: tid });
182                // Leave the original target for the renderer's best-effort fallback.
183            }
184        }
185    }
186}