yara-x 1.15.0

A pure Rust implementation of YARA.
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
#![cfg_attr(any(), rustfmt::skip)]
#![allow(clippy::duplicated_attributes)]

use std::fmt::{Debug, Display, Formatter};
use std::io;
use serde::Serialize;

use thiserror::Error;

use yara_x_macros::ErrorEnum;
use yara_x_macros::ErrorStruct;
use yara_x_parser::ast;

use crate::compiler::report::{Level, Patch, Report, ReportBuilder, CodeLoc, Label, Footer};

/// Error returned by [`crate::Compiler::emit_wasm_file`].
#[derive(Error, Debug)]
#[error(transparent)]
#[doc(hidden)]
pub struct EmitWasmError(#[from] anyhow::Error);

/// Error returned by [`crate::Compiler::switch_warning`] when the warning
/// code is not valid.
#[derive(Error, Debug, Eq, PartialEq)]
#[error("`{0}` is not a valid warning code")]
pub struct InvalidWarningCode(String);

impl InvalidWarningCode {
    pub(crate) fn new(code: String) -> Self {
        Self(code)
    }
}

/// Error returned while serializing/deserializing compiled rules.
#[derive(Error, Debug)]
pub enum SerializationError {
    /// The data being deserialized was created with an incompatible version
    /// of YARA-X.
    #[error("incompatible version, expected {expected} got {actual}")]
    InvalidVersion {
        /// The expected version.
        expected: u32,
        /// The actual version found in the file.
        actual: u32,
    },

    /// The data being deserialized doesn't contain YARA-X serialized rules.
    #[error("not a YARA-X compiled rules file")]
    InvalidFormat,

    /// Error occurred while encoding YARA-X rules.
    #[error("cannot encode YARA-X rules")]
    EncodeError(#[from] bincode::error::EncodeError),

    /// Error occurred while decoding YARA-X rules.
    #[error("cannot decode YARA-X rules")]
    DecodeError(#[from] bincode::error::DecodeError),

    /// I/O error while trying to read or write serialized data.
    #[error(transparent)]
    IoError(#[from] io::Error),

    /// Error occurred while deserializing WASM code.
    #[error("invalid YARA-X compiled rules file")]
    InvalidWASM(#[from] anyhow::Error),
}

/// Error returned when rule compilation fails.
#[allow(missing_docs)]
#[non_exhaustive]
#[derive(ErrorEnum, Error, Clone, PartialEq, Eq)]
#[derive(Serialize)]
#[serde(tag = "type")]
pub enum CompileError {
    ArbitraryRegexpPrefix(Box<ArbitraryRegexpPrefix>),
    AssignmentMismatch(Box<AssignmentMismatch>),
    CircularIncludes(Box<CircularIncludes>),
    ConflictingRuleIdentifier(Box<ConflictingRuleIdentifier>),
    CustomError(Box<CustomError>),
    DuplicateModifier(Box<DuplicateModifier>),
    DuplicatePattern(Box<DuplicatePattern>),
    DuplicateRule(Box<DuplicateRule>),
    DuplicateTag(Box<DuplicateTag>),
    EmptyPatternSet(Box<EmptyPatternSet>),
    EntrypointUnsupported(Box<EntrypointUnsupported>),
    IncludeError(Box<IncludeError>),
    IncludeNotAllowed(Box<IncludeNotAllowed>),
    IncludeNotFound(Box<IncludeNotFound>),
    InvalidBase64Alphabet(Box<InvalidBase64Alphabet>),
    InvalidEscapeSequence(Box<InvalidEscapeSequence>),
    InvalidFloat(Box<InvalidFloat>),
    InvalidInteger(Box<InvalidInteger>),
    InvalidMetadata(Box<InvalidMetadata>),
    InvalidModifier(Box<InvalidModifier>),
    InvalidModifierCombination(Box<InvalidModifierCombination>),
    InvalidPattern(Box<InvalidPattern>),
    InvalidRange(Box<InvalidRange>),
    InvalidRegexp(Box<InvalidRegexp>),
    InvalidRegexpModifier(Box<InvalidRegexpModifier>),
    InvalidRuleName(Box<InvalidRuleName>),
    InvalidTag(Box<InvalidTag>),
    InvalidUTF8(Box<InvalidUTF8>),
    MethodNotAllowedInWith(Box<MethodNotAllowedInWith>),
    MismatchingTypes(Box<MismatchingTypes>),
    MissingMetadata(Box<MissingMetadata>),
    MixedGreediness(Box<MixedGreediness>),
    NumberOutOfRange(Box<NumberOutOfRange>),
    PotentiallySlowLoop(Box<PotentiallySlowLoop>),
    SlowPattern(Box<SlowPattern>),
    SyntaxError(Box<SyntaxError>),
    TooManyPatterns(Box<TooManyPatterns>),
    UnexpectedEscapeSequence(Box<UnexpectedEscapeSequence>),
    UnexpectedNegativeNumber(Box<UnexpectedNegativeNumber>),
    UnknownField(Box<UnknownField>),
    UnknownIdentifier(Box<UnknownIdentifier>),
    UnknownModule(Box<UnknownModule>),
    UnknownPattern(Box<UnknownPattern>),
    UnknownTag(Box<UnknownTag>),
    UnusedPattern(Box<UnusedPattern>),
    WrongArguments(Box<WrongArguments>),
    WrongType(Box<WrongType>),
}

impl CompileError {
    pub(crate) fn from(
        report_builder: &ReportBuilder,
        err: ast::Error,
    ) -> Self {
        match err {
            ast::Error::SyntaxError { message, span } => {
                SyntaxError::build(report_builder, message, report_builder.span_to_code_loc(span))
            }
            ast::Error::InvalidInteger { message, span } => {
                InvalidInteger::build(report_builder, message, report_builder.span_to_code_loc(span))
            }
            ast::Error::InvalidFloat { message, span } => {
                InvalidFloat::build(report_builder, message, report_builder.span_to_code_loc(span))
            }
            ast::Error::InvalidRegexpModifier { message, span } => {
                InvalidRegexpModifier::build(
                    report_builder,
                    message,
                    report_builder.span_to_code_loc(span),
                )
            }
            ast::Error::InvalidEscapeSequence { message, span } => {
                InvalidEscapeSequence::build(
                    report_builder,
                    message,
                    report_builder.span_to_code_loc(span),
                )
            }
            ast::Error::UnexpectedEscapeSequence(span) => {
                UnexpectedEscapeSequence::build(report_builder, report_builder.span_to_code_loc(span))
            }
            ast::Error::InvalidUTF8(span) => {
                InvalidUTF8::build(report_builder, report_builder.span_to_code_loc(span))
            }
        }
    }

    /// Utility function that receives an array of strings and joins them
    /// together separated by commas and with "or" before the last one.
    /// For example, if input is `["s1", "s2", "s3"]` the result is:
    ///
    /// ```text
    /// str1, str2 or str3
    /// ```
    ///
    /// If `quotes` is true, the strings are enclosed in back tilts, like this:
    ///
    /// ```text
    /// `str1`, `str2` or `str3`
    /// ```
    ///
    pub(crate) fn join_with_or<S: ToString>(s: &[S], quotes: bool) -> String {
        let mut strings = if quotes {
            s.iter()
                .map(|s| format!("`{}`", s.to_string()))
                .collect::<Vec<String>>()
        } else {
            s.iter().map(|s| s.to_string()).collect::<Vec<String>>()
        };

        // Sort alphabetically.
        strings.sort();

        // Deduplicate repeated items.
        strings.dedup();

        match strings.len() {
            1 => strings[0].to_owned(),
            2 => format!("{} or {}", strings[0], strings[1]),
            l => {
                format!(
                    "{}, or {}",
                    strings[..l - 1].join(", "),
                    strings[l - 1]
                )
            }
        }
    }
}

/// A syntax error was found in the rule.
#[derive(ErrorStruct, Clone, Debug, PartialEq, Eq)]
#[associated_enum(CompileError)]
#[error(code = "E001", title = "syntax error")]
#[label("{error}", error_loc)]
pub struct SyntaxError {
    report: Report,
    error: String,
    error_loc: CodeLoc,
}

/// Some expression has an unexpected type.
#[derive(ErrorStruct, Clone, Debug, PartialEq, Eq)]
#[associated_enum(CompileError)]
#[error(code = "E002", title = "wrong type")]
#[label(
    "expression should be {expected_types}, but it is {actual_type}",
    error_loc
)]
#[footer(help, Level::HELP)]
pub struct WrongType {
    report: Report,
    expected_types: String,
    actual_type: String,
    error_loc: CodeLoc,
    help: Option<String>,
}

/// Operands have mismatching types.
#[derive(ErrorStruct, Clone, Debug, PartialEq, Eq)]
#[associated_enum(CompileError)]
#[error(code = "E003", title = "mismatching types")]
#[label("this expression is `{type1}`", type1_loc)]
#[label("this expression is `{type2}`", type2_loc)]
pub struct MismatchingTypes {
    report: Report,
    type1: String,
    type2: String,
    type1_loc: CodeLoc,
    type2_loc: CodeLoc,
}

/// Wrong arguments when calling a function.
#[derive(ErrorStruct, Clone, Debug, PartialEq, Eq)]
#[associated_enum(CompileError)]
#[error(code = "E004", title = "wrong arguments")]
#[label("wrong arguments in this call", error_loc)]
#[footer(note)]
pub struct WrongArguments {
    report: Report,
    error_loc: CodeLoc,
    note: Option<String>,
}

/// Mismatch between number of variables and number of values in a loop
/// expression.
#[derive(ErrorStruct, Clone, Debug, PartialEq, Eq)]
#[associated_enum(CompileError)]
#[error(code = "E005", title = "assignment mismatch")]
#[label("this expects {expected_values} value(s)", error_loc)]
#[label("this produces {actual_values} value(s)", iterable_loc)]
pub struct AssignmentMismatch {
    report: Report,
    expected_values: u8,
    actual_values: u8,
    iterable_loc: CodeLoc,
    error_loc: CodeLoc,
}

/// Negative number used where positive number was expected.
#[derive(ErrorStruct, Clone, Debug, PartialEq, Eq)]
#[associated_enum(CompileError)]
#[error(code = "E006", title = "unexpected negative number")]
#[label("this number can not be negative", error_loc)]
pub struct UnexpectedNegativeNumber {
    report: Report,
    error_loc: CodeLoc,
}

/// A number is out of the allowed range.
#[derive(ErrorStruct, Clone, Debug, PartialEq, Eq)]
#[associated_enum(CompileError)]
#[error(code = "E007", title = "number out of range")]
#[label("this number is out of the allowed range [{min}-{max}]", error_loc)]
pub struct NumberOutOfRange {
    report: Report,
    min: i64,
    max: i64,
    error_loc: CodeLoc,
}

/// Unknown field or method name.
#[derive(ErrorStruct, Clone, Debug, PartialEq, Eq)]
#[associated_enum(CompileError)]
#[error(code = "E008", title = "unknown field or method `{identifier}`")]
#[label("this field or method doesn't exist", error_loc)]
pub struct UnknownField {
    report: Report,
    identifier: String,
    error_loc: CodeLoc,
}

/// Unknown identifier.
#[derive(ErrorStruct, Clone, Debug, PartialEq, Eq)]
#[associated_enum(CompileError)]
#[error(code = "E009", title = "unknown identifier `{identifier}`")]
#[label("this identifier has not been declared", identifier_loc)]
#[footer(note)]
pub struct UnknownIdentifier {
    report: Report,
    identifier: String,
    identifier_loc: CodeLoc,
    note: Option<String>,
}

impl UnknownIdentifier {
    /// Name of the unknown identifier.
    #[inline]
    pub fn identifier(&self) -> &str {
        self.identifier.as_str()
    }
    /// Location of the unknown identifier.
    pub(crate) fn identifier_location(&self) -> &CodeLoc {
        &self.identifier_loc
    }
}

/// Unknown module.
#[derive(ErrorStruct, Clone, Debug, PartialEq, Eq)]
#[associated_enum(CompileError)]
#[error(code = "E010", title = "unknown module `{identifier}`")]
#[label("module `{identifier}` not found", error_loc)]
pub struct UnknownModule {
    report: Report,
    identifier: String,
    error_loc: CodeLoc,
}

/// Invalid range.
#[derive(ErrorStruct, Clone, Debug, PartialEq, Eq)]
#[associated_enum(CompileError)]
#[error(code = "E011", title = "invalid range")]
#[label("{error}", error_loc)]
pub struct InvalidRange {
    report: Report,
    error: String,
    error_loc: CodeLoc,
}

/// Two rules have the same name.
#[derive(ErrorStruct, Clone, Debug, PartialEq, Eq)]
#[associated_enum(CompileError)]
#[error(code = "E012", title = "duplicate rule `{new_rule}`")]
#[label(
    "duplicate declaration of `{new_rule}`",
    duplicate_rule_loc,
    Level::ERROR
)]
#[label(
    "`{new_rule}` declared here for the first time",
    existing_rule_loc,
    Level::NOTE
)]
pub struct DuplicateRule {
    report: Report,
    new_rule: String,
    duplicate_rule_loc: CodeLoc,
    existing_rule_loc: CodeLoc,
}


