tensorlogic-compiler 0.1.1

Compiler for transforming logic expressions into tensor computation graphs
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
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
//! Modal and temporal logic compilation to tensor operations.
//!
//! This module implements compilation strategies for modal and temporal logic operators,
//! enabling reasoning about possibility, necessity, and temporal sequences in tensor form.
//!
//! # Modal Logic
//!
//! Modal logic extends classical logic with operators for reasoning about necessity and possibility:
//!
//! - **Box (□P)**: "P is necessarily true" - P holds in all possible worlds/states
//! - **Diamond (◇P)**: "P is possibly true" - P holds in at least one possible world/state
//!
//! ## Tensor Representation
//!
//! Modal operators require an additional "world" or "state" dimension in tensors:
//! - Predicates are evaluated over multiple possible worlds
//! - Box reduces over worlds using min/product (all worlds must satisfy P)
//! - Diamond reduces over worlds using max/sum (at least one world satisfies P)
//!
//! # Temporal Logic (LTL)
//!
//! Temporal logic extends classical logic with operators for reasoning about sequences over time:
//!
//! - **Next (XP)**: "P is true in the next state" (requires backend support for shifts)
//! - **Eventually (FP)**: "P will be true in some future state"
//! - **Always (GP)**: "P is true in all future states"
//! - **Until (P U Q)**: "P holds until Q becomes true" (complex, requires scan operations)

use anyhow::Result;
use tensorlogic_ir::{EinsumGraph, EinsumNode, TLExpr};

use crate::config::{ModalStrategy, TemporalStrategy};
use crate::context::{CompileState, CompilerContext};

use super::compile_expr;

/// Special axis name for modal "world" dimension
const WORLD_AXIS: &str = "__world__";

/// Special axis name for temporal "time" dimension
const TIME_AXIS: &str = "__time__";

/// Compile a Box (□) modal operator: "P is necessarily true in all possible worlds"
///
/// Tensor semantics:
/// - Reduces over the world axis using the configured modal strategy
/// - Default: Min reduction (all worlds must satisfy P)
/// - Alternative: Product reduction for probabilistic interpretation
pub(crate) fn compile_box(
    inner: &TLExpr,
    ctx: &mut CompilerContext,
    graph: &mut EinsumGraph,
) -> Result<CompileState> {
    // Ensure world axis exists in context
    let world_axis = ensure_world_axis(ctx);

    // Compile inner expression (should now have world axis available)
    let inner_state = compile_expr(inner, ctx, graph)?;

    // Get the modal strategy from config
    let strategy = ctx.config.modal_strategy;

    // Check if the inner expression actually uses the world axis
    if !inner_state.axes.contains(world_axis) {
        // If inner doesn't use world axis, just return it as-is
        // This handles predicates that don't reference possible worlds
        return Ok(inner_state);
    }

    // Apply reduction over world axis based on strategy
    match strategy {
        ModalStrategy::AllWorldsMin | ModalStrategy::Threshold { .. } => {
            // Use min reduction: all worlds must satisfy
            apply_reduction(&inner_state, world_axis, "min", ctx, graph)
        }
        ModalStrategy::AllWorldsProduct => {
            // Use product reduction: probabilistic interpretation
            apply_reduction(&inner_state, world_axis, "prod", ctx, graph)
        }
    }
}

/// Compile a Diamond (◇) modal operator: "P is possibly true in at least one world"
///
/// Tensor semantics:
/// - Reduces over the world axis using max/sum
/// - Default: Max reduction (at least one world satisfies P)
/// - Alternative: Sum reduction for probabilistic interpretation
pub(crate) fn compile_diamond(
    inner: &TLExpr,
    ctx: &mut CompilerContext,
    graph: &mut EinsumGraph,
) -> Result<CompileState> {
    // Ensure world axis exists
    let world_axis = ensure_world_axis(ctx);

    // Compile inner expression
    let inner_state = compile_expr(inner, ctx, graph)?;

    // Check if the inner expression actually uses the world axis
    if !inner_state.axes.contains(world_axis) {
        // If inner doesn't use world axis, just return it as-is
        return Ok(inner_state);
    }

    // Get the modal strategy from config
    let strategy = ctx.config.modal_strategy;

    // Apply reduction over world axis based on strategy
    match strategy {
        ModalStrategy::AllWorldsMin | ModalStrategy::Threshold { .. } => {
            // Use max reduction (dual of min for Box)
            apply_reduction(&inner_state, world_axis, "max", ctx, graph)
        }
        ModalStrategy::AllWorldsProduct => {
            // Use sum reduction (dual of product for probabilistic interpretation)
            apply_reduction(&inner_state, world_axis, "sum", ctx, graph)
        }
    }
}

