boreal 1.1.0

A library to evaluate YARA rules, used to scan bytes for textual and binary pattern
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
use std::{collections::HashMap, ops::Range};

use boreal_parser::expression::{Identifier, IdentifierOperation, IdentifierOperationType};

use super::expression::{compile_expression, Expr, Expression, Type};
use super::rule::RuleCompiler;
use super::{CompilationError, ImportedModule};
use crate::module::{Module as ModuleTrait, StaticFunction, StaticValue, Type as ValueType};

/// Module used during compilation
#[derive(Debug)]
pub struct Module {
    /// Name of the module
    pub name: &'static str,
    /// Static values of the module, usable directly during compilation
    static_values: HashMap<&'static str, StaticValue>,
    /// Dynamic types for values computed during scanning.
    dynamic_types: ValueType,
}

/// Index on a bounded value
#[derive(Debug, PartialEq)]
pub enum BoundedValueIndex {
    /// Index on the list of module values.
    ///
    /// This means using the dynamic value produced by the module.
    Module(usize),

    /// Index on the bounded stack.
    BoundedStack(usize),
}

/// Different type of expressions related to the use of a module.
#[derive(Debug)]
#[cfg_attr(all(test, feature = "serialize"), derive(PartialEq))]
pub struct ModuleExpression {
    /// Kind of the expression.
    pub kind: ModuleExpressionKind,

    /// List of operations to apply to the value to get the final value.
    pub operations: ModuleOperations,
}

impl ModuleExpression {
    #[cfg(feature = "serialize")]
    pub(super) fn deserialize<R: std::io::Read>(
        ctx: &crate::wire::DeserializeContext,
        reader: &mut R,
    ) -> std::io::Result<Self> {
        wire::deserialize_module_expression(ctx, reader)
    }
}

// Allowed because only used in tests
#[allow(unpredictable_function_pointer_comparisons)]
#[cfg_attr(all(test, feature = "serialize"), derive(PartialEq))]
pub enum ModuleExpressionKind {
    /// Operations on a bounded module value.
    BoundedModuleValueUse {
        /// Index of the bounded value.
        index: BoundedValueIndex,
    },

    /// A value coming from a function exposed by a module.
    StaticFunction {
        /// The function to call.
        fun: StaticFunction,

        /// Index of the module.
        #[cfg(feature = "serialize")]
        module_index: usize,

        /// List of subfields to apply to access the function.
        #[cfg(feature = "serialize")]
        subfields: Vec<String>,
    },
}

/// Operations to apply to a module value.
#[derive(Debug)]
#[cfg_attr(all(test, feature = "serialize"), derive(PartialEq))]
pub struct ModuleOperations {
    /// List of expressions that needs to be evaluated to compute all of the operations.
    ///
    /// This list is in its own Vec instead of inlined in each operation so that they
    /// can be evaluated separately, which makes the evaluation of operations simpler
    /// as it can be done immutably.
    ///
    /// The expressions are stored in the same order the operations will be evaluated.
    pub expressions: Vec<Expression>,

    /// List of operations to apply to the module value.
    pub operations: Vec<ValueOperation>,
}

/// Operations on identifiers.
#[derive(Debug, PartialEq)]
pub enum ValueOperation {
    /// Object subfield, i.e. `value.subfield`.
    Subfield(String),
    /// Array/dict subscript, i.e. `value[subscript]`.
    ///
    /// The value used as the subscript index is stored in [`ModuleOperations::expressions`].
    Subscript,
    /// Function call, i.e. `value(arguments)`.
    ///
    /// The value is the number of expressions to pick from [`ModuleOperations::expressions`]
    /// to form the arguments of the function call.
    FunctionCall(usize),
}

// XXX: custom Debug impl needed because derive does not work with the fn fields.
impl std::fmt::Debug for ModuleExpressionKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::BoundedModuleValueUse { index } => f
                .debug_struct("BoundedModuleValueUse")
                .field("index", index)
                .finish(),
            Self::StaticFunction {
                fun,
                #[cfg(feature = "serialize")]
                module_index,
                #[cfg(feature = "serialize")]
                subfields,
            } => {
                let mut d = f.debug_struct("Function");

                let _r = d.field("fun", &(*fun as usize));
                #[cfg(feature = "serialize")]
                {
                    let _r = d.field("module_index", module_index);
                    let _r = d.field("subfields", subfields);
                }

                d.finish()
            }
        }
    }
}

