zirium 0.0.5

Lossless textual MLIR syntax parsing and semantic processing
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
use std::{
    fs,
    io::{ErrorKind, Write},
    process::{Command, Stdio},
};

const INPUT: &str = "module {\n  // Initial value.\n  %c = arith.constant 7 : i32\n  // Double it.\n  %sum = arith.addi %c, %c : i32 // selected\n  \"example.observe\"(%sum) : (i32) -> ()\n}\n";

fn run_stdin(query: &str, input: &str) -> std::process::Output {
    let mut child = Command::new(env!("CARGO_BIN_EXE_zirium"))
        .arg(query)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .unwrap();
    if let Err(error) = child.stdin.take().unwrap().write_all(input.as_bytes()) {
        assert_eq!(error.kind(), ErrorKind::BrokenPipe, "{error}");
    }
    child.wait_with_output().unwrap()
}

fn temporary_path(name: &str, extension: &str) -> std::path::PathBuf {
    std::env::temp_dir().join(format!(
        "zirium-cli-{}-{name}.{extension}",
        std::process::id()
    ))
}

#[test]
fn stdin_selection_retains_shell_and_comments() {
    let output = run_stdin("select(op(\"arith.addi\"))", INPUT);
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    let text = String::from_utf8(output.stdout).unwrap();
    assert!(text.contains("builtin.module"));
    assert!(text.contains("// Double it."));
    assert!(text.contains("arith.addi"));
    assert!(text.contains("// selected"));
    assert!(!text.contains("arith.constant"));
    assert!(!text.contains("example.observe"));
}

