pliron-derive 0.18.0

Derive macros for pliron
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
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) The pliron contributors

mod derive_attr;
mod derive_decontext;
mod derive_entity;
mod derive_format;
mod derive_op;
mod derive_type;
mod interfaces;
mod irfmt;
mod verify_succ;

use proc_macro::TokenStream;
use syn::parse_quote;

use derive_format::DeriveIRObject;

/// A hash map with a fast, non-cryptographic hasher and deterministic iteration order.
type IMap<K, V> = indexmap::IndexMap<K, V, rustc_hash::FxBuildHasher>;

/// `#[def_attribute(...)]`: Annotate a Rust struct as a new IR attribute.
///
/// *Note*: It is suggested to use the [pliron_attr] macro instead of using this macro directly.
///         The documention here is useful though, because [pliron_attr]'s `name` field expands
///         to this macro.
///
/// The argument to the macro is the fully qualified name of the attribute in the form of
/// `"dialect.attribute_name"`.
///
/// The macro will leave the struct definition unchanged, but it will generate an implementation of
/// the pliron::Attribute trait and implements other internal traits and types resources required
/// to use the IR attribute.
///
/// **Note**: pre-requisite traits for `Attribute` must already be implemented.
///         Additionaly, [Eq] and [Hash](core::hash::Hash) must be implemented by the type.
///
/// Usage:
///
/// ```
/// use pliron::derive::{def_attribute, format_attribute, verify_succ};
///
/// #[verify_succ]
/// #[def_attribute("my_dialect.attribute")]
/// #[format_attribute]
/// #[derive(Debug, Clone, PartialEq, Eq, Hash)]
/// pub struct StringAttr(String);
/// # use pliron::{printable::{State, Printable}, context::Context};
/// ```
#[proc_macro_attribute]
pub fn def_attribute(args: TokenStream, input: TokenStream) -> TokenStream {
    to_token_stream(derive_attr::def_attribute(args, input))
}

/// `#[def_type(...)]`: Annotate a Rust struct as a new IR type.
///
/// *Note*: It is suggested to use the [pliron_type] macro instead of using this macro directly.
///         The documention here is useful though, because [pliron_type]'s `name` field expands
///         to this macro.
///
/// The argument to the macro is the fully qualified name of the type in the form of
/// `"dialect.type_name"`.
///
/// The macro will leave the struct definition unchanged, but it will generate an implementation of
/// the pliron::Type trait and implements other internal traits and types resources required
/// to use the IR type.
///
/// **Note**: pre-requisite traits for `Type` must already be implemented.
///         Additionaly, [Hash](core::hash::Hash) and [Eq] must be implemented by the rust type.
///
/// Usage:
///
/// ```
/// use pliron::derive::{def_type, format_type, verify_succ};
/// #[verify_succ]
/// #[def_type("my_dialect.unit")]
/// #[format_type]
/// #[derive(Debug, Clone, PartialEq, Eq, Hash)]
/// pub struct UnitType;
/// ```
#[proc_macro_attribute]
pub fn def_type(args: TokenStream, input: TokenStream) -> TokenStream {
    to_token_stream(derive_type::def_type(args, input))
}

/// Derive get methods for types that retrieve interned types.
///
/// *Note*: It is suggested to use the [pliron_type] macro instead of using this macro directly.
///         The documention here is useful though, because [pliron_type]'s `generate_get` field
///         expands to this macro.
///
/// This macro generates a `get` method that returns a uniqued instance of the type.
/// For unit structs (no fields), it takes only a `Context` parameter.
/// For structs with fields, it takes a `Context` parameter plus a parameter for each field.
///
/// ## Examples
///
/// ### Named fields struct:
/// ```
/// use pliron::derive::{def_type, derive_type_get, format_type, verify_succ};
/// use pliron::context::Context;
///
/// #[verify_succ]
/// #[def_type("my_dialect.vector_type")]
/// #[format_type]
/// #[derive_type_get]  // Auto-generates get method
/// #[derive(Debug, Clone, PartialEq, Eq, Hash)]
/// pub struct VectorType {
///     elem_ty: u32,
///     num_elems: u32,
/// }
///
/// // Usage of the auto-generated get method:
/// # fn example(ctx: &Context) {
/// let vector_type = VectorType::get(ctx, 42, 8); // get(ctx, elem_ty, num_elems)
/// # }
/// ```
///
/// ### Tuple struct:
/// ```
/// use pliron::derive::{def_type, derive_type_get, format_type, verify_succ};
/// use pliron::context::Context;
///
/// #[verify_succ]
/// #[def_type("my_dialect.tuple_type")]
/// #[format_type]
/// #[derive_type_get]  // Auto-generates get method
/// #[derive(Debug, Clone, PartialEq, Eq, Hash)]
/// pub struct TupleType(u32, String, bool);
///
/// // Usage of the auto-generated get method:
/// # fn example(ctx: &Context) {
/// let tuple_type = TupleType::get(ctx, 42, "hello".to_string(), true); // get(ctx, field_0, field_1, field_2)
/// # }
/// ```
///
/// ### Unit struct:
/// ```
/// use pliron::derive::{def_type, derive_type_get, format_type, verify_succ};
/// use pliron::context::Context;
///
/// #[verify_succ]
/// #[def_type("my_dialect.unit_type")]
/// #[format_type]
/// #[derive_type_get]  // Auto-generates get method
/// #[derive(Debug, Clone, PartialEq, Eq, Hash)]
/// pub struct UnitType;
///
/// // Usage of the auto-generated get method:
/// # fn example(ctx: &Context) {
/// let unit_type = UnitType::get(ctx); // get(ctx) - no additional parameters
/// # }
/// ```
#[proc_macro_attribute]
pub fn derive_type_get(args: TokenStream, input: TokenStream) -> TokenStream {
    to_token_stream(derive_type::derive_type_get(args, input))
}

/// `#[verify_succ]`: Implement [Verify](../pliron/common_traits/trait.Verify.html)
/// for a Rust struct or enum with a verifier that always succeeds.
///
/// This leaves the original item unchanged and adds:
/// `impl Verify for T { fn verify(...) -> Result<()> { Ok(()) } }`.
///
/// Usage:
///
/// ```
/// use pliron::derive::verify_succ;
/// use pliron::{common_traits::Verify, context::Context};
///
/// #[verify_succ]
/// struct AlwaysValid;
///
/// let ctx = Context::new();
/// assert!(AlwaysValid.verify(&ctx).is_ok());
/// ```
#[proc_macro_attribute]
pub fn verify_succ(args: TokenStream, input: TokenStream) -> TokenStream {
    to_token_stream(verify_succ::verify_succ_impl(args.into(), input.into()))
}

