tensorlogic-ir 0.1.0

Intermediate representation (IR) and AST types for TensorLogic
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
//! Effect system for tracking computational effects in TensorLogic expressions.
//!
//! This module provides an effect system that tracks various kinds of computational
//! effects in logical expressions and tensor operations, enabling:
//!
//! - **Effect tracking**: Know which operations have side effects
//! - **Differentiability**: Track which operations support gradient computation
//! - **Probabilistic reasoning**: Distinguish deterministic from stochastic operations
//! - **Memory safety**: Track memory access patterns
//! - **Effect polymorphism**: Functions parametric over effects
//!
//! # Examples
//!
//! ```
//! use tensorlogic_ir::effect_system::{Effect, EffectSet, ComputationalEffect};
//!
//! // Pure computation (no side effects)
//! let pure_effect = EffectSet::pure();
//! assert!(pure_effect.is_pure());
//!
//! // Differentiable operation
//! let diff_effect = EffectSet::new()
//!     .with(Effect::Computational(ComputationalEffect::Pure))
//!     .with(Effect::Differentiable);
//!
//! // Combine effects
//! let combined = pure_effect.union(&diff_effect);
//! assert!(combined.contains(&Effect::Differentiable));
//! ```

use serde::{Deserialize, Serialize};
use std::collections::HashSet;
use std::fmt;

use crate::IrError;

/// Computational purity effects.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum ComputationalEffect {
    /// Pure computation (no side effects, referentially transparent)
    Pure,
    /// Impure computation (may have side effects)
    Impure,
    /// I/O operations (reading/writing external state)
    IO,
}

impl fmt::Display for ComputationalEffect {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ComputationalEffect::Pure => write!(f, "Pure"),
            ComputationalEffect::Impure => write!(f, "Impure"),
            ComputationalEffect::IO => write!(f, "IO"),
        }
    }
}

/// Memory access effects.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum MemoryEffect {
    /// Read-only memory access
    ReadOnly,
    /// Read-write memory access
    ReadWrite,
    /// Memory allocation
    Allocating,
}

impl fmt::Display for MemoryEffect {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            MemoryEffect::ReadOnly => write!(f, "ReadOnly"),
            MemoryEffect::ReadWrite => write!(f, "ReadWrite"),
            MemoryEffect::Allocating => write!(f, "Allocating"),
        }
    }
}

/// Probabilistic effects.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum ProbabilisticEffect {
    /// Deterministic computation (same inputs → same outputs)
    Deterministic,
    /// Stochastic computation (involves randomness)
    Stochastic,
}

impl fmt::Display for ProbabilisticEffect {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ProbabilisticEffect::Deterministic => write!(f, "Deterministic"),
            ProbabilisticEffect::Stochastic => write!(f, "Stochastic"),
        }
    }
}

/// Individual effect kinds.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Effect {
    /// Computational purity
    Computational(ComputationalEffect),
    /// Memory access pattern
    Memory(MemoryEffect),
    /// Probabilistic behavior
    Probabilistic(ProbabilisticEffect),
    /// Supports automatic differentiation
    Differentiable,
    /// Does not support automatic differentiation
    NonDifferentiable,
    /// Asynchronous computation
    Async,
    /// Parallel computation
    Parallel,
    /// Custom user-defined effect
    Custom(String),
}

impl Effect {
    /// Check if this effect is pure
    pub fn is_pure(&self) -> bool {
        matches!(self, Effect::Computational(ComputationalEffect::Pure))
    }

    /// Check if this effect is impure
    pub fn is_impure(&self) -> bool {
        matches!(
            self,
            Effect::Computational(ComputationalEffect::Impure | ComputationalEffect::IO)
        )
    }

    /// Check if this effect is differentiable
    pub fn is_differentiable(&self) -> bool {
        matches!(self, Effect::Differentiable)
    }

    /// Check if this effect is stochastic
    pub fn is_stochastic(&self) -> bool {
        matches!(self, Effect::Probabilistic(ProbabilisticEffect::Stochastic))
    }
}

