sails-idl-ast 1.0.0-beta.5

IDL AST model for the Sails framework
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
#![no_std]

extern crate alloc;

pub mod codec;
mod hash;
mod interface_id;

use alloc::{
    boxed::Box,
    format,
    string::{String, ToString as _},
    vec,
    vec::Vec,
};
use core::{
    fmt::{Display, Write},
    str::FromStr,
};
pub use interface_id::InterfaceId;
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

// -------------------------------- IDL model ---------------------------------
pub type Annotation = (String, Option<String>);

/// Root AST node representing a single parsed Sails IDL document.
///
/// Mirrors one `.idl` file from the specification:
/// - `globals` correspond to global `!@...` annotations at the top of the file;
/// - `program` holds an optional `program <ident> { ... }` block;
/// - `services` contains all top-level `service <ident> { ... }` definitions.
#[derive(Debug, Default, Clone, PartialEq)]
#[cfg_attr(
    feature = "templates",
    derive(askama::Template),
    template(path = "idl.askama", escape = "none")
)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct IdlDoc {
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Vec::is_empty")
    )]
    pub globals: Vec<Annotation>,
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub program: Option<ProgramUnit>,
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Vec::is_empty")
    )]
    pub services: Vec<ServiceUnit>,
}

impl IdlDoc {
    #[cfg(feature = "serde")]
    pub fn to_json_string(&self) -> Result<String, serde_json::Error> {
        serde_json::to_string(self)
    }

    #[cfg(feature = "serde")]
    pub fn to_json_string_pretty(&self) -> Result<String, serde_json::Error> {
        serde_json::to_string_pretty(self)
    }
}

/// AST node describing a `program` block.
///
/// A program is an entry point that:
/// - declares constructor functions in `constructors { ... }`,
/// - exposes one or more services in `services { ... }`,
/// - may define shared types in `types { ... }`,
/// - may contain documentation comments and annotations.
///
/// Call [`ProgramUnit::normalize`] after construction to populate `entry_id` on each constructor.
#[derive(Debug, Default, Clone, PartialEq)]
#[cfg_attr(
    feature = "templates",
    derive(askama::Template),
    template(path = "program.askama", escape = "none")
)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct ProgramUnit {
    pub name: String,
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Vec::is_empty")
    )]
    pub ctors: Vec<CtorFunc>,
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Vec::is_empty")
    )]
    pub services: Vec<ServiceExpo>,
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Vec::is_empty")
    )]
    pub types: Vec<Type>,
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Vec::is_empty")
    )]
    pub docs: Vec<String>,
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Vec::is_empty")
    )]
    pub annotations: Vec<Annotation>,
}

impl ProgramUnit {
    /// Compute `entry_id` for each constructor from `@entry_id` annotation,
    /// falling back to declaration-order index.
    /// Must be called after parsing, before any reordering.
    pub fn normalize(&mut self) {
        for (idx, ctor) in self.ctors.iter_mut().enumerate() {
            ctor.entry_id = entry_id_from_annotations(&ctor.annotations, idx as u16);
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct ServiceIdent {
    pub name: String,
    #[cfg_attr(
        feature = "serde",
        serde(
            default,
            skip_serializing_if = "Option::is_none",
            with = "serde_opt_str"
        )
    )]
    pub interface_id: Option<InterfaceId>,
}

impl Display for ServiceIdent {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.write_str(&self.name)?;
        if let Some(id) = self.interface_id {
            f.write_str("@")?;
            id.fmt(f)?;
        }
        Ok(())
    }
}

impl FromStr for ServiceIdent {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let (name, interface_id) = match s.split_once('@') {
            None => (s.trim().to_string(), None),
            Some((name, id_str)) => {
                if name.is_empty() {
                    return Err("name is empty".to_string());
                }
                if id_str.is_empty() {
                    return Err("interface_id is empty".to_string());
                }

                // Delegate parsing to InterfaceId's FromStr
                let id = id_str.trim().parse::<InterfaceId>()?;
                (name.trim().to_string(), Some(id))
            }
        };
        Ok(ServiceIdent { name, interface_id })
    }
}