/// `#[def_op(...)]`: Create a new IR operation.
///
/// *Note*: It is suggested to use the [pliron_op] macro instead of using this macro directly.
///         The documention here is useful though, because [pliron_op]'s `name` field expands
///         to this macro.
///
/// The argument to the macro is the fully qualified name of the operation in the form of
/// `"dialect.op_name"`.
///
/// The macro assumes an empty struct and will add the `op: Ptr<Operation>` field used to access
/// the underlying Operation in the context.
///
/// The macro will automatically derive the `Clone`, `Copy`, `Hash`, `PartialEq` and `Eq` traits
/// for the new struct definition.
///
/// **Note**: pre-requisite traits for `Op` (Printable, Verify etc) must already be implemented
///
/// Usage:
///
/// ```
/// use pliron::derive::{def_op, format_op, verify_succ};
///
/// #[verify_succ]
/// #[def_op("my_dialect.op")]
/// #[format_op]
/// pub struct MyOp;
/// ```
/// The example will create a struct definition equivalent to:
///
/// ```
/// #[derive(Clone, Copy, PartialEq, Eq, Hash)]
/// pub struct MyOp {
///   op: Ptr<Operation>,
/// }
/// # use pliron::{context::Ptr, operation::Operation};
/// ```
#[proc_macro_attribute]
pub fn def_op(args: TokenStream, input: TokenStream) -> TokenStream {
    to_token_stream(derive_op::def_op(args, input))
}

/// Derive getter and setters for operation attributes listed as arguments.
///
/// *Note*: It is suggested to use the [pliron_op] macro instead of using this macro directly.
///         The documention here is useful though, because [pliron_op]'s `attributes` field
///         expands to this macro.
///
/// The arguments are a comma separated list of attribute names
/// (which must be an [Identifier](../pliron/identifier/struct.Identifier.html)),
/// each of which may have an optional concrete Rust type specified,
/// denoting the [Attribute](../pliron/attribute/trait.Attribute.html)'s concrete type.
///
/// ```
/// # use pliron::derive::{def_op, derive_attr_get_set, format_op, verify_succ};
/// // A test for the `derive_attr_get_set` macro.
/// #[verify_succ]
/// #[def_op("llvm.with_attrs")]
/// #[format_op]
/// #[derive_attr_get_set(name1_any_attr, name2_ty_attr : pliron::builtin::attributes::TypeAttr)]
/// pub struct WithAttrsOp {}
/// ```
///
/// This expands to add the following getter / setter items:
/// ```Rust
/// # use pliron::derive::{def_op, format_op, derive_attr_get_set};
/// # use core::cell::Ref;
/// # use pliron::dict_key;
/// # use pliron::{attribute::AttrObj, context::Context};
/// # use pliron::{builtin::attributes::TypeAttr};
/// # use pliron::derive::verify_succ;
/// # #[verify_succ]
/// #[format_op]
/// #[def_op("llvm.with_attrs")]
/// pub struct WithAttrsOp {}
/// dict_key!(ATTR_KEY_NAME1_ANY_ATTR, "name1_any_attr");
/// dict_key!(ATTR_KEY_NAME2_TY_ATTR, "name2_ty_attr");
/// impl WithAttrsOp {
///   pub fn get_attr_name1_any_attr<'a>
///     (&self, ctx: &'a Context)-> Option<Ref<'a, AttrObj>> { todo!() }
///   pub fn set_attr_name1_any_attr(&self, ctx: &Context, value: AttrObj) { todo!() }
///   pub fn get_attr_name2_ty_attr<'a>
///     (&self, ctx: &'a Context) -> Option<Ref<'a, TypeAttr>> { todo!() }
///   pub fn set_attr_name2_ty_attr(&self, ctx: &Context, value: TypeAttr) { todo!() }
/// }
/// ```
#[proc_macro_attribute]
pub fn derive_attr_get_set(args: TokenStream, input: TokenStream) -> TokenStream {
    to_token_stream(derive_op::derive_attr_get_set(args, input))
}

/// Derive getter methods and / or operand type interfaces for operation operands.
///
/// *Note*: It is suggested to use the [pliron_op] macro instead of using this macro directly.
///         The documention here is useful though, because [pliron_op]'s `operands` field expands
///         to this macro.
///
/// The arguments are a comma-separated list where each entry is:
/// - `name` or `name: Type` for a named operand getter `get_operand_<name>()`.
/// - `_` or `_: Type` to skip getter generation for that position.
///
/// When `Type` is provided, this macro derives
/// [OperandNOfType](../pliron/builtin/op_interfaces/trait.OperandNOfType.html)
/// for the corresponding operand index.
///
/// The op is allowed to have more operands than those specified in the macro arguments.
/// They just won't have getters or type interfaces generated for them.
///
/// ```
/// use pliron::derive::{def_op, format_op, operands, verify_succ};
/// use pliron::builtin::types::{IntegerType, UnitType};
///
/// #[verify_succ]
/// #[def_op("dialect.with_operands")]
/// #[format_op]
/// #[operands(lhs: IntegerType, _, rhs, _: UnitType)]
/// pub struct WithOperandsOp {}
/// ```
#[proc_macro_attribute]
pub fn operands(args: TokenStream, input: TokenStream) -> TokenStream {
    to_token_stream(derive_op::operands(args, input))
}

/// Derive getter methods and / or result type interfaces for operation results.
///
/// *Note*: It is suggested to use the [pliron_op] macro instead of using this macro directly.
///         The documention here is useful though, because [pliron_op]'s `results` field expands
///         to this macro.
///
/// The arguments are a comma-separated list where each entry is:
/// - `name` or `name: Type` for a named result getter `get_result_<name>()`.
/// - `_` or `_: Type` to skip getter generation for that position.
///
/// When `Type` is provided, this macro derives
/// [ResultNOfType](../pliron/builtin/op_interfaces/trait.ResultNOfType.html)
/// for the corresponding result index.
///
/// The op is allowed to have more results than those specified in the macro arguments.
/// They just won't have getters or type interfaces generated for them.
///
/// ```
/// use pliron::derive::{def_op, format_op, results, verify_succ};
/// use pliron::builtin::types::{IntegerType, UnitType};
///
/// #[verify_succ]
/// #[def_op("dialect.with_results")]
/// #[format_op]
/// #[results(out: IntegerType, _: UnitType)]
/// pub struct WithResultsOp {}
/// ```
#[proc_macro_attribute]
pub fn results(args: TokenStream, input: TokenStream) -> TokenStream {
    to_token_stream(derive_op::results(args, input))
}

