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
//! # AST
//! Abstract Syntax Tree representation contains tree node that
//! represent full cycle and aspects of the programming language, and
//! represent `Turing-complete` state machine.

use crate::types::semantic::ExtendedExpression;
use nom_locate::LocatedSpan;
#[cfg(feature = "codec")]
use serde::{
    de::{self, Deserializer, MapAccess, Visitor},
    ser::{SerializeStruct, Serializer},
    Deserialize, Serialize,
};

/// Max priority level fpr expressions operations
pub const MAX_PRIORITY_LEVEL_FOR_EXPRESSIONS: u8 = 9;

/// Basic `Ident` entity for elements of AST
#[derive(Clone, Debug, Copy, PartialEq, Eq)]
pub struct Ident<'a>(LocatedSpan<&'a str>);

/// Ident methods mirroring `LocatedSpan`
impl<'a> Ident<'a> {
    #[must_use]
    pub fn new(ident: &'a str) -> Ident<'a> {
        Self(LocatedSpan::new(ident))
    }

    #[must_use]
    pub fn fragment(&self) -> &'a str {
        self.0.fragment()
    }

    #[must_use]
    pub fn location_line(&self) -> u32 {
        self.0.location_line()
    }

    #[must_use]
    pub fn location_offset(&self) -> usize {
        self.0.location_offset()
    }
}

impl<'a> std::fmt::Display for Ident<'a> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.fragment())
    }
}

impl<'a> From<&'a str> for Ident<'a> {
    fn from(value: &'a str) -> Ident<'a> {
        Ident::new(value)
    }
}

/// Ident Serializer
#[cfg(feature = "codec")]
impl<'a> Serialize for Ident<'a> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let fragment = self.0.into_fragment_and_extra();
        let mut state = serializer.serialize_struct("Ident", 4)?;
        state.serialize_field("offset", &self.0.location_offset())?;
        state.serialize_field("line", &self.0.location_line())?;
        state.serialize_field("fragment", &fragment.0)?;
        state.serialize_field("extra", &fragment.1)?;
        state.end()
    }
}

/// Ident Deserializer
#[cfg(feature = "codec")]
impl<'de: 'a, 'a> Deserialize<'de> for Ident<'a> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        // grcov-excl-start
        struct IdentVisitor<'a> {
            marker: std::marker::PhantomData<fn() -> Ident<'a>>,
        }

        impl<'de: 'a, 'a> Visitor<'de> for IdentVisitor<'a> {
            type Value = Ident<'de>;

            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
                formatter.write_str("struct Ident")
            }

            fn visit_map<V>(self, mut map: V) -> Result<Ident<'de>, V::Error>
            where
                V: MapAccess<'de>,
            {
                let mut offset = None;
                let mut line = None;
                let mut fragment = None;
                let mut extra = None;
                while let Some(key) = map.next_key::<String>()? {
                    match key.as_str() {
                        "offset" => {
                            if offset.is_some() {
                                return Err(de::Error::duplicate_field("offset"));
                            }
                            offset = Some(map.next_value()?);
                        }
                        "line" => {
                            if line.is_some() {
                                return Err(de::Error::duplicate_field("line"));
                            }
                            line = Some(map.next_value()?);
                        }
                        "fragment" => {
                            if fragment.is_some() {
                                return Err(de::Error::duplicate_field("fragment"));
                            }
                            fragment = Some(map.next_value()?);
                        }
                        "extra" => {
                            if extra.is_some() {
                                return Err(de::Error::duplicate_field("extra"));
                            }
                            extra = Some(map.next_value()?);
                        }
                        _ => return Err(de::Error::unknown_field(&key, FIELDS)),
                    }
                }
                let offset = offset.ok_or_else(|| de::Error::missing_field("offset"))?;
                let line = line.ok_or_else(|| de::Error::missing_field("line"))?;
                let fragment = fragment.ok_or_else(|| de::Error::missing_field("fragment"))?;
                #[allow(clippy::let_unit_value)]
                let extra = extra.ok_or_else(|| de::Error::missing_field("extra"))?;
                let located =
                    unsafe { LocatedSpan::new_from_raw_offset(offset, line, fragment, extra) };
                Ok(Ident(located))
            }
            // grcov-excl-end
        }

        const FIELDS: &[&str] = &["offset", "line", "fragment", "extra"];
        deserializer.deserialize_struct(
            "Ident",
            FIELDS,
            IdentVisitor {
                marker: std::marker::PhantomData,
            },
        )
    }
}