/// Type describing an iterator generated by a module
#[derive(Debug)]
pub enum IteratorType {
    /// An array. This yields elements of the inner type
    Array(ValueType),
    /// A dictionary. This yields two elements: the key (a string), and the value, of the inner
    /// type.
    Dictionary(ValueType),
}

pub(crate) fn compile_module(module: &dyn ModuleTrait) -> Module {
    Module {
        name: module.get_name(),
        static_values: module.get_static_values(),
        dynamic_types: ValueType::Object(module.get_dynamic_types()),
    }
}

/// Compile the use of an bounded identifier.
///
/// A for expression can generate an identifier that is referring to a partially resolved module
/// value. This identifier can then be used to compute the value in full, which this function is
/// for.
///
/// For example:
///
/// ```no_rust
/// for any section in pe.sections: (section.virtual_size == 0x00000224)
/// ```
///
/// `pe.sections` will be compiled by [`compile_identifier`], and
/// `section.virtual_size` will be compiled by this function.
pub(super) fn compile_bounded_identifier_use<'a, 'b>(
    compiler: &'b mut RuleCompiler<'a>,
    starting_type: &'b ValueType,
    identifier: Identifier,
    identifier_stack_index: usize,
) -> Result<ModuleUse<'a, 'b>, CompilationError> {
    let mut module_use = ModuleUse {
        compiler,
        operations_expressions: Vec::new(),
        operations: Vec::with_capacity(identifier.operations.len()),
        current_span: identifier.name_span,
        kind: ModuleUseKind::Dynamic {
            current_type: starting_type,
            bounded_value_index: BoundedValueIndex::BoundedStack(identifier_stack_index),
        },
    };

    for op in identifier.operations {
        module_use.add_operation(op)?;
    }

    Ok(module_use)
}

/// Compile the use of an identifier referring to a module.
///
/// This returns an object that can generate either:
/// - an expression and a type, if the use is to be transformed into an expression
/// - a bounded value and an iterator type, if the use is for an iterable.
pub(super) fn compile_identifier<'a, 'b>(
    compiler: &'b mut RuleCompiler<'a>,
    module: &'b ImportedModule,
    identifier: Identifier,
    identifier_span: &Range<usize>,
) -> Result<ModuleUse<'a, 'b>, CompilationError> {
    let nb_ops = identifier.operations.len();

    // Extract first operation, it must be a subfielding.
    let mut ops = identifier.operations.into_iter();
    let Some(IdentifierOperation {
        op: first_op,
        span: first_op_span,
    }) = ops.next()
    else {
        return Err(CompilationError::InvalidIdentifierUse {
            span: identifier_span.clone(),
        });
    };
    let subfield = match first_op {
        IdentifierOperationType::Subfield(subfield) => subfield,
        IdentifierOperationType::Subscript(_) => {
            return Err(CompilationError::InvalidIdentifierType {
                actual_type: "object".to_string(),
                expected_type: "array or dictionary".to_string(),
                span: identifier.name_span,
            });
        }
        IdentifierOperationType::FunctionCall(_) => {
            return Err(CompilationError::InvalidIdentifierType {
                actual_type: "object".to_string(),
                expected_type: "function".to_string(),
                span: identifier.name_span,
            });
        }
    };

    // First try to get from the static values
    let mut module_use = match module.module.static_values.get(&*subfield) {
        Some(value) => ModuleUse {
            compiler,
            operations_expressions: Vec::new(),
            operations: Vec::with_capacity(nb_ops),
            current_span: identifier.name_span,
            kind: ModuleUseKind::Static {
                current_value: value,
                module_index: module.module_index,
                applied_subfields: vec![subfield],
            },
        },
        None => {
            // otherwise, use dynamic types, and apply the first operation (so that it will be
            // applied on scan).
            let mut module_use = ModuleUse {
                compiler,
                operations_expressions: Vec::new(),
                operations: Vec::with_capacity(nb_ops),
                current_span: identifier.name_span,
                kind: ModuleUseKind::Dynamic {
                    current_type: &module.module.dynamic_types,
                    bounded_value_index: BoundedValueIndex::Module(module.module_index),
                },
            };
            module_use.add_operation(IdentifierOperation {
                op: IdentifierOperationType::Subfield(subfield),
                span: first_op_span,
            })?;
            module_use
        }
    };

    for op in ops {
        module_use.add_operation(op)?;
    }
    Ok(module_use)
}