/// A rule has the same name as a module or global variable.
#[derive(ErrorStruct, Clone, Debug, PartialEq, Eq)]
#[associated_enum(CompileError)]
#[error(
    code = "E013",
    title = "rule `{identifier}` conflicts with an existing identifier"
)]
#[label("identifier already in use by a module or global variable", error_loc)]
pub struct ConflictingRuleIdentifier {
    report: Report,
    identifier: String,
    error_loc: CodeLoc,
}

/// A regular expression is invalid.
#[derive(ErrorStruct, Clone, Debug, PartialEq, Eq)]
#[associated_enum(CompileError)]
#[error(code = "E014", title = "invalid regular expression")]
#[label("{error}", error_loc)]
#[footer(note)]
pub struct InvalidRegexp {
    report: Report,
    error: String,
    error_loc: CodeLoc,
    note: Option<String>,
}

/// A regular expression contains a mixture of greedy and non-greedy quantifiers.
#[derive(ErrorStruct, Clone, Debug, PartialEq, Eq)]
#[associated_enum(CompileError)]
#[error(
    code = "E015",
    title = "mixing greedy and non-greedy quantifiers in regular expression"
)]
#[label("this is {quantifier1_greediness}", quantifier1_loc)]
#[label("this is {quantifier2_greediness}", quantifier2_loc)]
pub struct MixedGreediness {
    report: Report,
    quantifier1_greediness: String,
    quantifier2_greediness: String,
    quantifier1_loc: CodeLoc,
    quantifier2_loc: CodeLoc,
}