/// `GetName` trait, represent name of specific entity.
pub trait GetName {
    fn name(&self) -> String;
}

/// `GetLocation` represent location of source data for AST element.
/// Useful to locate specific source code location, especially for `Ident`.
pub trait GetLocation {
    fn location(&self) -> CodeLocation;
}

/// Import name element of AST
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "codec", derive(Serialize, Deserialize))]
pub struct ImportName<'a>(#[cfg_attr(feature = "codec", serde(borrow))] Ident<'a>);

impl GetName for ImportName<'_> {
    fn name(&self) -> String {
        (*self.0.fragment()).to_string()
    }
}

impl<'a> ImportName<'a> {
    #[must_use]
    pub const fn new(ident: Ident<'a>) -> Self {
        Self(ident)
    }
}

/// Imports with full path of import
pub type ImportPath<'a> = Vec<ImportName<'a>>;

/// `ConstantName` constant name for `Constant` elements of AST
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "codec", derive(Serialize, Deserialize))]
pub struct ConstantName<'a>(#[cfg_attr(feature = "codec", serde(borrow))] Ident<'a>);

impl<'a> ConstantName<'a> {
    /// Init `ConstantName`, especially useful for testing
    #[must_use]
    pub const fn new(name: Ident<'a>) -> Self {
        Self(name)
    }
}

impl GetLocation for ConstantName<'_> {
    fn location(&self) -> CodeLocation {
        CodeLocation::new(self.0.location_line(), self.0.location_offset())
    }
}

impl GetName for ConstantName<'_> {
    fn name(&self) -> String {
        (*self.0.fragment()).to_string()
    }
}

/// `FunctionName` function name for `Function` elements of AST.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "codec", derive(Serialize, Deserialize))]
pub struct FunctionName<'a>(#[cfg_attr(feature = "codec", serde(borrow))] Ident<'a>);

impl<'a> FunctionName<'a> {
    #[must_use]
    pub const fn new(name: Ident<'a>) -> Self {
        Self(name)
    }
}

impl GetLocation for FunctionName<'_> {
    fn location(&self) -> CodeLocation {
        CodeLocation::new(self.0.location_line(), self.0.location_offset())
    }
}

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

/// `ParameterName` parameter name element of AST, used for `Function`
/// parameters declaration.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "codec", derive(Serialize, Deserialize))]
pub struct ParameterName<'a>(#[cfg_attr(feature = "codec", serde(borrow))] Ident<'a>);

impl<'a> ParameterName<'a> {
    #[must_use]
    pub const fn new(name: Ident<'a>) -> Self {
        Self(name)
    }
}

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

/// `ValueName` value name element of AST. It's basic entity for:
/// - `Struct` type declaration
/// - `LetBinding` declaration
/// - `Binding` declaration
/// - `ExpressionValue` declaration
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "codec", derive(Serialize, Deserialize))]
pub struct ValueName<'a>(#[cfg_attr(feature = "codec", serde(borrow))] Ident<'a>);

impl<'a> ValueName<'a> {
    #[must_use]
    pub const fn new(name: Ident<'a>) -> Self {
        Self(name)
    }
}

impl GetLocation for ValueName<'_> {
    fn location(&self) -> CodeLocation {
        CodeLocation::new(self.0.location_line(), self.0.location_offset())
    }
}