/// Derive [Printable](../pliron/printable/trait.Printable.html) and
/// [Parsable](../pliron/parsable/trait.Parsable.html) for Rust types.
/// Use this for types other than `Op`, `Type` and `Attribute`s.
///
/// A format string can be specified as an argument to the macro, to customize the syntax.
/// Without a format string, the default syntax is used. For enums, no format string is allowed
/// on the enum itself, but it is allowed on its variants.
///
/// Primarily, the following two are used to refer to fields in a struct or tuple:
///   1. A named variable `$name` specifies a named struct field.
///   2. An unnamed variable `$i` specifies the i'th field of a tuple struct.
///
/// Struct (or tuple) fields that are either [Option] or [Vec] (or an array) must to be specified
/// using the `opt` and `vec` directives respectively (i.e., a format string is mandatory).
///
/// The `opt` directive takes one mandatory argument, a variable specifying the field name with
/// type `Option`. It also supports optional `label` and `delimiters` directives:
/// 1. `label($name)`: uses `name :` as a prefix for the optional value.
/// 2. `delimiters(`open`, `close`)`: wraps the optional value with the given delimiters.
///
/// The `vec` directive takes two arguments, the first is a variable specifying the field name
/// with type `Vec` (or array) and the second is another directive to specify a
/// [ListSeparator](../pliron/printable/enum.ListSeparator.html).
///
/// The following directives are supported:
///   1. `NewLine`: takes no argument, and specifies a newline to be used as list separator.
///   2. ``CharNewline(`c`)``: takes a single character argument that will be followed by a newline.
///   3. ``Char(`c`)``: takes a single character argument that will be used as separator.
///   4. ``CharSpace(`c`)``: takes a single character argument that will be followed by a space.
///
/// Generic structs and enums are supported. The macro preserves generic parameters on the
/// generated `Printable` and `Parsable` impls, but it does not synthesize trait bounds.
/// Any generic field that is parsed or printed through the format must therefore carry explicit
/// bounds on the type itself. In practice, this usually means a bound like
/// `T: Printable + Parsable<Arg = (), Parsed = T>`.
///
/// Examples:
/// 1. Derive for a struct, with no format string (default format):
///    (Note that the field u64 has both `Printable` and `Parsable` implemented).
/// ```
/// use pliron::derive::format;
/// #[format]
/// struct IntWrapper {
///    inner: u64,
/// }
/// ```
/// 2. An example with a custom format string:
/// ```
/// use pliron::derive::format;
/// #[format("`BubbleWrap` `[` $inner `]`")]
/// struct IntWrapperCustom {
///   inner: u64,
/// }
/// ```
/// 3. An example for an enum (custom format strings are allowed for the variants only).
/// ```
/// use pliron::derive::format;
/// use pliron::{builtin::types::IntegerType, r#type::TypedHandle};
/// #[format]
/// enum Enum {
///     A(TypedHandle<IntegerType>),
///     B {
///         one: TypedHandle<IntegerType>,
///         two: u64,
///     },
///     C,
///     #[format("`<` $upper `/` $lower `>`")]
///     Op {
///         upper: u64,
///         lower: u64,
///     },
/// }
/// ```
/// 4. An example with `Option` and `Vec` fields
/// ```
/// use pliron::derive::format;
/// #[format("`<` opt($a) `;` vec($b, Char(`,`)) `>`")]
/// struct OptAndVec {
///    a: Option<u64>,
///    b: Vec<u64>,
///}
/// ```
/// 5. An example with a generic field and explicit bounds:
/// ```
/// use pliron::derive::format;
/// use pliron::{parsable::Parsable, printable::Printable};
///
/// #[format]
/// struct Wrapper<T>
/// where
///     T: Printable + Parsable<Arg = (), Parsed = T>,
/// {
///     value: T,
/// }
/// ```
/// 6. An example with an optional field using `label` and `delimiters` in `opt`:
/// ```
/// use pliron::derive::format;
/// #[format("`<` opt($a, label($value), delimiters(`(`, `)`)) `>`")]
/// struct OptionalField {
///    a: Option<u64>,
/// }
/// ```
#[proc_macro_attribute]
pub fn format(args: TokenStream, input: TokenStream) -> TokenStream {
    to_token_stream(derive_format::derive(
        args,
        input,
        DeriveIRObject::AnyOtherRustType,
    ))
}

