use super::entities::EntityCandidate;
use super::kinds::{classify, Kind};
use super::pack::{LanguagePack, Slot, VerbRule};
use super::quotes::QuoteMap;
use super::register::Register;
use std::collections::BTreeMap;
pub struct Scope<'a> {
pub register: &'a Register,
pub quotes: &'a QuoteMap,
pub mentions: &'a [EntityCandidate],
}
pub struct RelationCandidate {
pub subject: String,
pub relation: String,
pub object: String,
pub rule: String,
pub span: [usize; 2],
pub base: f32,
pub gap: usize,
pub stance: Stance,
pub single_filler: bool,
}
const MAX_GAP_BYTES: usize = 30;
pub fn extract_relations(
text: &str,
entities: &[EntityCandidate],
ontology: &BTreeMap<String, String>,
pack: &LanguagePack,
scope: &Scope,
) -> Vec<RelationCandidate> {
let mut relations = Vec::new();
debug_assert!(entities.windows(2).all(|w| w[0].start <= w[1].start));
for (i, subj) in entities.iter().enumerate() {
for obj in &entities[i + 1..] {
if obj.start >= subj.end && obj.start - subj.end > MAX_GAP_BYTES {
break;
}
if subj.normalized == obj.normalized {
continue;
}
if !scope.quotes.contains_span(text, subj.start, obj.end) {
continue;
}
if let Some(m) = find_relation_pattern(text, subj, obj, pack, scope) {
let (s, o) = if m.swapped { (obj, subj) } else { (subj, obj) };
relations.push(RelationCandidate {
single_filler: pack.single_filler_relations.contains(&m.relation.as_str()),
subject: s.normalized.clone(),
relation: normalize_relation(&m.relation, ontology),
object: o.normalized.clone(),
rule: m.rule,
span: [subj.start, m.span_end.unwrap_or(obj.end)],
base: m.base,
gap: m.gap,
stance: m.stance,
});
}
}
}
relations
}
struct PatternMatch {
relation: String,
rule: String,
base: f32,
gap: usize,
swapped: bool,
span_end: Option<usize>,
stance: Stance,
}
impl PatternMatch {
fn new(relation: &str, rule: impl Into<String>, base: f32, gap: usize) -> Self {
Self {
relation: relation.to_string(),
rule: rule.into(),
base,
gap,
swapped: false,
span_end: None,
stance: Stance::Asserted,
}
}
fn swapped(self, swapped: bool) -> Self {
Self { swapped, ..self }
}
fn stance(self, stance: Stance) -> Self {
Self { stance, ..self }
}
fn span_end(self, span_end: usize) -> Self {
Self {
span_end: Some(span_end),
..self
}
}
}
fn find_ascii_ci_word(haystack: &str, needle: &str) -> Option<(usize, usize)> {
debug_assert!(needle.is_ascii() && !needle.is_empty());
let (hay, needle) = (haystack.as_bytes(), needle.as_bytes());
if hay.len() < needle.len() {
return None;
}
(0..=hay.len() - needle.len())
.find(|&i| {
hay[i..i + needle.len()].eq_ignore_ascii_case(needle)
&& !hay
.get(i.wrapping_sub(1))
.is_some_and(u8::is_ascii_alphanumeric)
&& !hay
.get(i + needle.len())
.is_some_and(u8::is_ascii_alphanumeric)
})
.map(|i| (i, i + needle.len()))
}
fn find_ascii_ci(haystack: &str, needle: &str) -> Option<(usize, usize)> {
debug_assert!(needle.is_ascii() && !needle.is_empty());
let needle = needle.as_bytes();
haystack
.as_bytes()
.windows(needle.len())
.position(|w| w.eq_ignore_ascii_case(needle))
.map(|start| (start, start + needle.len()))
}
fn possessed_noun_phrase_len(rest: &str, pack: &LanguagePack) -> usize {
let punct = rest
.find([',', '.', ';', ':', '!', '?'])
.unwrap_or(rest.len());
let conjunction = find_ascii_ci(rest, pack.phrase_conjunction)
.map(|(start, _)| start)
.unwrap_or(rest.len());
punct.min(conjunction)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Stance {
Asserted,
Denied,
Suspended,
}
fn has_infinitive(between: &str, pack: &LanguagePack) -> bool {
between
.split_whitespace()
.any(|word| word == pack.infinitive_marker)
}
fn assertion_stance(between: &str, pack: &LanguagePack) -> Stance {
let mut denied = false;
for word in between.split(|c: char| !c.is_ascii_alphanumeric() && c != '\'') {
if pack.suspending_words.contains(&word) {
return Stance::Suspended;
}
if word.ends_with(pack.negation_clitic) || pack.negators.contains(&word) {
denied = true;
}
}
if denied {
Stance::Denied
} else {
Stance::Asserted
}
}
fn suspended_before(text: &str, from: usize, pack: &LanguagePack) -> bool {
text[..from]
.split(|c: char| !c.is_ascii_alphanumeric())
.any(|word| {
let word = word.to_lowercase();
pack.suspending_words.contains(&word.as_str()) || word == pack.infinitive_marker
})
}
fn ends_in_question(text: &str, from: usize) -> bool {
let tail = &text[from..];
matches!(tail.find(['.', '!', '?']), Some(i) if tail[i..].starts_with('?'))
}
fn heads_possessed_phrase(phrase: &str, start: usize, end: usize, pack: &LanguagePack) -> bool {
let after = phrase[end..].trim();
let closes = after.is_empty()
|| after
.split(|c: char| !c.is_alphabetic())
.next()
.is_some_and(|word| {
pack.possessive_tails
.contains(&word.to_lowercase().as_str())
});
closes && find_ascii_ci(&fold_apostrophe(&phrase[..start]), pack.possessive_clitic).is_none()
}
fn reversed_possessive_phrase<'a>(between: &'a str, pack: &LanguagePack) -> Option<&'a str> {
let rest = between.strip_prefix(pack.possessive_clitic)?;
if !rest.starts_with(' ') {
return None;
}
let (phrase, copula) = rest.trim().rsplit_once(' ')?;
pack.possessive_copulas
.contains(&copula)
.then(|| phrase.trim_end())
}
fn is_possessive_link(between: &str, pack: &LanguagePack) -> bool {
let trimmed = between.trim();
if pack.possessive_copulas.contains(&trimmed) || is_appositive_link(between, pack) {
return true;
}
match trimmed.split_once(' ') {
Some((copula, negator)) => {
pack.possessive_copulas.contains(&copula) && pack.negators.contains(&negator)
}
None => trimmed
.strip_suffix(pack.negation_clitic)
.is_some_and(|copula| pack.possessive_copulas.contains(&copula)),
}
}
fn is_appositive_link(between: &str, pack: &LanguagePack) -> bool {
let Some(rest) = between.trim_start().strip_prefix(',') else {
return false;
};
rest.split_whitespace()
.all(|word| pack.appositive_modifiers.contains(&word))
}
fn of_genitive_noun<'a>(between: &'a str, pack: &LanguagePack) -> Option<&'a str> {
let trimmed = between.trim();
let rest = match trimmed.strip_prefix(',') {
Some(rest) => rest,
None => {
let (link, rest) = trimmed.split_once(' ')?;
pack.possessive_copulas.contains(&link).then_some(rest)?
}
};
let mut words = rest.split_whitespace();
if words.next_back()? != pack.genitive_link {
return None;
}
let noun = words.next_back()?;
words
.all(|word| pack.appositive_modifiers.contains(&word) || pack.negators.contains(&word))
.then_some(noun)
}
fn opens_possessive(text: &str, from: usize, pack: &LanguagePack) -> bool {
clitic_len(&text.as_bytes()[from..], pack).is_some()
}
fn clitic_len(bytes: &[u8], pack: &LanguagePack) -> Option<usize> {
let clitic = pack.possessive_clitic.as_bytes();
if bytes
.get(..clitic.len())
.is_some_and(|head| head.eq_ignore_ascii_case(clitic))
{
return Some(clitic.len());
}
const CURLY: &[u8] = "\u{2019}".as_bytes();
let rest = &clitic[1..];
(bytes.starts_with(CURLY)
&& bytes
.get(CURLY.len()..CURLY.len() + rest.len())
.is_some_and(|tail| tail.eq_ignore_ascii_case(rest)))
.then_some(CURLY.len() + rest.len())
}
fn fold_apostrophe(text: &str) -> String {
text.replace('\u{2019}', "'")
}
fn find_relation_pattern(
text: &str,
subj: &EntityCandidate,
obj: &EntityCandidate,
pack: &LanguagePack,
scope: &Scope,
) -> Option<PatternMatch> {
if subj.end > obj.start {
return None;
}
let (start, end) = (subj.end, obj.start);
let gap = end - start;
if gap > MAX_GAP_BYTES {
return None;
}
let between = &fold_apostrophe(&text[start..end].to_lowercase());
let stance = match assertion_stance(between, pack) {
Stance::Denied if suspended_before(text, subj.start, pack) => Stance::Suspended,
other => other,
};
if stance == Stance::Suspended || ends_in_question(text, obj.end) {
return None;
}
if conditioned_before(text, subj.start, pack) {
return None;
}
if !has_infinitive(between, pack) {
if let Some(m) = match_rules(text, obj, pack, between, gap) {
return Some(m.stance(stance));
}
}
if !usable_mention(subj, pack)
|| !usable_mention(obj, pack)
|| !pronoun_is_unambiguous(subj, pack, scope)
|| !pronoun_is_unambiguous(obj, pack, scope)
{
return None;
}
let found = match_pronoun_possessive(text, subj, obj, pack, scope, between, gap)
.or_else(|| match_kin_prefix(text, subj, obj, pack, scope, between, gap))
.or_else(|| match_plural_pair(text, subj, obj, pack, scope, between, gap))
.or_else(|| match_phrase_rules(text, subj, obj, pack, scope, between, gap))?;
Some(match found.stance {
Stance::Asserted => found.stance(stance),
_ => found,
})
}
fn conditioned_before(text: &str, from: usize, pack: &LanguagePack) -> bool {
let prefix = &text[..from];
let clause_start = prefix
.rfind([
';', ':', '\u{2014}', '"', '\u{201C}', '\u{201D}', '\u{2018}',
])
.map(|i| i + prefix[i..].chars().next().map_or(1, char::len_utf8))
.max(prefix.rfind("--").map(|i| i + 2))
.unwrap_or(0);
text[clause_start..from]
.split(|c: char| !c.is_alphabetic())
.enumerate()
.any(|(index, word)| {
let lower = word.to_lowercase();
pack.suspending_words.contains(&lower.as_str())
&& (word == lower || (index == 0 && lower != "may"))
})
}
fn usable_mention(entity: &EntityCandidate, pack: &LanguagePack) -> bool {
!(entity.pronoun
&& pack
.plural_pronouns
.contains(&entity.text.to_lowercase().as_str()))
}
fn pronoun_fits_phrase(
text: &str,
entity: &EntityCandidate,
pack: &LanguagePack,
subject: bool,
) -> bool {
if !entity.pronoun {
return true;
}
let word = entity.text.to_lowercase();
if matches!(word.as_str(), "my" | "his" | "their" | "its" | "our") {
return false;
}
subject || object_pronoun_ends_phrase(text, entity.end, pack)
}
fn object_pronoun_ends_phrase(text: &str, from: usize, pack: &LanguagePack) -> bool {
let rest = text[from..].trim_start();
match rest.chars().next() {
None => true,
Some(c) if !c.is_alphabetic() => true,
Some(_) => {
let word: String = rest
.chars()
.take_while(|c| c.is_alphabetic())
.collect::<String>()
.to_lowercase();
pack.object_followers.contains(&word.as_str())
}
}
}
fn pronoun_is_unambiguous(entity: &EntityCandidate, pack: &LanguagePack, scope: &Scope) -> bool {
!entity.pronoun
|| is_first_person(entity, pack)
|| pack
.possessive_pronouns
.contains(&entity.text.to_lowercase().as_str())
|| lone_antecedent(entity, scope)
}
fn lone_antecedent(pronoun: &EntityCandidate, scope: &Scope) -> bool {
scope
.mentions
.iter()
.filter(|m| !m.pronoun && m.end <= pronoun.start)
.count()
<= 1
}
fn kind_of(text: &str, entity: &EntityCandidate, pack: &LanguagePack, scope: &Scope) -> Kind {
classify(text, entity, scope.register, pack)
}
fn window_tokens(between: &str) -> Option<Vec<&str>> {
if between
.chars()
.any(|c| !(c.is_alphabetic() || c.is_whitespace() || matches!(c, ',' | '\'' | '-')))
{
return None;
}
let mut tokens = Vec::new();
let mut start = None;
for (index, c) in between
.char_indices()
.chain(std::iter::once((between.len(), ' ')))
{
if c.is_whitespace() || c == ',' {
if let Some(from) = start.take() {
tokens.push(&between[from..index]);
}
if c == ',' {
tokens.push(",");
}
} else {
start.get_or_insert(index);
}
}
Some(tokens)
}
fn match_phrase_rules(
text: &str,
subj: &EntityCandidate,
obj: &EntityCandidate,
pack: &LanguagePack,
scope: &Scope,
between: &str,
gap: usize,
) -> Option<PatternMatch> {
if !pronoun_fits_phrase(text, subj, pack, true) || !pronoun_fits_phrase(text, obj, pack, false)
{
return None;
}
let mut tokens = window_tokens(between)?;
if tokens.first() == Some(&",") {
if !matches!(tokens.get(1), Some(&"who") | Some(&"whom")) {
return None;
}
tokens.drain(..2);
}
while tokens
.last()
.is_some_and(|w| pack.phrase_trailers.contains(w))
{
tokens.pop();
}
if tokens.is_empty() || tokens.contains(&",") {
return None;
}
if opens_possessive(text, obj.end, pack) {
return None;
}
let (subject_kind, object_kind) = (
kind_of(text, subj, pack, scope),
kind_of(text, obj, pack, scope),
);
for split in 0..tokens.len() {
if !tokens[..split]
.iter()
.all(|w| pack.phrase_fillers.contains(w))
{
break;
}
let rest = tokens[split..].join(" ");
for rule in pack.phrase_rules {
if !rule.phrases.contains(&rest.as_str()) {
continue;
}
if !rule.subject.admits(subject_kind) || !rule.object.admits(object_kind) {
continue;
}
return Some(
PatternMatch::new(rule.relation, rule.rule, rule.base, gap).swapped(rule.passive),
);
}
}
None
}
fn match_plural_pair(
text: &str,
subj: &EntityCandidate,
obj: &EntityCandidate,
pack: &LanguagePack,
scope: &Scope,
between: &str,
gap: usize,
) -> Option<PatternMatch> {
if between.trim() != "and" || subj.pronoun || obj.pronoun {
return None;
}
if text[..subj.start].trim_end().ends_with(',') {
return None;
}
let mut words = text[obj.end..]
.split(|c: char| !c.is_alphabetic() && c != '\'')
.filter(|w| !w.is_empty());
let copula = words.next()?.to_lowercase();
if !pack.plural_copulas.contains(&copula.as_str()) {
return None;
}
let mut word = words.next()?.to_lowercase();
let mut denied = false;
if pack.negators.contains(&word.as_str()) {
denied = true;
word = words.next()?.to_lowercase();
}
let mut skipped = 0;
while skipped < 2
&& (pack.appositive_modifiers.contains(&word.as_str())
|| pack.plural_modifiers.contains(&word.as_str()))
{
word = words.next()?.to_lowercase();
skipped += 1;
}
let (_, relation, base) = pack
.plural_nouns
.iter()
.find(|(noun, _, _)| *noun == word)?;
if !Slot::Person.admits(kind_of(text, subj, pack, scope))
|| !Slot::Person.admits(kind_of(text, obj, pack, scope))
{
return None;
}
let mut found = PatternMatch::new(relation, format!("plural-{word}-pattern"), *base, gap);
if denied {
found = found.stance(Stance::Denied);
}
Some(found)
}
fn match_kin_prefix(
text: &str,
subj: &EntityCandidate,
obj: &EntityCandidate,
pack: &LanguagePack,
scope: &Scope,
between: &str,
gap: usize,
) -> Option<PatternMatch> {
let pronoun_possessor = subj.pronoun
&& pack
.possessive_pronouns
.contains(&subj.text.to_lowercase().as_str());
let rest = if pronoun_possessor {
between
} else if subj.pronoun {
return None;
} else {
between.strip_prefix(pack.possessive_clitic)?
};
if !rest.starts_with(' ') {
return None;
}
let tokens = window_tokens(rest.trim_end_matches([' ', ',']))?;
let (noun, modifiers) = tokens.split_last()?;
if tokens.contains(&",")
|| !modifiers
.iter()
.all(|w| pack.appositive_modifiers.contains(w))
{
return None;
}
let (_, relation, base) = pack.possessive_nouns.iter().find(|(n, _, _)| n == noun)?;
if obj.pronoun {
return None;
}
if !Slot::Person.admits(kind_of(text, subj, pack, scope))
|| !Slot::Person.admits(kind_of(text, obj, pack, scope))
{
return None;
}
if pronoun_possessor && !possessor_is_sure(subj, scope, pack) {
return None;
}
let base = if pronoun_possessor {
base - 0.12
} else {
*base
};
Some(PatternMatch::new(relation, format!("kin-prefix-{noun}-pattern"), base, gap).swapped(true))
}
fn match_pronoun_possessive(
text: &str,
subj: &EntityCandidate,
obj: &EntityCandidate,
pack: &LanguagePack,
scope: &Scope,
between: &str,
gap: usize,
) -> Option<PatternMatch> {
if !obj.pronoun
|| subj.pronoun
|| !pack
.possessive_pronouns
.contains(&obj.text.to_lowercase().as_str())
|| !is_possessive_link(between, pack)
{
return None;
}
let rest = &text[obj.end..];
let phrase = &rest[..possessed_noun_phrase_len(rest, pack)];
if !phrase.starts_with(' ') {
return None;
}
if !Slot::Person.admits(kind_of(text, subj, pack, scope)) {
return None;
}
if !possessor_is_sure(obj, scope, pack) {
return None;
}
for (noun, relation, base) in pack.possessive_nouns {
let Some((noun_start, noun_end)) = find_ascii_ci_word(phrase, noun) else {
continue;
};
if !heads_possessed_phrase(phrase, noun_start, noun_end, pack)
|| !phrase[..noun_start].split_whitespace().all(|w| {
pack.appositive_modifiers
.contains(&w.to_lowercase().as_str())
})
{
continue;
}
let base = if is_first_person(obj, pack) {
*base
} else {
base - 0.12
};
return Some(
PatternMatch::new(relation, format!("pronoun-{noun}-pattern"), base, gap)
.span_end(obj.end + noun_end),
);
}
None
}
fn is_first_person(entity: &EntityCandidate, pack: &LanguagePack) -> bool {
pack.first_person_pronouns
.contains(&entity.text.to_lowercase().as_str())
}
fn possessor_is_sure(pronoun: &EntityCandidate, scope: &Scope, pack: &LanguagePack) -> bool {
is_first_person(pronoun, pack)
|| (lone_antecedent(pronoun, scope)
&& scope
.register
.allows(&pronoun.text, &pronoun.normalized, pack))
}
fn match_rules(
text: &str,
obj: &EntityCandidate,
pack: &LanguagePack,
between: &str,
gap: usize,
) -> Option<PatternMatch> {
let after_obj = &text[obj.end..];
let bytes = after_obj.as_bytes();
let clitic_len = clitic_len(bytes, pack).unwrap_or(0);
let possessive = clitic_len > 0 && matches!(bytes.get(clitic_len), Some(b' ') | Some(b'.'));
if possessive && is_possessive_link(between, pack) {
let rest = &after_obj[clitic_len..];
let phrase = &rest[..possessed_noun_phrase_len(rest, pack)];
let phrase_start = obj.end + clitic_len;
for (noun, relation, base) in pack.possessive_nouns {
let Some((noun_start, noun_end)) = find_ascii_ci_word(phrase, noun) else {
continue;
};
if !heads_possessed_phrase(phrase, noun_start, noun_end, pack) {
continue;
}
return Some(
PatternMatch::new(relation, format!("possessive-{noun}-pattern"), *base, gap)
.span_end(phrase_start + noun_end),
);
}
}
if let Some(noun) = of_genitive_noun(between, pack) {
if !opens_possessive(text, obj.end, pack) {
if let Some((_, relation, base)) =
pack.possessive_nouns.iter().find(|(n, _, _)| *n == noun)
{
return Some(PatternMatch::new(
relation,
format!("of-genitive-{noun}-pattern"),
*base,
gap,
));
}
}
}
if let Some(phrase) = reversed_possessive_phrase(between, pack) {
if !opens_possessive(text, obj.end, pack) {
for (noun, relation, base) in pack.possessive_nouns {
let Some((noun_start, noun_end)) = find_ascii_ci_word(phrase, noun) else {
continue;
};
if !heads_possessed_phrase(phrase, noun_start, noun_end, pack) {
continue;
}
return Some(
PatternMatch::new(relation, format!("possessive-{noun}-pattern"), *base, gap)
.swapped(true),
);
}
}
}
if let Some(m) = match_verb_rules(between, pack.verb_rules, gap) {
return Some(m);
}
if between.contains(pack.relative_opener) {
if let Some(m) = match_verb_rules(between, pack.relative_rules, gap) {
return Some(m);
}
}
None
}
fn match_verb_rules(between: &str, rules: &[VerbRule], gap: usize) -> Option<PatternMatch> {
rules
.iter()
.find(|rule| {
between.contains(rule.marker) && rule.also.map_or(true, |also| between.contains(also))
})
.map(|rule| {
let passive = rule
.passive_marker
.is_some_and(|marker| between.contains(marker));
PatternMatch::new(rule.relation, rule.rule, rule.base, gap).swapped(passive)
})
}
pub fn normalize_relation(rel: &str, ontology: &BTreeMap<String, String>) -> String {
if ontology.is_empty() {
return rel.to_string();
}
let rel_lower = rel.to_lowercase();
if let Some(canonical) = ontology.get(&rel_lower) {
canonical.clone()
} else {
rel.to_string()
}
}