impl GetName for ValueName<'_> {
    fn name(&self) -> String {
        (*self.0.fragment()).to_string()
    }
}

/// `CodeLocation` code location of source for AST elements.
/// Contains: `line` nad `position`.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "codec", derive(Serialize, Deserialize))]
pub struct CodeLocation(u32, usize);

impl CodeLocation {
    /// Initialize code location with:
    /// - `location` - line of source code
    /// - `offset` - position on the line of source code
    #[must_use]
    pub const fn new(location: u32, offset: usize) -> Self {
        Self(location, offset)
    }

    /// Get location line in the source
    #[must_use]
    pub const fn line(&self) -> u32 {
        self.0
    }

    /// Get location position on the line in the source
    #[must_use]
    pub const fn offset(&self) -> usize {
        self.1
    }
}

/// `PrimitiveTypes` primitive types elements of AST.
/// It's represent basic (primitive) types.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(
    feature = "codec",
    derive(Serialize, Deserialize),
    serde(tag = "type", content = "content")
)]
pub enum PrimitiveTypes {
    U8,
    U16,
    U32,
    U64,
    I8,
    I16,
    I32,
    I64,
    F32,
    F64,
    Bool,
    Char,
    String,
    Ptr,
    None,
}

impl GetName for PrimitiveTypes {
    fn name(&self) -> String {
        match self {
            Self::U8 => "u8".to_string(),
            Self::U16 => "u16".to_string(),
            Self::U32 => "u32".to_string(),
            Self::U64 => "u64".to_string(),
            Self::I8 => "i8".to_string(),
            Self::I16 => "i16".to_string(),
            Self::I32 => "i32".to_string(),
            Self::I64 => "i64".to_string(),
            Self::F32 => "f32".to_string(),
            Self::F64 => "f64".to_string(),
            Self::Bool => "bool".to_string(),
            Self::Char => "char".to_string(),
            Self::String => "str".to_string(),
            Self::Ptr => "ptr".to_string(),
            Self::None => "()".to_string(),
        }
    }
}

/// `ExpressionStructValue` expression struct value element of AST.
/// Used for expression value declaration. The basic entity is:
/// - value name of struct type
/// - value struct type attribute
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "codec", derive(Serialize, Deserialize))]
pub struct ExpressionStructValue<'a> {
    /// Value name of struct typed value
    #[cfg_attr(feature = "codec", serde(borrow))]
    pub name: ValueName<'a>,
    /// Attribute name of struct typed value
    pub attribute: ValueName<'a>,
}

/// `StructType` struct type basic element used for `StructTypes`.
/// It contains basic elements:
/// - attribute name
/// - attribute type
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "codec", derive(Serialize, Deserialize))]
pub struct StructType<'a> {
    /// Attribute name entity of struct type
    #[cfg_attr(feature = "codec", serde(borrow))]
    pub attr_name: Ident<'a>,
    /// Attribute type entity of struct type
    pub attr_type: Type<'a>,
}

impl GetName for StructType<'_> {
    fn name(&self) -> String {
        (*self.attr_name.fragment()).to_string()
    }
}

/// `StructTypes` struct type element of AST.
/// Basic entity to declare struct complex types and its attributes.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "codec", derive(Serialize, Deserialize))]
pub struct StructTypes<'a> {
    /// Struct type name
    #[cfg_attr(feature = "codec", serde(borrow))]
    pub name: Ident<'a>,
    /// Struct type attributes
    pub attributes: Vec<StructType<'a>>,
}

impl GetLocation for StructTypes<'_> {
    fn location(&self) -> CodeLocation {
        CodeLocation::new(self.name.location_line(), self.name.location_offset())
    }
}

impl<'a> GetName for StructTypes<'a> {
    fn name(&self) -> String {
        (*self.name.fragment()).to_string()
    }
}