/// A set of patterns doesn't contain any patterns.
#[derive(ErrorStruct, Clone, Debug, PartialEq, Eq)]
#[associated_enum(CompileError)]
#[error(code = "E016", title = "no matching patterns")]
#[label("there's no pattern in this set", error_loc)]
#[footer(note)]
pub struct EmptyPatternSet {
    report: Report,
    error_loc: CodeLoc,
    note: Option<String>,
}

/// The `entrypoint` keyword is not supported.
#[derive(ErrorStruct, Clone, Debug, PartialEq, Eq)]
#[associated_enum(CompileError)]
#[error(code = "E017", title = "`entrypoint` is unsupported")]
#[label("the `entrypoint` keyword is not supported anymore", error_loc)]
pub struct EntrypointUnsupported {
    report: Report,
    error_loc: CodeLoc,
}

/// Some pattern may be potentially slow.
#[derive(ErrorStruct, Clone, Debug, PartialEq, Eq)]
#[associated_enum(CompileError)]
#[error(code = "E018", title = "slow pattern")]
#[label("this pattern may slow down the scan", error_loc)]
#[footer(note)]
pub struct SlowPattern {
    report: Report,
    error_loc: CodeLoc,
    note: Option<String>,
}

/// A pattern has modifiers that can't be used together.
#[derive(ErrorStruct, Clone, Debug, PartialEq, Eq)]
#[associated_enum(CompileError)]
#[error(
    code = "E019",
    title = "invalid modifier combination: `{modifier1}` `{modifier2}`"
)]
#[label("`{modifier1}` modifier used here", modifier1_loc)]
#[label("`{modifier2}` modifier used here", modifier2_loc)]
#[footer(note)]
pub struct InvalidModifierCombination {
    report: Report,
    modifier1: String,
    modifier2: String,
    modifier1_loc: CodeLoc,
    modifier2_loc: CodeLoc,
    note: Option<String>,
}