/// Derive [Printable](../pliron/printable/trait.Printable.html) and
/// [Parsable](../pliron/parsable/trait.Parsable.html) for [Op](../pliron/op/trait.Op.html)s
///
/// *Note*: It is suggested to use the [pliron_op] macro instead of using this macro directly.
///         The documention here is useful though, because [pliron_op]'s `format` field
///         expands to this macro.
///
/// This derive only supports a syntax in which results appear before the opid:
///   `res1, ... = opid ...`
/// The format string specifies what comes after the opid.
///   1. A named variable `$name` specifies a named attribute of the operation.
///      This cannot be combined with the [attr_dict](#attr_dict) directive.
///   2. An unnamed variable `$i` specifies `operands[i]`, except when inside some directives.
///      This cannot be combined with the "operands" directive.
///   3. The "type" directive specifies that a type must be parsed. It takes one argument,
///      which is an unnamed variable `$i` with `i` specifying `result[i]`. This cannot be
///      combined with the "types" directive.
///   4. The "region" directive specifies that a region must be parsed. It takes one argument,
///      which is an unnamed variable `$i` with `i` specifying `region[i]`. This cannot be
///      combined with the "regions" directive.
///   5. The <a name="attr"></a> "attr" directive can be used to specify attribute on an `Op` when
///      the attribute's rust type is fixed at compile time. It takes two mandatory and two optional
///      arguments.
///
///      1. The first operand is a named variable `$name` which is used as a key into the
///         operation's attribute dictionary
///      2. The second is the concrete rust type of the attribute. This second argument can be a
///         named variable `$name` (with `name` being in scope) or a literal string denoting the path
///         to a rust type (e.g. `` `::pliron::builtin::attributes::IntegerAttr` ``).
///      3. Two additional optional arguments can be specified:
///         * The "label" directive, with one argument, a named variable `$label`, which
///           specifies the label to be used while printing / parsing the attribute.
///         * The "delimiters" directive, which takes two literal arguments,
///           specifying the opening and closing delimiters to be used while printing / parsing.
///
///      The advantage over specifying an attribute using the [attr](#attr) directive (as against
///      just using a named variable) is that the attribute-id is not a part of the syntax
///      here (because the type is statically known, allowing us to be able to parse it),
///      thus allowing it to be more succinct. This cannot be combined with the [attr_dict](#attr_dict)
///      directive.
///   6. The "succ" directive specifies an operation's successor. It takes one argument,
///      which is an unnamed variable `$i` with `i` specifying `successor[i]`.
///   7. The "operands" directive specifies all the operands of an operation. It takes one argument
///      which is a directive specifying the separator between operands. This cannot be combined
///      with using unnamed variables `$i` to refer to operands.
///      The following directives are supported:
///        1. `NewLine`: takes no argument, and specifies a newline to be used as list separator.
///        2. ``CharNewline(`c`)``: takes a single character argument that will be followed by a newline.
///        3. ``Char(`c`)``: takes a single character argument that will be used as separator.
///        4. ``CharSpace(`c`)``: takes a single character argument that will be followed by a space.
///   8. The "successors" directive specifies all the successors of an operation. It takes one argument
///      which is a directive specifying the separator between successors. The separator directive is
///      same as that for "operands" above. This cannot be combined with the "succ" directive.
///   9. The "regions" directive specifies all the regions of an operation. It takes one argument
///      which is a directive specifying the separator between regions. The separator directive is same
///      as that for "operands" above. This cannot be combined with the "region" directive.
///  10. The <a name="attr_dict"></a> "attr_dict" directive specifies an
///      [AttributeDict](../pliron/attribute/struct.AttributeDict.html).
///      It cannot be combined with any of [attr](#attr), [opt_attr](#opt_attr) directives or
///      a named variable (`$name`).
///  11. The "types" directive specifies all the result types of an operation. It takes one argument
///      which is a directive specifying the separator between result types. The separator directive is
///      same as that for "operands" above. This cannot be combined with the "type" directive.
///  12. The "typesig" directive prints the full type signature of an operation as
///      `(operand_types) -> (result_types)`. It takes no arguments. When parsing, the operand
///      types are consumed and ignored; only the result types are used to build the operation.
///      This cannot be combined with any of "type", "types", "opdtype" or "opdtypes" directives.
///  13. The "opdtype" directive specifies that an operand type should be printed. It takes one
///      argument, which is an unnamed variable `$i` with `i` specifying `operands[i]`. This cannot
///      be combined with the "opdtypes" or "typesig" directives. **Note**: Parsed operand types
///      are ignored, and not validated against actual operand types.
///  14. The "opdtypes" directive specifies all the operand types of an operation. It takes one
///      argument which is a directive specifying the separator between operand types. The separator
///      directive is same as that for "operands" above. This cannot be combined with the "opdtype"
///      or "typesig" directives. **Note**: Parsed operand types are ignored and not validated against
///      actual operand types.
///  15. The <a name="opt_attr"></a> "opt_attr" directive specifies an optional attribute on an `Op`.
///      It takes two or more arguments, which are same as those of the [attr](#attr) directive.
///      This cannot be combined with the [attr_dict](#attr_dict) directive.
///
/// Named attributes, `attr` and `opt_attr` print the marker
/// [`!outlined`](../pliron/irfmt/outlined/constant.OUTLINED_ATTR_MARKER.html) instead of an
/// attribute that [attr_should_outline](../pliron/attribute/fn.attr_should_outline.html).
/// `attr_dict` drops the whole entry.
///
/// Examples:
/// 1. Derive for a struct, with no format string (default format):
/// ```
/// use pliron::derive::{def_op, format_op, verify_succ};
/// #[verify_succ]
/// #[format_op]
/// #[def_op("test.myop")]
/// struct MyOp;
/// ```
/// 2. An example with a custom format string:
/// ```
/// use pliron::derive::{def_op, derive_op_interface_impl, format_op, verify_succ};
/// use pliron::{op::Op, builtin::op_interfaces::{OneOpdInterface, OneResultInterface}};
/// #[verify_succ]
/// #[format_op("$0 `<` $attr `>` `:` type($0)")]
/// #[def_op("test.one_result_one_operand")]
/// #[derive_op_interface_impl(OneOpdInterface, OneResultInterface)]
/// struct OneResultOneOperandOp;
/// ```
/// More examples can be seen in the tests for this macro in `pliron-derive/tests/format_op.rs`.
#[proc_macro_attribute]
pub fn format_op(args: TokenStream, input: TokenStream) -> TokenStream {
    to_token_stream(derive_format::derive(args, input, DeriveIRObject::Op))
}

/// Derive [Printable](../pliron/printable/trait.Printable.html) and
/// [Parsable](../pliron/parsable/trait.Parsable.html) for
/// [Attribute](../pliron/attribute/trait.Attribute.html)s
///
/// *Note*: It is suggested to use the [pliron_attr] macro instead of using this macro directly.
///
/// Refer to [macro@format] for the syntax specification and examples.
#[proc_macro_attribute]
pub fn format_attribute(args: TokenStream, input: TokenStream) -> TokenStream {
    to_token_stream(derive_format::derive(
        args,
        input,
        DeriveIRObject::Attribute,
    ))
}

/// Derive [Printable](../pliron/printable/trait.Printable.html) and
/// [Parsable](../pliron/parsable/trait.Parsable.html) for
/// [Type](../pliron/type/trait.Type.html)s
///
/// *Note*: It is suggested to use the [pliron_type] macro instead of using this macro directly.
///
/// Refer to [macro@format] for the syntax specification and examples.
#[proc_macro_attribute]
pub fn format_type(args: TokenStream, input: TokenStream) -> TokenStream {
    to_token_stream(derive_format::derive(args, input, DeriveIRObject::Type))
}

pub(crate) fn to_token_stream(res: syn::Result<proc_macro2::TokenStream>) -> TokenStream {
    let tokens = match res {
        Ok(tokens) => tokens,
        Err(error) => {
            let error = error.to_compile_error();
            quote::quote!(
                #error
            )
        }
    };
    TokenStream::from(tokens)
}