impl fmt::Display for Effect {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Effect::Computational(e) => write!(f, "{}", e),
            Effect::Memory(e) => write!(f, "{}", e),
            Effect::Probabilistic(e) => write!(f, "{}", e),
            Effect::Differentiable => write!(f, "Diff"),
            Effect::NonDifferentiable => write!(f, "NonDiff"),
            Effect::Async => write!(f, "Async"),
            Effect::Parallel => write!(f, "Parallel"),
            Effect::Custom(name) => write!(f, "{}", name),
        }
    }
}

/// Set of effects for an expression or operation.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct EffectSet {
    effects: HashSet<Effect>,
}

impl EffectSet {
    /// Create an empty effect set
    pub fn new() -> Self {
        EffectSet {
            effects: HashSet::new(),
        }
    }

    /// Create a pure effect set (pure + deterministic + differentiable)
    pub fn pure() -> Self {
        let mut effects = HashSet::new();
        effects.insert(Effect::Computational(ComputationalEffect::Pure));
        effects.insert(Effect::Probabilistic(ProbabilisticEffect::Deterministic));
        effects.insert(Effect::Memory(MemoryEffect::ReadOnly));
        EffectSet { effects }
    }

    /// Create an impure effect set
    pub fn impure() -> Self {
        let mut effects = HashSet::new();
        effects.insert(Effect::Computational(ComputationalEffect::Impure));
        EffectSet { effects }
    }

    /// Create a differentiable effect set
    pub fn differentiable() -> Self {
        let mut effects = HashSet::new();
        effects.insert(Effect::Differentiable);
        EffectSet { effects }
    }

    /// Create a stochastic effect set
    pub fn stochastic() -> Self {
        let mut effects = HashSet::new();
        effects.insert(Effect::Probabilistic(ProbabilisticEffect::Stochastic));
        EffectSet { effects }
    }

    /// Add an effect to this set
    pub fn with(mut self, effect: Effect) -> Self {
        self.effects.insert(effect);
        self
    }

    /// Add multiple effects
    pub fn with_all(mut self, effects: impl IntoIterator<Item = Effect>) -> Self {
        self.effects.extend(effects);
        self
    }

    /// Check if this set contains a specific effect
    pub fn contains(&self, effect: &Effect) -> bool {
        self.effects.contains(effect)
    }

    /// Check if this effect set is pure (contains Pure computational effect and no impure effects)
    pub fn is_pure(&self) -> bool {
        // Either empty or contains Pure and no impure effects
        if self.effects.is_empty() {
            return true;
        }

        let has_pure = self
            .effects
            .iter()
            .any(|e| matches!(e, Effect::Computational(ComputationalEffect::Pure)));

        let has_impure = self.effects.iter().any(|e| {
            matches!(
                e,
                Effect::Computational(ComputationalEffect::Impure | ComputationalEffect::IO)
            )
        });

        has_pure && !has_impure
    }

    /// Check if this effect set is impure
    pub fn is_impure(&self) -> bool {
        self.effects.iter().any(|e| e.is_impure())
    }

    /// Check if this effect set is differentiable
    pub fn is_differentiable(&self) -> bool {
        self.effects.iter().any(|e| e.is_differentiable())
            && !self
                .effects
                .iter()
                .any(|e| matches!(e, Effect::NonDifferentiable))
    }

    /// Check if this effect set is stochastic
    pub fn is_stochastic(&self) -> bool {
        self.effects.iter().any(|e| e.is_stochastic())
    }

    /// Get all effects in this set
    pub fn effects(&self) -> impl Iterator<Item = &Effect> {
        self.effects.iter()
    }

    /// Union of two effect sets
    pub fn union(&self, other: &EffectSet) -> EffectSet {
        let mut effects = self.effects.clone();
        effects.extend(other.effects.iter().cloned());
        EffectSet { effects }
    }

    /// Intersection of two effect sets
    pub fn intersection(&self, other: &EffectSet) -> EffectSet {
        let effects = self.effects.intersection(&other.effects).cloned().collect();
        EffectSet { effects }
    }

    /// Check if this effect set is a subset of another (subtyping)
    pub fn is_subset_of(&self, other: &EffectSet) -> bool {
        self.effects.is_subset(&other.effects)
    }