pub(super) struct ModuleUse<'a, 'b> {
    compiler: &'b mut RuleCompiler<'a>,

    // Expressions that needs to be evaluated to be able to evaluate the operations.
    operations_expressions: Vec<Expression>,

    // Operations that will need to be evaluated at scanning time.
    operations: Vec<ValueOperation>,

    // Current span of the module + added operations.
    current_span: Range<usize>,

    kind: ModuleUseKind<'b>,
}

enum ModuleUseKind<'a> {
    /// A static value, coming from the `get_static_values` methods.
    ///
    /// This kind is kept for as long as possible, so that the compiled expression
    /// can be optimized if possible.
    Static {
        current_value: &'a StaticValue,
        module_index: usize,
        applied_subfields: Vec<String>,
    },
    /// A static function.
    ///
    /// Once we reach the function, we cannot keep the next values as static values,
    /// so we store the function pointer in the expression and keep the following operations
    /// to be evaluated.
    StaticFunction {
        fun: StaticFunction,
        current_type: &'a ValueType,
        module_index: usize,
        applied_subfields: Vec<String>,
    },
    /// A dynamic value, coming from the `get_dynamic_values` methods.
    ///
    /// Since the value is dynamic, we can only type check it here, and keep the
    /// operations to evaluate.
    Dynamic {
        current_type: &'a ValueType,
        bounded_value_index: BoundedValueIndex,
    },
}

impl ModuleUse<'_, '_> {
    fn add_operation(&mut self, op: IdentifierOperation) -> Result<(), CompilationError> {
        let res = match op.op {
            IdentifierOperationType::Subfield(subfield) => {
                let res = self.kind.subfield(&subfield);
                match &mut self.kind {
                    ModuleUseKind::Static {
                        applied_subfields, ..
                    } => applied_subfields.push(subfield),
                    ModuleUseKind::StaticFunction { .. } | ModuleUseKind::Dynamic { .. } => {
                        self.operations.push(ValueOperation::Subfield(subfield));
                    }
                }
                res
            }
            IdentifierOperationType::Subscript(subscript) => {
                let Expr { expr, ty, span } = compile_expression(self.compiler, *subscript)?;

                self.operations_expressions.push(expr);
                self.operations.push(ValueOperation::Subscript);
                self.kind.subscript(ty, span)
            }
            IdentifierOperationType::FunctionCall(arguments) => {
                self.operations
                    .push(ValueOperation::FunctionCall(arguments.len()));

                let mut arguments_types = Vec::with_capacity(arguments.len());
                for arg in arguments {
                    let res = compile_expression(self.compiler, arg)?;
                    self.operations_expressions.push(res.expr);
                    arguments_types.push(res.ty);
                }

                self.kind.function_call(&arguments_types)
            }
        };

        match res {
            Err(TypeError::UnknownSubfield(subfield)) => {
                Err(CompilationError::UnknownIdentifierField {
                    field_name: subfield,
                    span: op.span,
                })
            }
            Err(TypeError::WrongType {
                actual_type,
                expected_type,
            }) => Err(CompilationError::InvalidIdentifierType {
                actual_type,
                expected_type,
                span: self.current_span.clone(),
            }),
            Err(TypeError::WrongIndexType {
                actual_type,
                expected_type,
                span,
            }) => Err(CompilationError::InvalidIdentifierIndexType {
                ty: actual_type.to_string(),
                span,
                expected_type: expected_type.to_string(),
            }),
            Err(TypeError::WrongFunctionArguments { arguments_types }) => {
                Err(CompilationError::InvalidIdentifierCall {
                    arguments_types,
                    span: op.span,
                })
            }
            Ok(()) => {
                self.current_span.end = op.span.end;
                Ok(())
            }
        }
    }