/// Single service export entry inside a `program { services { ... } }` section.
///
/// Represents a link between:
/// - the exported service name visible to the client,
/// - an optional low-level `route` (transport / path) used by the runtime,
/// - may contain documentation comments and annotations.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct ServiceExpo {
    #[cfg_attr(feature = "serde", serde(flatten))]
    pub name: ServiceIdent,
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub route: Option<String>,
    pub route_idx: u8,
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Vec::is_empty")
    )]
    pub docs: Vec<String>,
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Vec::is_empty")
    )]
    pub annotations: Vec<Annotation>,
}

/// Constructor function of a program, declared in `constructors { ... }`.
///
/// A constructor describes how to create or initialize a program instance:
/// - `name` is the constructor identifier,
/// - `params` are the IDL-level arguments,
/// - `entry_id` is the on-chain entry identifier (computed from `@entry_id` annotation or declaration order),
/// - may contain documentation comments and annotations.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct CtorFunc {
    pub name: String,
    #[cfg_attr(feature = "serde", serde(default))]
    pub params: Vec<FuncParam>,
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Option::is_none")
    )]
    pub throws: Option<TypeDecl>,
    #[cfg_attr(feature = "serde", serde(default))]
    pub entry_id: u16,
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Vec::is_empty")
    )]
    pub docs: Vec<String>,
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Vec::is_empty")
    )]
    pub annotations: Vec<Annotation>,
}

/// AST node describing a `service` definition.
///
/// A service is an interface that:
/// - may `extends` other services, inheriting their events, functions and types,
/// - defines `funcs` in `functions { ... }`,
/// - defines `events` in `events { ... }`,
/// - defines service-local `types { ... }`,
/// - may contain documentation comments and annotations.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(
    feature = "templates",
    derive(askama::Template),
    template(path = "service.askama", escape = "none")
)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct ServiceUnit {
    #[cfg_attr(feature = "serde", serde(flatten))]
    pub name: ServiceIdent,
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Vec::is_empty")
    )]
    pub extends: Vec<ServiceIdent>,
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Vec::is_empty")
    )]
    pub funcs: Vec<ServiceFunc>,
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Vec::is_empty")
    )]
    pub events: Vec<ServiceEvent>,
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Vec::is_empty")
    )]
    pub types: Vec<Type>,
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Vec::is_empty")
    )]
    pub docs: Vec<String>,
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Vec::is_empty")
    )]
    pub annotations: Vec<Annotation>,
}

impl ServiceUnit {
    /// Stabilize ordering for deterministic output and comparisons.
    ///
    /// Also computes `entry_id` for each func and event from `@entry_id` annotation,
    /// falling back to declaration-order index.
    pub fn normalize(&mut self) {
        self.events.sort_by_key(|e| e.name.to_lowercase());
        self.funcs.sort_by_key(|f| f.name.to_lowercase());
        self.extends.sort_by_key(|e| e.name.to_lowercase());
        // Assign entry_id AFTER sort: use @entry_id annotation if present,
        // otherwise the post-sort (alphabetical) index, which matches scale-codec ordering.
        for (idx, func) in self.funcs.iter_mut().enumerate() {
            func.entry_id = entry_id_from_annotations(&func.annotations, idx as u16);
        }
        for (idx, event) in self.events.iter_mut().enumerate() {
            event.entry_id = entry_id_from_annotations(&event.annotations, idx as u16);
        }
    }

    /// Returns `true` if the service is annotated with `@partial`.
    ///
    /// Partial services describe a subset of an existing on-chain service and require
    /// explicit `@entry_id` annotations on all functions and events.
    pub fn is_partial(&self) -> bool {
        self.annotations.iter().any(|(k, _)| k == "partial")
    }
}

fn entry_id_from_annotations(annotations: &[(String, Option<String>)], fallback: u16) -> u16 {
    annotations
        .iter()
        .find(|(k, _)| k == "entry_id")
        .and_then(|(_, v)| v.as_ref()?.parse::<u16>().ok())
        .unwrap_or(fallback)
}