/// `Type` element of AST.
/// Basic entity that represents types. Basic type entity is:
/// - Primitive types
/// - Struct types
/// - Arrays
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(
    feature = "codec",
    derive(Serialize, Deserialize),
    serde(tag = "type", content = "content")
)]
pub enum Type<'a> {
    Primitive(PrimitiveTypes),
    #[cfg_attr(feature = "codec", serde(borrow))]
    Struct(StructTypes<'a>),
    Array(Box<Self>, u32),
}

impl<'a> GetName for Type<'a> {
    fn name(&self) -> String {
        match self {
            Self::Primitive(primitive) => primitive.name(),
            Self::Struct(struct_type) => (*struct_type.name.fragment()).to_string(),
            Self::Array(array_type, size) => {
                format!("[{:?};{:?}]", array_type.name(), size)
            }
        }
    }
}

/// `ConstantValue` constant value element of AST.
/// Used for `ConstantExpression`. Constant value basic entities:
/// - `constant` it can contain other constant
/// - `value` - primitive value (like numbers etc.)
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(
    feature = "codec",
    derive(Serialize, Deserialize),
    serde(tag = "type", content = "content")
)]
pub enum ConstantValue<'a> {
    #[cfg_attr(feature = "codec", serde(borrow))]
    Constant(ConstantName<'a>),
    Value(PrimitiveValue),
}

/// `ConstantExpression` constant expression element of AST.
/// Used to declare constants.
/// The constant expression value based on other constant or primitive values.
/// Constant Expression can contain optional expression operation with other
/// constant expression. So it can be represented as Constant expression
/// tree as operations with other constant expressions.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "codec", derive(Serialize, Deserialize))]
pub struct ConstantExpression<'a> {
    /// Constant value - can be other constant 0r primitive value
    #[cfg_attr(feature = "codec", serde(borrow))]
    pub value: ConstantValue<'a>,
    /// Constant expression optional expression operation with other constant expression declarations.
    pub operation: Option<(ExpressionOperations, Box<ConstantExpression<'a>>)>,
}

/// `Constant` constant declaration element of AST.
/// Basic constant entity contains:
/// - constant name
/// - constant type
/// - constant value - based on constant expression
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "codec", derive(Serialize, Deserialize))]
pub struct Constant<'a> {
    /// Constant name
    #[cfg_attr(feature = "codec", serde(borrow))]
    pub name: ConstantName<'a>,
    /// Constant type
    pub constant_type: Type<'a>,
    /// Constant value based on constant expression
    pub constant_value: ConstantExpression<'a>,
}

impl GetLocation for Constant<'_> {
    fn location(&self) -> CodeLocation {
        self.name.location()
    }
}

impl GetName for Constant<'_> {
    fn name(&self) -> String {
        (*self.name.0.fragment()).to_string()
    }
}

/// `FunctionParameter` function parameter element of AST.
/// Used for `FunctionStatement` declaration.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "codec", derive(Serialize, Deserialize))]
pub struct FunctionParameter<'a> {
    /// Function parameter name
    #[cfg_attr(feature = "codec", serde(borrow))]
    pub name: ParameterName<'a>,
    /// Function parameter type
    pub parameter_type: Type<'a>,
}

/// `FunctionStatement` it's one of the most basic element of AST.
/// Basic entity of program logic. It contains function declaration and
/// function body.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "codec", derive(Serialize, Deserialize))]
pub struct FunctionStatement<'a, E: ExtendedExpression> {
    /// Function name
    #[cfg_attr(feature = "codec", serde(borrow))]
    pub name: FunctionName<'a>,
    /// Function parameters
    pub parameters: Vec<FunctionParameter<'a>>,
    /// Function result type
    pub result_type: Type<'a>,
    /// Function body
    pub body: Vec<BodyStatement<'a, E>>,
}

impl<E: ExtendedExpression> GetLocation for FunctionStatement<'_, E> {
    fn location(&self) -> CodeLocation {
        self.name.location()
    }
}