    pub(super) fn into_expression(self) -> Option<(Expression, Type)> {
        let (expr, ty) = match self.kind {
            ModuleUseKind::Static { current_value, .. } => {
                match current_value {
                    // Those are all primitive values. This means there are no operations applied, and
                    // we can directly generate a primitive expression.
                    StaticValue::Integer(v) => (Expression::Integer(*v), ValueType::Integer),
                    StaticValue::Float(v) => (Expression::Double(*v), ValueType::Float),
                    StaticValue::Bytes(v) => (
                        Expression::Bytes(self.compiler.bytes_pool.insert(v)),
                        ValueType::Bytes,
                    ),
                    StaticValue::Boolean(v) => (Expression::Boolean(*v), ValueType::Boolean),

                    _ => return None,
                }
            }
            ModuleUseKind::StaticFunction {
                fun,
                current_type,
                module_index,
                applied_subfields,
            } => {
                #[cfg(not(feature = "serialize"))]
                {
                    let _ = module_index;
                    drop(applied_subfields);
                }
                let expr = Expression::Module(ModuleExpression {
                    kind: ModuleExpressionKind::StaticFunction {
                        fun,
                        #[cfg(feature = "serialize")]
                        module_index,
                        #[cfg(feature = "serialize")]
                        subfields: applied_subfields,
                    },
                    operations: ModuleOperations {
                        expressions: self.operations_expressions,
                        operations: self.operations,
                    },
                });

                (expr, current_type.clone())
            }
            ModuleUseKind::Dynamic {
                current_type,
                bounded_value_index,
            } => {
                let expr = Expression::Module(ModuleExpression {
                    kind: ModuleExpressionKind::BoundedModuleValueUse {
                        index: bounded_value_index,
                    },
                    operations: ModuleOperations {
                        expressions: self.operations_expressions,
                        operations: self.operations,
                    },
                });
                (expr, current_type.clone())
            }
        };

        let ty = match ty {
            ValueType::Integer => Type::Integer,
            ValueType::Float => Type::Float,
            ValueType::Bytes => Type::Bytes,
            ValueType::Boolean => Type::Boolean,
            _ => return None,
        };
        Some((expr, ty))
    }

    pub(super) fn into_iterator_expression(self) -> Option<(ModuleExpression, IteratorType)> {
        match self.kind {
            ModuleUseKind::Static { .. } | ModuleUseKind::StaticFunction { .. } => None,
            ModuleUseKind::Dynamic {
                current_type,
                bounded_value_index,
            } => {
                let expr = ModuleExpression {
                    kind: ModuleExpressionKind::BoundedModuleValueUse {
                        index: bounded_value_index,
                    },
                    operations: ModuleOperations {
                        expressions: self.operations_expressions,
                        operations: self.operations,
                    },
                };
                let ty = match current_type {
                    ValueType::Array { value_type, .. } => {
                        IteratorType::Array((**value_type).clone())
                    }
                    ValueType::Dictionary { value_type, .. } => {
                        IteratorType::Dictionary((**value_type).clone())
                    }
                    _ => return None,
                };

                Some((expr, ty))
            }
        }
    }
}

#[derive(Debug)]
enum TypeError {
    UnknownSubfield(String),
    WrongType {
        actual_type: String,
        expected_type: String,
    },
    WrongIndexType {
        actual_type: Type,
        expected_type: Type,
        span: Range<usize>,
    },
    WrongFunctionArguments {
        arguments_types: Vec<String>,
    },
}