/// Service function entry inside `service { functions { ... } }`.
///
/// - `params` is the ordered list of IDL parameters;
/// - `output` is the return type (use `PrimitiveType::Void` for `()` / no value);
/// - `throws` is an optional error type after the `throws` keyword;
/// - `is_query` marks read-only / query functions as defined by the spec;
/// - `entry_id` is the on-chain entry identifier (computed from `@entry_id` annotation or declaration order);
/// - may contain documentation comments and annotations.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct ServiceFunc {
    pub name: String,
    #[cfg_attr(feature = "serde", serde(default))]
    pub params: Vec<FuncParam>,
    pub output: TypeDecl,
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub throws: Option<TypeDecl>,
    pub kind: FunctionKind,
    #[cfg_attr(feature = "serde", serde(default))]
    pub entry_id: u16,
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Vec::is_empty")
    )]
    pub docs: Vec<String>,
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Vec::is_empty")
    )]
    pub annotations: Vec<Annotation>,
}

/// Function kind based on mutability.
#[derive(Debug, Default, PartialEq, Eq, Clone, Copy, PartialOrd, Ord)]
#[cfg_attr(
    feature = "serde",
    derive(Serialize, Deserialize),
    serde(rename_all = "lowercase")
)]
pub enum FunctionKind {
    #[default]
    Command,
    Query,
}

impl ServiceFunc {
    /// Returns `true` if the function is declared with a `()` return type,
    /// i.e. it does not produce a value on success.
    pub fn returns_void(&self) -> bool {
        use PrimitiveType::*;
        use TypeDecl::*;
        self.output == Primitive(Void)
    }
}

/// Function parameter used in constructors and service functions.
///
/// Stores the parameter name as written in IDL and its fully resolved type
/// (`TypeDecl`), preserving declaration order.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct FuncParam {
    pub name: String,
    #[cfg_attr(feature = "serde", serde(rename = "type"))]
    pub type_decl: TypeDecl,
}

impl Display for FuncParam {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        let FuncParam { name, type_decl } = self;
        write!(f, "{name}: {type_decl}")
    }
}

/// Service event is represented as an enum variant with an associated payload.
///
/// Events in `events { ... }` are modeled as `EnumVariant` with a `StructDef`
/// describing fields of the event, so the same machinery as for enums can be reused.
pub type ServiceEvent = EnumVariant;

/// Generalized type descriptor used throughout the AST.
///
/// Covers all kinds of IDL types:
/// - primitive types (`Primitive`),
/// - slices and fixed arrays (`Slice`, `Array`),
/// - tuples (`Tuple`),
/// - named types (e.g. `Point<u32>`)
///     - container types like `Option<T>`, `Result<T, E>`
///     - user-defined types with generics (`UserDefined`),
/// - generic type parameters (e.g. `T`).
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(
    feature = "serde",
    derive(Serialize, Deserialize),
    serde(rename_all = "lowercase", tag = "kind")
)]
pub enum TypeDecl {
    /// Slice type `[T]`.
    Slice { item: Box<TypeDecl> },
    /// Fixed-length array type `[T; N]`.
    Array { item: Box<TypeDecl>, len: u32 },
    /// Tuple type `(T1, T2, ...)`, including `()` for an empty tuple.
    Tuple { types: Vec<TypeDecl> },
    /// Generic type parameter reference declared by the surrounding [`Type`].
    Generic { name: String },
    /// Named type, possibly generic (e.g. `Point<u32>`).
    Named {
        name: String,
        #[cfg_attr(
            feature = "serde",
            serde(default, skip_serializing_if = "Vec::is_empty")
        )]
        generics: Vec<TypeDecl>,
    },
    /// Built-in primitive type from `PrimitiveType`.
    #[cfg_attr(feature = "serde", serde(untagged))]
    Primitive(#[cfg_attr(feature = "serde", serde(with = "serde_str"))] PrimitiveType),
}

impl TypeDecl {
    pub fn named(name: impl Into<String>) -> TypeDecl {
        Self::named_with_generics(name, vec![])
    }

    pub fn named_with_generics(name: impl Into<String>, generics: Vec<TypeDecl>) -> TypeDecl {
        TypeDecl::Named {
            name: name.into(),
            generics,
        }
    }

    pub fn generic(name: impl Into<String>) -> TypeDecl {
        TypeDecl::Generic { name: name.into() }
    }