/// Map a [`TemporalStrategy`] to the tag string embedded in `temporal_until:<tag>:<axis>`.
fn until_tag(strategy: TemporalStrategy) -> &'static str {
    match strategy {
        TemporalStrategy::Max | TemporalStrategy::LogSumExp => "max",
        TemporalStrategy::Sum => "prod",
    }
}

/// Compile Next (X) temporal operator: "P is true in the next time step"
///
/// Emits a `temporal_next:<axis>` unary node that the backend handles via
/// [`tensorlogic_scirs_backend::temporal_ops::shift_next`].
pub(crate) fn compile_next(
    inner: &TLExpr,
    ctx: &mut CompilerContext,
    graph: &mut EinsumGraph,
) -> Result<CompileState> {
    let time_axis = ensure_time_axis(ctx);

    // Compile the inner expression.
    let inner_state = compile_expr(inner, ctx, graph)?;

    // If the inner expression does not involve the time axis, Next is identity.
    if !inner_state.axes.contains(time_axis) {
        return Ok(inner_state);
    }

    let time_idx = inner_state
        .axes
        .chars()
        .position(|c| c == time_axis)
        .expect("just checked the time axis is present");

    // Create output tensor.
    let out_tensor = ctx.fresh_temp();
    let out_idx = graph.add_tensor(out_tensor);

    // Emit the unary temporal_next node.
    let node = EinsumNode::elem_unary(
        format!("temporal_next:{}", time_idx),
        inner_state.tensor_idx,
        out_idx,
    );
    graph.add_node(node)?;

    Ok(CompileState {
        tensor_idx: out_idx,
        axes: inner_state.axes,
    })
}

/// Compile Eventually (F) temporal operator: "P will be true in some future state"
///
/// Tensor semantics:
/// - Reduces over future time using max/sum
pub(crate) fn compile_eventually(
    inner: &TLExpr,
    ctx: &mut CompilerContext,
    graph: &mut EinsumGraph,
) -> Result<CompileState> {
    // Ensure time axis exists
    let time_axis = ensure_time_axis(ctx);

    // Compile inner expression
    let inner_state = compile_expr(inner, ctx, graph)?;

    // Check if the inner expression uses the time axis
    if !inner_state.axes.contains(time_axis) {
        return Ok(inner_state);
    }

    // Get temporal strategy from config
    let strategy = ctx.config.temporal_strategy;

    // Apply reduction based on strategy
    match strategy {
        TemporalStrategy::Max | TemporalStrategy::LogSumExp => {
            // Use max: true if true in any future state
            apply_reduction(&inner_state, time_axis, "max", ctx, graph)
        }
        TemporalStrategy::Sum => {
            // Use sum: probabilistic interpretation
            apply_reduction(&inner_state, time_axis, "sum", ctx, graph)
        }
    }
}

/// Compile Always (G) temporal operator: "P is true in all future states"
///
/// Tensor semantics:
/// - Reduces over future time using min/product
pub(crate) fn compile_always(
    inner: &TLExpr,
    ctx: &mut CompilerContext,
    graph: &mut EinsumGraph,
) -> Result<CompileState> {
    // Ensure time axis exists
    let time_axis = ensure_time_axis(ctx);

    // Compile inner expression
    let inner_state = compile_expr(inner, ctx, graph)?;

    // Check if the inner expression uses the time axis
    if !inner_state.axes.contains(time_axis) {
        return Ok(inner_state);
    }

    // Get temporal strategy from config
    let strategy = ctx.config.temporal_strategy;

    // Apply reduction based on strategy
    match strategy {
        TemporalStrategy::Max | TemporalStrategy::LogSumExp => {
            // Use min: true only if true in all future states
            apply_reduction(&inner_state, time_axis, "min", ctx, graph)
        }
        TemporalStrategy::Sum => {
            // Use product: probabilistic interpretation
            apply_reduction(&inner_state, time_axis, "prod", ctx, graph)
        }
    }
}