/// Declare an [Op](../pliron/op/trait.Op.html) interface, which can be implemented
/// by any `Op`.
///
/// If the interface requires any other interface to be already implemented,
/// they can be specified super-traits.
///
/// When an `Op` is verified, its interfaces are also automatically verified,
/// with guarantee that a super-interface is verified before an interface itself is.
///
/// Example: Here `SameOperandsAndResultType` and `SymbolOpInterface` are super interfaces
/// for the new interface `MyOpIntr`.
/// ```
/// # use pliron::builtin::op_interfaces::{SameOperandsAndResultType, SymbolOpInterface};
/// # use pliron::derive::{op_interface};
/// # use pliron::{op::Op, context::Context, result::Result};
///   /// MyOpIntr is my first op interface.
///   #[op_interface]
///   trait MyOpIntr: SameOperandsAndResultType + SymbolOpInterface {
///       fn verify(_op: &dyn Op, _ctx: &Context) -> Result<()>
///       where Self: Sized,
///       {
///           Ok(())
///       }
///   }
/// ```
#[proc_macro_attribute]
pub fn op_interface(_attr: TokenStream, item: TokenStream) -> TokenStream {
    let supertrait = parse_quote! { ::pliron::op::Op };
    let verifier_type = parse_quote! { ::pliron::op::OpInterfaceVerifier };
    let target_marker_trait = parse_quote! { ::pliron::op::OpInterfaceMarker };

    to_token_stream(interfaces::interface_define(
        item,
        supertrait,
        verifier_type,
        true,
        target_marker_trait,
    ))
}

/// Implement [Op](../pliron/op/trait.Op.html) Interface for an Op. The interface trait must define
/// a `verify` function with type [OpInterfaceVerifier](../pliron/op/type.OpInterfaceVerifier.html)
///
/// Usage:
/// ```
/// # use pliron::derive::{def_op, format_op, op_interface, op_interface_impl, verify_succ};
///
/// #[verify_succ]
/// #[def_op("dialect.name")]
/// #[format_op]
/// struct MyOp;
///
/// #[op_interface]
/// pub trait MyOpInterface {
///     fn gubbi(&self);
///     fn verify(op: &dyn Op, ctx: &Context) -> Result<()>
///     where Self: Sized,
///     {
///         Ok(())
///     }
/// }
///
/// #[op_interface_impl]
/// impl MyOpInterface for MyOp {
///     fn gubbi(&self) { println!("gubbi"); }
/// }
/// # use pliron::{
/// #     op::Op, context::Context, result::Result, common_traits::Verify
/// # };
/// ```
#[proc_macro_attribute]
pub fn op_interface_impl(_attr: TokenStream, item: TokenStream) -> TokenStream {
    let interface_verifiers_slice = parse_quote! { ::pliron::op::OP_INTERFACE_VERIFIERS };
    let all_verifiers_fn_type = parse_quote! { ::pliron::op::OpInterfaceAllVerifiers };
    to_token_stream(interfaces::interface_impl(
        item.into(),
        interface_verifiers_slice,
        all_verifiers_fn_type,
        interfaces::RegisterBoxedCast::Skip,
        interfaces::ImplsMarkerTrait::Skip,
    ))
}

/// `#[pliron_type(...)]`: Unified macro for defining IR types.
///
/// This macro provides a simplified, unified syntax for defining IR types by expanding
/// into the existing type definition macros. It supports the following configuration options:
///
/// - `name = "dialect.type_name"`: The fully qualified name of the type (required).\
///   Expands to [def_type].
/// - `format = "format_string"`: Custom format string for printing/parsing (optional).\
///   Expands to [format_type].
/// - `verifier = "succ"`: Verifier implementation, currently only "succ" is supported (optional).\
///   Expands to [macro@verify_succ].
/// - `generate_get = true/false`: Whether to generate a get method for the type (optional, default: false).\
///   Expands to [derive_type_get].
///
/// ## Examples
///
/// ### Basic type definition:
/// ```
/// use pliron::derive::pliron_type;
///
/// #[pliron_type(name = "test.unit_type", format, verifier = "succ")]
/// #[derive(Debug, Clone, PartialEq, Eq, Hash)]
/// pub struct UnitType;
/// ```
///
/// ### Type with custom format:
/// ```
/// use pliron::derive::pliron_type;
///
/// #[pliron_type(
///     name = "test.flags_type",
///     format = "`type` `{` $flags `}`",
///     verifier = "succ"
/// )]
/// #[derive(Debug, Clone, PartialEq, Eq, Hash)]
/// struct FlagsType {
///     flags: u32,
/// }
/// ```
///
/// ### Type with get method generation:
/// ```
/// use pliron::derive::pliron_type;
///
/// #[pliron_type(
///     name = "test.vector_type",
///     generate_get = true,
///     format,
///     verifier = "succ"
/// )]
/// #[derive(Debug, Clone, PartialEq, Eq, Hash)]
/// struct VectorType {
///     elem_ty: u32,
///     num_elems: u32,
/// }
/// ```
#[proc_macro_attribute]
pub fn pliron_type(args: TokenStream, input: TokenStream) -> TokenStream {
    to_token_stream(derive_entity::pliron_type(args, input))
}

/// `#[pliron_attr(...)]`: Unified macro for defining IR attributes.
///
/// This macro provides a simplified, unified syntax for defining IR attributes by expanding
/// into the existing attribute definition macros. It supports the following configuration options:
///
/// - `name = "dialect.attribute_name"`: The fully qualified name of the attribute (required).\
///   Expands to [def_attribute].
/// - `format = "format_string"`: Custom format string for printing/parsing (optional).\
///   Expands to [format_attribute].
/// - `verifier = "succ"`: Verifier implementation, currently only "succ" is supported (optional).\
///   Expands to [macro@verify_succ].
///
/// ## Examples
///
/// ### Basic attribute definition:
/// ```
/// use pliron::derive::pliron_attr;
///
/// #[pliron_attr(name = "test.string_attr", format, verifier = "succ")]
/// #[derive(Debug, Clone, PartialEq, Eq, Hash)]
/// struct StringAttr {
///     value: String,
/// }
/// ```
///
/// ### Attribute with custom format:
/// ```
/// use pliron::derive::pliron_attr;
///
/// #[pliron_attr(
///     name = "test.string_attr",
///     format = "`attr` `(` $value `)`",
///     verifier = "succ"
/// )]
/// #[derive(Debug, Clone, PartialEq, Eq, Hash)]
/// struct StringAttr {
///     value: String,
/// }
/// ```
#[proc_macro_attribute]
pub fn pliron_attr(args: TokenStream, input: TokenStream) -> TokenStream {
    to_token_stream(derive_entity::pliron_attr(args, input))
}