    pub fn tuple(types: Vec<TypeDecl>) -> TypeDecl {
        TypeDecl::Tuple { types }
    }

    pub fn option(item: TypeDecl) -> TypeDecl {
        TypeDecl::Named {
            name: "Option".to_string(),
            generics: vec![item],
        }
    }

    pub fn result(ok: TypeDecl, err: TypeDecl) -> TypeDecl {
        TypeDecl::Named {
            name: "Result".to_string(),
            generics: vec![ok, err],
        }
    }

    pub fn option_type_decl(ty: &TypeDecl) -> Option<TypeDecl> {
        match ty {
            TypeDecl::Named { name, generics } if name == "Option" => {
                if let [item] = generics.as_slice() {
                    Some(item.clone())
                } else {
                    None
                }
            }
            _ => None,
        }
    }

    pub fn result_type_decl(ty: &TypeDecl) -> Option<(TypeDecl, TypeDecl)> {
        match ty {
            TypeDecl::Named { name, generics } if name == "Result" => {
                if let [ok, err] = generics.as_slice() {
                    Some((ok.clone(), err.clone()))
                } else {
                    None
                }
            }
            _ => None,
        }
    }

    #[cfg(feature = "serde")]
    pub fn to_json_string(&self) -> Result<String, serde_json::Error> {
        serde_json::to_string(self)
    }

    #[cfg(feature = "serde")]
    pub fn to_json_string_pretty(&self) -> Result<String, serde_json::Error> {
        serde_json::to_string_pretty(self)
    }
}

impl Display for TypeDecl {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        use TypeDecl::*;
        match self {
            Slice { item } => write!(f, "[{item}]"),
            Array { item, len } => write!(f, "[{item}; {len}]"),
            Tuple { types } => {
                f.write_char('(')?;
                for (i, ty) in types.iter().enumerate() {
                    if i > 0 {
                        f.write_str(", ")?;
                    }
                    write!(f, "{ty}")?;
                }
                f.write_char(')')?;
                Ok(())
            }
            Generic { name } => f.write_str(name),
            Named { name, generics } => {
                write!(f, "{name}")?;
                if !generics.is_empty() {
                    f.write_char('<')?;
                    for (i, g) in generics.iter().enumerate() {
                        if i > 0 {
                            f.write_str(", ")?;
                        }
                        write!(f, "{g}")?;
                    }
                    f.write_char('>')?;
                }
                Ok(())
            }
            Primitive(primitive_type) => write!(f, "{primitive_type}"),
        }
    }
}

/// Enumeration of all built-in primitive types supported by the IDL.
///
/// Includes booleans, characters, signed/unsigned integers, string, and
/// platform-specific identifiers and hashes (ActorId, CodeId, MessageId,
/// H160/H256/U256) used by the runtime.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u8)]
pub enum PrimitiveType {
    /// Unit / void type `()`.
    Void,
    Bool,
    Char,
    String,
    U8,
    U16,
    U32,
    U64,
    U128,
    I8,
    I16,
    I32,
    I64,
    I128,
    /// Identifier of an actor / service instance.
    ActorId,
    /// Identifier of deployed code.
    CodeId,
    /// Identifier of a message.
    MessageId,
    /// 160-bit hash / address type.
    H160,
    /// 256-bit hash (32-byte array) type.
    H256,
    /// 256-bit unsigned integer type.
    U256,
}

impl PrimitiveType {
    /// Returns the canonical textual representation used when rendering IDL.
    pub const fn as_str(&self) -> &'static str {
        use PrimitiveType::*;
        match self {
            Void => "()",
            Bool => "bool",
            Char => "char",
            String => "String",
            U8 => "u8",
            U16 => "u16",
            U32 => "u32",
            U64 => "u64",
            U128 => "u128",
            I8 => "i8",
            I16 => "i16",
            I32 => "i32",
            I64 => "i64",
            I128 => "i128",
            ActorId => "ActorId",
            CodeId => "CodeId",
            MessageId => "MessageId",
            H160 => "H160",
            H256 => "H256",
            U256 => "U256",
        }
    }
}