impl ModuleUseKind<'_> {
    fn subfield(&mut self, subfield: &str) -> Result<(), TypeError> {
        match self {
            Self::Static { current_value, .. } => {
                if let StaticValue::Object(map) = *current_value {
                    match map.get(subfield) {
                        Some(v) => {
                            *current_value = v;
                            return Ok(());
                        }
                        None => return Err(TypeError::UnknownSubfield(subfield.to_string())),
                    }
                }
            }
            Self::StaticFunction { current_type, .. } | Self::Dynamic { current_type, .. } => {
                if let ValueType::Object(map) = current_type {
                    match map.get(subfield) {
                        Some(v) => {
                            *current_type = v;
                            return Ok(());
                        }
                        None => return Err(TypeError::UnknownSubfield(subfield.to_string())),
                    }
                }
            }
        }

        Err(TypeError::WrongType {
            actual_type: self.type_to_string(),
            expected_type: "object".to_owned(),
        })
    }

    fn subscript(
        &mut self,
        subscript_type: Type,
        subscript_span: Range<usize>,
    ) -> Result<(), TypeError> {
        let check_subscript_type = |expected_type: Type| {
            if subscript_type == expected_type {
                Ok(())
            } else {
                Err(TypeError::WrongIndexType {
                    actual_type: subscript_type,
                    expected_type,
                    span: subscript_span,
                })
            }
        };

        match self {
            Self::Static { .. } => (),
            Self::StaticFunction { current_type, .. } | Self::Dynamic { current_type, .. } => {
                match current_type {
                    ValueType::Array { value_type, .. } => {
                        check_subscript_type(Type::Integer)?;
                        *current_type = value_type;
                        return Ok(());
                    }
                    ValueType::Dictionary { value_type, .. } => {
                        check_subscript_type(Type::Bytes)?;
                        *current_type = value_type;
                        return Ok(());
                    }
                    _ => (),
                }
            }
        }

        Err(TypeError::WrongType {
            actual_type: self.type_to_string(),
            expected_type: "array or dictionary".to_string(),
        })
    }

    fn function_call(&mut self, actual_args_types: &[Type]) -> Result<(), TypeError> {
        match self {
            Self::Static {
                current_value,
                module_index,
                applied_subfields,
            } => {
                if let StaticValue::Function {
                    arguments_types,
                    return_type,
                    fun,
                } = current_value
                {
                    check_all_arguments_types(arguments_types, actual_args_types)?;
                    *self = Self::StaticFunction {
                        fun: *fun,
                        current_type: return_type,
                        module_index: *module_index,
                        applied_subfields: std::mem::take(applied_subfields),
                    };
                    return Ok(());
                }
            }
            Self::StaticFunction { current_type, .. } | Self::Dynamic { current_type, .. } => {
                if let ValueType::Function {
                    arguments_types,
                    return_type,
                } = current_type
                {
                    check_all_arguments_types(arguments_types, actual_args_types)?;
                    *current_type = return_type;
                    return Ok(());
                }
            }
        }

        Err(TypeError::WrongType {
            actual_type: self.type_to_string(),
            expected_type: "function".to_owned(),
        })
    }

    fn type_to_string(&self) -> String {
        match self {
            Self::Static { current_value, .. } => match current_value {
                StaticValue::Integer(_) => "integer",
                StaticValue::Float(_) => "float",
                StaticValue::Bytes(_) => "bytes",
                StaticValue::Boolean(_) => "boolean",
                StaticValue::Object(_) => "object",
                StaticValue::Function { .. } => "function",
            },
            Self::StaticFunction { current_type, .. } | Self::Dynamic { current_type, .. } => {
                match current_type {
                    ValueType::Integer => "integer",
                    ValueType::Float => "float",
                    ValueType::Bytes => "bytes",
                    ValueType::Regex => "regex",
                    ValueType::Boolean => "boolean",
                    ValueType::Array { .. } => "array",
                    ValueType::Dictionary { .. } => "dict",
                    ValueType::Object(_) => "object",
                    ValueType::Function { .. } => "function",
                }
            }
        }
        .to_owned()
    }
}

fn check_all_arguments_types(
    valid_types_vec: &[Vec<ValueType>],
    actual_types: &[Type],
) -> Result<(), TypeError> {
    if valid_types_vec.is_empty() && actual_types.is_empty() {
        return Ok(());
    }

    for valid_types in valid_types_vec {
        if arguments_types_are_equal(valid_types, actual_types) {
            return Ok(());
        }
    }

    Err(TypeError::WrongFunctionArguments {
        arguments_types: actual_types.iter().map(ToString::to_string).collect(),
    })
}

fn arguments_types_are_equal(valid_types: &[ValueType], actual_types: &[Type]) -> bool {
    if valid_types.len() != actual_types.len() {
        return false;
    }
    for (expected, actual) in valid_types.iter().zip(actual_types.iter()) {
        let expected = module_type_to_expr_type(expected);
        match expected {
            Some(expected) => {
                if expected != *actual {
                    return false;
                }
            }
            None => return false,
        }
    }

    true
}

fn module_type_to_expr_type(v: &ValueType) -> Option<Type> {
    match v {
        ValueType::Integer => Some(Type::Integer),
        ValueType::Float => Some(Type::Float),
        ValueType::Bytes => Some(Type::Bytes),
        ValueType::Regex => Some(Type::Regex),
        ValueType::Boolean => Some(Type::Boolean),
        _ => None,
    }
}