/// A pattern has duplicate modifiers.
#[derive(ErrorStruct, Clone, Debug, PartialEq, Eq)]
#[associated_enum(CompileError)]
#[error(code = "E020", title = "duplicate pattern modifier")]
#[label("duplicate modifier", error_loc)]
pub struct DuplicateModifier {
    report: Report,
    error_loc: CodeLoc,
}

/// A rule has duplicate tags.
#[derive(ErrorStruct, Clone, Debug, PartialEq, Eq)]
#[associated_enum(CompileError)]
#[error(code = "E021", title = "duplicate tag `{tag}`")]
#[label("duplicate tag", error_loc)]
pub struct DuplicateTag {
    report: Report,
    tag: String,
    error_loc: CodeLoc,
}

/// A rule defines a pattern that is not used in the condition.
#[derive(ErrorStruct, Clone, Debug, PartialEq, Eq)]
#[associated_enum(CompileError)]
#[error(code = "E022", title = "unused pattern `{pattern_ident}`")]
#[label("this pattern was not used in the condition", error_loc)]
pub struct UnusedPattern {
    report: Report,
    pattern_ident: String,
    error_loc: CodeLoc,
}

/// A rule has two patterns with the same identifier.
#[derive(ErrorStruct, Clone, Debug, PartialEq, Eq)]
#[associated_enum(CompileError)]
#[error(code = "E023", title = "duplicate pattern `{pattern_ident}`")]
#[label("duplicate declaration of `{pattern_ident}`", error_loc)]
#[label(
    "`{pattern_ident}` declared here for the first time",
    note_loc,
    Level::NOTE
)]
pub struct DuplicatePattern {
    report: Report,
    pattern_ident: String,
    error_loc: CodeLoc,
    note_loc: CodeLoc,
}