/// Compile Until (U) temporal operator: "P holds until Q becomes true"
///
/// Emits a `temporal_until:<tag>:<axis>` binary node that the backend handles
/// via [`tensorlogic_scirs_backend::temporal_ops::until_scan`].
pub(crate) fn compile_until(
    before: &TLExpr,
    after: &TLExpr,
    ctx: &mut CompilerContext,
    graph: &mut EinsumGraph,
) -> Result<CompileState> {
    let time_axis = ensure_time_axis(ctx);

    // Compile both sub-expressions.
    let before_state = compile_expr(before, ctx, graph)?;
    let after_state = compile_expr(after, ctx, graph)?;

    // Build the union of axes (same logic as compile_and in logic_ops.rs).
    let mut output_axes = String::new();
    let mut seen = std::collections::HashSet::new();

    for c in before_state.axes.chars() {
        if seen.insert(c) {
            output_axes.push(c);
        }
    }
    for c in after_state.axes.chars() {
        if seen.insert(c) {
            output_axes.push(c);
        }
    }

    // Ensure the time axis is in the output — it may not be there if both
    // operands are time-independent.  We force it by checking:
    if !output_axes.contains(time_axis) {
        output_axes.push(time_axis);
    }

    // Broadcast `before_state` and `after_state` to the union axes when needed.
    let mut before_aligned = before_state;
    let mut after_aligned = after_state;

    if before_aligned.axes != output_axes {
        let bspec = format!("{}->{}", before_aligned.axes, output_axes);
        let btmp = ctx.fresh_temp();
        let btmp_idx = graph.add_tensor(btmp);
        let bnode = EinsumNode::new(bspec, vec![before_aligned.tensor_idx], vec![btmp_idx]);
        graph.add_node(bnode)?;
        before_aligned = CompileState {
            tensor_idx: btmp_idx,
            axes: output_axes.clone(),
        };
    }

    if after_aligned.axes != output_axes {
        let aspec = format!("{}->{}", after_aligned.axes, output_axes);
        let atmp = ctx.fresh_temp();
        let atmp_idx = graph.add_tensor(atmp);
        let anode = EinsumNode::new(aspec, vec![after_aligned.tensor_idx], vec![atmp_idx]);
        graph.add_node(anode)?;
        after_aligned = CompileState {
            tensor_idx: atmp_idx,
            axes: output_axes.clone(),
        };
    }

    // Determine the positional index of the time axis in the output axes string.
    let time_idx = output_axes
        .chars()
        .position(|c| c == time_axis)
        .expect("time axis was inserted into output_axes above");

    // Choose the semantics tag from the temporal strategy.
    let tag = until_tag(ctx.config.temporal_strategy);

    // Emit the binary temporal_until node.
    let out_tensor = ctx.fresh_temp();
    let out_idx = graph.add_tensor(out_tensor);

    let node = EinsumNode::elem_binary(
        format!("temporal_until:{}:{}", tag, time_idx),
        before_aligned.tensor_idx,
        after_aligned.tensor_idx,
        out_idx,
    );
    graph.add_node(node)?;

    Ok(CompileState {
        tensor_idx: out_idx,
        axes: output_axes,
    })
}

/// Compile Release (R) temporal operator: "Q holds until and including when P first holds"
///
/// # Semantics
///
/// P R Q (P releases Q) means Q must hold continuously unless/until P becomes true;
/// if P never holds, Q must hold forever. Release is the dual of Until: P R Q ≡ ¬(¬P U ¬Q).
///
/// # Exact finite-trace recurrence
///
/// Emits a `temporal_release:<tag>:<axis>` binary node computed via the unified backward scan:
/// ```text
/// u[T-1] = AND(q[T-1], OR(p[T-1], boundary=1.0))
/// u[k]   = AND(q[k],   OR(p[k],   u[k+1]))           for k = T-2..0
/// ```
/// MaxMin semantics: AND=min, OR=max.
/// ProbSumProduct semantics: AND(x,y)=x*y, OR(x,y)=x+y-x*y.
///
/// Operand order: arg0 = p (releaser), arg1 = q (released).
pub(crate) fn compile_release(
    p: &TLExpr,
    q: &TLExpr,
    ctx: &mut CompilerContext,
    graph: &mut EinsumGraph,
) -> Result<CompileState> {
    let time_axis = ensure_time_axis(ctx);

    let p_state = compile_expr(p, ctx, graph)?;
    let q_state = compile_expr(q, ctx, graph)?;

    let mut output_axes = String::new();
    let mut seen = std::collections::HashSet::new();
    for c in p_state.axes.chars() {
        if seen.insert(c) {
            output_axes.push(c);
        }
    }
    for c in q_state.axes.chars() {
        if seen.insert(c) {
            output_axes.push(c);
        }
    }
    if !output_axes.contains(time_axis) {
        output_axes.push(time_axis);
    }

    let mut p_aligned = p_state;
    let mut q_aligned = q_state;

    if p_aligned.axes != output_axes {
        let spec = format!("{}->{}", p_aligned.axes, output_axes);
        let tmp = ctx.fresh_temp();
        let tmp_idx = graph.add_tensor(tmp);
        let node = EinsumNode::new(spec, vec![p_aligned.tensor_idx], vec![tmp_idx]);
        graph.add_node(node)?;
        p_aligned = CompileState {
            tensor_idx: tmp_idx,
            axes: output_axes.clone(),
        };
    }

    if q_aligned.axes != output_axes {
        let spec = format!("{}->{}", q_aligned.axes, output_axes);
        let tmp = ctx.fresh_temp();
        let tmp_idx = graph.add_tensor(tmp);
        let node = EinsumNode::new(spec, vec![q_aligned.tensor_idx], vec![tmp_idx]);
        graph.add_node(node)?;
        q_aligned = CompileState {
            tensor_idx: tmp_idx,
            axes: output_axes.clone(),
        };
    }

    let time_idx = output_axes
        .chars()
        .position(|c| c == time_axis)
        .expect("time axis was inserted into output_axes above");

    let tag = until_tag(ctx.config.temporal_strategy);

    let out_tensor = ctx.fresh_temp();
    let out_idx = graph.add_tensor(out_tensor);

    let node = EinsumNode::elem_binary(
        format!("temporal_release:{}:{}", tag, time_idx),
        p_aligned.tensor_idx,
        q_aligned.tensor_idx,
        out_idx,
    );
    graph.add_node(node)?;

    Ok(CompileState {
        tensor_idx: out_idx,
        axes: output_axes,
    })
}