impl<E: ExtendedExpression> GetName for FunctionStatement<'_, E> {
    fn name(&self) -> String {
        (*self.name.0.fragment()).to_string()
    }
}

/// `PrimitiveValue` represents primitive value element of AST.
/// Values based on primitive types.
/// Used for `ConstantValue` and `ExpressionValue`.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(
    feature = "codec",
    derive(Serialize, Deserialize),
    serde(tag = "type", content = "content")
)]
pub enum PrimitiveValue {
    U8(u8),
    U16(u16),
    U32(u32),
    U64(u64),
    I8(i8),
    I16(i16),
    I32(i32),
    I64(i64),
    F32(f32),
    F64(f64),
    Bool(bool),
    String(String),
    Char(char),
    Ptr,
    None,
}

impl PrimitiveValue {
    #[must_use]
    pub const fn get_type(&self) -> Type<'_> {
        match self {
            Self::U8(_) => Type::Primitive(PrimitiveTypes::U8),
            Self::U16(_) => Type::Primitive(PrimitiveTypes::U16),
            Self::U32(_) => Type::Primitive(PrimitiveTypes::U32),
            Self::U64(_) => Type::Primitive(PrimitiveTypes::U64),
            Self::I8(_) => Type::Primitive(PrimitiveTypes::I8),
            Self::I16(_) => Type::Primitive(PrimitiveTypes::I16),
            Self::I32(_) => Type::Primitive(PrimitiveTypes::I32),
            Self::I64(_) => Type::Primitive(PrimitiveTypes::I64),
            Self::F32(_) => Type::Primitive(PrimitiveTypes::F32),
            Self::F64(_) => Type::Primitive(PrimitiveTypes::F64),
            Self::Char(_) => Type::Primitive(PrimitiveTypes::Char),
            Self::Bool(_) => Type::Primitive(PrimitiveTypes::Bool),
            Self::String(_) => Type::Primitive(PrimitiveTypes::String),
            Self::Ptr => Type::Primitive(PrimitiveTypes::Ptr),
            Self::None => Type::Primitive(PrimitiveTypes::None),
        }
    }
}