/// A rule has an invalid pattern.
#[derive(ErrorStruct, Clone, Debug, PartialEq, Eq)]
#[associated_enum(CompileError)]
#[error(code = "E024", title = "invalid pattern `{pattern_ident}`")]
#[label("{error}", error_loc)]
#[footer(note)]
pub struct InvalidPattern {
    report: Report,
    pattern_ident: String,
    error: String,
    error_loc: CodeLoc,
    note: Option<String>,
}

/// Some rule condition uses a pattern that was not defined.
#[derive(ErrorStruct, Clone, Debug, PartialEq, Eq)]
#[associated_enum(CompileError)]
#[error(code = "E025", title = "unknown pattern `{pattern_ident}`")]
#[label("this pattern is not declared in the `strings` section", error_loc)]
pub struct UnknownPattern {
    report: Report,
    pattern_ident: String,
    error_loc: CodeLoc,
}

/// Wrong alphabet for the `base64` or `base64wide` modifiers.
#[derive(ErrorStruct, Clone, Debug, PartialEq, Eq)]
#[associated_enum(CompileError)]
#[error(code = "E026", title = "invalid base64 alphabet")]
#[label("{error}", error_loc)]
pub struct InvalidBase64Alphabet {
    report: Report,
    error: String,
    error_loc: CodeLoc,
}