#[cfg(feature = "serialize")]
mod wire {
    use std::io;

    use crate::wire::{Deserialize, Serialize};

    use crate::compiler::expression::Expression;
    use crate::module::StaticValue;
    use crate::wire::DeserializeContext;

    use super::{
        BoundedValueIndex, ModuleExpression, ModuleExpressionKind, ModuleOperations,
        StaticFunction, ValueOperation,
    };

    impl Serialize for ModuleExpression {
        fn serialize<W: io::Write>(&self, writer: &mut W) -> io::Result<()> {
            self.kind.serialize(writer)?;
            self.operations.serialize(writer)?;
            Ok(())
        }
    }

    pub(super) fn deserialize_module_expression<R: io::Read>(
        ctx: &DeserializeContext,
        reader: &mut R,
    ) -> io::Result<ModuleExpression> {
        let kind = deserialize_module_expression_kind(ctx, reader)?;
        let operations = deserialize_module_operations(ctx, reader)?;
        Ok(ModuleExpression { kind, operations })
    }

    impl Serialize for ModuleOperations {
        fn serialize<W: io::Write>(&self, writer: &mut W) -> io::Result<()> {
            self.expressions.serialize(writer)?;
            self.operations.serialize(writer)?;
            Ok(())
        }
    }

    fn deserialize_module_operations<R: io::Read>(
        ctx: &DeserializeContext,
        reader: &mut R,
    ) -> io::Result<ModuleOperations> {
        let len = u32::deserialize_reader(reader)?;
        let len = usize::try_from(len).map_err(|_| {
            io::Error::new(io::ErrorKind::InvalidData, format!("length too big: {len}"))
        })?;
        let mut expressions = Vec::with_capacity(len);
        for _ in 0..len {
            expressions.push(Expression::deserialize(ctx, reader)?);
        }
        let operations = <Vec<ValueOperation>>::deserialize_reader(reader)?;
        Ok(ModuleOperations {
            expressions,
            operations,
        })
    }

    impl Serialize for ModuleExpressionKind {
        fn serialize<W: io::Write>(&self, writer: &mut W) -> io::Result<()> {
            match self {
                Self::BoundedModuleValueUse { index } => {
                    0_u8.serialize(writer)?;
                    index.serialize(writer)?;
                }
                Self::StaticFunction {
                    fun: _,
                    module_index,
                    subfields,
                } => {
                    1_u8.serialize(writer)?;
                    module_index.serialize(writer)?;
                    subfields.serialize(writer)?;
                }
            }

            Ok(())
        }
    }

    fn deserialize_module_expression_kind<R: io::Read>(
        ctx: &DeserializeContext,
        reader: &mut R,
    ) -> io::Result<ModuleExpressionKind> {
        let discriminant = u8::deserialize_reader(reader)?;
        match discriminant {
            0 => {
                let index = BoundedValueIndex::deserialize_reader(reader)?;
                Ok(ModuleExpressionKind::BoundedModuleValueUse { index })
            }
            1 => {
                let module_index = usize::deserialize_reader(reader)?;
                let subfields = <Vec<String>>::deserialize_reader(reader)?;
                let Some(value) = ctx.modules_static_values.get(module_index) else {
                    return Err(io::Error::new(
                        io::ErrorKind::InvalidData,
                        format!("Unknown module with index {module_index} used in expression"),
                    ));
                };
                match get_function_from_subfield_ops(value, &subfields) {
                    Some(fun) => Ok(ModuleExpressionKind::StaticFunction {
                        fun,
                        module_index,
                        subfields,
                    }),
                    None => {
                        Err(io::Error::new(
                            io::ErrorKind::InvalidData,
                            format!("Invalid subfields {subfields:?} in expression using module with index {module_index}")
                        ))
                    }
                }
            }
            v => Err(io::Error::new(
                io::ErrorKind::InvalidData,
                format!("invalid discriminant when deserializing a module expression kind: {v}"),
            )),
        }
    }

    fn get_function_from_subfield_ops(
        mut value: &StaticValue,
        subfields: &[String],
    ) -> Option<StaticFunction> {
        for subfield in subfields {
            match value {
                StaticValue::Object(map) => value = map.get(&**subfield)?,
                _ => return None,
            }
        }
        match value {
            StaticValue::Function { fun, .. } => Some(*fun),
            _ => None,
        }
    }