/// Compile WeakUntil (W) temporal operator: "P holds until Q, but Q may never hold"
///
/// # Semantics
///
/// P W Q (P weak until Q): P must hold continuously until Q becomes true; unlike strong Until,
/// Q is not required to ever become true. WeakUntil: P W Q ≡ (P U Q) ∨ □P.
///
/// # Exact finite-trace recurrence
///
/// Emits a `temporal_weakuntil:<tag>:<axis>` binary node computed via the unified backward scan:
/// ```text
/// u[T-1] = OR(q[T-1], AND(p[T-1], boundary=1.0))
/// u[k]   = OR(q[k],   AND(p[k],   u[k+1]))           for k = T-2..0
/// ```
/// MaxMin semantics: OR=max, AND=min.
/// ProbSumProduct semantics: OR(x,y)=x+y-x*y, AND(x,y)=x*y.
///
/// Operand order: arg0 = p (before/left), arg1 = q (after/right).
pub(crate) fn compile_weak_until(
    p: &TLExpr,
    q: &TLExpr,
    ctx: &mut CompilerContext,
    graph: &mut EinsumGraph,
) -> Result<CompileState> {
    let time_axis = ensure_time_axis(ctx);

    let p_state = compile_expr(p, ctx, graph)?;
    let q_state = compile_expr(q, ctx, graph)?;

    let mut output_axes = String::new();
    let mut seen = std::collections::HashSet::new();
    for c in p_state.axes.chars() {
        if seen.insert(c) {
            output_axes.push(c);
        }
    }
    for c in q_state.axes.chars() {
        if seen.insert(c) {
            output_axes.push(c);
        }
    }
    if !output_axes.contains(time_axis) {
        output_axes.push(time_axis);
    }

    let mut p_aligned = p_state;
    let mut q_aligned = q_state;

    if p_aligned.axes != output_axes {
        let spec = format!("{}->{}", p_aligned.axes, output_axes);
        let tmp = ctx.fresh_temp();
        let tmp_idx = graph.add_tensor(tmp);
        let node = EinsumNode::new(spec, vec![p_aligned.tensor_idx], vec![tmp_idx]);
        graph.add_node(node)?;
        p_aligned = CompileState {
            tensor_idx: tmp_idx,
            axes: output_axes.clone(),
        };
    }

    if q_aligned.axes != output_axes {
        let spec = format!("{}->{}", q_aligned.axes, output_axes);
        let tmp = ctx.fresh_temp();
        let tmp_idx = graph.add_tensor(tmp);
        let node = EinsumNode::new(spec, vec![q_aligned.tensor_idx], vec![tmp_idx]);
        graph.add_node(node)?;
        q_aligned = CompileState {
            tensor_idx: tmp_idx,
            axes: output_axes.clone(),
        };
    }

    let time_idx = output_axes
        .chars()
        .position(|c| c == time_axis)
        .expect("time axis was inserted into output_axes above");

    let tag = until_tag(ctx.config.temporal_strategy);

    let out_tensor = ctx.fresh_temp();
    let out_idx = graph.add_tensor(out_tensor);

    let node = EinsumNode::elem_binary(
        format!("temporal_weakuntil:{}:{}", tag, time_idx),
        p_aligned.tensor_idx,
        q_aligned.tensor_idx,
        out_idx,
    );
    graph.add_node(node)?;

    Ok(CompileState {
        tensor_idx: out_idx,
        axes: output_axes,
    })
}