impl Display for PrimitiveType {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.write_str(self.as_str())
    }
}

impl core::str::FromStr for PrimitiveType {
    type Err = String;

    /// Parses a primitive type from its textual representation used in IDL.
    ///
    /// Accepts several common aliases and case variations (e.g. `string` / `String`,
    /// `actor_id` / `ActorId`) for convenience.
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        use PrimitiveType::*;
        match s {
            "()" => Ok(Void),
            "bool" => Ok(Bool),
            "char" => Ok(Char),
            "String" | "string" => Ok(String),
            "u8" => Ok(U8),
            "u16" => Ok(U16),
            "u32" => Ok(U32),
            "u64" => Ok(U64),
            "u128" => Ok(U128),
            "i8" => Ok(I8),
            "i16" => Ok(I16),
            "i32" => Ok(I32),
            "i64" => Ok(I64),
            "i128" => Ok(I128),

            "ActorId" | "actor" | "actor_id" => Ok(ActorId),
            "CodeId" | "code" | "code_id" => Ok(CodeId),
            "MessageId" | "messageid" | "message_id" => Ok(MessageId),

            "H256" | "h256" => Ok(H256),
            "U256" | "u256" => Ok(U256),
            "H160" | "h160" => Ok(H160),

            other => Err(format!("Unknown primitive type: {other}")),
        }
    }
}

/// Top-level named type definition inside `types { ... }` of a service or program.
///
/// `Type` describes either a struct or enum with an optional list of generic
/// type parameters, along with documentation and annotations taken from IDL.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(
    feature = "templates",
    derive(askama::Template),
    template(path = "type.askama", escape = "none")
)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Type {
    pub name: String,
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Vec::is_empty")
    )]
    pub type_params: Vec<TypeParameter>,
    #[cfg_attr(feature = "serde", serde(flatten))]
    pub def: TypeDef,
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Vec::is_empty")
    )]
    pub docs: Vec<String>,
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Vec::is_empty")
    )]
    pub annotations: Vec<Annotation>,
}

impl Type {
    #[cfg(feature = "serde")]
    pub fn to_json_string(&self) -> Result<String, serde_json::Error> {
        serde_json::to_string(self)
    }

    #[cfg(feature = "serde")]
    pub fn to_json_string_pretty(&self) -> Result<String, serde_json::Error> {
        serde_json::to_string_pretty(self)
    }
}

/// Generic type parameter in a type definition.
///
/// - `name` is the declared identifier of the parameter (e.g. `T`);
/// - `ty` is an optional concrete type bound / substitution; `None` means that
///   the parameter is left generic at this level.
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct TypeParameter {
    /// The name of the generic type parameter e.g. "T".
    pub name: String,
    /// The concrete type for the type parameter.
    ///
    /// `None` if the type parameter is skipped.
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub ty: Option<TypeDecl>,
}

impl Display for TypeParameter {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        let TypeParameter { name, ty: _ } = self;
        write!(f, "{name}")
    }
}

/// Underlying definition of a named type: either a struct or an enum.
///
/// This mirrors the two composite categories in the IDL:
/// - `Struct` - record / tuple / unit structs;
/// - `Enum` - tagged unions with variants that may carry payloads.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(
    feature = "serde",
    derive(Serialize, Deserialize),
    serde(rename_all = "lowercase", tag = "kind")
)]
pub enum TypeDef {
    Struct(StructDef),
    Enum(EnumDef),
    Alias(AliasDef),
}

/// Struct definition backing a named type or an enum variant payload.
///
/// A struct can represent:
/// - unit form (`fields.is_empty()`),
/// - classic form with named fields,
/// - tuple-like form with unnamed fields.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(
    feature = "templates",
    derive(askama::Template),
    template(path = "struct_def.askama", escape = "none")
)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct StructDef {
    #[cfg_attr(feature = "serde", serde(default))]
    pub fields: Vec<StructField>,
}

impl StructDef {
    /// Returns `true` if the struct has no fields (unit struct).
    pub fn is_unit(&self) -> bool {
        self.fields.is_empty()
    }

