use std::collections::BTreeMap;
use std::sync::Arc;
use techy::core::node::NodeTree;
use techy::serialize::SerialValue;
use crate::model::addr::{NodeAddr, TreeId};
use crate::model::aspects::{Label, NumberSource, PointId};
use crate::model::names::RefKind;
use crate::core::data::table::{PieceClass, ProjectCx, SingletonTable, Table, TableName};
use crate::lang::{Flm, FlmSpan};
use crate::stdlib::features::refpoints::{RefPointRecord, node_key, point_key, project_number};
use crate::lang::text::plain_text;
pub const LABELS: TableName<Labels> = TableName::new("flm.labels");
pub const ANCHORS: TableName<Anchors> = TableName::new("flm.anchors");
pub const REF_TARGETS: TableName<RefTargets> = TableName::new("flm.refs.targets");
pub const REF_RESOLUTIONS: TableName<RefResolutions> = TableName::new("flm.refs.resolutions");
pub const EXTERNAL_INDEX: TableName<ExternalIndex> = TableName::new("flm.refs.external-index");
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct SiteId {
pub addr: NodeAddr,
pub index: u32,
}
#[derive(Debug, Clone, Default)]
pub struct PointDisplay {
pub number: Option<NumberSource>,
pub content: Option<Arc<NodeTree<Flm>>>,
}
impl PointDisplay {
fn project(&self, cx: &dyn ProjectCx, tree: Option<TreeId>) -> SerialValue {
let mut entries = Vec::with_capacity(2);
if let Some(number) = &self.number {
entries.push(("number".to_string(), project_number(cx, tree, number)));
}
if let Some(content) = &self.content {
entries.push(("content".to_string(), SerialValue::Str(plain_text(content))));
}
SerialValue::Map(entries)
}
}
#[derive(Debug, Clone)]
pub struct DuplicateLabel {
pub label: Label,
pub first: PointId,
pub second: PointId,
pub span: FlmSpan,
}
#[derive(Debug, Clone)]
pub struct RefusedLabel {
pub label: Label,
pub point: PointId,
pub kind: RefKind,
pub accepted: Vec<String>,
pub span: FlmSpan,
}
#[derive(Debug, Clone, Default)]
pub struct Labels {
pub by_label: BTreeMap<Label, PointId>,
pub duplicates: Vec<DuplicateLabel>,
pub refused: Vec<RefusedLabel>,
}
impl Labels {
pub fn insert(&mut self, record: &RefPointRecord) {
let point = &record.point;
for (at, label) in point.labels.iter().enumerate() {
if at >= point.computed && !point.accepts.accepts(&label.ref_type) {
self.refused.push(RefusedLabel {
label: label.clone(),
point: record.id,
kind: point.kind.clone(),
accepted: point.accepts.listed().unwrap_or(&[]).to_vec(),
span: record.span.clone(),
});
continue;
}
match self.by_label.get(label) {
Some(first) if *first == record.id => {}
Some(first) => self.duplicates.push(DuplicateLabel {
label: label.clone(),
first: *first,
second: record.id,
span: record.span.clone(),
}),
None => {
self.by_label.insert(label.clone(), record.id);
}
}
}
}
}
impl Table for Labels {
fn absorb(&mut self, piece: Labels) {
for (label, point) in piece.by_label {
self.by_label.entry(label).or_insert(point);
}
self.duplicates.extend(piece.duplicates);
self.refused.extend(piece.refused);
}
fn project(&self, cx: &dyn ProjectCx) -> SerialValue {
let labels = self
.by_label
.iter()
.map(|(label, id)| (label.to_string(), SerialValue::Str(point_key(cx, *id))))
.collect();
let duplicates = self
.duplicates
.iter()
.map(|dup| {
SerialValue::Map(vec![
("label".to_string(), SerialValue::Str(dup.label.to_string())),
("first".to_string(), SerialValue::Str(point_key(cx, dup.first))),
("second".to_string(), SerialValue::Str(point_key(cx, dup.second))),
])
})
.collect();
let refused = self
.refused
.iter()
.map(|refusal| {
let accepted = refusal
.accepted
.iter()
.map(|one| SerialValue::Str(one.clone()))
.collect();
SerialValue::Map(vec![
("label".to_string(), SerialValue::Str(refusal.label.to_string())),
("point".to_string(), SerialValue::Str(point_key(cx, refusal.point))),
("kind".to_string(), SerialValue::Str(refusal.kind.to_string())),
("accepted".to_string(), SerialValue::List(accepted)),
])
})
.collect();
SerialValue::Map(vec![
("labels".to_string(), SerialValue::Map(labels)),
("duplicates".to_string(), SerialValue::List(duplicates)),
("refused".to_string(), SerialValue::List(refused)),
])
}
fn piece_class(&self) -> PieceClass {
if self.by_label.is_empty() && self.duplicates.is_empty() && self.refused.is_empty() {
PieceClass::Empty
} else {
PieceClass::DocumentFact
}
}
}
impl SingletonTable for Labels {
const NAME: &'static str = "flm.labels";
}
#[derive(Debug, Clone, Default)]
pub struct Anchors {
pub ids: BTreeMap<PointId, Option<String>>,
}
impl Anchors {
pub fn id(&self, point: PointId) -> Option<&str> {
self.ids.get(&point).and_then(|id| id.as_deref())
}
pub fn lookup(&self, point: PointId) -> Option<Option<&str>> {
self.ids.get(&point).map(|id| id.as_deref())
}
}
impl Table for Anchors {
fn absorb(&mut self, piece: Anchors) {
self.ids.extend(piece.ids);
}
fn project(&self, cx: &dyn ProjectCx) -> SerialValue {
SerialValue::Map(
self.ids
.iter()
.map(|(id, anchor)| {
let value = match anchor {
Some(anchor) => SerialValue::Str(anchor.clone()),
None => SerialValue::Null,
};
(point_key(cx, *id), value)
})
.collect(),
)
}
fn piece_class(&self) -> PieceClass {
if self.ids.is_empty() { PieceClass::Empty } else { PieceClass::DocumentFact }
}
}
impl SingletonTable for Anchors {
const NAME: &'static str = "flm.anchors";
}
#[derive(Debug, Clone)]
pub struct RefTarget {
pub point: PointId,
pub href: String,
pub display: PointDisplay,
}
#[derive(Debug, Clone, Default)]
pub struct RefTargets {
pub by_label: BTreeMap<Label, RefTarget>,
}
impl Table for RefTargets {
fn absorb(&mut self, piece: RefTargets) {
self.by_label.extend(piece.by_label);
}
fn project(&self, cx: &dyn ProjectCx) -> SerialValue {
SerialValue::Map(
self.by_label
.iter()
.map(|(label, target)| {
(
label.to_string(),
SerialValue::Map(vec![
("point".to_string(), SerialValue::Str(point_key(cx, target.point))),
("href".to_string(), SerialValue::Str(target.href.clone())),
(
"display".to_string(),
target.display.project(cx, Some(target.point.addr.tree)),
),
]),
)
})
.collect(),
)
}
fn piece_class(&self) -> PieceClass {
if self.by_label.is_empty() { PieceClass::Empty } else { PieceClass::DocumentFact }
}
}
impl SingletonTable for RefTargets {
const NAME: &'static str = "flm.refs.targets";
}
#[derive(Debug, Clone)]
pub enum Resolution {
Resolved {
point: Option<PointId>,
href: String,
display: PointDisplay,
},
Unresolved {
target: Label,
},
}
#[derive(Debug, Clone, Default)]
pub struct RefResolutions {
pub sites: BTreeMap<SiteId, Resolution>,
}
impl RefResolutions {
pub fn site(&self, site: SiteId) -> Option<&Resolution> {
self.sites.get(&site)
}
}
impl Table for RefResolutions {
fn absorb(&mut self, piece: RefResolutions) {
self.sites.extend(piece.sites);
}
fn project(&self, cx: &dyn ProjectCx) -> SerialValue {
SerialValue::Map(
self.sites
.iter()
.map(|(id, resolution)| {
let key = format!("{}#{}", node_key(cx, id.addr), id.index);
let value = match resolution {
Resolution::Resolved { point, href, display } => SerialValue::Map(vec![(
"resolved".to_string(),
SerialValue::Map(vec![
(
"point".to_string(),
match point {
Some(point) => SerialValue::Str(point_key(cx, *point)),
None => SerialValue::Str("external".to_string()),
},
),
("href".to_string(), SerialValue::Str(href.clone())),
(
"display".to_string(),
display.project(cx, point.map(|point| point.addr.tree)),
),
]),
)]),
Resolution::Unresolved { target } => SerialValue::Map(vec![(
"unresolved".to_string(),
SerialValue::Str(target.to_string()),
)]),
};
(key, value)
})
.collect(),
)
}
}
impl SingletonTable for RefResolutions {
const NAME: &'static str = "flm.refs.resolutions";
}
#[derive(Debug, Clone)]
pub struct ExternalTarget {
pub href: String,
pub display: Arc<NodeTree<Flm>>,
}
#[derive(Debug, Clone, Default)]
pub struct ExternalIndex {
pub targets: BTreeMap<Label, ExternalTarget>,
}
impl ExternalIndex {
pub fn new() -> ExternalIndex {
ExternalIndex::default()
}
pub fn with(mut self, label: Label, target: ExternalTarget) -> ExternalIndex {
self.targets.insert(label, target);
self
}
}
impl Table for ExternalIndex {
fn absorb(&mut self, piece: ExternalIndex) {
self.targets.extend(piece.targets);
}
fn project(&self, _cx: &dyn ProjectCx) -> SerialValue {
SerialValue::Map(
self.targets
.iter()
.map(|(label, target)| {
(
label.to_string(),
SerialValue::Map(vec![
("href".to_string(), SerialValue::Str(target.href.clone())),
("display".to_string(), SerialValue::Str(plain_text(&target.display))),
]),
)
})
.collect(),
)
}
fn piece_class(&self) -> PieceClass {
if self.targets.is_empty() { PieceClass::Empty } else { PieceClass::DocumentFact }
}
}
impl SingletonTable for ExternalIndex {
const NAME: &'static str = "flm.refs.external-index";
}
#[cfg(test)]
mod tests {
use super::*;
use crate::model::aspects::{AcceptedRefTypes, AnchorPolicy, RefPoint};
use crate::model::doc::FragmentLayout;
use crate::lang::{FlmOrigin, LangInputs, ParseOptions, build_language, parse_fragment};
use techy::core::node::NodeId;
use techy::source::{Source, SourceSpan};
fn root_id() -> NodeId {
let lang = build_language(LangInputs::new());
let source = Arc::new(Source::new("x").with_origin(FlmOrigin::none()));
let fragment =
parse_fragment(&lang, source, FragmentLayout::default(), &ParseOptions::default())
.expect("a parse of `x`");
fragment.tree().root().id()
}
fn span() -> FlmSpan {
let source = Arc::new(Source::new("").with_origin(FlmOrigin::none()));
SourceSpan::new(&source, 0..0)
}
fn record(root: NodeId, index: u32, labels: &[&str]) -> RefPointRecord {
RefPointRecord {
id: PointId { addr: NodeAddr::new(TreeId::tree(0), root), index },
point: RefPoint {
kind: RefKind::from("section"),
labels: labels.iter().map(|l| Label::parse(l).unwrap()).collect(),
malformed: Vec::new(),
computed: 0,
anchor: AnchorPolicy::Auto { prefix: "sec".to_string() },
number: None,
content: None,
accepts: AcceptedRefTypes::Any,
},
span: span(),
}
}
#[test]
fn a_repeated_label_is_recorded_as_a_duplicate_keeping_the_first_point() {
let root = root_id();
let (first, second) = (record(root, 1, &["sec:a"]), record(root, 2, &["sec:a", "sec:b"]));
let mut labels = Labels::default();
labels.insert(&first);
labels.insert(&second);
assert_eq!(labels.by_label[&Label::new("sec", "a")], first.id);
assert_eq!(labels.by_label[&Label::new("sec", "b")], second.id);
assert_eq!(labels.duplicates.len(), 1);
assert_eq!(labels.duplicates[0].second, second.id);
}
#[test]
fn a_labels_piece_states_a_document_fact_only_when_it_holds_a_label() {
let root = root_id();
assert_eq!(Labels::default().piece_class(), PieceClass::Empty);
let mut unlabeled = Labels::default();
unlabeled.insert(&record(root, 1, &[]));
assert_eq!(unlabeled.piece_class(), PieceClass::Empty);
let mut labeled = Labels::default();
labeled.insert(&record(root, 1, &["sec:a"]));
assert_eq!(labeled.piece_class(), PieceClass::DocumentFact);
}
#[test]
fn the_anchors_table_tells_an_unseen_point_from_one_without_an_anchor() {
let root = root_id();
let seen = PointId { addr: NodeAddr::new(TreeId::tree(0), root), index: 1 };
let collided = PointId { addr: NodeAddr::new(TreeId::tree(0), root), index: 2 };
let unseen = PointId { addr: NodeAddr::new(TreeId::tree(0), root), index: 3 };
let mut anchors = Anchors::default();
anchors.ids.insert(seen, Some("sec-intro".to_string()));
anchors.ids.insert(collided, None);
assert_eq!(anchors.id(seen), Some("sec-intro"));
assert_eq!(anchors.id(collided), None);
assert_eq!(anchors.lookup(collided), Some(None));
assert_eq!(anchors.lookup(unseen), None);
}
}