/// Compile StrongRelease (M) temporal operator: "Strong version of Release"
///
/// # Semantics
///
/// P M Q (P strong-releases Q): Q must hold until P becomes true, and P must eventually become true.
/// StrongRelease is the dual of WeakUntil: P M Q ≡ ¬(¬P W ¬Q).
///
/// # Exact finite-trace recurrence
///
/// Emits a `temporal_strongrelease:<tag>:<axis>` binary node computed via the unified backward scan:
/// ```text
/// u[T-1] = AND(q[T-1], OR(p[T-1], boundary=0.0))
/// u[k]   = AND(q[k],   OR(p[k],   u[k+1]))           for k = T-2..0
/// ```
/// MaxMin semantics: AND=min, OR=max.
/// ProbSumProduct semantics: AND(x,y)=x*y, OR(x,y)=x+y-x*y.
///
/// Operand order: arg0 = p (releaser), arg1 = q (released).
pub(crate) fn compile_strong_release(
    p: &TLExpr,
    q: &TLExpr,
    ctx: &mut CompilerContext,
    graph: &mut EinsumGraph,
) -> Result<CompileState> {
    let time_axis = ensure_time_axis(ctx);

    let p_state = compile_expr(p, ctx, graph)?;
    let q_state = compile_expr(q, ctx, graph)?;

    let mut output_axes = String::new();
    let mut seen = std::collections::HashSet::new();
    for c in p_state.axes.chars() {
        if seen.insert(c) {
            output_axes.push(c);
        }
    }
    for c in q_state.axes.chars() {
        if seen.insert(c) {
            output_axes.push(c);
        }
    }
    if !output_axes.contains(time_axis) {
        output_axes.push(time_axis);
    }

    let mut p_aligned = p_state;
    let mut q_aligned = q_state;

    if p_aligned.axes != output_axes {
        let spec = format!("{}->{}", p_aligned.axes, output_axes);
        let tmp = ctx.fresh_temp();
        let tmp_idx = graph.add_tensor(tmp);
        let node = EinsumNode::new(spec, vec![p_aligned.tensor_idx], vec![tmp_idx]);
        graph.add_node(node)?;
        p_aligned = CompileState {
            tensor_idx: tmp_idx,
            axes: output_axes.clone(),
        };
    }

    if q_aligned.axes != output_axes {
        let spec = format!("{}->{}", q_aligned.axes, output_axes);
        let tmp = ctx.fresh_temp();
        let tmp_idx = graph.add_tensor(tmp);
        let node = EinsumNode::new(spec, vec![q_aligned.tensor_idx], vec![tmp_idx]);
        graph.add_node(node)?;
        q_aligned = CompileState {
            tensor_idx: tmp_idx,
            axes: output_axes.clone(),
        };
    }

    let time_idx = output_axes
        .chars()
        .position(|c| c == time_axis)
        .expect("time axis was inserted into output_axes above");

    let tag = until_tag(ctx.config.temporal_strategy);

    let out_tensor = ctx.fresh_temp();
    let out_idx = graph.add_tensor(out_tensor);

    let node = EinsumNode::elem_binary(
        format!("temporal_strongrelease:{}:{}", tag, time_idx),
        p_aligned.tensor_idx,
        q_aligned.tensor_idx,
        out_idx,
    );
    graph.add_node(node)?;

    Ok(CompileState {
        tensor_idx: out_idx,
        axes: output_axes,
    })
}

// ========================================================================
// Helper Functions
// ========================================================================

/// Ensure the world axis exists in the compilation context.
/// Returns the axis character for the world dimension.
fn ensure_world_axis(ctx: &mut CompilerContext) -> char {
    // Check if world axis already assigned
    if let Some(&axis) = ctx.var_to_axis.get(WORLD_AXIS) {
        return axis;
    }

    // Add world domain if not present
    if !ctx.domains.contains_key(WORLD_AXIS) {
        // Default: 10 possible worlds (configurable via context)
        let world_size = ctx.config.modal_world_size.unwrap_or(10);
        ctx.add_domain(WORLD_AXIS, world_size);
    }

    // Assign axis for world variable and return it
    ctx.assign_axis(WORLD_AXIS)
}