/// Invalid integer.
#[derive(ErrorStruct, Clone, Debug, PartialEq, Eq)]
#[associated_enum(CompileError)]
#[error(code = "E027", title = "invalid integer")]
#[label("{error}", error_loc)]
pub struct InvalidInteger {
    report: Report,
    error: String,
    error_loc: CodeLoc,
}

/// Invalid float.
#[derive(ErrorStruct, Clone, Debug, PartialEq, Eq)]
#[associated_enum(CompileError)]
#[error(code = "E028", title = "invalid float")]
#[label("{error}", error_loc)]
pub struct InvalidFloat {
    report: Report,
    error: String,
    error_loc: CodeLoc,
}

/// A text pattern contains an invalid escape sequence.
#[derive(ErrorStruct, Clone, Debug, PartialEq, Eq)]
#[associated_enum(CompileError)]
#[error(code = "E029", title = "invalid escape sequence")]
#[label("{error}", error_loc)]
pub struct InvalidEscapeSequence {
    report: Report,
    error: String,
    error_loc: CodeLoc,
}

/// Invalid modifier for a regular expression.
#[derive(ErrorStruct, Clone, Debug, PartialEq, Eq)]
#[associated_enum(CompileError)]
#[error(code = "E030", title = "invalid regexp modifier `{modifier}`")]
#[label("invalid modifier", error_loc)]
pub struct InvalidRegexpModifier {
    report: Report,
    modifier: String,
    error_loc: CodeLoc,
}

/// A string literal contains escaped sequences and it shouldn't.
#[derive(ErrorStruct, Clone, Debug, PartialEq, Eq)]
#[associated_enum(CompileError)]
#[error(code = "E031", title = "unexpected escape sequence")]
#[label("escape sequences are not allowed in this string", error_loc)]
pub struct UnexpectedEscapeSequence {
    report: Report,
    error_loc: CodeLoc,
}


/// Source code contains invalid UTF-8 characters.
#[derive(ErrorStruct, Clone, Debug, PartialEq, Eq)]
#[associated_enum(CompileError)]
#[error(code = "E032", title = "invalid UTF-8")]
#[label("invalid UTF-8 character", error_loc)]
pub struct InvalidUTF8 {
    report: Report,
    error_loc: CodeLoc,
}

/// Some pattern has an invalid modifier.
#[derive(ErrorStruct, Clone, Debug, PartialEq, Eq)]
#[associated_enum(CompileError)]
#[error(code = "E033", title = "invalid pattern modifier")]
#[label("{error}", error_loc)]
pub struct InvalidModifier {
    report: Report,
    error: String,
    error_loc: CodeLoc,
}

/// A rule contains a loop that could be very slow.
///
/// This error indicates that a rule contains a `for` loop that may be very
/// slow because it iterates over a range with an upper bound that depends on
/// `filesize`. For very large files this may mean hundreds of millions of
/// iterations.
///
/// # Example
///
/// ```text
/// error[E034]: potentially slow loop
///  --> test.yar:1:34
///   |
/// 1 | rule t { condition: for any i in (0..filesize-1) : ( int32(i) == 0xcafebabe ) }
///   |                                  --------------- this range can be very large
///   |
/// ```
#[derive(ErrorStruct, Clone, Debug, PartialEq, Eq)]
#[associated_enum(CompileError)]
#[error(code = "E034", title = "potentially slow loop")]
#[label(
"this range can be very large",
    loc
)]
pub struct PotentiallySlowLoop {
    report: Report,
    loc: CodeLoc,
}

/// A rule has too many patterns.
#[derive(ErrorStruct, Clone, Debug, PartialEq, Eq)]
#[associated_enum(CompileError)]
#[error(code = "E035", title = "too many patterns in a rule")]
#[label("this rule has more than {max_num_patterns} patterns", error_loc)]
pub struct TooManyPatterns {
    report: Report,
    max_num_patterns: usize,
    error_loc: CodeLoc,
}