/// `#[pliron_op(...)]`: Unified macro for defining IR operations.
///
/// This macro provides a simplified, unified syntax for defining IR operations by expanding
/// into the existing operation definition macros. It supports the following configuration options:
///
/// - `name = "dialect.op_name"`: The fully qualified name of the operation (required).\
///   Expands to [def_op].
/// - `format = "format_string"`: Custom format string for printing/parsing (optional).\
///   Expands to [format_op].
/// - `interfaces = [Interface1, Interface2, ...]`: List of interfaces to implement (optional).\
///   Expands to [derive_op_interface_impl].
/// - `attributes = (attr_name: AttrType, ...)`: List of attributes with their types (optional).\
///   Expands to [derive_attr_get_set], generating getter and setter methods.
/// - `operands = (name, name: Type, _, _: Type, ...)`: List of operand specs (optional).\
///   Expands to [operands].
/// - `results = (name, name: Type, _, _: Type, ...)`: List of result specs (optional).\
///   Expands to [results].
/// - `verifier = "succ"`: Verifier implementation, currently only "succ" is supported (optional).\
///   Expands to [macro@verify_succ].
///
/// ## Examples
///
/// ### Basic operation definition:
/// ```
/// use pliron::derive::pliron_op;
///
/// #[pliron_op(name = "test.my_op", format, verifier = "succ")]
/// struct MyOp;
/// ```
///
/// ### Operation with custom format and interfaces:
/// ```
/// use pliron::derive::pliron_op;
/// use pliron::builtin::op_interfaces::NRegionsInterface;
///
/// #[pliron_op(
///     name = "test.if_op",
///     format = "`(`$0`)` region($0)",
///     interfaces = [ NRegionsInterface<1> ],
///     verifier = "succ"
/// )]
/// struct IfOp;
/// ```
///
/// ### Operation with specified attributes:
/// ```
/// use pliron::derive::pliron_op;
/// use pliron::builtin::attributes::{UnitAttr, IntegerAttr};
///
/// #[pliron_op(
///     name = "dialect.test",
///     format,
///     attributes = (attr1: UnitAttr, attr2: IntegerAttr),
///     verifier = "succ"
/// )]
/// struct CallOp;
/// ```
///
/// ### Operation with specified operands:
/// ```
/// use pliron::derive::pliron_op;
/// use pliron::builtin::types::{IntegerType, UnitType};
///
/// #[pliron_op(
///     name = "dialect.with_operands",
///     format,
///     operands = (lhs: IntegerType, _, rhs, _: UnitType),
///     verifier = "succ"
/// )]
/// struct WithOperandsOp;
/// ```
///
/// ### Operation with specified results:
/// ```
/// use pliron::derive::pliron_op;
/// use pliron::builtin::types::{IntegerType, UnitType};
///
/// #[pliron_op(
///     name = "dialect.with_results",
///     format,
///     results = (out: IntegerType, _: UnitType),
///     verifier = "succ"
/// )]
/// struct WithResultsOp;
/// ```
#[proc_macro_attribute]
pub fn pliron_op(args: TokenStream, input: TokenStream) -> TokenStream {
    to_token_stream(derive_entity::pliron_op(args, input))
}

/// Derive implementation of an [Op](../pliron/op/trait.Op.html) Interface for an Op.
/// Note that an impl can be derived only for those interfaces that do not require any
/// methods to be defined during the impl.
///
/// *Note*: It is suggested to use the [pliron_op] macro instead of using this macro directly.
///         The documention here is useful though, because [pliron_op]'s `interfaces` field
///         expands to this macro.
///
/// Usage:
/// ```
/// # use pliron::derive::{derive_op_interface_impl, format_op, op_interface, verify_succ};
///
/// #[verify_succ]
/// #[def_op("dialect.name")]
/// #[format_op]
/// #[derive_op_interface_impl(MyOpInterface)]
/// struct MyOp;
///
/// #[op_interface]
/// pub trait MyOpInterface {
///     fn gubbi(&self) { println!("gubbi"); }
///     fn verify(op: &dyn Op, ctx: &Context) -> Result<()>
///     where Self: Sized,
///     {
///         Ok(())
///     }
/// }
/// # use pliron::derive::def_op;
/// # use pliron::{
/// #     op::Op, context::Context, result::Result,
/// #     common_traits::Verify
/// # };
/// ```
#[proc_macro_attribute]
pub fn derive_op_interface_impl(attr: TokenStream, item: TokenStream) -> TokenStream {
    to_token_stream(interfaces::derive_op_interface_impl(attr, item))
}

/// Declare an [Attribute](../pliron/attribute/trait.Attribute.html) interface,
/// which can be implemented by any `Attribute`.
///
/// If the interface requires any other interface to be already implemented,
/// they can be specified super-traits.
///
/// When an `Attribute` is verified, its interfaces are also automatically verified,
/// with guarantee that a super-interface is verified before an interface itself is.
///
/// Example: Here `Super1` and `Super2` are super interfaces for the interface `MyAttrIntr`.
/// ```
/// # use pliron::{attribute::Attribute, context::Context, result::Result};
/// use pliron::derive::attr_interface;
///
/// #[attr_interface]
/// trait Super1 {
///     fn verify(_attr: &dyn Attribute, _ctx: &Context) -> Result<()>
///     where
///         Self: Sized,
///     {
///         Ok(())
///     }
/// }
///
/// #[attr_interface]
/// trait Super2 {
///     fn verify(_attr: &dyn Attribute, _ctx: &Context) -> Result<()>
///     where
///         Self: Sized,
///     {
///         Ok(())
///     }
/// }
///
/// // MyAttrIntr is my best attribute interface.
/// #[attr_interface]
/// trait MyAttrIntr: Super1 + Super2 {
///     fn verify(_attr: &dyn Attribute, _ctx: &Context) -> Result<()>
///     where
///         Self: Sized,
///     {
///         Ok(())
///     }
/// }
/// ```
#[proc_macro_attribute]
pub fn attr_interface(_attr: TokenStream, item: TokenStream) -> TokenStream {
    let supertrait = parse_quote! { ::pliron::attribute::Attribute };
    let verifier_type = parse_quote! { ::pliron::attribute::AttrInterfaceVerifier };
    let target_marker_trait = parse_quote! { ::pliron::attribute::AttrInterfaceMarker };

    let define = interfaces::interface_define(
        item.clone(),
        supertrait,
        verifier_type,
        true,
        target_marker_trait,
    );

    // Implement common traits for `dyn Interface` that we already implement for `AttrObj`.
    let obj_traits = interfaces::attr_interface_obj_traits(item);

    to_token_stream(define.and_then(|mut output| {
        output.extend(obj_traits?);
        Ok(output)
    }))
}