/// `ExpressionValue` expression value element of AST.
/// Basic entity for `Expression` elements of AST.
/// Expression value contains entities:
/// - `ValueName` - value name of expression
/// - `PrimitiveValue` - primitive value name of expression (for
///   example, it's numbers: 10, 3.2 and other primitive values)
/// - `FunctionCall` - function call (with parameters) of expression
/// - `StructValue` - value of expression based on `Struct` types.
/// - `Expression` - expression representation (sub branch)
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(
    feature = "codec",
    derive(Serialize, Deserialize),
    serde(tag = "type", content = "content")
)]
pub enum ExpressionValue<'a, E: ExtendedExpression> {
    /// Value name of expression
    #[cfg_attr(feature = "codec", serde(borrow))]
    ValueName(ValueName<'a>),
    /// Primitive value of expression (like numbers etc.)
    PrimitiveValue(PrimitiveValue),
    /// Function call (with parameters) of expression
    FunctionCall(FunctionCall<'a, E>),
    /// Value of expression based on `Struct` types.
    StructValue(ExpressionStructValue<'a>),
    /// Expression representation (sub branch)
    Expression(Box<Expression<'a, E>>),
    /// Extended expression
    ExtendedExpression(Box<E>),
}

/// `ExpressionOperations` expression operation element of AST.
/// Used for expression operations:
/// - `ConstantExpression` - expression of constant declaration
/// - `Expression` - part of operations for expressions
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(
    feature = "codec",
    derive(Serialize, Deserialize),
    serde(tag = "type", content = "content")
)]
pub enum ExpressionOperations {
    Plus,
    Minus,
    Multiply,
    Divide,
    ShiftLeft,
    ShiftRight,
    And,
    Or,
    Xor,
    Eq,
    NotEq,
    Great,
    Less,
    GreatEq,
    LessEq,
}

impl ExpressionOperations {
    /// Get expression operation priority level
    #[must_use]
    pub const fn priority(&self) -> u8 {
        match self {
            Self::Plus => 5,
            Self::Minus => 4,
            Self::Divide => 8,
            Self::Multiply | Self::ShiftLeft | Self::ShiftRight => {
                MAX_PRIORITY_LEVEL_FOR_EXPRESSIONS
            }
            Self::Or | Self::Xor => 6,
            Self::And
            | Self::Eq
            | Self::NotEq
            | Self::Great
            | Self::Less
            | Self::GreatEq
            | Self::LessEq => 7,
        }
    }
}

/// `Expression` element of AST is basic entity that
/// represent expression, and optionally expression with optional
/// operations with other expression. So it can be expression tree
/// with expression operations.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "codec", derive(Serialize, Deserialize))]
pub struct Expression<'a, E: ExtendedExpression> {
    /// Expression value itself
    #[cfg_attr(feature = "codec", serde(borrow))]
    pub expression_value: ExpressionValue<'a, E>,
    /// Optional expression operation with other expression value
    pub operation: Option<(ExpressionOperations, Box<Expression<'a, E>>)>,
}

impl<E: ExtendedExpression> GetLocation for Expression<'_, E> {
    fn location(&self) -> CodeLocation {
        // TODO: extend it
        CodeLocation::new(1, 0)
    }
}

/// `LetBinding` let binding element of AST. Basic entity
/// for `values` declarations.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "codec", derive(Serialize, Deserialize), serde(tag = "type"))]
pub struct LetBinding<'a, E: ExtendedExpression> {
    /// Value name of let binding
    #[cfg_attr(feature = "codec", serde(borrow))]
    pub name: ValueName<'a>,
    /// Mutability flag of binding
    pub mutable: bool,
    /// Optional type of value
    pub value_type: Option<Type<'a>>,
    /// Value expression to bind as result of let bending
    pub value: Box<Expression<'a, E>>,
}

impl<E: ExtendedExpression> GetLocation for LetBinding<'_, E> {
    fn location(&self) -> CodeLocation {
        self.name.location()
    }
}

impl<E: ExtendedExpression> GetName for LetBinding<'_, E> {
    fn name(&self) -> String {
        self.name.0.to_string()
    }
}

/// `Binding` binding element of AST. Basic entity
/// for `values` re-declaration, to bind new values for already
/// declared values.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "codec", derive(Serialize, Deserialize))]
pub struct Binding<'a, E: ExtendedExpression> {
    /// Binding value name
    #[cfg_attr(feature = "codec", serde(borrow))]
    pub name: ValueName<'a>,
    /// Value expression as result of binding
    pub value: Box<Expression<'a, E>>,
}

impl<E: ExtendedExpression> GetLocation for Binding<'_, E> {
    fn location(&self) -> CodeLocation {
        self.name.location()
    }
}

impl<E: ExtendedExpression> GetName for Binding<'_, E> {
    fn name(&self) -> String {
        self.name.0.to_string()
    }
}

/// `FunctionCall` function call element of AST.
/// Basic entity for function call representation.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "codec", derive(Serialize, Deserialize))]
pub struct FunctionCall<'a, E: ExtendedExpression> {
    /// Function name of called function
    #[cfg_attr(feature = "codec", serde(borrow))]
    pub name: FunctionName<'a>,
    /// Function parameters, represented through expression
    pub parameters: Vec<Expression<'a, E>>,
}

impl<E: ExtendedExpression> GetLocation for FunctionCall<'_, E> {
    fn location(&self) -> CodeLocation {
        self.name.location()
    }
}

impl<E: ExtendedExpression> GetName for FunctionCall<'_, E> {
    fn name(&self) -> String {
        (*self.name.0.fragment()).to_string()
    }
}