/// A rule has too many patterns.
#[derive(ErrorStruct, Clone, Debug, PartialEq, Eq)]
#[associated_enum(CompileError)]
#[error(code = "E036", title = "method not allowed in `with` statement")]
#[label("this method is not allowed here", error_loc)]
pub struct MethodNotAllowedInWith {
    report: Report,
    error_loc: CodeLoc,
}

/// Some metadata entry is invalid. This is only used if the compiler is
/// configured to check for valid metadata (see: [`crate::linters::Metadata`]).
///
/// ## Example
///
/// ```text
/// error[E037]: metadata `author` is not valid
/// --> test.yar:4:5
///   |
/// 4 |     author = 1234
///   |              ---- `author` must be a string
///   |
/// ```
#[derive(ErrorStruct, Clone, Debug, PartialEq, Eq)]
#[associated_enum(CompileError)]
#[error(code = "E037", title = "metadata `{name}` is not valid")]
#[label(
    "{label}",
    label_loc
)]
pub struct InvalidMetadata {
    report: Report,
    name: String,
    label_loc: CodeLoc,
    label: String,
}

/// Missing metadata. This is only used if the compiler is configured to check
/// for required metadata (see:  [`crate::linters::Metadata`]).
///
/// ## Example
///
/// ```text
/// error[E038]: required metadata is missing
///  --> test.yar:12:6
///    |
/// 12 | rule pants {
///    |      ----- required metadata "date" not found
///    |
/// ```
#[derive(ErrorStruct, Clone, Debug, PartialEq, Eq)]
#[associated_enum(CompileError)]
#[error(
    code = "E038",
    title = "required metadata is missing"
)]
#[label(
    "required metadata `{name}` not found",
    rule_loc
)]
#[footer(note)]
pub struct MissingMetadata {
    report: Report,
    rule_loc: CodeLoc,
    name: String,
    note: Option<String>,
}

/// Rule name does not match regex. This is only used if the compiler is
/// configured to check for it (see: [`crate::linters::RuleName`]).
///
/// ## Example
///
/// ```text
/// error[E039]: rule name does not match regex `APT_.*`
///  --> test.yar:13:6
///    |
/// 13 | rule pants {
///    |      ----- this rule name does not match regex `APT_.*`
///    |
/// ```
#[derive(ErrorStruct, Clone, Debug, PartialEq, Eq)]
#[associated_enum(CompileError)]
#[error(
    code = "E039",
    title = "rule name does not match regex `{regex}`"
)]
#[label(
    "this rule name does not match regex `{regex}`",
    rule_loc
)]
pub struct InvalidRuleName {
    report: Report,
    rule_loc: CodeLoc,
    regex: String,
}

/// Unknown tag. This is only used if the compiler is configured to check
/// for required tags (see:  [`crate::linters::Tags`]).
///
/// ## Example
///
/// ```text
/// error[E040]: tag not in allowed list
///  --> rules/test.yara:1:10
///   |
/// 1 | rule a : foo {
///   |          ^^^ tag `foo` not in allowed list
///   |
///   = note: Allowed tags: test, bar
/// ```
#[derive(ErrorStruct, Clone, Debug, PartialEq, Eq)]
#[associated_enum(CompileError)]
#[error(
    code = "E040",
    title = "tag not in allowed list"
)]
#[label(
    "tag `{name}` not in allowed list",
    tag_loc
)]
#[footer(note)]
pub struct UnknownTag {
    report: Report,
    tag_loc: CodeLoc,
    name: String,
    note: Option<String>,
}

/// Tag does not match regex. This is only used if the compiler is configured to
/// check for it (see: [`crate::linters::Tags`]).
///
/// ## Example
///
/// ```text
/// error[E041]: tag does not match regex `bar`
///  --> rules/test.yara:1:10
///   |
/// 1 | rule a : foo {
///   |          ^^^ tag `foo` does not match regex `bar`
///   |
/// ```
#[derive(ErrorStruct, Clone, Debug, PartialEq, Eq)]
#[associated_enum(CompileError)]
#[error(
    code = "E041",
    title = "tag does not match regex `{regex}`"
)]
#[label(
    "tag `{name}` does not match regex `{regex}`",
    tag_loc
)]
pub struct InvalidTag {
    report: Report,
    tag_loc: CodeLoc,
    name: String,
    regex: String,
}