#[test]
fn boolean_predicates_select_names_and_decoded_string_attributes() {
    let input = "module {\n  \"test.a\"() {tag = \"say \\22hi\\22\"} : () -> ()\n  \"test.b\"() {tag = 7 : i32} : () -> ()\n  \"test.c\"() : () -> ()\n}\n";
    let output = run_stdin(
        r#"select((op("test.a") or op("test.b")) and has_attr("tag") and not attr("tag", "other"))"#,
        input,
    );
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    let text = String::from_utf8(output.stdout).unwrap();
    assert!(text.contains("test.a"), "{text}");
    assert!(text.contains("test.b"), "{text}");
    assert!(!text.contains("test.c"), "{text}");

    let decoded = run_stdin(r#"select(attr("tag", "say \"hi\""))"#, input);
    assert!(
        decoded.status.success(),
        "{}",
        String::from_utf8_lossy(&decoded.stderr)
    );
    let text = String::from_utf8(decoded.stdout).unwrap();
    assert!(text.contains("test.a"), "{text}");
    assert!(!text.contains("test.b"), "{text}");
}

#[test]
fn builtin_dense_array_attributes_support_queries_and_ownership() {
    let input = "module {\n  \"stablehlo.reduce\"() ({\n    \"stablehlo.add\"() : () -> ()\n  }) {dimensions = array<i64: 1>} : () -> ()\n}\n";
    for (query, expected) in [
        (
            r#"select(op("stablehlo.reduce") and has_attr("dimensions")) | count"#,
            "1\n",
        ),
        (r#"select(op("stablehlo.add")) | parent | count"#, "1\n"),
        (
            r#"select(op("stablehlo.reduce")) | children | count"#,
            "1\n",
        ),
    ] {
        let output = run_stdin(query, input);
        assert!(
            output.status.success(),
            "{}",
            String::from_utf8_lossy(&output.stderr)
        );
        assert_eq!(String::from_utf8(output.stdout).unwrap(), expected);
    }
}

#[test]
fn malformed_predicates_produce_no_output() {
    for query in [
        r#"select(attr("tag" "value"))"#,
        r#"select(op("arith.addi") and)"#,
        r#"select(has_attr("bad name"))"#,
    ] {
        let output = run_stdin(query, INPUT);
        assert!(!output.status.success());
        assert!(output.stdout.is_empty());
        assert!(String::from_utf8_lossy(&output.stderr).contains("query error"));
    }
}

#[test]
fn closure_adds_shared_ssa_definition_once_with_comments() {
    let output = run_stdin("select(op(\"arith.addi\")) | closure", INPUT);
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    let text = String::from_utf8(output.stdout).unwrap();
    assert_eq!(text.matches("arith.constant").count(), 1, "{text}");
    assert_eq!(text.matches("// Initial value.").count(), 1, "{text}");
    assert!(text.find("arith.constant").unwrap() < text.find("arith.addi").unwrap());
    assert!(!text.contains("example.observe"));
}

#[test]
fn direct_ssa_navigation_is_ordered_deduplicated_and_composable() {
    let defs = run_stdin("select(op(\"arith.addi\")) | defs", INPUT);
    assert!(
        defs.status.success(),
        "{}",
        String::from_utf8_lossy(&defs.stderr)
    );
    let text = String::from_utf8(defs.stdout).unwrap();
    assert_eq!(text.matches("arith.constant").count(), 1, "{text}");
    assert!(!text.contains("arith.addi"), "{text}");

    let users = run_stdin("select(op(\"arith.constant\")) | users | count", INPUT);
    assert!(
        users.status.success(),
        "{}",
        String::from_utf8_lossy(&users.stderr)
    );
    assert_eq!(String::from_utf8(users.stdout).unwrap(), "1\n");

    let unused = run_stdin("select(op(\"example.observe\")) | users | count", INPUT);
    assert!(unused.status.success());
    assert_eq!(String::from_utf8(unused.stdout).unwrap(), "0\n");
}

#[test]
fn predicate_set_operations_are_ordered_and_composable() {
    let input = "module {\n  \"test.a\"() {group = \"keep\"} : () -> ()\n  \"test.b\"() {group = \"keep\"} : () -> ()\n  \"test.c\"() : () -> ()\n}\n";

    let union = run_stdin(
        r#"select(op("test.c")) | union(op("test.a") or has_attr("group"))"#,
        input,
    );
    assert!(
        union.status.success(),
        "{}",
        String::from_utf8_lossy(&union.stderr)
    );
    let text = String::from_utf8(union.stdout).unwrap();
    assert_eq!(text.matches("test.a").count(), 1, "{text}");
    assert_eq!(text.matches("test.b").count(), 1, "{text}");
    assert_eq!(text.matches("test.c").count(), 1, "{text}");
    assert!(
        text.find("test.a").unwrap() < text.find("test.c").unwrap(),
        "{text}"
    );

    let intersect = run_stdin(
        r#"select(has_attr("group")) | intersect(not op("test.b")) | count"#,
        input,
    );
    assert!(intersect.status.success());
    assert_eq!(String::from_utf8(intersect.stdout).unwrap(), "1\n");

    for query in [
        r#"select(has_attr("group")) | except(attr("group", "keep")) | count"#,
        r#"select(op("missing")) | union(op("missing")) | count"#,
        r#"select(op("missing")) | intersect(op("test.a")) | count"#,
        r#"select(op("test.a")) | except(op("missing")) | count"#,
    ] {
        let output = run_stdin(query, input);
        assert!(
            output.status.success(),
            "{}",
            String::from_utf8_lossy(&output.stderr)
        );
        let expected = if query.contains("except(op") {
            "1\n"
        } else {
            "0\n"
        };
        assert_eq!(String::from_utf8(output.stdout).unwrap(), expected);
    }

    let first = temporary_path("set-first", "mlir");
    let second = temporary_path("set-second", "mlir");
    fs::write(&first, input).unwrap();
    fs::write(&second, "module { \"test.d\"() : () -> () }\n").unwrap();
    let output = Command::new(env!("CARGO_BIN_EXE_zirium"))
        .arg(r#"select(op("test.a")) | union(op("test.d")) | count"#)
        .arg(&first)
        .arg(&second)
        .output()
        .unwrap();
    let _ = fs::remove_file(first);
    let _ = fs::remove_file(second);
    assert!(output.status.success());
    assert_eq!(String::from_utf8(output.stdout).unwrap(), "1\n1\n");
}

#[test]
fn ownership_navigation_is_one_step_and_handles_block_arguments() {
    let input = "\"builtin.module\"() ({\n  \"func.func\"() ({\n  ^entry(%arg0: i32):\n    %sum = \"arith.addi\"(%arg0, %arg0) : (i32, i32) -> i32\n    \"func.return\"(%sum) : (i32) -> ()\n  }) : () -> ()\n}) : () -> ()\n";

    let boundary = run_stdin("select(op(\"arith.addi\")) | defs", input);
    assert!(
        boundary.status.success(),
        "{}",
        String::from_utf8_lossy(&boundary.stderr)
    );
    let text = String::from_utf8(boundary.stdout).unwrap();
    assert!(text.contains("func.func"), "{text}");
    assert!(text.contains("arith.addi"), "{text}");

    let parent = run_stdin("select(op(\"arith.addi\")) | parent", input);
    assert!(parent.status.success());
    let text = String::from_utf8(parent.stdout).unwrap();
    assert!(text.contains("func.func"), "{text}");

    let children = run_stdin("select(op(\"func.func\")) | children", input);
    assert!(children.status.success());
    let text = String::from_utf8(children.stdout).unwrap();
    assert!(text.contains("arith.addi"), "{text}");
    assert!(text.contains("func.return"), "{text}");
}

#[test]
fn count_prints_one_scalar_line_per_input() {
    let first = temporary_path("count-first", "mlir");
    let second = temporary_path("count-second", "mlir");
    fs::write(&first, INPUT).unwrap();
    fs::write(&second, "module { func.return }\n").unwrap();
    let output = Command::new(env!("CARGO_BIN_EXE_zirium"))
        .arg("select(op(\"arith.addi\")) | count")
        .arg(&first)
        .arg(&second)
        .output()
        .unwrap();
    let _ = fs::remove_file(first);
    let _ = fs::remove_file(second);
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert_eq!(String::from_utf8(output.stdout).unwrap(), "1\n0\n");
}

#[test]
fn set_attr_keeps_the_changed_selection_and_comments() {
    let output = run_stdin(
        "select(op(\"arith.addi\")) | set_attr(\"analysis.tag\", \"hot\")",
        INPUT,
    );
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    let text = String::from_utf8(output.stdout).unwrap();
    assert_eq!(text.matches("analysis.tag = \"hot\"").count(), 1, "{text}");
    assert!(text.contains("// Double it."), "{text}");
    assert!(text.contains("// selected"), "{text}");
    assert!(!text.contains("arith.constant"), "{text}");
    assert!(!text.contains("example.observe"), "{text}");
}

#[test]
fn root_after_mutation_prints_the_validated_whole_document() {
    let output = run_stdin(
        "select(op(\"arith.addi\")) | set_attr(\"analysis.tag\", \"hot\") | root",
        INPUT,
    );
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    let text = String::from_utf8(output.stdout).unwrap();
    assert!(text.contains("analysis.tag = \"hot\""), "{text}");
    assert!(text.contains("arith.constant"), "{text}");
    assert!(text.contains("example.observe"), "{text}");
}

#[test]
fn generic_single_operand_edit_prints_a_parseable_function_type() {
    let input =
        "%item = \"sample.create\"() : () -> i64\n\"sample.forward\"(%item) : (i64) -> ()\n";
    let edited = run_stdin(
        r#"select(op("sample.forward")) | set_attr("roundtrip.marker", "present") | root"#,
        input,
    );
    assert!(
        edited.status.success(),
        "{}",
        String::from_utf8_lossy(&edited.stderr)
    );
    let printed = String::from_utf8(edited.stdout).unwrap();
    assert!(
        printed.contains("roundtrip.marker = \"present\""),
        "{printed}"
    );

    let reparsed = run_stdin(r#"select(op("sample.forward")) | count"#, &printed);
    assert!(
        reparsed.status.success(),
        "{printed}\n{}",
        String::from_utf8_lossy(&reparsed.stderr)
    );
    assert_eq!(reparsed.stdout, b"1\n", "{printed}");
}

#[test]
fn set_attr_mutates_the_selection_at_its_pipeline_position() {
    let output = run_stdin(
        "select(op(\"arith.addi\")) | set_attr(\"analysis.tag\", \"hot\") | closure | root",
        INPUT,
    );
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    let text = String::from_utf8(output.stdout).unwrap();
    assert_eq!(text.matches("analysis.tag = \"hot\"").count(), 1, "{text}");
    let constant = text.find("arith.constant").unwrap();
    let add = text.find("arith.addi").unwrap();
    let tag = text.find("analysis.tag = \"hot\"").unwrap();
    assert!(constant < add && add < tag, "{text}");
}

#[test]
fn remove_attr_keeps_selection_comments_and_other_attributes() {
    let input = "module {\n  // Keep this comment.\n  \"test.a\"() {analysis.tag = \"hot\", other = \"keep\"} : () -> () // trailing a\n  \"test.b\"() {analysis.tag = \"cold\"} : () -> () // trailing b\n}\n";
    let output = run_stdin(
        r#"select(op("test.a")) | remove_attr("analysis.tag")"#,
        input,
    );
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    let text = String::from_utf8(output.stdout).unwrap();
    assert!(!text.contains("analysis.tag"), "{text}");
    assert!(text.contains("other = \"keep\""), "{text}");
    assert!(text.contains("// Keep this comment."), "{text}");
    let selected_line = text.lines().find(|line| line.contains("test.a")).unwrap();
    assert!(selected_line.ends_with("// trailing a"), "{text}");
    assert!(!text.contains("// trailing b"), "{text}");
    assert!(!text.contains("test.b"), "{text}");
}

#[test]
fn remove_attr_absent_is_a_noop_and_composes_in_pipeline_order() {
    let absent_input = "module {\n  // Keep the first.\n  \"test.a\"() : () -> () // trailing a\n  // Keep the second.\n  \"test.b\"() : () -> () // trailing b\n}\n";
    let absent = run_stdin(
        r#"select(op("test.a") or op("test.b")) | remove_attr("missing.tag")"#,
        absent_input,
    );
    assert!(
        absent.status.success(),
        "{}",
        String::from_utf8_lossy(&absent.stderr)
    );
    let absent_text = String::from_utf8(absent.stdout).unwrap();
    let absent_lines = absent_text.lines().collect::<Vec<_>>();
    let a_line = absent_lines
        .iter()
        .find(|line| line.contains("test.a"))
        .unwrap();
    let b_line = absent_lines
        .iter()
        .find(|line| line.contains("test.b"))
        .unwrap();
    assert!(a_line.ends_with("// trailing a"), "{absent_text}");
    assert!(b_line.ends_with("// trailing b"), "{absent_text}");
    let first_comment = absent_text.find("// Keep the first.").unwrap();
    let test_a = absent_text.find("test.a").unwrap();
    let second_comment = absent_text.find("// Keep the second.").unwrap();
    let test_b = absent_text.find("test.b").unwrap();
    assert!(first_comment < test_a && test_a < second_comment && second_comment < test_b);

    let mixed_input = "module {\n  // Comment for a.\n  \"test.a\"() {analysis.tag = \"hot\"} : () -> () // trailing a\n  // Comment for b.\n  \"test.b\"() : () -> () // trailing b\n}\n";
    let mixed = run_stdin(
        r#"select(op("test.a") or op("test.b")) | remove_attr("analysis.tag")"#,
        mixed_input,
    );
    assert!(
        mixed.status.success(),
        "{}",
        String::from_utf8_lossy(&mixed.stderr)
    );
    let mixed_text = String::from_utf8(mixed.stdout).unwrap();
    assert!(!mixed_text.contains("analysis.tag"), "{mixed_text}");
    let comment_for_a = mixed_text.find("// Comment for a.").unwrap();
    let test_a = mixed_text.find("\"test.a\"").unwrap();
    let comment_for_b = mixed_text.find("// Comment for b.").unwrap();
    let test_b = mixed_text.find("\"test.b\"").unwrap();
    assert!(
        comment_for_a < test_a && test_a < comment_for_b && comment_for_b < test_b,
        "{mixed_text}"
    );
    assert_eq!(mixed_text.matches("// Comment for b.").count(), 1);
    let mixed_lines = mixed_text.lines().collect::<Vec<_>>();
    let a_line = mixed_lines
        .iter()
        .find(|line| line.contains("test.a"))
        .unwrap();
    let b_line = mixed_lines
        .iter()
        .find(|line| line.contains("test.b"))
        .unwrap();
    assert!(a_line.ends_with("// trailing a"), "{mixed_text}");
    assert!(b_line.ends_with("// trailing b"), "{mixed_text}");

    let output = run_stdin(
        r#"select(op("arith.addi")) | set_attr("analysis.tag", "hot") | remove_attr("analysis.tag") | closure | root"#,
        INPUT,
    );
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    let text = String::from_utf8(output.stdout).unwrap();
    assert!(!text.contains("analysis.tag"), "{text}");
    assert!(text.contains("arith.constant"), "{text}");
    assert!(text.contains("example.observe"), "{text}");
}

#[test]
fn remove_attr_rejects_unparsed_operations_before_editing_the_selection() {
    for input in [
        "module {\n  mystery.consume {debug.note = \"sealed\"}\n}\n",
        "module {\n  \"example.known\"() {debug.note = \"drop\"} : () -> ()\n  mystery.consume {debug.note = \"sealed\"}\n}\n",
    ] {
        let output = run_stdin(
            r#"select(op("example.known") or op("mystery.consume")) | remove_attr("debug.note")"#,
            input,
        );
        assert!(!output.status.success());
        assert!(output.stdout.is_empty());
        assert!(
            String::from_utf8_lossy(&output.stderr).contains("cannot edit an incomplete document"),
            "{}",
            String::from_utf8_lossy(&output.stderr)
        );
    }
}

#[test]
fn remove_attr_does_not_attach_a_parent_tail_to_a_nested_operation() {
    for child_attributes in [" {analysis.tag = \"hot\"}", ""] {
        let input = format!(
            "module {{\n  \"test.parent\"() ({{ \"test.child\"(){child_attributes} : () -> () }}) : () -> () // parent tail\n}}\n"
        );
        let output = run_stdin(
            r#"select(op("test.parent") or op("test.child")) | remove_attr("analysis.tag")"#,
            &input,
        );
        assert!(
            output.status.success(),
            "{}",
            String::from_utf8_lossy(&output.stderr)
        );
        let text = String::from_utf8(output.stdout).unwrap();
        assert_eq!(text.matches("// parent tail").count(), 1, "{text}");
        let child_line = text
            .lines()
            .find(|line| line.contains("test.child"))
            .unwrap();
        assert!(!child_line.contains("// parent tail"), "{text}");
        let parent_tail = text
            .lines()
            .find(|line| line.contains("// parent tail"))
            .unwrap();
        assert!(parent_tail.trim_start().starts_with('}'), "{text}");
    }
}

#[test]
fn rejected_composition_produces_no_output() {
    let output = run_stdin("select(op(\"arith.addi\")) | count | root", INPUT);
    assert!(!output.status.success());
    assert!(output.stdout.is_empty());
    assert!(String::from_utf8_lossy(&output.stderr).contains("root requires a selection"));
}

#[test]
fn invalid_set_attr_text_produces_no_output() {
    for query in [
        "select(op(\"arith.addi\")) | set_attr(\"bad name\", \"hot\") | root",
        "select(op(\"arith.addi\")) | set_attr(\"tag\", \"hot\nvalue\") | root",
    ] {
        let output = run_stdin(query, INPUT);
        assert!(!output.status.success());
        assert!(output.stdout.is_empty());
        assert!(String::from_utf8_lossy(&output.stderr).contains("query error"));
    }
}

#[test]
fn escaped_set_attr_root_output_is_parseable() {
    let input = "module {\n  %c = arith.constant 7 : i32\n  %sum = arith.addi %c, %c : i32\n}\n";
    let output = run_stdin(
        r#"select(op("arith.addi")) | set_attr("analysis.tag", "say \"hi\" \\ path") | root"#,
        input,
    );
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    let text = String::from_utf8(output.stdout).unwrap();
    assert!(text.contains(r#"analysis.tag = "say \"hi\" \\ path""#));
    let reparsed = run_stdin("select(op(\"builtin.module\"))", &text);
    assert!(
        reparsed.status.success(),
        "{}",
        String::from_utf8_lossy(&reparsed.stderr)
    );
}

#[test]
fn closure_at_function_argument_retains_complete_function_scope() {
    let input = "\"builtin.module\"() ({\n  \"func.func\"() ({\n  ^entry(%arg0: i32):\n    %sum = \"arith.addi\"(%arg0, %arg0) : (i32, i32) -> i32\n    \"func.return\"(%sum) : (i32) -> ()\n  }) : () -> ()\n  \"example.other\"() : () -> ()\n}) : () -> ()\n";
    let output = run_stdin("select(op(\"arith.addi\")) | closure", input);
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    let text = String::from_utf8(output.stdout).unwrap();
    assert!(text.contains("\"func.func\""), "{text}");
    assert!(text.contains("func.return %"), "{text}");
    assert!(!text.contains("example.other"), "{text}");
}

#[test]
fn closure_follows_recursive_symbol_once_without_sibling_symbols() {
    let input = "module {\n  func.func @recursive() {\n    func.call @recursive() : () -> ()\n    func.return\n  }\n  func.func @unrelated() { func.return }\n  func.func @caller() {\n    func.call @recursive() : () -> ()\n    func.return\n  }\n}\n";
    let output = run_stdin("select(op(\"func.call\")) | closure", input);
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    let text = String::from_utf8(output.stdout).unwrap();
    assert_eq!(text.matches("func.func @recursive").count(), 1, "{text}");
    assert_eq!(text.matches("func.call @recursive").count(), 2, "{text}");
    assert!(!text.contains("func.func @unrelated"), "{text}");
}

#[test]
fn closure_retains_cyclic_cfg_once_for_conditional_and_unconditional_branches() {
    let input = "module {\n  func.func @loop() {\n  ^entry:\n    cf.br ^loop\n  ^loop:\n    %condition = arith.constant 1 : i1\n    cf.cond_br %condition, ^loop, ^exit\n  ^exit:\n    func.return\n  }\n}\n";
    let output = run_stdin("select(op(\"cf.cond_br\")) | closure", input);
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    let text = String::from_utf8(output.stdout).unwrap();
    assert_eq!(text.matches("func.func @loop").count(), 1, "{text}");
    assert_eq!(text.matches("cf.br").count(), 1, "{text}");
    assert_eq!(text.matches("cf.cond_br").count(), 1, "{text}");
    assert_eq!(text.matches("arith.constant").count(), 1, "{text}");
    assert_eq!(text.matches("func.return").count(), 1, "{text}");
}

#[test]
fn closure_reports_unresolved_callee_from_strict_lowering() {
    let input = "module {\n  func.func @caller() {\n    func.call @missing() : () -> ()\n    func.return\n  }\n}\n";
    let output = run_stdin("select(op(\"func.call\")) | closure", input);
    assert!(!output.status.success());
    let diagnostic = String::from_utf8_lossy(&output.stderr);
    assert!(
        diagnostic.contains("could not resolve func.call callee `@missing`"),
        "{diagnostic}"
    );
}

#[test]
fn closure_reports_invalid_successor_from_strict_lowering() {
    let input = "module {\n  func.func @caller() {\n    cf.br ^missing\n  }\n}\n";
    let output = run_stdin("select(op(\"cf.br\")) | closure", input);
    assert!(!output.status.success());
    let diagnostic = String::from_utf8_lossy(&output.stderr);
    assert!(
        diagnostic.contains("unresolved block `^missing`"),
        "{diagnostic}"
    );
}

#[test]
fn closure_rejects_symbol_reference_on_unregistered_operation() {
    let input = "\"example.def\"() {sym_name = \"callee\"} : () -> ()\n\"example.call\"() {callee = @callee} : () -> ()\n";
    let output = run_stdin("select(op(\"example.call\")) | closure", input);
    assert!(!output.status.success());
    let diagnostic = String::from_utf8_lossy(&output.stderr);
    assert!(
        diagnostic.contains(
            "cannot determine reference semantics for unregistered operation `example.call`"
        ),
        "{diagnostic}"
    );
}

#[test]
fn short_program_file_flag_reads_query_with_final_newline() {
    let program = temporary_path("short-program", "zirium");
    fs::write(&program, "select(op(\"arith.addi\"))\n").unwrap();
    let mut child = Command::new(env!("CARGO_BIN_EXE_zirium"))
        .arg("-f")
        .arg(&program)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .unwrap();
    child
        .stdin
        .take()
        .unwrap()
        .write_all(INPUT.as_bytes())
        .unwrap();
    let output = child.wait_with_output().unwrap();
    let _ = fs::remove_file(program);
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert!(
        String::from_utf8(output.stdout)
            .unwrap()
            .contains("arith.addi")
    );
}

#[test]
fn long_program_file_flag_keeps_mlir_file_arguments() {
    let program = temporary_path("long-program", "zirium");
    let first = temporary_path("long-first", "mlir");
    let second = temporary_path("long-second", "mlir");
    fs::write(&program, "select(op(\"missing\"))").unwrap();
    fs::write(&first, INPUT).unwrap();
    fs::write(&second, INPUT).unwrap();
    let output = Command::new(env!("CARGO_BIN_EXE_zirium"))
        .arg("--program-file")
        .arg(&program)
        .arg(&first)
        .arg(&second)
        .output()
        .unwrap();
    let _ = fs::remove_file(program);
    let _ = fs::remove_file(first);
    let _ = fs::remove_file(second);
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert_eq!(String::from_utf8(output.stdout).unwrap(), "// -----\n");
}

#[test]
fn unreadable_program_file_fails_usefully() {
    let missing = temporary_path("missing-program", "zirium");
    let output = Command::new(env!("CARGO_BIN_EXE_zirium"))
        .arg("-f")
        .arg(&missing)
        .output()
        .unwrap();
    let diagnostic = String::from_utf8_lossy(&output.stderr);
    assert!(!output.status.success());
    assert!(
        diagnostic.contains("could not read program file"),
        "{diagnostic}"
    );
}

#[test]
fn selected_root_retains_owned_contents_and_comments() {
    let input = "// Root comment.\nmodule {\n  // Function comment.\n  func.func @f() {\n    // Nested comment.\n    func.return\n  }\n}\n";
    let output = run_stdin("select(op(\"builtin.module\"))", input);
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    let text = String::from_utf8(output.stdout).unwrap();
    assert_eq!(
        text,
        "// Root comment.\nbuiltin.module {\n  // Function comment.\n  func.func @f() -> () {\n    // Nested comment.\n    func.return\n  }\n}\n"
    );
}

#[test]
fn selected_function_with_argument_can_be_queried_again() {
    let input = "module { func.func @identity(%arg: i32) -> i32 { func.return %arg : i32 } }\n";
    let selected = run_stdin(r#"select(op("func.func"))"#, input);
    assert!(
        selected.status.success(),
        "{}",
        String::from_utf8_lossy(&selected.stderr)
    );
    let printed = String::from_utf8(selected.stdout).unwrap();
    let reparsed = run_stdin(r#"select(op("func.func")) | count"#, &printed);
    assert!(
        reparsed.status.success(),
        "{printed}\n{}",
        String::from_utf8_lossy(&reparsed.stderr)
    );
    assert_eq!(reparsed.stdout, b"1\n", "{printed}");
}

#[test]
fn selected_unknown_operation_preserves_enclosing_argument_names() {
    let input = "module {\n  func.func @pipeline(%source: i64) {\n    mystery.observe %source : i64\n    func.return\n  }\n}\n";
    let selected = run_stdin(r#"select(op("mystery.observe"))"#, input);
    assert!(
        selected.status.success(),
        "{}",
        String::from_utf8_lossy(&selected.stderr)
    );
    let printed = String::from_utf8(selected.stdout).unwrap();
    assert!(
        printed.contains("func.func @pipeline(%source: i64)"),
        "{printed}"
    );
    assert!(
        printed.contains("mystery.observe %source : i64"),
        "{printed}"
    );

    for (query, expected) in [
        (
            r#"select(op("mystery.observe")) | count"#,
            b"1\n".as_slice(),
        ),
        (
            r#"select(op("mystery.observe")) | parent | count"#,
            b"1\n".as_slice(),
        ),
        (
            r#"select(op("func.func")) | children | count"#,
            b"1\n".as_slice(),
        ),
    ] {
        let reparsed = run_stdin(query, &printed);
        assert!(
            reparsed.status.success(),
            "{printed}\n{}",
            String::from_utf8_lossy(&reparsed.stderr)
        );
        assert_eq!(reparsed.stdout, expected, "{printed}");
    }
}

#[test]
fn selected_unknown_operation_does_not_rewrite_attribute_strings() {
    let input = "module {\n  func.func @f(%arg: i32) attributes {note = \"%v0\"} {\n    vendor.use %arg : i32\n  }\n}\n";
    let selected = run_stdin(r#"select(op("vendor.use"))"#, input);
    assert!(
        selected.status.success(),
        "{}",
        String::from_utf8_lossy(&selected.stderr)
    );
    let printed = String::from_utf8(selected.stdout).unwrap();
    assert!(printed.contains("func.func @f(%arg: i32)"), "{printed}");
    assert!(printed.contains("note = \"%v0\""), "{printed}");
    assert!(printed.contains("vendor.use %arg : i32"), "{printed}");
}

#[test]
fn inline_nested_operation_does_not_steal_parent_comment() {
    let input = "module {\n  // Nested function.\n  func.func @inner() { func.return }\n}\n";
    let output = run_stdin("select(op(\"builtin.module\"))", input);
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    let text = String::from_utf8(output.stdout).unwrap();
    assert_eq!(text.matches("// Nested function.").count(), 1, "{text}");
    assert!(text.contains("func.func @inner() -> ()"), "{text}");
    assert!(text.contains("func.return"), "{text}");
}

#[test]
fn files_frame_empty_answers() {
    let directory = std::env::temp_dir();
    let first = directory.join(format!("zirium-cli-{}-a.mlir", std::process::id()));
    let second = directory.join(format!("zirium-cli-{}-b.mlir", std::process::id()));
    fs::write(&first, INPUT).unwrap();
    fs::write(&second, INPUT).unwrap();
    let output = Command::new(env!("CARGO_BIN_EXE_zirium"))
        .arg("select(op(\"missing\"))")
        .arg(&first)
        .arg(&second)
        .output()
        .unwrap();
    let _ = fs::remove_file(first);
    let _ = fs::remove_file(second);
    assert!(output.status.success());
    assert_eq!(String::from_utf8(output.stdout).unwrap(), "// -----\n");
}

#[test]
fn malformed_query_and_input_fail_usefully() {
    let bad_query = run_stdin("select(op(\"arith.addi\")", INPUT);
    assert!(!bad_query.status.success());
    assert!(String::from_utf8_lossy(&bad_query.stderr).contains("query error at byte"));
    let bad_input = run_stdin(
        "select(op(\"arith.addi\"))",
        "module {\n  %x = arith.constant nope : i32\n}\n",
    );
    assert!(!bad_input.status.success());
    let diagnostic = String::from_utf8_lossy(&bad_input.stderr);
    assert!(diagnostic.contains("could not parse stdin"), "{diagnostic}");
    assert!(diagnostic.contains("Syntax at bytes"), "{diagnostic}");
}

#[test]
fn lowering_failure_reports_identity_and_original_range() {
    let input = "module {\n  \"example.use\"(%missing) : (i32) -> ()\n}\n";
    let output = run_stdin("select(op(\"example.use\"))", input);
    assert!(!output.status.success());
    let diagnostic = String::from_utf8_lossy(&output.stderr);
    assert!(
        diagnostic.contains("diagnostic #1 at bytes"),
        "{diagnostic}"
    );
    assert!(
        diagnostic.contains("unresolved SSA value `%missing`"),
        "{diagnostic}"
    );
}

#[test]
fn arbitrary_generic_dialect_operations_support_structural_queries_and_edits() {
    let input = "\"builtin.module\"() ({\n  \"vendor.container\"() ({\n    \"vendor.compute\"() {tag = \"hot\", remove = \"yes\"} : () -> ()\n  }) : () -> ()\n}) : () -> ()\n";

    for (query, expected) in [
        (r#"select(attr("tag", "hot")) | count"#, "1\n"),
        (r#"select(op("vendor.compute")) | parent | count"#, "1\n"),
        (
            r#"select(op("vendor.container")) | children | count"#,
            "1\n",
        ),
    ] {
        let output = run_stdin(query, input);
        assert!(
            output.status.success(),
            "{}",
            String::from_utf8_lossy(&output.stderr)
        );
        assert_eq!(String::from_utf8(output.stdout).unwrap(), expected);
    }

    let edited = run_stdin(
        r#"select(op("vendor.compute")) | set_attr("added", "value") | remove_attr("remove")"#,
        input,
    );
    assert!(
        edited.status.success(),
        "{}",
        String::from_utf8_lossy(&edited.stderr)
    );
    let text = String::from_utf8(edited.stdout).unwrap();
    assert!(text.contains("added = \"value\""), "{text}");
    assert!(!text.contains("remove ="), "{text}");
}

#[test]
fn bounded_unknown_custom_operation_supports_name_count_ownership_and_exact_selection() {
    let input = "module {\n  vendor.compute strangely<balanced>(payload)\n}\n";
    let count = run_stdin(r#"select(op("vendor.compute")) | count"#, input);
    assert!(
        count.status.success(),
        "{}",
        String::from_utf8_lossy(&count.stderr)
    );
    assert_eq!(count.stdout, b"1\n");

    let parent_count = run_stdin(r#"select(op("vendor.compute")) | parent | count"#, input);
    assert!(parent_count.status.success());
    assert_eq!(parent_count.stdout, b"1\n");

    let child_count = run_stdin(r#"select(op("builtin.module")) | children | count"#, input);
    assert!(child_count.status.success());
    assert_eq!(child_count.stdout, b"1\n");

    let selected = run_stdin(r#"select(op("vendor.compute"))"#, input);
    assert!(
        selected.status.success(),
        "{}",
        String::from_utf8_lossy(&selected.stderr)
    );
    assert_eq!(
        String::from_utf8(selected.stdout).unwrap(),
        "builtin.module {\n  vendor.compute strangely<balanced>(payload)\n\n}\n"
    );
}

#[test]
fn unknown_custom_recovery_rejects_malformed_neighbors_closure_and_edits() {
    let malformed = run_stdin(
        r#"select(op("vendor.compute"))"#,
        "module { vendor.compute strangely<unclosed(payload) }\n",
    );
    assert!(!malformed.status.success());
    assert!(malformed.stdout.is_empty());

    let input = "module { vendor.compute strangely<balanced>(payload) }\n";
    let closure = run_stdin(r#"select(op("vendor.compute")) | closure"#, input);
    assert!(!closure.status.success());
    assert!(closure.stdout.is_empty());
    assert!(String::from_utf8_lossy(&closure.stderr).contains(
        "cannot determine reference semantics for unregistered operation `vendor.compute`"
    ));

    let edit = run_stdin(
        r#"select(op("vendor.compute")) | set_attr("tag", "value")"#,
        input,
    );
    assert!(!edit.status.success());
    assert!(edit.stdout.is_empty());
    assert!(String::from_utf8_lossy(&edit.stderr).contains("edit failed"));
}

#[test]
fn mutation_before_unknown_closure_failure_emits_no_stdout() {
    let input = "module {\n  \"vendor.known\"() : () -> ()\n  vendor.unknown opaque<payload>\n}\n";
    let output = run_stdin(
        r#"select(op("vendor.known")) | set_attr("tag", "value") | union(op("vendor.unknown")) | closure"#,
        input,
    );
    assert!(!output.status.success());
    assert!(output.stdout.is_empty());
}

#[test]
fn recovered_unknown_sibling_does_not_block_empty_or_understood_selections() {
    let input = "module {\n  \"vendor.known\"() : () -> ()\n  vendor.unknown opaque<payload>\n}\n";

    let empty = run_stdin(r#"select(op("vendor.missing"))"#, input);
    assert!(
        empty.status.success(),
        "{}",
        String::from_utf8_lossy(&empty.stderr)
    );
    assert!(empty.stdout.is_empty());

    let understood = run_stdin(r#"select(op("vendor.known"))"#, input);
    assert!(
        understood.status.success(),
        "{}",
        String::from_utf8_lossy(&understood.stderr)
    );
    let text = String::from_utf8(understood.stdout).unwrap();
    assert!(text.contains("vendor.known"), "{text}");
    assert!(!text.contains("vendor.unknown"), "{text}");
}