    /// Check if two effect sets are compatible
    pub fn is_compatible_with(&self, other: &EffectSet) -> bool {
        // Compatible if no conflicting effects
        !self.has_conflicts_with(other)
    }

    /// Check if there are conflicting effects
    fn has_conflicts_with(&self, other: &EffectSet) -> bool {
        // Pure and Impure conflict
        if (self.contains(&Effect::Computational(ComputationalEffect::Pure)) && other.is_impure())
            || (other.contains(&Effect::Computational(ComputationalEffect::Pure))
                && self.is_impure())
        {
            return true;
        }

        // Differentiable and NonDifferentiable conflict
        if (self.contains(&Effect::Differentiable) && other.contains(&Effect::NonDifferentiable))
            || (other.contains(&Effect::Differentiable)
                && self.contains(&Effect::NonDifferentiable))
        {
            return true;
        }

        false
    }

    /// Number of effects in this set
    pub fn len(&self) -> usize {
        self.effects.len()
    }

    /// Check if effect set is empty
    pub fn is_empty(&self) -> bool {
        self.effects.is_empty()
    }
}

impl Default for EffectSet {
    fn default() -> Self {
        Self::new()
    }
}

impl fmt::Display for EffectSet {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.effects.is_empty() {
            return write!(f, "{{}}");
        }

        write!(f, "{{")?;
        let mut first = true;
        for effect in &self.effects {
            if !first {
                write!(f, ", ")?;
            }
            write!(f, "{}", effect)?;
            first = false;
        }
        write!(f, "}}")
    }
}

/// Effect variable for effect polymorphism
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct EffectVar(pub String);

impl EffectVar {
    pub fn new(name: impl Into<String>) -> Self {
        EffectVar(name.into())
    }
}

impl fmt::Display for EffectVar {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "ε{}", self.0)
    }
}

/// Effect scheme for effect polymorphism (analogous to type schemes)
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum EffectScheme {
    /// Concrete effect set
    Concrete(EffectSet),
    /// Effect variable (for polymorphism)
    Variable(EffectVar),
    /// Union of effect schemes
    Union(Box<EffectScheme>, Box<EffectScheme>),
}

impl EffectScheme {
    /// Create a concrete effect scheme
    pub fn concrete(effects: EffectSet) -> Self {
        EffectScheme::Concrete(effects)
    }

    /// Create an effect variable
    pub fn variable(name: impl Into<String>) -> Self {
        EffectScheme::Variable(EffectVar::new(name))
    }

    /// Create a union of two effect schemes
    pub fn union(e1: EffectScheme, e2: EffectScheme) -> Self {
        EffectScheme::Union(Box::new(e1), Box::new(e2))
    }

    /// Substitute effect variables with concrete effect sets
    pub fn substitute(&self, subst: &EffectSubstitution) -> EffectScheme {
        match self {
            EffectScheme::Concrete(effects) => EffectScheme::Concrete(effects.clone()),
            EffectScheme::Variable(var) => {
                if let Some(effects) = subst.get(var) {
                    EffectScheme::Concrete(effects.clone())
                } else {
                    EffectScheme::Variable(var.clone())
                }
            }
            EffectScheme::Union(e1, e2) => {
                let s1 = e1.substitute(subst);
                let s2 = e2.substitute(subst);
                EffectScheme::union(s1, s2)
            }
        }
    }

    /// Evaluate to a concrete effect set (if possible)
    pub fn evaluate(&self, subst: &EffectSubstitution) -> Result<EffectSet, IrError> {
        match self {
            EffectScheme::Concrete(effects) => Ok(effects.clone()),
            EffectScheme::Variable(var) => {
                subst
                    .get(var)
                    .cloned()
                    .ok_or_else(|| IrError::UnboundVariable {
                        var: format!("effect variable {}", var),
                    })
            }
            EffectScheme::Union(e1, e2) => {
                let effects1 = e1.evaluate(subst)?;
                let effects2 = e2.evaluate(subst)?;
                Ok(effects1.union(&effects2))
            }
        }
    }
}