/// An error occurred while including a file.
///
/// ## Example
///
/// ```text
/// error[E042]: error including file
///  --> line:1:1
///   |
/// 1 | include "unknown"
///   | ^^^^^^^^^^^^^^^^^ failed with error: Permission denied (os error 13)
///   |
/// ```
#[derive(ErrorStruct, Clone, Debug, PartialEq, Eq)]
#[associated_enum(CompileError)]
#[error(
    code = "E042",
    title = "error including file"
)]
#[label(
    "failed with error: {error}",
    include_loc
)]
pub struct IncludeError {
    report: Report,
    include_loc: CodeLoc,
    error: String,
}

/// An included file was not found.
///
/// ## Example
///
/// ```text
/// error[E042]: include file not found
///  --> line:1:1
///   |
/// 1 | include "unknown"
///   | ^^^^^^^^^^^^^^^^^ `unknown` not found in any of the include directories
///   |
/// ```
#[derive(ErrorStruct, Clone, Debug, PartialEq, Eq)]
#[associated_enum(CompileError)]
#[error(
    code = "E043",
    title = "include file not found"
)]
#[label(
    "`{file_path}` not found in any of the include directories",
    include_loc
)]
pub struct IncludeNotFound {
    report: Report,
    file_path: String,
    include_loc: CodeLoc,
}

/// An include statement was used, but includes are disabled
///
/// # Example
///
/// ```text
/// error[E044]: include statements not allowed
///  --> line:1:1
///
/// 1 | include "some_file"
///   | ^^^^^^^^^^^^^^^^^^^ includes are disabled for this compilation
///   |
/// ```
#[derive(ErrorStruct, Clone, Debug, PartialEq, Eq)]
#[associated_enum(CompileError)]
#[error(
    code = "E044",
    title = "include statements not allowed"
)]
#[label(
    "includes are disabled for this compilation",
    include_loc
)]
pub struct IncludeNotAllowed {
    report: Report,
    include_loc: CodeLoc,
}

/// Indicates that a regular expression has a prefix that can be arbitrarily
/// long and matches any sequence of bytes.
///
/// # Example
///
/// ```text
/// error[E045]: arbitrary regular expression prefix  
///  --> line:3:11  
///   |  
/// 3 |     $a = /.*foo/s  
///   |           ^^ this prefix can be arbitrarily long and matches all bytes  
///   |
/// ```  
///
/// Regular expressions with such prefixes are problematic because YARA will
/// report a match at every file offset from the start of the file up to where
/// the rest of the pattern matches. In most cases, this prefix can be removed
/// without affecting the rule's semantics.
#[derive(ErrorStruct, Clone, Debug, PartialEq, Eq)]
#[associated_enum(CompileError)]
#[error(code = "E045", title = "arbitrary regular expression prefix")]
#[label("this prefix can be arbitrarily long and matches all bytes", error_loc)]
pub struct ArbitraryRegexpPrefix {
    report: Report,
    error_loc: CodeLoc,
}

/// Include statements have circular dependencies.
#[derive(ErrorStruct, Clone, Debug, PartialEq, Eq)]
#[associated_enum(CompileError)]
#[error(code = "E046", title = "circular include dependencies")]
#[label("include statement has circular dependencies", error_loc)]
#[footer(note)]
pub struct CircularIncludes {
    report: Report,
    error_loc: CodeLoc,
    note: Option<String>,
}

/// A custom error has occurred.
#[derive(ErrorStruct, Clone, Debug, PartialEq, Eq)]
#[associated_enum(CompileError)]
#[error(code = "E100", title = "{title}")]
#[label("{error}", error_loc)]
pub struct CustomError {
    report: Report,
    title: String,
    error: String,
    error_loc: CodeLoc,
}