    impl Serialize for BoundedValueIndex {
        fn serialize<W: io::Write>(&self, writer: &mut W) -> io::Result<()> {
            match self {
                Self::Module(v) => {
                    0_u8.serialize(writer)?;
                    v.serialize(writer)?;
                }
                Self::BoundedStack(v) => {
                    1_u8.serialize(writer)?;
                    v.serialize(writer)?;
                }
            }
            Ok(())
        }
    }

    impl Deserialize for BoundedValueIndex {
        fn deserialize_reader<R: io::Read>(reader: &mut R) -> io::Result<Self> {
            let discriminant = u8::deserialize_reader(reader)?;
            match discriminant {
                0 => Ok(Self::Module(usize::deserialize_reader(reader)?)),
                1 => Ok(Self::BoundedStack(usize::deserialize_reader(reader)?)),
                v => Err(io::Error::new(
                    io::ErrorKind::InvalidData,
                    format!("invalid discriminant when deserializing a bounded value index: {v}"),
                )),
            }
        }
    }

    impl Serialize for ValueOperation {
        fn serialize<W: io::Write>(&self, writer: &mut W) -> io::Result<()> {
            match self {
                ValueOperation::Subfield(v) => {
                    0_u8.serialize(writer)?;
                    v.serialize(writer)?;
                }
                ValueOperation::Subscript => 1_u8.serialize(writer)?,
                ValueOperation::FunctionCall(v) => {
                    2_u8.serialize(writer)?;
                    (*v as u64).serialize(writer)?;
                }
            }
            Ok(())
        }
    }

    impl Deserialize for ValueOperation {
        fn deserialize_reader<R: io::Read>(reader: &mut R) -> io::Result<Self> {
            let discriminant = u8::deserialize_reader(reader)?;
            match discriminant {
                0 => Ok(Self::Subfield(String::deserialize_reader(reader)?)),
                1 => Ok(Self::Subscript),
                2 => {
                    let v = usize::deserialize_reader(reader)?;
                    Ok(Self::FunctionCall(v))
                }
                v => Err(io::Error::new(
                    io::ErrorKind::InvalidData,
                    format!("invalid discriminant when deserializing a value operation: {v}"),
                )),
            }
        }
    }

    #[cfg(test)]
    mod tests {
        use super::*;
        use crate::module::{Math, Module, Time};
        use crate::wire::tests::{
            test_invalid_deserialization, test_round_trip, test_round_trip_custom_deser,
        };

        #[test]
        fn test_wire_module_expression() {
            let ctx = DeserializeContext::default();
            test_round_trip_custom_deser(
                &ModuleExpression {
                    kind: ModuleExpressionKind::BoundedModuleValueUse {
                        index: BoundedValueIndex::Module(5),
                    },
                    operations: ModuleOperations {
                        expressions: vec![],
                        operations: vec![],
                    },
                },
                |reader| deserialize_module_expression(&ctx, reader),
                &[0, 10],
            );
            test_round_trip_custom_deser(
                &ModuleOperations {
                    expressions: vec![Expression::Integer(23)],
                    operations: vec![
                        ValueOperation::Subscript,
                        ValueOperation::Subfield("abc".to_owned()),
                    ],
                },
                |reader| deserialize_module_operations(&ctx, reader),
                &[0, 4, 12],
            );
        }