/// Implement [Attribute](../pliron/attribute/trait.Attribute.html) Interface for an Attribute.
/// The interface trait must define a `verify` function with type
/// [AttrInterfaceVerifier](../pliron/attribute/type.AttrInterfaceVerifier.html).
///
/// Usage:
/// ```
/// use pliron::derive::{attr_interface, attr_interface_impl, def_attribute, format_attribute, verify_succ};
///
/// #[verify_succ]
/// #[def_attribute("dialect.name")]
/// #[format_attribute]
/// #[derive(PartialEq, Eq, Clone, Debug, Hash)]
/// struct MyAttr { }
///
///     /// My first attribute interface.
/// #[attr_interface]
/// trait MyAttrInterface {
///     fn monu(&self);
///     fn verify(attr: &dyn Attribute, ctx: &Context) -> Result<()>
///     where Self: Sized,
///     {
///          Ok(())
///     }
/// }
///
/// #[attr_interface_impl]
/// impl MyAttrInterface for MyAttr
/// {
///     fn monu(&self) { println!("monu"); }
/// }
/// # use pliron::{
/// #     printable::{self, Printable},
/// #     context::Context, result::Result, common_traits::Verify,
/// #     attribute::Attribute
/// # };
#[proc_macro_attribute]
pub fn attr_interface_impl(_attr: TokenStream, item: TokenStream) -> TokenStream {
    let interface_verifiers_slice = parse_quote! { ::pliron::attribute::ATTR_INTERFACE_VERIFIERS };
    let all_verifiers_fn_type = parse_quote! { ::pliron::attribute::AttrInterfaceAllVerifiers };
    to_token_stream(interfaces::interface_impl(
        item.into(),
        interface_verifiers_slice,
        all_verifiers_fn_type,
        interfaces::RegisterBoxedCast::Register,
        interfaces::ImplsMarkerTrait::Skip,
    ))
}

