use std::ops::Range;
use serde::Serialize;
use super::{Block, Schema, Squashed, Unit};
use crate::{markdown::BlockKind, text};
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(crate) struct Words {
labels: Vec<(String, String)>,
}
impl Words {
pub(crate) fn new(labels: Vec<(String, String)>) -> Words {
Words { labels }
}
pub(crate) fn keys_of(schema: &Schema) -> Words {
Words::new(
schema
.labels
.iter()
.map(|k| (k.clone(), k.clone()))
.collect(),
)
}
pub(crate) fn is_empty(&self) -> bool {
self.labels.is_empty()
}
pub(crate) fn first(&self) -> Option<&str> {
self.labels.first().map(|(k, _)| k.as_str())
}
pub(crate) fn has_key(&self, key: &str) -> bool {
self.labels.iter().any(|(k, _)| k == key)
}
pub(crate) fn iter(&self) -> impl Iterator<Item = (&str, &str)> {
self.labels.iter().map(|(k, w)| (k.as_str(), w.as_str()))
}
pub(crate) fn words(&self, key: &str) -> Option<&str> {
self.labels
.iter()
.find(|(k, _)| k == key)
.map(|(_, w)| w.as_str())
}
pub(crate) fn accepts(&self, words: &str) -> bool {
self.labels.iter().any(|(_, w)| w == words)
}
pub(crate) fn key_of(&self, words: &str) -> Option<&str> {
self.labels
.iter()
.find(|(_, w)| w == words)
.or_else(|| self.labels.iter().find(|(k, _)| k == words))
.map(|(k, _)| k.as_str())
}
pub(crate) fn listed(&self) -> String {
text::code_list(self.labels.iter().map(|(_, w)| format!("[{w}]")), " or ")
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Label {
Required,
Optional,
}
impl Block {
pub fn label_of(&self, rule: Option<&Unit>) -> Option<Label> {
let position =
rule.is_some_and(|r| self.sequence.iter().flatten().any(|p| std::ptr::eq(p, r)));
rule.and_then(|r| r.label)
.or_else(|| {
position
.then(|| self.each.as_ref().and_then(|e| e.label))
.flatten()
})
.or(self.label)
}
}
pub(crate) fn is_words(words: &str) -> bool {
!words.is_empty() && !words.contains(['[', ']']) && !words.starts_with('^')
}
pub(crate) fn carries_labels(kind: BlockKind) -> bool {
matches!(
kind,
BlockKind::Prose
| BlockKind::Blockquote
| BlockKind::BulletList
| BlockKind::NumberedList
| BlockKind::Table
)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Found {
pub at: Range<usize>,
pub words: String,
}
fn label_at(text: &str) -> Option<(&str, usize)> {
let inner = text.strip_prefix('[')?;
let end = inner.find([']', '['])?;
let words = &inner[..end];
(inner[end..].starts_with("] ") && words == words.trim() && is_words(words))
.then_some((words, end + 3))
}
pub(crate) fn task_box(text: &str) -> usize {
match text.as_bytes() {
[b'[', b' ' | b'x' | b'X', b']', b' ' | b'\t', ..] => 4,
_ => 0,
}
}
pub(crate) fn cut(text: &str, at: &Range<usize>) -> String {
format!("{}{}", &text[..at.start], &text[at.end..])
}
pub(crate) fn without(squashed: &Squashed, at: &Range<usize>) -> Squashed {
let mut map = squashed.map.clone();
map.drain(at.clone());
Squashed {
text: cut(&squashed.text, at),
map,
}
}
pub(crate) fn begins_with_key(text: &str, key: &str) -> bool {
!key.is_empty()
&& text
.strip_prefix(key)
.is_some_and(|rest| rest.is_empty() || rest.starts_with(' '))
}
pub(crate) struct Reader<'a> {
pub words: &'a Words,
pub item: bool,
pub labelled: bool,
pub keyed: bool,
pub key: &'a dyn Fn(&str) -> Option<String>,
}
impl Reader<'_> {
pub(crate) fn find(&self, text: &str) -> Option<Found> {
if self.words.is_empty() {
return None;
}
let base = if self.item { task_box(text) } else { 0 };
let rest = &text[base..];
let known = |w: &str| self.words.key_of(w).is_some();
let ok = |w: &str| self.labelled || known(w);
if self.keyed {
let first = rest.find(' ');
let mut fallback = None;
for (space, _) in rest.match_indices(" [") {
let start = base + space + 1;
let Some((words, len)) = label_at(&text[start..]) else {
continue;
};
if !ok(words) {
continue;
}
let found = Found {
at: start..start + len,
words: words.to_string(),
};
match (self.key)(&cut(text, &found.at)) {
Some(key) if key == rest[..space] => return Some(found),
None if Some(space) == first && known(words) => fallback = Some(found),
_ => {}
}
}
if fallback.is_some() {
return fallback;
}
}
let (words, len) = label_at(rest)?;
if !ok(words) {
return None;
}
let at = base..base + len;
let unlabelled = cut(text, &at);
if self.item && base == 0 && task_box(&unlabelled) > 0 {
return None;
}
if self.keyed
&& (self.key)(&unlabelled).is_some_and(|k| begins_with_key(&unlabelled[base..], &k))
{
return None;
}
Some(Found {
at,
words: words.to_string(),
})
}
}
impl Schema {
pub(crate) fn label_in(
&self,
words: &Words,
block: &Block,
rule: Option<&Unit>,
text: &str,
) -> Option<Found> {
if words.is_empty() || !carries_labels(block.kind) {
return None;
}
let key = |t: &str| rule.and_then(|r| r.key_in(self.formats_of(r), t));
Reader {
words,
item: matches!(block.kind, BlockKind::BulletList | BlockKind::NumberedList),
labelled: block.label_of(rule).is_some(),
keyed: rule.is_some_and(|r| self.unit_captures_key(r)),
key: &key,
}
.find(text)
}
pub(crate) fn unlabelled(
&self,
words: &Words,
block: &Block,
rule: Option<&Unit>,
text: &str,
) -> (String, Option<Found>) {
let squashed = super::squash(text);
match self.label_in(words, block, rule, &squashed) {
Some(found) => (cut(&squashed, &found.at), Some(found)),
None => (squashed, None),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn words(keys: &[&str]) -> Words {
Words::new(
keys.iter()
.map(|k| (k.to_string(), k.to_string()))
.collect(),
)
}
#[test]
fn a_label_is_words_in_brackets_and_a_space() {
assert_eq!(label_at("[human] D-2"), Some(("human", 8)));
assert_eq!(label_at("[un humain] x"), Some(("un humain", 12)));
assert_eq!(label_at("[human]: x"), None);
assert_eq!(label_at("[human][x] y"), None);
assert_eq!(label_at("[] x"), None);
assert_eq!(label_at("[ ] x"), None);
assert_eq!(label_at("[a[b] x"), None);
assert_eq!(label_at("[human]"), None);
assert_eq!(label_at("[^1] x"), None);
}
#[test]
fn a_label_stands_after_a_key_that_begins_the_unit_and_else_first() {
let w = words(&["human", "agent"]);
let key = |t: &str| {
t.split(' ')
.find(|k| k.starts_with("D-"))
.map(str::to_string)
};
let r = Reader {
words: &w,
item: true,
labelled: true,
keyed: true,
key: &key,
};
assert_eq!(r.find("D-2 [human] Why.").map(|f| f.at), Some(4..12));
assert_eq!(r.find("[human] D-2 Why."), None);
assert_eq!(r.find("[agent] See D-2.").map(|f| f.at), Some(0..8));
assert_eq!(r.find("[agent] **Topic**: x").map(|f| f.at), Some(0..8));
assert_eq!(r.find("[ ] [agent] WHEN x").map(|f| f.at), Some(4..12));
assert_eq!(r.find("[x] D-3 [agent] y").map(|f| f.at), Some(8..16));
assert_eq!(r.find("[agent] [ ] WHEN x"), None);
let step = |t: &str| t.starts_with("Step 1").then(|| "Step 1".to_string());
let s = Reader { key: &step, ..r };
assert_eq!(s.find("Step 1 [human] Do it.").map(|f| f.at), Some(7..15));
assert_eq!(r.find("[Mensch] x").map(|f| f.words), Some("Mensch".into()));
let plain = Reader {
labelled: false,
..r
};
assert_eq!(plain.find("[sic] x"), None);
assert_eq!(plain.find("[human] x").map(|f| f.at), Some(0..8));
}
}