        #[test]
        fn test_wire_module_expression_kind() {
            let time_module = Time;
            let time_static_values = time_module.get_static_values();
            let now_fun = match time_static_values.get("now") {
                Some(StaticValue::Function { fun, .. }) => *fun,
                _ => panic!("missing now function in time module"),
            };

            let math_module = Math;
            let math_static_values = math_module.get_static_values();
            let mean_fun = match math_static_values.get("mean") {
                Some(StaticValue::Function { fun, .. }) => *fun,
                _ => panic!("missing mean function in math module"),
            };

            let ctx = DeserializeContext {
                modules_static_values: vec![
                    StaticValue::Object(time_static_values),
                    StaticValue::Object(math_static_values),
                ],
            };

            test_round_trip_custom_deser(
                &ModuleExpressionKind::BoundedModuleValueUse {
                    index: BoundedValueIndex::Module(3),
                },
                |reader| deserialize_module_expression_kind(&ctx, reader),
                &[0, 2],
            );
            test_round_trip_custom_deser(
                &ModuleExpressionKind::StaticFunction {
                    fun: now_fun,
                    module_index: 0,
                    subfields: vec!["now".to_owned()],
                },
                |reader| deserialize_module_expression_kind(&ctx, reader),
                &[0, 1, 9],
            );
            test_round_trip_custom_deser(
                &ModuleExpressionKind::StaticFunction {
                    fun: mean_fun,
                    module_index: 1,
                    subfields: vec!["mean".to_owned()],
                },
                |reader| deserialize_module_expression_kind(&ctx, reader),
                &[0, 1, 9],
            );

            let test_fail_deser = |kind: ModuleExpressionKind| {
                let mut buf = Vec::new();
                kind.serialize(&mut buf).unwrap();
                let mut reader = io::Cursor::new(&*buf);
                assert!(deserialize_module_expression_kind(&ctx, &mut reader).is_err());
            };

            // Check invalid module_index value
            test_fail_deser(ModuleExpressionKind::StaticFunction {
                fun: mean_fun,
                module_index: 5,
                subfields: vec!["mean".to_owned()],
            });

            // Check invalid subfield value
            test_fail_deser(ModuleExpressionKind::StaticFunction {
                fun: mean_fun,
                module_index: 1,
                subfields: vec![],
            });
            test_fail_deser(ModuleExpressionKind::StaticFunction {
                fun: mean_fun,
                module_index: 1,
                subfields: vec!["toto".to_owned()],
            });
            test_fail_deser(ModuleExpressionKind::StaticFunction {
                fun: mean_fun,
                module_index: 1,
                subfields: vec!["MEAN_BYTES".to_owned(), "toto".to_owned()],
            });

            let mut reader = io::Cursor::new(b"\x05");
            assert!(deserialize_module_expression_kind(&ctx, &mut reader).is_err());
        }

        #[test]
        fn test_wire_bonded_value_index() {
            test_round_trip(&BoundedValueIndex::Module(15), &[0, 2]);
            test_round_trip(&BoundedValueIndex::BoundedStack(3), &[0, 2]);

            test_invalid_deserialization::<BoundedValueIndex>(b"\x05");
        }

        #[test]
        fn test_wire_value_operation() {
            test_round_trip(&ValueOperation::Subfield("aze".to_string()), &[0, 2]);
            test_round_trip(&ValueOperation::Subscript, &[0]);
            test_round_trip(&ValueOperation::FunctionCall(23), &[0, 2]);

            test_invalid_deserialization::<ValueOperation>(b"\x05");
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::module::{EvalContext, Value};
    use crate::test_helpers::test_type_traits_non_clonable;

    use super::*;

    #[cfg_attr(coverage_nightly, coverage(off))]
    fn test_fun(_ctx: &mut EvalContext, args: Vec<Value>) -> Option<Value> {
        drop(args);
        None
    }

    #[test]
    fn test_types_traits() {
        test_type_traits_non_clonable(compile_module(&crate::module::Time));
        test_type_traits_non_clonable(ValueOperation::Subfield("a".to_owned()));
        test_type_traits_non_clonable(BoundedValueIndex::Module(0));
        test_type_traits_non_clonable(ModuleOperations {
            expressions: Vec::new(),
            operations: Vec::new(),
        });
        test_type_traits_non_clonable(ModuleExpression {
            kind: ModuleExpressionKind::BoundedModuleValueUse {
                index: BoundedValueIndex::Module(0),
            },
            operations: ModuleOperations {
                expressions: Vec::new(),
                operations: Vec::new(),
            },
        });
        test_type_traits_non_clonable(ModuleExpressionKind::BoundedModuleValueUse {
            index: BoundedValueIndex::Module(0),
        });
        test_type_traits_non_clonable(ModuleExpressionKind::StaticFunction {
            fun: test_fun,
            #[cfg(feature = "serialize")]
            module_index: 0,
            #[cfg(feature = "serialize")]
            subfields: Vec::new(),
        });
        test_type_traits_non_clonable(IteratorType::Array(ValueType::Integer));
        test_type_traits_non_clonable(TypeError::UnknownSubfield("a".to_owned()));
    }
}