/// `Condition` condition declarations.
/// Used for `ExpressionCondition`. Contains basic condition
/// entities: `<. >, ==, <=, >=, !=`
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(
    feature = "codec",
    derive(Serialize, Deserialize),
    serde(tag = "type", content = "content")
)]
pub enum Condition {
    Great,
    Less,
    Eq,
    GreatEq,
    LessEq,
    NotEq,
}

/// `LogicCondition` declaration of logical condition operation.
/// It can contains only: `and`, `or`. Used for `IfCondition` element of AST.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(
    feature = "codec",
    derive(Serialize, Deserialize),
    serde(tag = "type", content = "content")
)]
pub enum LogicCondition {
    And,
    Or,
}

/// `ExpressionCondition` expression condition element of AST.
/// Used in `ExpressionLogicCondition` for `IfCondition` declaration.
/// It contains condition between twe expressions.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "codec", derive(Serialize, Deserialize))]
pub struct ExpressionCondition<'a, E: ExtendedExpression> {
    /// Left expression
    #[cfg_attr(feature = "codec", serde(borrow))]
    pub left: Expression<'a, E>,
    /// Condition between left and right expressions
    pub condition: Condition,
    /// Right expression
    pub right: Expression<'a, E>,
}

/// # Logic expression condition
/// `ExpressionLogicCondition` expression logic condition used for
/// `IfCondition` declaration.
/// Expression logic condition can contains left and optional right
/// parts. Right part represent logic condition (like `or`, `and`) to
/// other `ExpressionLogicCondition`. So finally ir can represent tree
/// expressions logic conditions.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "codec", derive(Serialize, Deserialize))]
pub struct ExpressionLogicCondition<'a, E: ExtendedExpression> {
    /// Left expression condition
    #[cfg_attr(feature = "codec", serde(borrow))]
    pub left: ExpressionCondition<'a, E>,
    /// Optional right side contain logic operation to other `ExpressionLogicCondition`
    pub right: Option<(LogicCondition, Box<ExpressionLogicCondition<'a, E>>)>,
}

/// `IfCondition` if-condition control flow element of AST.
/// One of the basic control flow. Basic entities:
/// - single expression condition
/// - logic expression condition tree
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(
    feature = "codec",
    derive(Serialize, Deserialize),
    serde(tag = "type", content = "content")
)]
pub enum IfCondition<'a, E: ExtendedExpression> {
    /// Single if condition based on expression
    #[cfg_attr(feature = "codec", serde(borrow))]
    Single(Expression<'a, E>),
    /// Logic expression condition tree
    Logic(ExpressionLogicCondition<'a, E>),
}

/// `IfStatement` if statement AST element.
/// Contains full representation of if statement with entities:
/// - if-condition
/// - If-body statement - body of if-condition success
/// - Ff-else-body statement - body of else-condition success
/// - Else-if-body statement - body of else-if-condition success
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "codec", derive(Serialize, Deserialize))]
pub struct IfStatement<'a, E: ExtendedExpression> {
    /// If-condition
    #[cfg_attr(feature = "codec", serde(borrow))]
    pub condition: IfCondition<'a, E>,
    /// If-body statement - body of if-condition success
    pub body: IfBodyStatements<'a, E>,
    /// If-else-body statement - body of else-condition success
    pub else_statement: Option<IfBodyStatements<'a, E>>,
    /// Else-if-body statement - body of else-if-condition success
    pub else_if_statement: Option<Box<IfStatement<'a, E>>>,
}

impl<E: ExtendedExpression> GetLocation for IfStatement<'_, E> {
    fn location(&self) -> CodeLocation {
        // TODO
        CodeLocation::new(1, 0)
    }
}