impl fmt::Display for EffectScheme {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            EffectScheme::Concrete(effects) => write!(f, "{}", effects),
            EffectScheme::Variable(var) => write!(f, "{}", var),
            EffectScheme::Union(e1, e2) => write!(f, "({}{})", e1, e2),
        }
    }
}

/// Substitution mapping effect variables to effect sets
pub type EffectSubstitution = std::collections::HashMap<EffectVar, EffectSet>;

/// Effect annotation for expressions
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct EffectAnnotation {
    /// The effect scheme for this expression
    pub scheme: EffectScheme,
    /// Optional description
    pub description: Option<String>,
}

impl EffectAnnotation {
    pub fn new(scheme: EffectScheme) -> Self {
        EffectAnnotation {
            scheme,
            description: None,
        }
    }

    pub fn with_description(mut self, description: impl Into<String>) -> Self {
        self.description = Some(description.into());
        self
    }

    /// Create a pure effect annotation
    pub fn pure() -> Self {
        EffectAnnotation::new(EffectScheme::concrete(EffectSet::pure()))
    }

    /// Create a differentiable effect annotation
    pub fn differentiable() -> Self {
        EffectAnnotation::new(EffectScheme::concrete(EffectSet::differentiable()))
    }
}

/// Infer effects for common operations
pub fn infer_operation_effects(op_name: &str) -> EffectSet {
    match op_name {
        // Pure logical operations
        "and" | "or" | "not" | "implies" => EffectSet::pure().with(Effect::Differentiable),

        // Arithmetic operations (pure and differentiable)
        "add" | "subtract" | "multiply" | "divide" => {
            EffectSet::pure().with(Effect::Differentiable)
        }

        // Quantifiers (pure but may not be differentiable)
        "exists" | "forall" => EffectSet::pure(),

        // Comparisons (pure but not differentiable)
        "equal" | "less_than" | "greater_than" => EffectSet::pure().with(Effect::NonDifferentiable),

        // Sampling operations (stochastic)
        "sample" | "random" => EffectSet::stochastic().with(Effect::NonDifferentiable),

        // I/O operations
        "read" | "write" => EffectSet::new()
            .with(Effect::Computational(ComputationalEffect::IO))
            .with(Effect::Memory(MemoryEffect::ReadWrite)),

        // Default: conservative (impure, non-differentiable)
        _ => EffectSet::impure().with(Effect::NonDifferentiable),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_effect_creation() {
        let pure = Effect::Computational(ComputationalEffect::Pure);
        assert!(pure.is_pure());
        assert!(!pure.is_impure());

        let impure = Effect::Computational(ComputationalEffect::Impure);
        assert!(!impure.is_pure());
        assert!(impure.is_impure());

        let diff = Effect::Differentiable;
        assert!(diff.is_differentiable());
    }

    #[test]
    fn test_effect_set_pure() {
        let pure_set = EffectSet::pure();
        assert!(pure_set.is_pure());
        assert!(!pure_set.is_impure());
        assert!(pure_set.contains(&Effect::Computational(ComputationalEffect::Pure)));
    }

    #[test]
    fn test_effect_set_differentiable() {
        let diff_set = EffectSet::differentiable();
        assert!(diff_set.is_differentiable());
        assert!(diff_set.contains(&Effect::Differentiable));
    }

    #[test]
    fn test_effect_set_union() {
        let pure = EffectSet::pure();
        let diff = EffectSet::differentiable();
        let combined = pure.union(&diff);

        assert!(combined.contains(&Effect::Computational(ComputationalEffect::Pure)));
        assert!(combined.contains(&Effect::Differentiable));
    }

    #[test]
    fn test_effect_set_intersection() {
        let set1 = EffectSet::pure().with(Effect::Differentiable);
        let set2 = EffectSet::differentiable();
        let intersection = set1.intersection(&set2);

        assert!(intersection.contains(&Effect::Differentiable));
        assert!(!intersection.contains(&Effect::Computational(ComputationalEffect::Pure)));
    }

    #[test]
    fn test_effect_set_subset() {
        let small = EffectSet::pure();
        let large = EffectSet::pure().with(Effect::Differentiable);

        assert!(small.is_subset_of(&large));
        assert!(!large.is_subset_of(&small));
    }

    #[test]
    fn test_effect_conflicts() {
        let pure = EffectSet::pure();
        let impure = EffectSet::impure();

        assert!(!pure.is_compatible_with(&impure));
        assert!(!impure.is_compatible_with(&pure));
    }

    #[test]
    fn test_effect_scheme_concrete() {
        let scheme = EffectScheme::concrete(EffectSet::pure());
        let subst = EffectSubstitution::new();
        let effects = scheme.evaluate(&subst).expect("unwrap");

        assert!(effects.is_pure());
    }

    #[test]
    fn test_effect_scheme_variable() {
        let var = EffectVar::new("e1");
        let scheme = EffectScheme::Variable(var.clone());

        let mut subst = EffectSubstitution::new();
        subst.insert(var, EffectSet::pure());

        let effects = scheme.evaluate(&subst).expect("unwrap");
        assert!(effects.is_pure());
    }

    #[test]
    fn test_effect_scheme_union() {
        let scheme1 = EffectScheme::concrete(EffectSet::pure());
        let scheme2 = EffectScheme::concrete(EffectSet::differentiable());
        let union_scheme = EffectScheme::union(scheme1, scheme2);

        let subst = EffectSubstitution::new();
        let effects = union_scheme.evaluate(&subst).expect("unwrap");

        assert!(effects.is_pure());
        assert!(effects.is_differentiable());
    }

    #[test]
    fn test_effect_annotation() {
        let annotation = EffectAnnotation::pure().with_description("Pure computation");

        assert_eq!(annotation.description.as_deref(), Some("Pure computation"));
    }

    #[test]
    fn test_infer_operation_effects() {
        let and_effects = infer_operation_effects("and");
        assert!(and_effects.is_pure());
        assert!(and_effects.is_differentiable());

        let sample_effects = infer_operation_effects("sample");
        assert!(sample_effects.is_stochastic());

        let io_effects = infer_operation_effects("read");
        assert!(io_effects.is_impure());
    }

    #[test]
    fn test_effect_set_stochastic() {
        let stochastic = EffectSet::stochastic();
        assert!(stochastic.is_stochastic());
        assert!(stochastic.contains(&Effect::Probabilistic(ProbabilisticEffect::Stochastic)));
    }

    #[test]
    fn test_memory_effects() {
        let read_only = Effect::Memory(MemoryEffect::ReadOnly);
        let read_write = Effect::Memory(MemoryEffect::ReadWrite);

        let set1 = EffectSet::new().with(read_only);
        let set2 = EffectSet::new().with(read_write);

        assert_ne!(set1, set2);
    }

    #[test]
    fn test_custom_effect() {
        let custom = Effect::Custom("GPUCompute".to_string());
        let set = EffectSet::new().with(custom.clone());

        assert!(set.contains(&custom));
    }

    #[test]
    fn test_effect_display() {
        let pure = Effect::Computational(ComputationalEffect::Pure);
        assert_eq!(pure.to_string(), "Pure");

        let diff = Effect::Differentiable;
        assert_eq!(diff.to_string(), "Diff");

        let custom = Effect::Custom("MyEffect".to_string());
        assert_eq!(custom.to_string(), "MyEffect");
    }

    #[test]
    fn test_effect_set_display() {
        let set = EffectSet::pure().with(Effect::Differentiable);
        let display = set.to_string();

        assert!(display.contains("Pure") || display.contains("Diff"));
        assert!(display.starts_with('{'));
        assert!(display.ends_with('}'));
    }

    #[test]
    fn test_effect_var_display() {
        let var = EffectVar::new("1");
        assert_eq!(var.to_string(), "ε1");
    }

    #[test]
    fn test_non_differentiable_conflicts() {
        let diff = EffectSet::new().with(Effect::Differentiable);
        let non_diff = EffectSet::new().with(Effect::NonDifferentiable);

        assert!(!diff.is_compatible_with(&non_diff));
    }
}