Skip to main content

tract_data/dim/
sym.rs

1use itertools::Itertools;
2use parking_lot::ReentrantMutex;
3use std::cell::RefCell;
4use std::collections::HashMap;
5use std::fmt::{self, Display};
6use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
7use std::sync::{Arc, Weak};
8use string_interner::DefaultStringInterner;
9use string_interner::Symbol as _;
10
11use crate::TractResult;
12
13use super::parse::parse_assertion;
14use super::{Assertion, TDim, parse_tdim};
15
16static SCOPE_COUNTER: AtomicUsize = AtomicUsize::new(0);
17
18/// Wrapper with lock-free hot-path flags alongside the scope data lock.
19/// Derefs to the inner mutex so existing `scope.0.lock()` call sites keep
20/// working.
21pub struct SymbolScopeInner {
22    /// Lock-free: true iff `scenarios` is non-empty. Maintained by
23    /// `add_scenario` / `add_scenario_assertion`. Lets `guess_scenario` skip
24    /// the lock entirely on the common no-scenarios path.
25    has_scenarios: AtomicBool,
26    data: ReentrantMutex<RefCell<SymbolScopeData>>,
27}
28
29impl Default for SymbolScopeInner {
30    fn default() -> Self {
31        SymbolScopeInner { has_scenarios: AtomicBool::new(false), data: Default::default() }
32    }
33}
34
35impl std::ops::Deref for SymbolScopeInner {
36    type Target = ReentrantMutex<RefCell<SymbolScopeData>>;
37    fn deref(&self) -> &Self::Target {
38        &self.data
39    }
40}
41
42#[derive(Clone, Default)]
43pub struct SymbolScope(pub Arc<SymbolScopeInner>);
44
45impl PartialEq for SymbolScope {
46    fn eq(&self, other: &Self) -> bool {
47        Arc::ptr_eq(&self.0, &other.0)
48    }
49}
50
51impl Eq for SymbolScope {}
52
53pub struct SymbolScopeData {
54    id: usize,
55    table: DefaultStringInterner,
56    assertions: Vec<Assertion>,
57    scenarios: Vec<(String, Vec<Assertion>)>,
58}
59
60impl Default for SymbolScopeData {
61    fn default() -> Self {
62        SymbolScopeData {
63            id: SCOPE_COUNTER.fetch_add(1, Ordering::Relaxed),
64            table: DefaultStringInterner::default(),
65            assertions: Vec::new(),
66            scenarios: Vec::new(),
67        }
68    }
69}
70
71impl SymbolScope {
72    pub fn id(&self) -> usize {
73        let locked = self.0.lock();
74        let locked = locked.borrow();
75        locked.id
76    }
77
78    pub fn proof_cache_session(&self) -> ProofCacheSession {
79        ProofCacheSession::new(self.id())
80    }
81
82    pub fn get(&self, name: &str) -> Option<Symbol> {
83        let locked = self.0.lock();
84        let locked = locked.borrow();
85        locked.table.get(name).map(|sym| Symbol(Arc::downgrade(&self.0), sym))
86    }
87
88    /// Get or create the coordinate symbol for axis `k` (named "🎯{k}").
89    pub fn coord_sym(&self, k: usize) -> Symbol {
90        self.sym(&format!("🎯{k}"))
91    }
92
93    pub fn sym(&self, name: &str) -> Symbol {
94        let locked = self.0.lock();
95        let mut locked = locked.borrow_mut();
96        let sym = locked.table.get_or_intern(name);
97        Symbol(Arc::downgrade(&self.0), sym)
98    }
99
100    pub fn new_with_prefix(&self, prefix: &str) -> Symbol {
101        let locked = self.0.lock();
102        let mut locked = locked.borrow_mut();
103        let sym = if locked.table.get(prefix).is_none() {
104            locked.table.get_or_intern(prefix)
105        } else {
106            let mut i = 0;
107            loop {
108                let s = format!("{prefix}_{i}");
109                if locked.table.get(&s).is_none() {
110                    break locked.table.get_or_intern(s);
111                }
112                i += 1;
113            }
114        };
115        Symbol(Arc::downgrade(&self.0), sym)
116    }
117
118    pub fn parse_tdim(&self, input: impl AsRef<str>) -> TractResult<TDim> {
119        parse_tdim(self, input.as_ref())
120    }
121
122    pub fn add_assertion(&self, assert: impl Into<String>) -> TractResult<()> {
123        let assert = assert.into();
124        let assert = parse_assertion(self, &assert)?;
125        let locked = self.0.lock();
126        let mut locked = locked.borrow_mut();
127        locked.assertions.push(assert);
128        Ok(())
129    }
130
131    pub fn with_assertion(self, assert: impl Into<String>) -> TractResult<Self> {
132        self.add_assertion(assert)?;
133        Ok(self)
134    }
135
136    pub fn all_assertions(&self) -> Vec<Assertion> {
137        let locked = self.0.lock();
138        let locked = locked.borrow();
139        locked.assertions.clone()
140    }
141
142    pub fn all_scenarios(&self) -> impl IntoIterator<Item = (String, Vec<Assertion>)> {
143        let locked = self.0.lock();
144        let locked = locked.borrow();
145        locked.scenarios.clone()
146    }
147
148    pub fn add_scenario(&self, scenario: impl Into<String>) -> TractResult<()> {
149        let locked = self.0.lock();
150        let mut locked = locked.borrow_mut();
151        let s = scenario.into();
152        if !locked.scenarios.iter().any(|sc| sc.0 == s) {
153            locked.scenarios.push((s, vec![]));
154            self.0.has_scenarios.store(true, Ordering::Relaxed);
155        }
156        Ok(())
157    }
158
159    pub fn add_scenario_assertion(
160        &self,
161        scenario: impl Into<String>,
162        assertion: impl Into<String>,
163    ) -> TractResult<()> {
164        let assert = parse_assertion(self, &assertion.into())?;
165        let s = scenario.into();
166        let locked = self.0.lock();
167        let mut locked = locked.borrow_mut();
168        if let Some(s) = locked.scenarios.iter_mut().find(|sc| sc.0 == s) {
169            s.1.push(assert);
170        } else {
171            locked.scenarios.push((s, vec![assert]));
172            self.0.has_scenarios.store(true, Ordering::Relaxed);
173        }
174        Ok(())
175    }
176
177    pub fn with_scenario_assertion(
178        self,
179        scenario: impl Into<String>,
180        assertion: impl Into<String>,
181    ) -> TractResult<Self> {
182        self.add_scenario_assertion(scenario, assertion)?;
183        Ok(self)
184    }
185
186    pub fn with_scenario(self, scenario: impl Into<String>) -> TractResult<Self> {
187        self.add_scenario(scenario)?;
188        Ok(self)
189    }
190
191    pub fn all_symbols(&self) -> Vec<Symbol> {
192        self.0
193            .lock()
194            .borrow()
195            .table
196            .into_iter()
197            .map(|is| Symbol(Arc::downgrade(&self.0), is.0))
198            .collect()
199    }
200
201    pub fn guess_scenario(&self, values: &SymbolValues) -> TractResult<Option<usize>> {
202        // Hot path: most scopes have no scenarios. Skip the lock entirely.
203        if !self.0.has_scenarios.load(Ordering::Relaxed) {
204            return Ok(None);
205        }
206        let locked = self.0.lock();
207        let locked = locked.borrow();
208        if locked.scenarios.is_empty() {
209            return Ok(None);
210        }
211        let mut maybe = None;
212        for (ix, (_name, assertions)) in locked.scenarios.iter().enumerate() {
213            if assertions.iter().any(|a| a.check(values) == Some(false)) {
214                continue;
215            } else if assertions.iter().all(|a| a.check(values) == Some(true)) {
216                return Ok(Some(ix));
217            } else if maybe.is_none() {
218                maybe = Some(ix);
219            } else {
220                return Ok(None);
221            }
222        }
223        if maybe.is_some() {
224            Ok(maybe)
225        } else {
226            anyhow::bail!("No possible scenario");
227        }
228    }
229}
230
231thread_local! {
232    static PROOF_CACHE: RefCell<Option<ProofCache>> = const { RefCell::new(None) };
233}
234
235struct ProofCache {
236    scope_id: usize,
237    depth: usize,
238    cache: HashMap<TDim, bool>,
239}
240
241pub struct ProofCacheSession {
242    active: bool,
243}
244
245impl ProofCacheSession {
246    pub fn new(scope_id: usize) -> Self {
247        let active = PROOF_CACHE.with(|cell| {
248            let mut borrow = cell.borrow_mut();
249            match &mut *borrow {
250                None => {
251                    *borrow = Some(ProofCache { scope_id, depth: 1, cache: HashMap::new() });
252                    true
253                }
254                Some(pc) if pc.scope_id == scope_id => {
255                    pc.depth += 1;
256                    true
257                }
258                Some(_) => false,
259            }
260        });
261        ProofCacheSession { active }
262    }
263}
264
265impl Drop for ProofCacheSession {
266    fn drop(&mut self) {
267        if !self.active {
268            return;
269        }
270        PROOF_CACHE.with(|cell| {
271            let mut borrow = cell.borrow_mut();
272            if let Some(pc) = &mut *borrow {
273                pc.depth -= 1;
274                if pc.depth == 0 {
275                    *borrow = None;
276                }
277            }
278        });
279    }
280}
281
282impl SymbolScopeData {
283    pub fn all_assertions(&self) -> &[Assertion] {
284        &self.assertions
285    }
286
287    pub fn assertions(&self, scenario: Option<&str>) -> impl Iterator<Item = &'_ Assertion> {
288        self.assertions.iter().chain(
289            scenario
290                .and_then(|s| self.scenarios.iter().find(|s2| s2.0 == s))
291                .map(|s| &*s.1)
292                .unwrap_or(&[])
293                .iter(),
294        )
295    }
296
297    pub fn scenarios(&self) -> impl Iterator<Item = &'_ str> {
298        self.scenarios.iter().map(|s| &*s.0)
299    }
300
301    pub fn scenario(&self, s: &str) -> impl Iterator<Item = &'_ Assertion> {
302        self.scenarios.iter().find(|sc| sc.0 == s).map(|sc| &*sc.1).unwrap_or(&[]).iter()
303    }
304
305    pub fn resolving<R>(&self, sym: &Symbol, f: impl FnOnce(&str) -> R) -> Option<R> {
306        self.table.resolve(sym.1).map(f)
307    }
308
309    #[allow(clippy::mutable_key_type)]
310    pub fn prove_positive_or_zero(&self, t: &TDim) -> bool {
311        if let TDim::Val(v) = t {
312            return *v >= 0;
313        }
314        let cached = PROOF_CACHE.with(|cell| {
315            let borrow = cell.borrow();
316            if let Some(pc) = &*borrow {
317                debug_assert_eq!(pc.scope_id, self.id, "ProofCacheSession scope_id mismatch");
318                pc.cache.get(t).copied()
319            } else {
320                None
321            }
322        });
323        if let Some(result) = cached {
324            return result;
325        }
326        let result = self.prove_positive_or_zero_inner(t);
327        PROOF_CACHE.with(|cell| {
328            let mut borrow = cell.borrow_mut();
329            if let Some(pc) = &mut *borrow {
330                pc.cache.insert(t.clone(), result);
331            }
332        });
333        result
334    }
335
336    #[allow(clippy::mutable_key_type)]
337    fn prove_positive_or_zero_inner(&self, t: &TDim) -> bool {
338        self.prove_positive_or_zero_inner_with_extra(t, &[])
339    }
340
341    #[allow(clippy::mutable_key_type)]
342    fn prove_positive_or_zero_inner_with_extra(&self, t: &TDim, extra: &[Assertion]) -> bool {
343        let positives = self
344            .assertions
345            .iter()
346            .chain(extra.iter())
347            .filter_map(|i| i.as_known_positive())
348            .collect_vec();
349        let mut visited = vec![];
350        let mut todo = vec![t.clone()];
351        while let Some(t) = todo.pop() {
352            if t.as_i64().is_some_and(|i| i >= 0) {
353                return true;
354            }
355            if t.inclusive_bound(self, false).is_some_and(|l| l >= 0) {
356                return true;
357            }
358            // Div(a, q) with q >= 1 is non-negative whenever a is non-negative.
359            if let TDim::Div(a, q) = &t
360                && *q >= 1
361                && self.prove_positive_or_zero_inner_with_extra(a, extra)
362            {
363                return true;
364            }
365            let syms = t.symbols();
366            for s in syms {
367                let me = t.guess_slope(&s);
368                for pos in &positives {
369                    if pos.symbols().contains(&s) {
370                        let other = pos.guess_slope(&s);
371                        // t * a - pos * b >= 0 with pos >= 0 proves t >= 0 only for
372                        // a = me.1 * |other.0| > 0: a zero slope (s only in a
373                        // product) would turn any t into 0 - 0
374                        if other.0 != 0 && me.0.signum() == other.0.signum() {
375                            let new = t.clone() * me.1 * other.0.abs()
376                                - pos.clone() * me.0.abs() * other.1;
377                            if !visited.contains(&new) {
378                                todo.push(new);
379                            }
380                        }
381                    }
382                }
383            }
384            visited.push(t);
385            if visited.len() > 10 {
386                break;
387            }
388        }
389        false
390    }
391
392    pub(crate) fn prove_positive_or_zero_with_extra(&self, t: &TDim, extra: &[Assertion]) -> bool {
393        if let TDim::Val(v) = t {
394            return *v >= 0;
395        }
396        // Skip the proof cache for extra-assertion calls (cache is keyed without extra context)
397        self.prove_positive_or_zero_inner_with_extra(t, extra)
398    }
399
400    pub(crate) fn prove_strict_positive_with_extra(&self, b: &TDim, extra: &[Assertion]) -> bool {
401        self.prove_positive_or_zero_with_extra(&(b.clone() - 1), extra)
402    }
403}
404
405impl fmt::Debug for SymbolScope {
406    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
407        let locked = self.0.lock();
408        let locked = locked.borrow();
409        write!(
410            f,
411            "symbols: {}; assertions: {}; {}",
412            locked.table.into_iter().map(|(_, s)| s).sorted().join(", "),
413            locked.assertions.iter().map(|s| s.to_string()).sorted().join(", "),
414            locked
415                .scenarios
416                .iter()
417                .map(|s| format!(
418                    "{}: {}",
419                    s.0,
420                    s.1.iter().map(|s| s.to_string()).sorted().join(", ")
421                ))
422                .join(" ; "),
423        )
424    }
425}
426
427#[derive(Clone)]
428pub struct Symbol(Weak<SymbolScopeInner>, string_interner::DefaultSymbol);
429
430impl Eq for Symbol {}
431
432impl PartialEq for Symbol {
433    fn eq(&self, other: &Self) -> bool {
434        self.1 == other.1
435    }
436}
437
438impl Symbol {
439    pub fn scope(&self) -> Option<SymbolScope> {
440        self.0.upgrade().map(SymbolScope)
441    }
442}
443
444impl PartialOrd for Symbol {
445    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
446        Some(self.cmp(other))
447    }
448}
449
450impl Ord for Symbol {
451    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
452        self.1.cmp(&other.1)
453    }
454}
455
456impl std::hash::Hash for Symbol {
457    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
458        self.1.hash(state)
459    }
460}
461
462impl std::fmt::Display for Symbol {
463    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
464        if let Some(scope) = self.scope() {
465            let lock = scope.0.lock();
466            let lock = lock.borrow();
467            if let Some(s) = lock.table.resolve(self.1) {
468                return write!(f, "{s}");
469            }
470        }
471        write!(f, "<Sym{}>", self.1.to_usize())
472    }
473}
474
475impl fmt::Debug for Symbol {
476    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
477        Display::fmt(&self, f)
478    }
479}
480
481#[derive(Clone, Debug, Default)]
482pub struct SymbolValues {
483    values: HashMap<Symbol, i64>,
484}
485
486impl SymbolValues {
487    pub fn with(mut self, s: &Symbol, v: i64) -> Self {
488        self.set(s, v);
489        self
490    }
491
492    pub fn set(&mut self, s: &Symbol, v: i64) {
493        self.values.insert(s.clone(), v);
494    }
495
496    pub fn get(&self, s: &Symbol) -> Option<i64> {
497        self.values.get(s).copied()
498    }
499
500    /// View the bindings as `Symbol → TDim` (each `i64` lifted to `TDim::Val`),
501    /// for callers that need to plug into APIs taking `HashMap<Symbol, TDim>`.
502    pub fn to_dim_map(&self) -> HashMap<Symbol, TDim> {
503        self.values.iter().map(|(s, v)| (s.clone(), TDim::Val(*v))).collect()
504    }
505}
506
507#[cfg(test)]
508mod tests {
509    use super::*;
510
511    #[test]
512    fn as_known_positive_gte() {
513        let s = SymbolScope::default();
514        assert_eq!(
515            parse_assertion(&s, "S>=0").unwrap().as_known_positive(),
516            Some(s.parse_tdim("S").unwrap())
517        );
518    }
519
520    #[test]
521    fn as_known_positive_gt() {
522        let s = SymbolScope::default();
523        assert_eq!(
524            parse_assertion(&s, "S>0").unwrap().as_known_positive(),
525            Some(s.parse_tdim("S-1").unwrap())
526        );
527    }
528
529    #[test]
530    fn as_known_positive_lte() {
531        let s = SymbolScope::default();
532        assert_eq!(
533            parse_assertion(&s, "S<=0").unwrap().as_known_positive(),
534            Some(s.parse_tdim("-S").unwrap())
535        );
536    }
537
538    #[test]
539    fn as_known_positive_lt() {
540        let s = SymbolScope::default();
541        assert_eq!(
542            parse_assertion(&s, "S<0").unwrap().as_known_positive(),
543            Some(s.parse_tdim("-S - 1").unwrap())
544        );
545    }
546
547    #[test]
548    fn prove_positive_0() {
549        let s = SymbolScope::default();
550        assert!(s.parse_tdim("0").unwrap().prove_positive_or_zero());
551    }
552
553    #[test]
554    fn prove_positive_1() {
555        let s = SymbolScope::default();
556        assert!(s.parse_tdim("1").unwrap().prove_positive_or_zero());
557    }
558
559    #[test]
560    fn prove_positive_neg1() {
561        let s = SymbolScope::default();
562        assert!(!s.parse_tdim("-1").unwrap().prove_positive_or_zero());
563    }
564
565    #[test]
566    fn prove_positive_add_0() {
567        let s = SymbolScope::default();
568        assert!(!s.parse_tdim("s+1").unwrap().prove_positive_or_zero());
569    }
570}