/// `BodyStatement` one of the basic AST elements.
/// It's part of Function body.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(
    feature = "codec",
    derive(Serialize, Deserialize),
    serde(tag = "type", content = "content")
)]
pub enum BodyStatement<'a, E: ExtendedExpression> {
    /// Let-binding function declaration
    #[cfg_attr(feature = "codec", serde(borrow))]
    LetBinding(LetBinding<'a, E>),
    /// Binding function declaration
    Binding(Binding<'a, E>),
    /// Function call
    FunctionCall(FunctionCall<'a, E>),
    /// If-condition control flow statement
    If(IfStatement<'a, E>),
    /// Loop control flow statement
    Loop(Vec<LoopBodyStatement<'a, E>>),
    /// Expression statement
    Expression(Expression<'a, E>),
    /// Return statement
    Return(Expression<'a, E>),
}

/// `IfBodyStatement` statement of if-body elements tree of AST.
/// Used as body statement of If-control flow.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(
    feature = "codec",
    derive(Serialize, Deserialize),
    serde(tag = "type", content = "content")
)]
pub enum IfBodyStatement<'a, E: ExtendedExpression> {
    #[cfg_attr(feature = "codec", serde(borrow))]
    LetBinding(LetBinding<'a, E>),
    Binding(Binding<'a, E>),
    FunctionCall(FunctionCall<'a, E>),
    If(IfStatement<'a, E>),
    Loop(Vec<LoopBodyStatement<'a, E>>),
    Return(Expression<'a, E>),
}

/// `IfLoopBodyStatement` statement of loop-if-body elements tree of AST.
/// Used as body statement of If-control flow in the `Loop` AST element.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "codec", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "codec", serde(tag = "type", content = "content"))]
pub enum IfLoopBodyStatement<'a, E: ExtendedExpression> {
    #[cfg_attr(feature = "codec", serde(borrow))]
    LetBinding(LetBinding<'a, E>),
    Binding(Binding<'a, E>),
    FunctionCall(FunctionCall<'a, E>),
    If(IfStatement<'a, E>),
    Loop(Vec<LoopBodyStatement<'a, E>>),
    Return(Expression<'a, E>),
    Break,
    Continue,
}

/// `IfBodyStatements` set of elements in the AST, that represents
/// control flow: `if`, `loop`
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(
    feature = "codec",
    derive(Serialize, Deserialize),
    serde(tag = "type", content = "content")
)]
pub enum IfBodyStatements<'a, E: ExtendedExpression> {
    #[cfg_attr(feature = "codec", serde(borrow))]
    If(Vec<IfBodyStatement<'a, E>>),
    Loop(Vec<IfLoopBodyStatement<'a, E>>),
}

/// `LoopBodyStatement` statement of loop-body elements tree of AST.
/// Used as body statement of loop-control flow.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(
    feature = "codec",
    derive(Serialize, Deserialize),
    serde(tag = "type", content = "content")
)]
pub enum LoopBodyStatement<'a, E: ExtendedExpression> {
    #[cfg_attr(feature = "codec", serde(borrow))]
    LetBinding(LetBinding<'a, E>),
    Binding(Binding<'a, E>),
    FunctionCall(FunctionCall<'a, E>),
    If(IfStatement<'a, E>),
    Loop(Vec<LoopBodyStatement<'a, E>>),
    Return(Expression<'a, E>),
    Break,
    Continue,
}

/// `MainStatement` main AST statement for all elements.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(
    feature = "codec",
    derive(Serialize, Deserialize),
    serde(tag = "type", content = "content")
)]
pub enum MainStatement<'a, E: ExtendedExpression> {
    /// Import declarations
    #[cfg_attr(feature = "codec", serde(borrow))]
    Import(ImportPath<'a>),
    /// Constant declarations
    Constant(Constant<'a>),
    /// Type declaration
    Types(StructTypes<'a>),
    /// Function declaration and function body-statement
    Function(FunctionStatement<'a, E>),
}

/// # Main
/// Stack of `MainStatement` main AST elements. That gather
/// tries of AST, to represent full sort of source code.
pub type Main<'a, E> = Vec<MainStatement<'a, E>>;