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.to_i64().is_ok_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                        if me.0.signum() == other.0.signum() {
372                            let new = t.clone() * me.1 * other.0.abs()
373                                - pos.clone() * me.0.abs() * other.1;
374                            if !visited.contains(&new) {
375                                todo.push(new);
376                            }
377                        }
378                    }
379                }
380            }
381            visited.push(t);
382            if visited.len() > 10 {
383                break;
384            }
385        }
386        false
387    }
388
389    pub(crate) fn prove_positive_or_zero_with_extra(&self, t: &TDim, extra: &[Assertion]) -> bool {
390        if let TDim::Val(v) = t {
391            return *v >= 0;
392        }
393        // Skip the proof cache for extra-assertion calls (cache is keyed without extra context)
394        self.prove_positive_or_zero_inner_with_extra(t, extra)
395    }
396
397    pub(crate) fn prove_strict_positive_with_extra(&self, b: &TDim, extra: &[Assertion]) -> bool {
398        self.prove_positive_or_zero_with_extra(&(b.clone() - 1), extra)
399    }
400}
401
402impl fmt::Debug for SymbolScope {
403    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
404        let locked = self.0.lock();
405        let locked = locked.borrow();
406        write!(
407            f,
408            "symbols: {}; assertions: {}; {}",
409            locked.table.into_iter().map(|(_, s)| s).sorted().join(", "),
410            locked.assertions.iter().map(|s| s.to_string()).sorted().join(", "),
411            locked
412                .scenarios
413                .iter()
414                .map(|s| format!(
415                    "{}: {}",
416                    s.0,
417                    s.1.iter().map(|s| s.to_string()).sorted().join(", ")
418                ))
419                .join(" ; "),
420        )
421    }
422}
423
424#[derive(Clone)]
425pub struct Symbol(Weak<SymbolScopeInner>, string_interner::DefaultSymbol);
426
427impl Eq for Symbol {}
428
429impl PartialEq for Symbol {
430    fn eq(&self, other: &Self) -> bool {
431        self.1 == other.1
432    }
433}
434
435impl Symbol {
436    pub fn scope(&self) -> Option<SymbolScope> {
437        self.0.upgrade().map(SymbolScope)
438    }
439}
440
441impl PartialOrd for Symbol {
442    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
443        Some(self.cmp(other))
444    }
445}
446
447impl Ord for Symbol {
448    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
449        self.1.cmp(&other.1)
450    }
451}
452
453impl std::hash::Hash for Symbol {
454    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
455        self.1.hash(state)
456    }
457}
458
459impl std::fmt::Display for Symbol {
460    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
461        if let Some(scope) = self.scope() {
462            let lock = scope.0.lock();
463            let lock = lock.borrow();
464            if let Some(s) = lock.table.resolve(self.1) {
465                return write!(f, "{s}");
466            }
467        }
468        write!(f, "<Sym{}>", self.1.to_usize())
469    }
470}
471
472impl fmt::Debug for Symbol {
473    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
474        Display::fmt(&self, f)
475    }
476}
477
478#[derive(Clone, Debug, Default)]
479pub struct SymbolValues {
480    values: HashMap<Symbol, i64>,
481}
482
483impl SymbolValues {
484    pub fn with(mut self, s: &Symbol, v: i64) -> Self {
485        self.set(s, v);
486        self
487    }
488
489    pub fn set(&mut self, s: &Symbol, v: i64) {
490        self.values.insert(s.clone(), v);
491    }
492
493    pub fn get(&self, s: &Symbol) -> Option<i64> {
494        self.values.get(s).copied()
495    }
496
497    /// View the bindings as `Symbol → TDim` (each `i64` lifted to `TDim::Val`),
498    /// for callers that need to plug into APIs taking `HashMap<Symbol, TDim>`.
499    pub fn to_dim_map(&self) -> HashMap<Symbol, TDim> {
500        self.values.iter().map(|(s, v)| (s.clone(), TDim::Val(*v))).collect()
501    }
502}
503
504#[cfg(test)]
505mod tests {
506    use super::*;
507
508    #[test]
509    fn as_known_positive_gte() {
510        let s = SymbolScope::default();
511        assert_eq!(
512            parse_assertion(&s, "S>=0").unwrap().as_known_positive(),
513            Some(s.parse_tdim("S").unwrap())
514        );
515    }
516
517    #[test]
518    fn as_known_positive_gt() {
519        let s = SymbolScope::default();
520        assert_eq!(
521            parse_assertion(&s, "S>0").unwrap().as_known_positive(),
522            Some(s.parse_tdim("S-1").unwrap())
523        );
524    }
525
526    #[test]
527    fn as_known_positive_lte() {
528        let s = SymbolScope::default();
529        assert_eq!(
530            parse_assertion(&s, "S<=0").unwrap().as_known_positive(),
531            Some(s.parse_tdim("-S").unwrap())
532        );
533    }
534
535    #[test]
536    fn as_known_positive_lt() {
537        let s = SymbolScope::default();
538        assert_eq!(
539            parse_assertion(&s, "S<0").unwrap().as_known_positive(),
540            Some(s.parse_tdim("-S - 1").unwrap())
541        );
542    }
543
544    #[test]
545    fn prove_positive_0() {
546        let s = SymbolScope::default();
547        assert!(s.parse_tdim("0").unwrap().prove_positive_or_zero());
548    }
549
550    #[test]
551    fn prove_positive_1() {
552        let s = SymbolScope::default();
553        assert!(s.parse_tdim("1").unwrap().prove_positive_or_zero());
554    }
555
556    #[test]
557    fn prove_positive_neg1() {
558        let s = SymbolScope::default();
559        assert!(!s.parse_tdim("-1").unwrap().prove_positive_or_zero());
560    }
561
562    #[test]
563    fn prove_positive_add_0() {
564        let s = SymbolScope::default();
565        assert!(!s.parse_tdim("s+1").unwrap().prove_positive_or_zero());
566    }
567}