    /// Returns `true` if the struct is inline and purely positional:
    /// all fields are unnamed and have no docs or annotations.
    pub fn is_inline(&self) -> bool {
        self.fields
            .iter()
            .all(|f| f.name.is_none() && f.docs.is_empty() && f.annotations.is_empty())
    }

    /// Returns `true` if the struct is tuple-like (all fields are unnamed).
    pub fn is_tuple(&self) -> bool {
        self.fields.iter().all(|f| f.name.is_none())
    }

    #[cfg(feature = "serde")]
    pub fn to_json_string(&self) -> Result<String, serde_json::Error> {
        serde_json::to_string(self)
    }

    #[cfg(feature = "serde")]
    pub fn to_json_string_pretty(&self) -> Result<String, serde_json::Error> {
        serde_json::to_string_pretty(self)
    }
}

/// Field of a struct or of an enum variant payload.
///
/// `name` is `None` for tuple-like structs / variants; otherwise it stores the
/// field identifier from IDL. Each field keeps its own documentation and annotations.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(
    feature = "templates",
    derive(askama::Template),
    template(path = "field.askama", escape = "none")
)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct StructField {
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub name: Option<String>,
    #[cfg_attr(feature = "serde", serde(rename = "type"))]
    pub type_decl: TypeDecl,
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Vec::is_empty")
    )]
    pub docs: Vec<String>,
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Vec::is_empty")
    )]
    pub annotations: Vec<Annotation>,
}

/// Enum definition backing a named enum type.
///
/// Stores the ordered list of `EnumVariant` items that form a tagged union.
/// Each variant may be unit-like, classic (named fields) or tuple-like.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct EnumDef {
    #[cfg_attr(feature = "serde", serde(default))]
    pub variants: Vec<EnumVariant>,
}

/// Single variant of an enum or service event.
///
/// - `name` is the variant identifier,
/// - `def` is a `StructDef` describing the payload shape (unit / classic / tuple),
/// - `entry_id` is the on-chain entry identifier; meaningful for service events,
///   computed by [`ServiceUnit::normalize`] from `@entry_id` annotation or declaration order,
/// - `docs` and `annotations` are attached to the variant in IDL.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(
    feature = "templates",
    derive(askama::Template),
    template(path = "variant.askama", escape = "none")
)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct EnumVariant {
    pub name: String,
    #[cfg_attr(feature = "serde", serde(flatten))]
    pub def: StructDef,
    #[cfg_attr(feature = "serde", serde(default))]
    pub entry_id: u16,
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Vec::is_empty")
    )]
    pub docs: Vec<String>,
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Vec::is_empty")
    )]
    pub annotations: Vec<Annotation>,
}

/// Alias definition backing a named alias type.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct AliasDef {
    pub target: TypeDecl,
}

#[cfg(feature = "serde")]
mod serde_str {
    use super::*;
    use core::str::FromStr;
    use serde::{Deserializer, Serializer};

    pub(super) fn serialize<T, S>(value: &T, serializer: S) -> Result<S::Ok, S::Error>
    where
        T: Display,
        S: Serializer,
    {
        serializer.collect_str(value)
    }

    pub(super) fn deserialize<'de, T, D>(deserializer: D) -> Result<T, D::Error>
    where
        T: FromStr,
        <T as FromStr>::Err: Display,
        D: Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        T::from_str(s.as_str()).map_err(serde::de::Error::custom)
    }
}

#[cfg(feature = "serde")]
mod serde_opt_str {
    use super::*;
    use core::str::FromStr;
    use serde::{Deserializer, Serializer};

    pub(super) fn serialize<T, S>(value: &Option<T>, serializer: S) -> Result<S::Ok, S::Error>
    where
        T: Display,
        S: Serializer,
    {
        match value {
            Some(value) => serializer.collect_str(value),
            None => serializer.serialize_none(),
        }
    }

    pub(super) fn deserialize<'de, T, D>(deserializer: D) -> Result<Option<T>, D::Error>
    where
        T: FromStr,
        <T as FromStr>::Err: Display,
        D: Deserializer<'de>,
    {
        let opt = Option::<String>::deserialize(deserializer)?;
        opt.map(|s| T::from_str(s.as_str()).map_err(serde::de::Error::custom))
            .transpose()
    }
}