/// Ensure the time axis exists in the compilation context.
/// Returns the axis character for the time dimension.
fn ensure_time_axis(ctx: &mut CompilerContext) -> char {
    // Check if time axis already assigned
    if let Some(&axis) = ctx.var_to_axis.get(TIME_AXIS) {
        return axis;
    }

    // Add time domain if not present
    if !ctx.domains.contains_key(TIME_AXIS) {
        // Default: 100 time steps (configurable via context)
        let time_size = ctx.config.temporal_time_steps.unwrap_or(100);
        ctx.add_domain(TIME_AXIS, time_size);
    }

    // Assign axis for time variable and return it
    ctx.assign_axis(TIME_AXIS)
}

/// Apply a reduction operation over a specific axis.
///
/// Creates an einsum spec that reduces over the given axis using the specified operation.
fn apply_reduction(
    state: &CompileState,
    axis_to_reduce: char,
    reduction_op: &str,
    ctx: &mut CompilerContext,
    graph: &mut EinsumGraph,
) -> Result<CompileState> {
    // Build output axes (all input axes except the one being reduced)
    let output_axes: String = state
        .axes
        .chars()
        .filter(|&c| c != axis_to_reduce)
        .collect();

    // Create einsum spec with reduction
    // Format: "op(input_axes->output_axes)" where op is the reduction operation
    let spec = format!("{}({}->{})", reduction_op, state.axes, output_axes);

    // Create result tensor
    let result_name = ctx.fresh_temp();
    let result_idx = graph.add_tensor(result_name);

    // Create reduction node
    let node = EinsumNode::new(spec, vec![state.tensor_idx], vec![result_idx]);
    graph.add_node(node)?;

    Ok(CompileState {
        tensor_idx: result_idx,
        axes: output_axes,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{CompilationConfig, CompilerContext};
    use tensorlogic_ir::{TLExpr, Term};

    #[test]
    fn test_ensure_world_axis() {
        let mut ctx = CompilerContext::new();
        let axis1 = ensure_world_axis(&mut ctx);
        let axis2 = ensure_world_axis(&mut ctx);

        // Should return same axis when called twice
        assert_eq!(axis1, axis2);
        assert!(ctx.domains.contains_key(WORLD_AXIS));
        assert!(ctx.var_to_axis.contains_key(WORLD_AXIS));
    }

    #[test]
    fn test_ensure_time_axis() {
        let mut ctx = CompilerContext::new();
        let axis1 = ensure_time_axis(&mut ctx);
        let axis2 = ensure_time_axis(&mut ctx);

        // Should return same axis when called twice
        assert_eq!(axis1, axis2);
        assert!(ctx.domains.contains_key(TIME_AXIS));
        assert!(ctx.var_to_axis.contains_key(TIME_AXIS));
    }

    #[test]
    fn test_compile_box_simple() {
        let mut ctx = CompilerContext::new();
        ctx.add_domain("Person", 10);

        let mut graph = EinsumGraph::new();

        // Box(P(x)) where P is some predicate
        let pred = TLExpr::pred("happy", vec![Term::var("x")]);

        // For this test, we expect it to work even if predicate doesn't exist
        // (it will fail at compilation, but modal logic setup should work)
        let result = compile_box(&pred, &mut ctx, &mut graph);

        // World axis should be created
        assert!(ctx.domains.contains_key(WORLD_AXIS));

        // Result may fail due to missing predicate info, but that's okay for this test
        let _ = result;
    }

    #[test]
    fn test_compile_diamond_simple() {
        let mut ctx = CompilerContext::new();
        ctx.add_domain("Person", 10);

        let mut graph = EinsumGraph::new();

        let pred = TLExpr::pred("possible", vec![Term::var("x")]);

        let result = compile_diamond(&pred, &mut ctx, &mut graph);

        // World axis should be created
        assert!(ctx.domains.contains_key(WORLD_AXIS));

        let _ = result;
    }

    #[test]
    fn test_compile_eventually_simple() {
        let mut ctx = CompilerContext::new();
        ctx.add_domain("Event", 5);

        let mut graph = EinsumGraph::new();

        let pred = TLExpr::pred("occurs", vec![Term::var("e")]);

        let result = compile_eventually(&pred, &mut ctx, &mut graph);

        // Time axis should be created
        assert!(ctx.domains.contains_key(TIME_AXIS));

        let _ = result;
    }

    #[test]
    fn test_compile_next_succeeds() {
        let mut ctx = CompilerContext::new();
        ctx.add_domain("Person", 5);
        ctx.add_domain(TIME_AXIS, 10);

        let mut graph = EinsumGraph::new();

        // Register a source tensor so predicate compilation can find it.
        let t_idx = graph.add_tensor("p");
        // Also add an input declaration so compile_pred can find axes.
        let _ = t_idx;

        // compile_next: we drive it directly with a pred that references variable "t"
        // which will be bound to the time axis.
        let pred = TLExpr::pred("p", vec![Term::var("t")]);
        let result = compile_next(&pred, &mut ctx, &mut graph);

        // The operator is now implemented — it should succeed.
        // (It may fail due to missing predicate signature, which is OK for this
        //  structural test — we just verify it doesn't bail with the old stub message.)
        match &result {
            Err(e) => {
                let msg = e.to_string();
                assert!(
                    !msg.contains("shift operations which are not available"),
                    "compile_next must not produce the old stub error; got: {msg}"
                );
            }
            Ok(state) => {
                // If compilation succeeded, verify the time axis is in the output.
                let time_axis = ctx.var_to_axis.get(TIME_AXIS).copied();
                if let Some(ta) = time_axis {
                    // The output axes may or may not have time_axis depending on
                    // whether the predicate used it; just check the graph is non-empty.
                    assert!(
                        !graph.nodes.is_empty() || !state.axes.contains(ta),
                        "graph should have at least one node when temporal op was emitted"
                    );
                }
            }
        }
    }

    #[test]
    fn test_compile_until_succeeds() {
        let mut ctx = CompilerContext::new();
        ctx.add_domain("Person", 5);
        ctx.add_domain(TIME_AXIS, 10);

        let mut graph = EinsumGraph::new();

        let pred1 = TLExpr::pred("p", vec![Term::var("x")]);
        let pred2 = TLExpr::pred("q", vec![Term::var("x")]);
        let result = compile_until(&pred1, &pred2, &mut ctx, &mut graph);

        // The operator is now implemented — it should not bail with the old stub message.
        match &result {
            Err(e) => {
                let msg = e.to_string();
                assert!(
                    !msg.contains("scan operations which are not available"),
                    "compile_until must not produce the old stub error; got: {msg}"
                );
            }
            Ok(state) => {
                // Time axis must be present in output axes.
                let time_axis = ctx
                    .var_to_axis
                    .get(TIME_AXIS)
                    .copied()
                    .expect("time axis should be assigned");
                assert!(
                    state.axes.contains(time_axis),
                    "time axis '{time_axis}' must appear in Until output axes '{}'",
                    state.axes
                );
            }
        }
    }

    #[test]
    fn test_compile_until_time_axis_in_output() {
        // Verify that when at least one operand references time, the output also has time.
        let mut ctx = CompilerContext::new();
        ctx.add_domain("Event", 8);
        ctx.add_domain(TIME_AXIS, 20);

        // Force registration by calling ensure_time_axis via compile_until.
        let mut graph = EinsumGraph::new();
        let pred1 = TLExpr::pred("p", vec![Term::var("e")]);
        let pred2 = TLExpr::pred("q", vec![Term::var("e")]);

        let result = compile_until(&pred1, &pred2, &mut ctx, &mut graph);

        match result {
            Err(e) => {
                let msg = e.to_string();
                assert!(
                    !msg.contains("scan operations which are not available"),
                    "compile_until stub message must not appear; got: {msg}"
                );
            }
            Ok(state) => {
                let time_axis = ctx
                    .var_to_axis
                    .get(TIME_AXIS)
                    .copied()
                    .expect("time axis allocated");
                assert!(
                    state.axes.contains(time_axis),
                    "time axis in Until output: {} not in {}",
                    time_axis,
                    state.axes
                );
            }
        }
    }

    #[test]
    fn test_compile_until_different_shape_operands() {
        // "before" has axes x, t; "after" has axis y, t  — union should be x, y, t.
        let mut ctx = CompilerContext::new();
        ctx.add_domain("X", 4);
        ctx.add_domain("Y", 3);
        ctx.add_domain(TIME_AXIS, 10);

        let mut graph = EinsumGraph::new();

        let pred_a = TLExpr::pred("p", vec![Term::var("x"), Term::var("t")]);
        let pred_b = TLExpr::pred("q", vec![Term::var("y"), Term::var("t")]);

        let result = compile_until(&pred_a, &pred_b, &mut ctx, &mut graph);

        match result {
            Err(e) => {
                let msg = e.to_string();
                assert!(
                    !msg.contains("scan operations which are not available"),
                    "compile_until stub must not appear; got: {msg}"
                );
            }
            Ok(state) => {
                // Output must have at least the time axis.
                let time_axis = ctx
                    .var_to_axis
                    .get(TIME_AXIS)
                    .copied()
                    .expect("time axis allocated");
                assert!(
                    state.axes.contains(time_axis),
                    "time axis in union output: {} not in {}",
                    time_axis,
                    state.axes
                );
            }
        }
    }

    #[test]
    fn test_modal_strategy_configuration() {
        // Test different modal strategies
        let ctx = CompilerContext::with_config(CompilationConfig::hard_boolean());
        assert_eq!(ctx.config.modal_strategy, ModalStrategy::AllWorldsMin);

        let ctx = CompilerContext::with_config(CompilationConfig::soft_differentiable());
        assert_eq!(ctx.config.modal_strategy, ModalStrategy::AllWorldsProduct);
    }

    #[test]
    fn test_temporal_strategy_configuration() {
        // Test different temporal strategies
        let ctx = CompilerContext::with_config(CompilationConfig::hard_boolean());
        assert_eq!(ctx.config.temporal_strategy, TemporalStrategy::Max);

        let ctx = CompilerContext::with_config(CompilationConfig::soft_differentiable());
        assert_eq!(ctx.config.temporal_strategy, TemporalStrategy::Sum);
    }

    #[test]
    fn test_compile_release_succeeds() {
        let mut ctx = CompilerContext::new();
        ctx.add_domain("Person", 5);
        ctx.add_domain(TIME_AXIS, 10);

        let mut graph = EinsumGraph::new();

        let pred_p = TLExpr::pred("p", vec![Term::var("x")]);
        let pred_q = TLExpr::pred("q", vec![Term::var("x")]);
        let result = compile_release(&pred_p, &pred_q, &mut ctx, &mut graph);

        match &result {
            Err(e) => {
                let msg = e.to_string();
                // Must not produce old approximation-related messages
                assert!(
                    !msg.contains("approximation"),
                    "compile_release must not mention approximation; got: {msg}"
                );
            }
            Ok(state) => {
                let time_axis = ctx
                    .var_to_axis
                    .get(TIME_AXIS)
                    .copied()
                    .expect("time axis should be assigned");
                assert!(
                    state.axes.contains(time_axis),
                    "time axis '{time_axis}' must appear in Release output axes '{}'",
                    state.axes
                );
            }
        }
    }

    #[test]
    fn test_compile_weak_until_succeeds() {
        let mut ctx = CompilerContext::new();
        ctx.add_domain("Person", 5);
        ctx.add_domain(TIME_AXIS, 10);

        let mut graph = EinsumGraph::new();

        let pred_p = TLExpr::pred("p", vec![Term::var("x")]);
        let pred_q = TLExpr::pred("q", vec![Term::var("x")]);
        let result = compile_weak_until(&pred_p, &pred_q, &mut ctx, &mut graph);

        match &result {
            Err(e) => {
                let msg = e.to_string();
                assert!(
                    !msg.contains("approximation"),
                    "compile_weak_until must not mention approximation; got: {msg}"
                );
            }
            Ok(state) => {
                let time_axis = ctx
                    .var_to_axis
                    .get(TIME_AXIS)
                    .copied()
                    .expect("time axis should be assigned");
                assert!(
                    state.axes.contains(time_axis),
                    "time axis '{time_axis}' must appear in WeakUntil output axes '{}'",
                    state.axes
                );
            }
        }
    }

    #[test]
    fn test_compile_strong_release_succeeds() {
        let mut ctx = CompilerContext::new();
        ctx.add_domain("Person", 5);
        ctx.add_domain(TIME_AXIS, 10);

        let mut graph = EinsumGraph::new();

        let pred_p = TLExpr::pred("p", vec![Term::var("x")]);
        let pred_q = TLExpr::pred("q", vec![Term::var("x")]);
        let result = compile_strong_release(&pred_p, &pred_q, &mut ctx, &mut graph);

        match &result {
            Err(e) => {
                let msg = e.to_string();
                assert!(
                    !msg.contains("approximation"),
                    "compile_strong_release must not mention approximation; got: {msg}"
                );
            }
            Ok(state) => {
                let time_axis = ctx
                    .var_to_axis
                    .get(TIME_AXIS)
                    .copied()
                    .expect("time axis should be assigned");
                assert!(
                    state.axes.contains(time_axis),
                    "time axis '{time_axis}' must appear in StrongRelease output axes '{}'",
                    state.axes
                );
            }
        }
    }
}