use super::figures::{Figures, NumberRules, scan, sentence_at, sentence_span};
const JOINERS: &[&str] = &["while", "whilst", "whereas", "but", "sedangkan", "tetapi", "tapi", "namun", "padahal"];
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct AttributionRules {
pub numbers: NumberRules,
pub integers_up_to: f64,
}
impl Default for AttributionRules {
fn default() -> Self {
Self { numbers: NumberRules::default(), integers_up_to: 10.0 }
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Misattributed {
pub number: String,
pub sentence: String,
pub named: String,
pub owners: Vec<String>,
}
#[derive(Clone, Debug)]
struct Entity {
label: String,
aliases: Vec<String>,
group: bool,
figures: Figures,
}
#[derive(Clone, Debug, Default)]
pub struct Entities {
list: Vec<Entity>,
}
#[derive(Clone, Copy, Debug)]
struct Mention {
entity: usize,
start: usize,
end: usize,
}
impl Entities {
pub fn new() -> Self {
Self::default()
}
pub fn is_empty(&self) -> bool {
self.list.is_empty()
}
fn entry(&mut self, label: &str) -> usize {
let label = label.trim();
if let Some(index) = self.find(label) {
return index;
}
self.list.push(Entity { label: label.to_owned(), aliases: Vec::new(), group: false, figures: Figures::new() });
self.list.len() - 1
}
fn find(&self, label: &str) -> Option<usize> {
let label = label.trim();
self.list.iter().position(|entity| entity.label.to_lowercase() == label.to_lowercase())
}
pub fn add(&mut self, label: &str, aliases: &[String], group: bool, facts: &serde_json::Value) {
if label.trim().is_empty() {
return;
}
let index = self.entry(label);
if let Some(entity) = self.list.get_mut(index) {
for alias in aliases {
let alias = alias.trim();
if !alias.is_empty() && !entity.aliases.iter().any(|known| known.eq_ignore_ascii_case(alias)) {
entity.aliases.push(alias.to_owned());
}
}
entity.group |= group;
entity.figures.add_json(facts);
}
}
pub fn add_group(&mut self, label: &str) {
self.add(label, &[], true, &serde_json::Value::Null);
}
pub fn add_json(&mut self, value: &serde_json::Value, label_key: &str) -> Result<(), String> {
match value {
serde_json::Value::Array(records) => {
for (index, record) in records.iter().enumerate() {
self.add_record(record, label_key).map_err(|problem| format!("item {index}: {problem}"))?;
}
Ok(())
}
serde_json::Value::Object(per_label) => {
for (label, facts) in per_label {
self.add(label, &[], false, facts);
}
Ok(())
}
other => Err(format!("expected a list of records or an object of facts per entity, got {}", kind(other))),
}
}
fn add_record(&mut self, record: &serde_json::Value, label_key: &str) -> Result<(), String> {
let serde_json::Value::Object(fields) = record else {
return Err(format!("expected a record (an object), got {}", kind(record)));
};
let label = match fields.get(label_key) {
Some(serde_json::Value::String(label)) => label.as_str(),
Some(serde_json::Value::Number(_)) | Some(serde_json::Value::Bool(_)) => {
return Err(format!("`{label_key}` must be a string"));
}
Some(serde_json::Value::Null) | None => return Ok(()),
Some(_) => return Err(format!("`{label_key}` must be a string")),
};
let aliases = match fields.get("aliases") {
None | Some(serde_json::Value::Null) => Vec::new(),
Some(serde_json::Value::Array(aliases)) => aliases
.iter()
.map(|alias| alias.as_str().map(str::to_owned).ok_or("`aliases` must be a list of strings"))
.collect::<Result<Vec<_>, _>>()?,
Some(_) => return Err("`aliases` must be a list of strings".to_owned()),
};
let group = match fields.get("group") {
None | Some(serde_json::Value::Null) => false,
Some(serde_json::Value::Bool(group)) => *group,
Some(_) => return Err("`group` must be a bool".to_owned()),
};
let facts: serde_json::Map<String, serde_json::Value> = fields
.iter()
.filter(|(name, _)| !matches!(name.as_str(), "aliases" | "group") && name.as_str() != label_key)
.map(|(name, value)| (name.clone(), value.clone()))
.collect();
self.add(label, &aliases, group, &serde_json::Value::Object(facts));
Ok(())
}
pub fn misattributed(&self, text: &str, scope: Option<&str>, rules: AttributionRules) -> Vec<Misattributed> {
if self.list.is_empty() {
return Vec::new();
}
let scope_label = scope.map(str::trim).filter(|label| !label.is_empty());
let scope = scope_label.map(|label| self.find(label).unwrap_or(self.list.len()));
let label = |index: usize| match self.list.get(index) {
Some(entity) => entity.label.clone(),
None => scope_label.unwrap_or_default().to_owned(),
};
let mentions = self.mentions(text);
let blanked = blank(text, &mentions);
let numbers = scan(&blanked);
let spans: Vec<(usize, usize)> = numbers.iter().map(|number| (number.at, number.end)).collect();
let mut found = Vec::new();
for number in numbers {
if number.plain_value().is_some_and(|value| value <= rules.integers_up_to || is_a_year(value)) {
continue;
}
let owners: Vec<usize> = self
.list
.iter()
.enumerate()
.filter(|(_, entity)| entity.figures.holds(&number, rules.numbers))
.map(|(index, _)| index)
.collect();
if owners.is_empty() {
continue;
}
let Some(named) = self.given_to(text, &mentions, number.at, number.end, scope, &owners) else {
continue;
};
if owners.contains(&named) || listed(text, &mentions, &spans, number.at, named, &owners) {
continue;
}
found.push(Misattributed {
number: number.text,
sentence: sentence_at(text, number.at),
named: label(named),
owners: owners.into_iter().map(label).collect(),
});
}
found
}
fn given_to(
&self,
text: &str,
mentions: &[Mention],
start: usize,
end: usize,
scope: Option<usize>,
owners: &[usize],
) -> Option<usize> {
let (sentence_start, sentence_end) = sentence_span(text, start);
let clause = clause_span(text, sentence_start, sentence_end, start, mentions);
let (clause_start, clause_end) = (clause.start, clause.end);
let within = |from: usize, to: usize, specific: bool| -> Vec<Mention> {
mentions
.iter()
.filter(|mention| mention.start >= from && mention.end <= to)
.filter(|mention| !specific || self.list.get(mention.entity).is_some_and(|entity| !entity.group))
.copied()
.collect()
};
let opens_the_clause = text.get(clause_start..start).is_some_and(|before| {
!before.trim_end_matches(|c: char| c.is_alphabetic() || c == '$').contains(char::is_alphabetic)
});
let pick = |specific: bool| {
let in_clause = within(clause_start, clause_end, specific);
let sentence = within(sentence_start, sentence_end, specific);
let ahead = within(sentence_start, clause.next_statement, specific);
before(&in_clause, start)
.or_else(|| if opens_the_clause { after(&in_clause, end) } else { None })
.or_else(|| before(&sentence, start))
.or_else(|| after(&ahead, end))
};
let named = pick(false).or(scope)?;
let Some(group) = self.list.get(named).filter(|entity| entity.group) else {
return Some(named);
};
if let Some(specific) = pick(true) {
return Some(specific);
}
if scope.is_some_and(|scope| owners.contains(&scope)) || group.figures.is_empty() {
return None;
}
Some(named)
}
fn mentions(&self, text: &str) -> Vec<Mention> {
let chars: Vec<(usize, char)> = text.char_indices().collect();
let mut labels: Vec<(Vec<String>, usize)> = self
.list
.iter()
.enumerate()
.flat_map(|(index, entity)| {
std::iter::once(&entity.label).chain(&entity.aliases).map(move |label| (label, index))
})
.map(|(label, index)| (label.split_whitespace().map(str::to_lowercase).collect::<Vec<_>>(), index))
.filter(|(words, _)| !words.is_empty())
.collect();
labels
.sort_by_key(|(words, _)| std::cmp::Reverse(words.iter().map(|word| word.chars().count()).sum::<usize>()));
let mut taken = vec![false; chars.len()];
let mut found = Vec::new();
for (words, entity) in &labels {
let mut from = 0;
while from < chars.len() {
let Some(length) = match_at(&chars, from, words) else {
from += 1;
continue;
};
let span = from..from + length;
if taken.get(span.clone()).is_some_and(|taken| taken.iter().any(|taken| *taken)) {
from += 1;
continue;
}
taken.get_mut(span.clone()).into_iter().flatten().for_each(|taken| *taken = true);
let start = chars.get(span.start).map_or(text.len(), |(byte, _)| *byte);
let end = chars.get(span.end).map_or(text.len(), |(byte, _)| *byte);
found.push(Mention { entity: *entity, start, end });
from = span.end;
}
}
found
}
}
fn listed(
text: &str,
mentions: &[Mention],
figures: &[(usize, usize)],
at: usize,
named: usize,
owners: &[usize],
) -> bool {
let (sentence_start, sentence_end) = sentence_span(text, at);
let clause = clause_span(text, sentence_start, sentence_end, at, mentions);
let mut earlier: Vec<&Mention> =
mentions.iter().filter(|mention| mention.start >= clause.start && mention.end <= at).collect();
earlier.sort_by_key(|mention| mention.start);
let Some(last) = earlier.pop() else { return false };
let mut run = vec![last.entity];
let mut next = last;
while let Some(previous) = earlier.pop() {
let figure_between = figures.iter().any(|(start, end)| *start >= previous.end && *end <= next.start);
if figure_between {
break;
}
run.push(previous.entity);
next = previous;
}
run.len() >= 2 && run.contains(&named) && run.iter().any(|entity| owners.contains(entity))
}
fn before(mentions: &[Mention], start: usize) -> Option<usize> {
mentions
.iter()
.filter(|mention| mention.end <= start)
.max_by_key(|mention| mention.end)
.map(|mention| mention.entity)
}
fn after(mentions: &[Mention], end: usize) -> Option<usize> {
mentions
.iter()
.filter(|mention| mention.start >= end)
.min_by_key(|mention| mention.start)
.map(|mention| mention.entity)
}
fn match_at(chars: &[(usize, char)], at: usize, words: &[String]) -> Option<usize> {
if at > 0 && chars.get(at - 1).is_some_and(|(_, c)| c.is_alphanumeric()) {
return None;
}
let mut index = at;
for (number, word) in words.iter().enumerate() {
if number > 0 {
let spaces_from = index;
while chars.get(index).is_some_and(|(_, c)| c.is_whitespace()) {
index += 1;
}
if index == spaces_from {
return None;
}
}
for expected in word.chars() {
let (_, written) = chars.get(index)?;
if written.to_lowercase().ne(expected.to_lowercase()) {
return None;
}
index += 1;
}
}
if chars.get(index).is_some_and(|(_, c)| c.is_alphanumeric()) {
return None;
}
Some(index - at)
}
fn blank(text: &str, mentions: &[Mention]) -> String {
text.char_indices()
.map(|(at, c)| {
if mentions.iter().any(|mention| at >= mention.start && at < mention.end) {
" ".repeat(c.len_utf8())
} else {
c.to_string()
}
})
.collect()
}
struct Clause {
start: usize,
end: usize,
next_statement: usize,
}
fn clause_span(text: &str, sentence_start: usize, sentence_end: usize, at: usize, mentions: &[Mention]) -> Clause {
let sentence = text.get(sentence_start..sentence_end).unwrap_or_default();
let mut breaks: Vec<(usize, usize, bool)> = Vec::new();
let chars: Vec<(usize, char)> = sentence.char_indices().collect();
for (position, &(offset, c)) in chars.iter().enumerate() {
let next_is_space = chars.get(position + 1).is_some_and(|(_, next)| next.is_whitespace());
let previous_is_space = position > 0 && chars.get(position - 1).is_some_and(|(_, prev)| prev.is_whitespace());
let cuts = match c {
',' | ';' => next_is_space,
'(' | ')' | '[' | ']' => true,
'-' | '\u{2013}' | '\u{2014}' => next_is_space && previous_is_space,
_ => false,
};
if cuts {
breaks.push((offset, offset + c.len_utf8(), false));
}
}
let mut word_start = None;
for (position, &(offset, c)) in chars.iter().enumerate() {
if c.is_alphabetic() {
word_start.get_or_insert(offset);
let ends = chars.get(position + 1).is_none_or(|(_, next)| !next.is_alphabetic());
if let (true, Some(from)) = (ends, word_start) {
let to = offset + c.len_utf8();
let word = sentence.get(from..to).unwrap_or_default().to_lowercase();
if JOINERS.contains(&word.as_str()) {
breaks.push((from, to, true));
}
word_start = None;
}
} else {
word_start = None;
}
}
breaks.retain(|(from, to, _)| {
let (from, to) = (sentence_start + from, sentence_start + to);
!mentions.iter().any(|mention| from < mention.end && to > mention.start)
});
let at = at.saturating_sub(sentence_start);
let start = breaks.iter().filter(|(_, end, _)| *end <= at).map(|(_, end, _)| *end).max().unwrap_or(0);
let end =
breaks.iter().filter(|(from, _, _)| *from >= at).map(|(from, _, _)| *from).min().unwrap_or(sentence.len());
let next_statement = breaks
.iter()
.filter(|(from, _, joiner)| *joiner && *from >= at)
.map(|(from, _, _)| *from)
.min()
.unwrap_or(sentence.len());
Clause { start: sentence_start + start, end: sentence_start + end, next_statement: sentence_start + next_statement }
}
fn is_a_year(value: f64) -> bool {
(1900.0..=2100.0).contains(&value) && value.fract() == 0.0
}
fn kind(value: &serde_json::Value) -> &'static str {
match value {
serde_json::Value::Null => "null",
serde_json::Value::Bool(_) => "a bool",
serde_json::Value::Number(_) => "a number",
serde_json::Value::String(_) => "a string",
serde_json::Value::Array(_) => "a list",
serde_json::Value::Object(_) => "an object",
}
}
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::indexing_slicing)]
mod tests {
use serde_json::json;
use super::*;
use crate::grounding::figures::Tolerance;
fn rules() -> AttributionRules {
AttributionRules {
numbers: NumberRules { tolerance: Tolerance::Rounding, ratios_as_percent: true },
integers_up_to: 10.0,
}
}
fn shop() -> Entities {
let mut entities = Entities::new();
entities
.add_json(
&json!([
{"entity": "Electronics", "aliases": ["gadgets"], "revenue": 48200, "share": 0.3125, "orders": 1240, "growth_pct": 12.4},
{"entity": "Garden Tools", "aliases": ["garden"], "revenue": 21900, "share": 0.1419, "orders": 615, "growth_pct": -3.8},
{"entity": "Toys", "revenue": 15350, "share": 0.0995, "orders": 702, "growth_pct": 7.1},
{"entity": "All categories", "aliases": ["the store", "overall"], "group": true, "revenue": 154250, "orders": 4310}
]),
"entity",
)
.unwrap();
entities.add_group("categories");
entities
}
fn found(text: &str, scope: Option<&str>) -> Vec<(String, String, Vec<String>)> {
shop()
.misattributed(text, scope, rules())
.into_iter()
.map(|wrong| (wrong.number, wrong.named, wrong.owners))
.collect()
}
#[test]
fn true_attributions_pass() {
let report = "Electronics led with $48.2k in revenue (31.25% of sales) on 1,240 orders. \
Garden Tools fell 3.8% to 21,900, while Toys grew 7.1% to 15,350. \
31% of revenue came from gadgets, 14% from garden. \
Across all categories the store took 154,250 on 4,310 orders.";
assert_eq!(found(report, None), []);
}
#[test]
fn a_figure_of_another_entity_is_caught() {
assert_eq!(
found("Toys reached 31.25% of sales.", None),
[("31.25%".to_owned(), "Toys".to_owned(), vec!["Electronics".to_owned()])]
);
assert_eq!(found("Gadgets took 702 orders.", None)[0].2, ["Toys"]);
}
#[test]
fn swapped_entities_are_caught() {
let wrong = found("Electronics grew 7.1% and Toys grew 12.4%.", None);
assert_eq!(wrong.len(), 2);
assert_eq!((wrong[0].1.as_str(), wrong[1].1.as_str()), ("Electronics", "Toys"));
}
#[test]
fn a_swapped_metric_is_not_a_misattribution_of_the_entity() {
assert_eq!(found("Toys had 702 in revenue.", None), []);
}
#[test]
fn a_figure_of_another_entity_under_another_metric_is_caught() {
assert_eq!(found("Garden Tools revenue was 1,240.", None)[0].2, ["Electronics"]);
}
#[test]
fn the_longest_label_wins_and_whole_words_only() {
let mut entities = Entities::new();
entities.add("Garden", &[], false, &json!({"revenue": 500}));
entities.add("Garden Tools", &[], false, &json!({"revenue": 21900}));
entities.add("Store 12", &[], false, &json!({"revenue": 777}));
assert!(entities.misattributed("Garden tools made 21,900.", None, rules()).is_empty());
assert_eq!(entities.misattributed("Garden made 21,900.", None, rules()).len(), 1);
assert!(entities.misattributed("Gardens made 21,900. Store 12 made 777.", None, rules()).is_empty());
}
#[test]
fn a_group_word_lets_the_named_entity_or_the_scope_decide() {
assert_eq!(found("Among categories, Electronics took 48,200.", None), []);
assert_eq!(found("Among categories, Toys took 48,200.", None)[0].1, "Toys");
assert_eq!(found("These categories took 48,200.", Some("Electronics")), []);
assert_eq!(found("These categories took 48,200.", None), []);
assert_eq!(found("The store took 154,250 on 4,310 orders.", None), []);
assert_eq!(found("Overall revenue was 48,200.", None)[0].1, "All categories");
}
#[test]
fn the_scope_is_the_entity_of_a_field_that_names_none() {
assert_eq!(found("Revenue grew 12.4% on 1,240 orders.", Some("Electronics")), []);
assert_eq!(found("Revenue grew 12.4% on 1,240 orders.", Some("Toys")).len(), 2);
assert_eq!(found("Toys grew 7.1%.", Some("Electronics")), []);
assert_eq!(found("Revenue was 15,350.", Some("Books"))[0].1, "Books");
}
#[test]
fn small_counts_years_and_unowned_figures_are_not_judged() {
assert_eq!(found("In 2026 Toys opened 4 stores and earned 99,999.", None), []);
let mut entities = shop();
entities.add("Books", &[], false, &json!({"stores": 3, "opened": 2025}));
assert!(entities.misattributed("Toys opened 3 stores in 2025.", None, rules()).is_empty());
let loose = AttributionRules { integers_up_to: 0.0, ..rules() };
assert_eq!(entities.misattributed("Toys opened 3 stores.", None, loose)[0].owners, ["Books"]);
}
#[test]
fn clauses_bound_the_nearest_entity() {
assert_eq!(found("31% of revenue came from gadgets, 14% from garden.", None), []);
assert_eq!(found("14% of revenue came from gadgets, 31% from garden.", None).len(), 2);
assert_eq!(found("Electronics revenue is 48,200 whereas Toys 21,900.", None)[0].1, "Toys");
let mut entities = shop();
entities.add("New Buyers", &[], false, &json!({"share": 0.2}));
let text = "Orders came from Toys, which took 15,350 with 3 new buyers.";
assert!(entities.misattributed(text, None, rules()).is_empty());
assert_eq!(found("Electronics led, ahead of Toys with 48,200.", None)[0].1, "Toys");
}
#[test]
fn a_comma_inside_a_label_ends_no_clause() {
let mut offers = Entities::new();
offers.add("Buy One, Get One", &[], false, &json!({"share": 0.1277}));
offers.add("Get One", &[], false, &json!({"share": 0.617}));
offers.add("Flat 20 Off", &[], false, &json!({"share": 0.0426}));
let text = "Get One led with 61.70%, followed by Buy One, Get One at 12.77% and Flat 20 Off at 4.26%.";
assert!(offers.misattributed(text, None, rules()).is_empty());
let swapped = "Get One led with 12.77%, followed by Buy One, Get One at 61.70%.";
assert_eq!(offers.misattributed(swapped, None, rules()).len(), 2);
}
#[test]
fn figures_after_a_list_of_entities_go_to_them_in_order() {
assert_eq!(found("Electronics and Toys followed at 31.25% and 9.95%.", None), []);
assert_eq!(found("Toys and Electronics followed at 31.25% and 9.95%.", None), []);
assert_eq!(found("Electronics at 9.95% and Toys at 31.25%.", None).len(), 2);
assert_eq!(found("Garden Tools and Toys followed at 31.25%.", None).len(), 1);
}
#[test]
fn a_joining_word_ends_the_search_ahead() {
assert_eq!(found("Revenue rose 31.25%, while Toys fell.", None), []);
assert_eq!(found("Revenue rose 31.25% for Toys.", None).len(), 1);
}
#[test]
fn rows_and_objects_make_entities() {
let mut rows = Entities::new();
rows.add_json(
&json!([
{"entity": "North", "metric": "revenue", "value": 5100},
{"entity": "north", "metric": "visits", "value": 830},
{"entity": "South", "metric": "revenue", "value": 4400},
{"entity": null, "metric": "revenue", "value": 1}
]),
"entity",
)
.unwrap();
assert!(rows.misattributed("North had 830 visits and 5,100 in revenue.", None, rules()).is_empty());
assert_eq!(rows.misattributed("South had 830 visits.", None, rules())[0].owners, ["North"]);
let mut per_label = Entities::new();
per_label.add_json(&json!({"North": {"revenue": 5100}, "South": {"revenue": 4400}}), "entity").unwrap();
assert_eq!(per_label.misattributed("North made 4,400.", None, rules())[0].named, "North");
let mut named = Entities::new();
named.add_json(&json!([{"name": "East", "revenue": 3000}]), "name").unwrap();
assert!(named.misattributed("East made 3,000.", None, rules()).is_empty());
}
#[test]
fn malformed_entities_are_reported() {
let mut entities = Entities::new();
assert!(entities.add_json(&json!("Garden"), "entity").unwrap_err().contains("a string"));
assert!(entities.add_json(&json!([1]), "entity").unwrap_err().starts_with("item 0"));
assert!(entities.add_json(&json!([{"entity": 5}]), "entity").unwrap_err().contains("must be a string"));
assert!(entities.add_json(&json!([{"entity": "A", "aliases": "a"}]), "entity").is_err());
assert!(entities.add_json(&json!([{"entity": "A", "group": "yes"}]), "entity").is_err());
}
#[test]
fn unicode_and_multibyte_text_keeps_its_offsets() {
let mut entities = Entities::new();
entities.add("Café Düsseldorf", &[], false, &json!({"revenue": 5100}));
entities.add("Été", &[], false, &json!({"revenue": 4400}));
assert!(entities.misattributed("Café düsseldorf — 5.100 € — été 4.400 €.", None, rules()).is_empty());
assert_eq!(entities.misattributed("ÉTÉ réalise 5.100 €.", None, rules())[0].named, "Été");
}
}