/// Declare a [Type](../pliron/type/trait.Type.html) interface,
/// which can be implemented by any `Type`.
///
/// If the interface requires any other interface to be already implemented,
/// they can be specified super-traits.
///
/// When an `Attribute` is verified, its interfaces are also automatically verified,
/// with guarantee that a super-interface is verified before an interface itself is.
///
/// Example: Here `Super1` and `Super2` are super interfaces for the interface `MyTypeIntr`.
/// ```
/// use pliron::derive::type_interface;
/// # use pliron::{r#type::Type, context::Context, result::Result};
/// #[type_interface]
/// trait Super1 {
///     fn verify(_type: &dyn Type, _ctx: &Context) -> Result<()>
///     where
///         Self: Sized,
///     {
///         Ok(())
///     }
/// }
///
/// #[type_interface]
/// trait Super2 {
///     fn verify(_type: &dyn Type, _ctx: &Context) -> Result<()>
///     where
///         Self: Sized,
///     {
///         Ok(())
///     }
/// }
///
/// #[type_interface]
/// // MyTypeIntr is my best type interface.
/// trait MyTypeIntr: Super1 + Super2 {
///     fn verify(_type: &dyn Type, _ctx: &Context) -> Result<()>
///     where
///         Self: Sized,
///     {
///         Ok(())
///     }
/// }
/// ```
#[proc_macro_attribute]
pub fn type_interface(_attr: TokenStream, item: TokenStream) -> TokenStream {
    let supertrait = parse_quote! { ::pliron::r#type::Type };
    let verifier_type = parse_quote! { ::pliron::r#type::TypeInterfaceVerifier };
    let target_marker_trait = parse_quote! { ::pliron::r#type::TypeInterfaceMarker };

    to_token_stream(interfaces::interface_define(
        item,
        supertrait,
        verifier_type,
        false,
        target_marker_trait,
    ))
}

/// Implement [Type](../pliron/type/trait.Type.html) Interface for a Type.
/// The interface trait must define a `verify` function with type
/// [TypeInterfaceVerifier](../pliron/type/type.TypeInterfaceVerifier.html).
///
/// Usage:
/// ```
/// use pliron::derive::{def_type, format_type, type_interface, type_interface_impl, verify_succ};
///
/// #[verify_succ]
/// #[def_type("dialect.name")]
/// #[format_type]
/// #[derive(PartialEq, Eq, Clone, Debug, Hash)]
/// struct MyType { }
///
/// #[type_interface]
/// /// My first type interface.
/// trait MyTypeInterface {
///     fn monu(&self);
///     fn verify(r#type: &dyn Type, ctx: &Context) -> Result<()>
///     where Self: Sized,
///     {
///          Ok(())
///     }
/// }
///
/// #[type_interface_impl]
/// impl MyTypeInterface for MyType
/// {
///     fn monu(&self) { println!("monu"); }
/// }
/// # use pliron::{
/// #     printable::{self, Printable},
/// #     context::Context, result::Result, common_traits::Verify,
/// #     r#type::Type
/// # };
#[proc_macro_attribute]
pub fn type_interface_impl(_attr: TokenStream, item: TokenStream) -> TokenStream {
    let interface_verifiers_slice = parse_quote! { ::pliron::r#type::TYPE_INTERFACE_VERIFIERS };
    let all_verifiers_fn_type = parse_quote! { ::pliron::r#type::TypeInterfaceAllVerifiers };
    let impls_marker_trait = parse_quote! { ::pliron::r#type::TypeImplsInterface };
    to_token_stream(interfaces::interface_impl(
        item.into(),
        interface_verifiers_slice,
        all_verifiers_fn_type,
        interfaces::RegisterBoxedCast::Skip,
        interfaces::ImplsMarkerTrait::Implement(impls_marker_trait),
    ))
}

/// Implement [StableHash](../pliron/irbuild/decontext/trait.StableHash.html)
/// for a struct or enum, assuming every field's type already implements it.
/// For an enum, the matched variant's discriminant is also mixed into the hash.
///
/// This also registers the impl with [type_to_trait!](../pliron/macro.type_to_trait.html).
///
/// Usage:
///
/// ```
/// use pliron::{derive::StableHash, r#type::TypeHandle};
///
/// #[derive(StableHash)]
/// struct MyAttr {
///     ty: TypeHandle,
///     val: u64,
/// }
/// ```
///
/// This fails to compile because `NotHashable` doesn't implement `StableHash`:
/// ```compile_fail
/// use pliron::derive::StableHash;
///
/// struct NotHashable;
///
/// #[derive(StableHash)]
/// struct MyAttr {
///     val: NotHashable,
/// }
/// ```
#[proc_macro_derive(StableHash)]
pub fn stable_hash(input: TokenStream) -> TokenStream {
    to_token_stream(derive_decontext::derive_stable_hash(input.into()))
}

/// Implement [CloneIntoContext](../pliron/irbuild/decontext/trait.CloneIntoContext.html)
/// for a struct or enum, assuming every field's type already implements it. For an enum,
/// the matched variant is reconstructed with its (cloned) fields.
///
/// Usage:
///
/// ```
/// use pliron::{derive::CloneIntoContext, r#type::TypeHandle};
///
/// #[derive(CloneIntoContext)]
/// struct MyAttr {
///     ty: TypeHandle,
///     val: u64,
/// }
/// ```
///
/// A generic struct, with the field's bound written explicitly:
/// ```
/// use pliron::{
///     context::Context, derive::CloneIntoContext,
///     irbuild::decontext::CloneIntoContext as CloneIntoContextTrait,
/// };
///
/// #[derive(CloneIntoContext)]
/// struct Wrapper<T: CloneIntoContextTrait> {
///     inner: T,
/// }
///
/// let src_ctx = Context::new();
/// let mut dst_ctx = Context::new();
/// let cloned = Wrapper { inner: 42u64 }.clone_into_context(&src_ctx, &mut dst_ctx);
/// assert_eq!(cloned.inner, 42);
/// ```
///
/// This fails to compile because `NotCloneable` doesn't implement `CloneIntoContext`:
/// ```compile_fail
/// use pliron::derive::CloneIntoContext;
///
/// struct NotCloneable;
///
/// #[derive(CloneIntoContext)]
/// struct MyAttr {
///     val: NotCloneable,
/// }
/// ```
#[proc_macro_derive(CloneIntoContext)]
pub fn clone_into_context(input: TokenStream) -> TokenStream {
    to_token_stream(derive_decontext::derive_clone_into_context(input.into()))
}

/// Implement [CloneAttributeIntoContext](../pliron/irbuild/decontext/trait.CloneAttributeIntoContext.html)
/// for an [Attribute](../pliron/attribute/trait.Attribute.html) by delegating to its own
/// [CloneIntoContext](../pliron/irbuild/decontext/trait.CloneIntoContext.html) impl and boxing the result.
///
/// The type must already implement
/// [CloneIntoContext](../pliron/irbuild/decontext/trait.CloneIntoContext.html) (e.g. via
/// [`#[derive(CloneIntoContext)]`](derive@CloneIntoContext),
/// or [`impl_clone_into_context_for_clone!`](../pliron/macro.impl_clone_into_context_for_clone.html)).
///
/// Usage:
///
/// ```
/// use pliron::{
///     attribute::AttrObj, context::Context,
///     derive::{CloneAttributeIntoContext, CloneIntoContext, pliron_attr},
///     irbuild::decontext::CloneIntoContext as _, printable::Printable,
/// };
///
/// #[pliron_attr(name = "test.point_attr", format = "`<` $x `>`", verifier = "succ")]
/// #[derive(Debug, Clone, PartialEq, Eq, Hash, CloneIntoContext, CloneAttributeIntoContext)]
/// struct PointAttr {
///     x: i32,
/// }
///
/// let src_ctx = Context::new();
/// let mut dst_ctx = Context::new();
/// let a: AttrObj = Box::new(PointAttr { x: 1 });
/// let a2 = a.clone_into_context(&src_ctx, &mut dst_ctx);
/// assert_eq!(a.disp(&src_ctx).to_string(), a2.disp(&dst_ctx).to_string());
/// ```
#[proc_macro_derive(CloneAttributeIntoContext)]
pub fn clone_attribute_into_context(input: TokenStream) -> TokenStream {
    to_token_stream(derive_decontext::derive_clone_attribute_into_context(
        input.into(),
    ))
}

/// Implement [CloneTypeIntoContext](../pliron/irbuild/decontext/trait.CloneTypeIntoContext.html)
/// for a [Type](../pliron/type/trait.Type.html) by delegating to its own
/// [CloneIntoContext](../pliron/irbuild/decontext/trait.CloneIntoContext.html) impl,
/// then re-interning the clone into `dst_ctx`.
///
/// The type must already implement
/// [CloneIntoContext](../pliron/irbuild/decontext/trait.CloneIntoContext.html) (e.g. via
/// [`#[derive(CloneIntoContext)]`](derive@CloneIntoContext),
/// or [`impl_clone_into_context_for_clone!`](../pliron/macro.impl_clone_into_context_for_clone.html)).
///
/// Usage:
///
/// ```
/// use pliron::{
///     context::Context,
///     derive::{CloneIntoContext, CloneTypeIntoContext, pliron_type},
///     irbuild::decontext::CloneIntoContext as _, printable::Printable,
/// };
///
/// #[pliron_type(
///     name = "test.point_type",
///     format = "`<` $x `>`",
///     generate_get = true,
///     verifier = "succ"
/// )]
/// #[derive(Debug, Clone, PartialEq, Eq, Hash, CloneIntoContext, CloneTypeIntoContext)]
/// struct PointType {
///     x: i32,
/// }
///
/// let src_ctx = Context::new();
/// let mut dst_ctx = Context::new();
/// let p = PointType::get(&src_ctx, 1).to_handle();
/// let p2 = p.clone_into_context(&src_ctx, &mut dst_ctx);
/// assert_eq!(p.disp(&src_ctx).to_string(), p2.disp(&dst_ctx).to_string());
/// ```
#[proc_macro_derive(CloneTypeIntoContext)]
pub fn clone_type_into_context(input: TokenStream) -> TokenStream {
    to_token_stream(derive_decontext::derive_clone_type_into_context(
        input.into(),
    ))
}