Skip to main content

libmagic_rs/parser/
ast.rs

1// Copyright (c) 2025-2026 the libmagic-rs contributors
2// SPDX-License-Identifier: Apache-2.0
3
4//! Abstract Syntax Tree definitions for magic rules
5//!
6//! This module contains the core data structures that represent parsed magic rules
7//! and their components, including offset specifications, type kinds, operators, and values.
8
9use serde::{Deserialize, Serialize};
10use std::num::{NonZeroU32, NonZeroUsize};
11
12/// The width of the length prefix for Pascal strings.
13///
14/// Uppercase suffix letters (`/H`, `/L`) indicate big-endian byte order.
15/// Lowercase suffix letters (`/h`, `/l`) indicate little-endian byte order.
16///
17/// # Examples
18///
19/// ```
20/// use libmagic_rs::parser::ast::PStringLengthWidth;
21/// let width = PStringLengthWidth::OneByte;
22/// assert_eq!(width.byte_count(), 1);
23///
24/// let width = PStringLengthWidth::TwoByteBE;
25/// assert_eq!(width.byte_count(), 2);
26///
27/// let width = PStringLengthWidth::FourByteLE;
28/// assert_eq!(width.byte_count(), 4);
29/// ```
30#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
31#[allow(clippy::enum_variant_names)]
32#[non_exhaustive]
33pub enum PStringLengthWidth {
34    /// 1-byte length prefix (default, `/B` suffix)
35    ///
36    /// # Examples
37    ///
38    /// ```
39    /// use libmagic_rs::parser::ast::PStringLengthWidth;
40    /// let width = PStringLengthWidth::OneByte;
41    /// assert_eq!(width.byte_count(), 1);
42    /// ```
43    OneByte,
44    /// 2-byte big-endian length prefix (`/H` suffix)
45    ///
46    /// # Examples
47    ///
48    /// ```
49    /// use libmagic_rs::parser::ast::PStringLengthWidth;
50    /// let width = PStringLengthWidth::TwoByteBE;
51    /// assert_eq!(width.byte_count(), 2);
52    /// ```
53    TwoByteBE,
54    /// 2-byte little-endian length prefix (`/h` suffix)
55    ///
56    /// # Examples
57    ///
58    /// ```
59    /// use libmagic_rs::parser::ast::PStringLengthWidth;
60    /// let width = PStringLengthWidth::TwoByteLE;
61    /// assert_eq!(width.byte_count(), 2);
62    /// ```
63    TwoByteLE,
64    /// 4-byte big-endian length prefix (`/L` suffix)
65    ///
66    /// # Examples
67    ///
68    /// ```
69    /// use libmagic_rs::parser::ast::PStringLengthWidth;
70    /// let width = PStringLengthWidth::FourByteBE;
71    /// assert_eq!(width.byte_count(), 4);
72    /// ```
73    FourByteBE,
74    /// 4-byte little-endian length prefix (`/l` suffix)
75    ///
76    /// # Examples
77    ///
78    /// ```
79    /// use libmagic_rs::parser::ast::PStringLengthWidth;
80    /// let width = PStringLengthWidth::FourByteLE;
81    /// assert_eq!(width.byte_count(), 4);
82    /// ```
83    FourByteLE,
84}
85
86impl PStringLengthWidth {
87    /// Returns the number of bytes used for the length prefix.
88    #[must_use]
89    pub fn byte_count(&self) -> usize {
90        match self {
91            Self::OneByte => 1,
92            Self::TwoByteBE | Self::TwoByteLE => 2,
93            Self::FourByteBE | Self::FourByteLE => 4,
94        }
95    }
96}
97
98/// Arithmetic operation applied to the value read at an indirect offset's
99/// `base_offset` before the result is used as the final file offset.
100///
101/// magic(5) supports `+`, `-`, `*`, `/`, `%`, `&`, `|`, and `^` between the
102/// pointer-type specifier and the operand inside the parentheses. Addition
103/// and subtraction collapse to [`IndirectAdjustmentOp::Add`] with a signed
104/// `adjustment` (so `(N.X-1)` is `Add(-1)` rather than a separate `Sub`
105/// variant); the remaining operators each have a dedicated variant.
106///
107/// The default is [`IndirectAdjustmentOp::Add`]; an indirect offset with no
108/// arithmetic — just `(base.type)` — is encoded as `Add` with `adjustment:
109/// 0`, preserving backwards compatibility.
110///
111/// # Examples
112///
113/// ```
114/// use libmagic_rs::parser::ast::IndirectAdjustmentOp;
115///
116/// assert_eq!(IndirectAdjustmentOp::default(), IndirectAdjustmentOp::Add);
117/// ```
118#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
119#[non_exhaustive]
120pub enum IndirectAdjustmentOp {
121    /// Addition (also covers subtraction via negative `adjustment`).
122    ///
123    /// # Examples
124    ///
125    /// ```
126    /// use libmagic_rs::parser::ast::IndirectAdjustmentOp;
127    /// assert_eq!(IndirectAdjustmentOp::default(), IndirectAdjustmentOp::Add);
128    /// ```
129    #[default]
130    Add,
131    /// Multiplication: `pointer_value * adjustment`.
132    ///
133    /// # Examples
134    ///
135    /// ```
136    /// use libmagic_rs::parser::ast::IndirectAdjustmentOp;
137    /// let op = IndirectAdjustmentOp::Mul;
138    /// assert_eq!(op, IndirectAdjustmentOp::Mul);
139    /// ```
140    Mul,
141    /// Truncating integer division: `pointer_value / adjustment`. Division
142    /// by zero is rejected by the evaluator with an error.
143    ///
144    /// # Examples
145    ///
146    /// ```
147    /// use libmagic_rs::parser::ast::IndirectAdjustmentOp;
148    /// let op = IndirectAdjustmentOp::Div;
149    /// assert_eq!(op, IndirectAdjustmentOp::Div);
150    /// ```
151    Div,
152    /// Remainder: `pointer_value % adjustment`. Modulo by zero is rejected
153    /// by the evaluator with an error.
154    ///
155    /// # Examples
156    ///
157    /// ```
158    /// use libmagic_rs::parser::ast::IndirectAdjustmentOp;
159    /// let op = IndirectAdjustmentOp::Mod;
160    /// assert_eq!(op, IndirectAdjustmentOp::Mod);
161    /// ```
162    Mod,
163    /// Bitwise AND: `pointer_value & adjustment`.
164    ///
165    /// # Examples
166    ///
167    /// ```
168    /// use libmagic_rs::parser::ast::IndirectAdjustmentOp;
169    /// let op = IndirectAdjustmentOp::And;
170    /// assert_eq!(op, IndirectAdjustmentOp::And);
171    /// ```
172    And,
173    /// Bitwise OR: `pointer_value | adjustment`.
174    ///
175    /// # Examples
176    ///
177    /// ```
178    /// use libmagic_rs::parser::ast::IndirectAdjustmentOp;
179    /// let op = IndirectAdjustmentOp::Or;
180    /// assert_eq!(op, IndirectAdjustmentOp::Or);
181    /// ```
182    Or,
183    /// Bitwise XOR: `pointer_value ^ adjustment`.
184    ///
185    /// # Examples
186    ///
187    /// ```
188    /// use libmagic_rs::parser::ast::IndirectAdjustmentOp;
189    /// let op = IndirectAdjustmentOp::Xor;
190    /// assert_eq!(op, IndirectAdjustmentOp::Xor);
191    /// ```
192    Xor,
193}
194
195/// Offset specification for locating data in files
196#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
197#[non_exhaustive]
198pub enum OffsetSpec {
199    /// Absolute offset from file start (or from file end if negative)
200    ///
201    /// Positive values are offsets from the start of the file.
202    /// Negative values are offsets from the end of the file (same as `FromEnd`).
203    ///
204    /// # Examples
205    ///
206    /// ```
207    /// use libmagic_rs::parser::ast::OffsetSpec;
208    ///
209    /// let offset = OffsetSpec::Absolute(0x10); // Read at byte 16 from start
210    /// let from_end = OffsetSpec::Absolute(-4); // 4 bytes before end of file
211    /// ```
212    Absolute(i64),
213
214    /// Indirect offset through pointer dereferencing
215    ///
216    /// Reads a pointer value at `base_offset`, interprets it according to `pointer_type`
217    /// and `endian`, then combines `adjustment` with the pointer value using
218    /// `adjustment_op` to get the final offset. The default `adjustment_op`
219    /// is [`IndirectAdjustmentOp::Add`], so `(base.type)` and
220    /// `(base.type+N)` / `(base.type-N)` use addition (subtraction is
221    /// encoded as `Add` with a negative `adjustment`). magic(5) also
222    /// supports multiplicative and bitwise forms inside the parens, e.g.
223    /// `(0x200.s*2)` ([`IndirectAdjustmentOp::Mul`]).
224    ///
225    /// # Examples
226    ///
227    /// ```
228    /// use libmagic_rs::parser::ast::{OffsetSpec, TypeKind, Endianness, IndirectAdjustmentOp};
229    ///
230    /// let indirect = OffsetSpec::Indirect {
231    ///     base_offset: 0x20,
232    ///     base_relative: false,
233    ///     pointer_type: TypeKind::Long { endian: Endianness::Little, signed: false },
234    ///     adjustment: 4,
235    ///     adjustment_op: IndirectAdjustmentOp::Add,
236    ///     result_relative: false,
237    ///     endian: Endianness::Little,
238    /// };
239    /// ```
240    Indirect {
241        /// Base offset to read pointer from. When `base_relative` is
242        /// `true`, this value is added to the current anchor (last-match
243        /// position) rather than being treated as an absolute file
244        /// position.
245        base_offset: i64,
246        /// If `true`, `base_offset` is relative to the current anchor
247        /// (i.e., `(&N.X)` syntax in magic files). Defaults to `false`
248        /// for backwards compatibility with existing AST snapshots; the
249        /// serde `default` attribute lets older serialized AST round-trip.
250        #[serde(default)]
251        base_relative: bool,
252        /// Type of pointer value
253        pointer_type: TypeKind,
254        /// Operand combined with the pointer value via `adjustment_op`.
255        ///
256        /// For `IndirectAdjustmentOp::Add`, the operand is signed (negative
257        /// values encode subtraction). For multiplicative and bitwise ops
258        /// the operand is interpreted as `i64` but typically magic files
259        /// supply non-negative literals.
260        adjustment: i64,
261        /// Arithmetic operation applied to the pointer value with
262        /// `adjustment` as the operand. Defaults to
263        /// [`IndirectAdjustmentOp::Add`] for legacy AST consumers via
264        /// serde's `default` attribute.
265        #[serde(default)]
266        adjustment_op: IndirectAdjustmentOp,
267        /// If `true`, the resolved offset is added to the current anchor
268        /// instead of being treated as an absolute file position. This
269        /// corresponds to magic-file `&(...)` syntax wrapping an indirect
270        /// spec, e.g., `&(0x10.l)`.
271        #[serde(default)]
272        result_relative: bool,
273        /// Endianness for pointer reading
274        endian: Endianness,
275    },
276
277    /// Relative offset from previous match position
278    ///
279    /// # Examples
280    ///
281    /// ```
282    /// use libmagic_rs::parser::ast::OffsetSpec;
283    ///
284    /// let relative = OffsetSpec::Relative(8); // 8 bytes after previous match
285    /// ```
286    Relative(i64),
287
288    /// Offset from end of file (negative values move towards start)
289    ///
290    /// # Examples
291    ///
292    /// ```
293    /// use libmagic_rs::parser::ast::OffsetSpec;
294    ///
295    /// let from_end = OffsetSpec::FromEnd(-16); // 16 bytes before end of file
296    /// ```
297    FromEnd(i64),
298}
299
300/// Control-flow directive carried by [`TypeKind::Meta`].
301///
302/// These are not value-reading types -- they correspond to magic(5)
303/// control-flow keywords (`default`, `clear`, `name`, `use`, `indirect`,
304/// `offset`) that modify how a rule set is traversed rather than reading
305/// bytes from the buffer. All six variants are fully evaluated by the
306/// engine: `default`/`clear` manage per-level sibling-matched state;
307/// `name`/`use` implement subroutine dispatch; `indirect` re-applies the
308/// root rule database at a resolved offset; and `offset` emits the
309/// current file position as `Value::Uint` for printf-style formatting.
310#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
311#[non_exhaustive]
312pub enum MetaType {
313    /// `default` directive: fires when no sibling at the same indentation
314    /// level has matched at the current offset. See magic(5) for the
315    /// "default" type semantics.
316    ///
317    /// # Examples
318    ///
319    /// ```
320    /// use libmagic_rs::parser::ast::MetaType;
321    /// let meta = MetaType::Default;
322    /// assert_eq!(meta, MetaType::Default);
323    /// ```
324    Default,
325    /// `clear` directive: resets the sibling-matched flag so a later
326    /// `default` sibling can fire even if an earlier sibling matched.
327    /// See magic(5) for the "clear" type semantics.
328    ///
329    /// # Examples
330    ///
331    /// ```
332    /// use libmagic_rs::parser::ast::MetaType;
333    /// let meta = MetaType::Clear;
334    /// assert_eq!(meta, MetaType::Clear);
335    /// ```
336    Clear,
337    /// `name <identifier>` directive: declares a named subroutine that
338    /// can be invoked later via [`MetaType::Use`]. See magic(5) for the
339    /// "name" type semantics.
340    ///
341    /// # Examples
342    ///
343    /// ```
344    /// use libmagic_rs::parser::ast::MetaType;
345    /// let meta = MetaType::Name("part2".to_string());
346    /// assert_eq!(meta, MetaType::Name("part2".to_string()));
347    /// ```
348    Name(String),
349    /// `use <identifier>` directive: invokes a named subroutine
350    /// previously declared via [`MetaType::Name`]. See magic(5) for the
351    /// "use" type semantics.
352    ///
353    /// # Examples
354    ///
355    /// ```
356    /// use libmagic_rs::parser::ast::MetaType;
357    /// let meta = MetaType::Use("part2".to_string());
358    /// assert_eq!(meta, MetaType::Use("part2".to_string()));
359    /// ```
360    Use(String),
361    /// `indirect` directive: re-applies the entire magic database at the
362    /// resolved offset. See magic(5) for the "indirect" type semantics.
363    ///
364    /// # Examples
365    ///
366    /// ```
367    /// use libmagic_rs::parser::ast::MetaType;
368    /// let meta = MetaType::Indirect;
369    /// assert_eq!(meta, MetaType::Indirect);
370    /// ```
371    Indirect,
372    /// `offset` type keyword: reports the current file offset rather than
373    /// reading a typed value from the buffer. See magic(5) for the
374    /// "offset" type semantics.
375    ///
376    /// Evaluation: the engine resolves the rule's offset specification
377    /// to an absolute position and emits a `RuleMatch` whose `value` is
378    /// `Value::Uint(position)`. Message templates can reference that
379    /// value through printf-style format specifiers (e.g. `%lld`),
380    /// which are substituted by
381    /// [`crate::output::format::format_magic_message`] at description-
382    /// assembly time. The only supported operator is `x` (`AnyValue`);
383    /// any other operator is `debug!`-logged and skipped.
384    ///
385    /// # Examples
386    ///
387    /// ```
388    /// use libmagic_rs::parser::ast::MetaType;
389    /// let meta = MetaType::Offset;
390    /// assert_eq!(meta, MetaType::Offset);
391    /// ```
392    Offset,
393}
394
395/// Data type specifications for interpreting bytes
396#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
397#[non_exhaustive]
398pub enum TypeKind {
399    /// Single byte
400    ///
401    /// # Examples
402    ///
403    /// ```
404    /// use libmagic_rs::parser::ast::TypeKind;
405    ///
406    /// let byte = TypeKind::Byte { signed: true };
407    /// assert_eq!(byte, TypeKind::Byte { signed: true });
408    /// ```
409    Byte {
410        /// Whether value is signed
411        signed: bool,
412    },
413    /// 16-bit integer
414    ///
415    /// # Examples
416    ///
417    /// ```
418    /// use libmagic_rs::parser::ast::{TypeKind, Endianness};
419    ///
420    /// let short = TypeKind::Short { endian: Endianness::Little, signed: true };
421    /// assert_eq!(short, TypeKind::Short { endian: Endianness::Little, signed: true });
422    /// ```
423    Short {
424        /// Byte order
425        endian: Endianness,
426        /// Whether value is signed
427        signed: bool,
428    },
429    /// 32-bit integer
430    ///
431    /// # Examples
432    ///
433    /// ```
434    /// use libmagic_rs::parser::ast::{TypeKind, Endianness};
435    ///
436    /// let long = TypeKind::Long { endian: Endianness::Big, signed: false };
437    /// assert_eq!(long, TypeKind::Long { endian: Endianness::Big, signed: false });
438    /// ```
439    Long {
440        /// Byte order
441        endian: Endianness,
442        /// Whether value is signed
443        signed: bool,
444    },
445    /// 64-bit integer
446    ///
447    /// # Examples
448    ///
449    /// ```
450    /// use libmagic_rs::parser::ast::{TypeKind, Endianness};
451    ///
452    /// let quad = TypeKind::Quad { endian: Endianness::Big, signed: true };
453    /// assert_eq!(quad, TypeKind::Quad { endian: Endianness::Big, signed: true });
454    /// ```
455    Quad {
456        /// Byte order
457        endian: Endianness,
458        /// Whether value is signed
459        signed: bool,
460    },
461    /// 32-bit IEEE 754 floating-point
462    ///
463    /// # Examples
464    ///
465    /// ```
466    /// use libmagic_rs::parser::ast::{TypeKind, Endianness};
467    ///
468    /// let float = TypeKind::Float { endian: Endianness::Big };
469    /// assert_eq!(float, TypeKind::Float { endian: Endianness::Big });
470    /// ```
471    Float {
472        /// Byte order
473        endian: Endianness,
474    },
475    /// 64-bit IEEE 754 double-precision floating-point
476    ///
477    /// # Examples
478    ///
479    /// ```
480    /// use libmagic_rs::parser::ast::{TypeKind, Endianness};
481    ///
482    /// let double = TypeKind::Double { endian: Endianness::Big };
483    /// assert_eq!(double, TypeKind::Double { endian: Endianness::Big });
484    /// ```
485    Double {
486        /// Byte order
487        endian: Endianness,
488    },
489    /// 32-bit Unix timestamp (seconds since epoch)
490    ///
491    /// # Examples
492    ///
493    /// ```
494    /// use libmagic_rs::parser::ast::{TypeKind, Endianness};
495    ///
496    /// let date = TypeKind::Date { endian: Endianness::Big, utc: true };
497    /// assert_eq!(date, TypeKind::Date { endian: Endianness::Big, utc: true });
498    /// ```
499    Date {
500        /// Byte order
501        endian: Endianness,
502        /// true = UTC, false = local time
503        utc: bool,
504    },
505    /// 64-bit Unix timestamp (seconds since epoch)
506    ///
507    /// # Examples
508    ///
509    /// ```
510    /// use libmagic_rs::parser::ast::{TypeKind, Endianness};
511    ///
512    /// let qdate = TypeKind::QDate { endian: Endianness::Little, utc: false };
513    /// assert_eq!(qdate, TypeKind::QDate { endian: Endianness::Little, utc: false });
514    /// ```
515    QDate {
516        /// Byte order
517        endian: Endianness,
518        /// true = UTC, false = local time
519        utc: bool,
520    },
521    /// String data
522    ///
523    /// The `flags` field carries the modifier flags parsed from the
524    /// `/[cCwWtTbf]` suffix on a `string` rule. Default flags (all
525    /// `false`) preserve the existing byte-exact comparison path; any
526    /// non-default flag routes the rule through
527    /// `compare_string_with_flags` in `src/evaluator/types/string.rs`.
528    /// See [`StringFlags`] for per-flag semantics.
529    ///
530    /// # Examples
531    ///
532    /// ```
533    /// use libmagic_rs::parser::ast::{StringFlags, TypeKind};
534    ///
535    /// let s = TypeKind::String { max_length: None, flags: StringFlags::default() };
536    /// assert_eq!(s, TypeKind::String { max_length: None, flags: StringFlags::default() });
537    ///
538    /// let case_insensitive = TypeKind::String {
539    ///     max_length: None,
540    ///     flags: StringFlags::default().with_ignore_lowercase(true),
541    /// };
542    /// assert!(matches!(case_insensitive, TypeKind::String { flags, .. } if flags.ignore_lowercase));
543    /// ```
544    String {
545        /// Maximum length to read
546        max_length: Option<usize>,
547        /// Modifier flags from the `/[cCwWtTbf]` suffix
548        flags: StringFlags,
549    },
550    /// UCS-2 (16-bit Unicode) string with explicit byte order.
551    ///
552    /// Backs the magic(5) `lestring16` (little-endian) and `bestring16`
553    /// (big-endian) keywords. Each character occupies two bytes in the
554    /// file; the reader stops at a U+0000 terminator (encoded as the
555    /// 2-byte sequence `0x00 0x00`) or at the end of the buffer. The
556    /// decoded value is returned as a Rust `String` (so non-ASCII
557    /// characters are preserved when valid UCS-2).
558    ///
559    /// # Examples
560    ///
561    /// ```
562    /// use libmagic_rs::parser::ast::{TypeKind, Endianness};
563    ///
564    /// let le = TypeKind::String16 { endian: Endianness::Little };
565    /// assert_eq!(le, TypeKind::String16 { endian: Endianness::Little });
566    ///
567    /// let be = TypeKind::String16 { endian: Endianness::Big };
568    /// assert_eq!(be, TypeKind::String16 { endian: Endianness::Big });
569    /// ```
570    String16 {
571        /// Endianness for the 16-bit code units.
572        endian: Endianness,
573    },
574    /// Pascal string (length-prefixed, supports 1/2/4-byte prefix, with optional max length)
575    ///
576    /// Pascal strings store the length as a prefix (1, 2, or 4 bytes, with configurable endianness), followed by
577    /// that many bytes of string data. Unlike C strings, they are not null-terminated.
578    ///
579    /// # Examples
580    ///
581    /// ```
582    /// use libmagic_rs::parser::ast::{TypeKind, PStringLengthWidth};
583    ///
584    /// let pstring = TypeKind::PString { max_length: None, length_width: PStringLengthWidth::OneByte, length_includes_itself: false };
585    /// assert_eq!(pstring, TypeKind::PString { max_length: None, length_width: PStringLengthWidth::OneByte, length_includes_itself: false });
586    ///
587    /// let limited = TypeKind::PString { max_length: Some(64), length_width: PStringLengthWidth::TwoByteBE, length_includes_itself: false };
588    /// assert_eq!(limited, TypeKind::PString { max_length: Some(64), length_width: PStringLengthWidth::TwoByteBE, length_includes_itself: false });
589    ///
590    /// // /J flag: stored length includes the length field itself
591    /// let jpeg = TypeKind::PString { max_length: None, length_width: PStringLengthWidth::TwoByteBE, length_includes_itself: true };
592    /// assert_eq!(jpeg, TypeKind::PString { max_length: None, length_width: PStringLengthWidth::TwoByteBE, length_includes_itself: true });
593    /// ```
594    PString {
595        /// Maximum length to read (caps the length value)
596        max_length: Option<usize>,
597        /// Width of the length prefix
598        length_width: PStringLengthWidth,
599        /// Whether the stored length includes the length field itself (`/J` flag)
600        length_includes_itself: bool,
601    },
602    /// Regular expression matching against file contents
603    ///
604    /// Regex rules match a POSIX-extended regular expression pattern against the
605    /// file buffer. Patterns are compiled with multi-line mode always enabled
606    /// (matching libmagic's unconditional `REG_NEWLINE`), so `^` and `$` match
607    /// at line boundaries and `.` does not match `\n`. The `flags` control
608    /// case sensitivity and anchor advance semantics; the `count` field
609    /// controls the scan window (byte or line bounds). The scan window is
610    /// always capped at 8192 bytes (matching GNU `file`'s `FILE_REGEX_MAX`;
611    /// enforced in the evaluator).
612    ///
613    /// # Examples
614    ///
615    /// ```
616    /// use libmagic_rs::parser::ast::{RegexCount, RegexFlags, TypeKind};
617    /// use std::num::NonZeroU32;
618    ///
619    /// // Plain `regex` -- no flags, default 8192-byte scan window.
620    /// let plain = TypeKind::Regex {
621    ///     flags: RegexFlags::default(),
622    ///     count: RegexCount::Default,
623    /// };
624    ///
625    /// // `regex/1l` -- scan the first line only.
626    /// let first_line = TypeKind::Regex {
627    ///     flags: RegexFlags::default(),
628    ///     count: RegexCount::Lines(NonZeroU32::new(1)),
629    /// };
630    ///
631    /// // `regex/cs` -- case-insensitive, anchor advances to match-start.
632    /// let case_insensitive_start = TypeKind::Regex {
633    ///     flags: RegexFlags {
634    ///         case_insensitive: true,
635    ///         start_offset: true,
636    ///     },
637    ///     count: RegexCount::Default,
638    /// };
639    /// ```
640    Regex {
641        /// Modifier flags from the `/[cs]` suffix (`/c` case-insensitive,
642        /// `/s` start-offset anchor). Line-mode is encoded by the
643        /// [`RegexCount::Lines`] variant of `count`, not a flag.
644        flags: RegexFlags,
645        /// Scan window specifier: default 8192 bytes, explicit byte
646        /// count, or explicit line count. See [`RegexCount`] for the
647        /// three cases.
648        count: RegexCount,
649    },
650    /// Multi-byte pattern search within a bounded range
651    ///
652    /// Search rules look for a literal byte pattern within `range` bytes of
653    /// the offset. Unlike [`TypeKind::String`], which only matches at the
654    /// exact offset, `search` scans forward up to `range` bytes for the
655    /// first occurrence. The range is **mandatory** per GNU `file`'s
656    /// magic(5) specification and is stored as a [`NonZeroUsize`] so a
657    /// zero-range search is unrepresentable.
658    ///
659    /// # Examples
660    ///
661    /// ```
662    /// use libmagic_rs::parser::ast::TypeKind;
663    /// use std::num::NonZeroUsize;
664    ///
665    /// // `search/256` -- scan up to 256 bytes for the literal pattern.
666    /// let bounded = TypeKind::Search {
667    ///     range: NonZeroUsize::new(256).unwrap(),
668    ///     flags: libmagic_rs::parser::ast::SearchFlags::default(),
669    /// };
670    /// ```
671    Search {
672        /// Scan window width in bytes, starting at the rule's offset.
673        range: NonZeroUsize,
674        /// Modifier flags from the `/[sCcWwTtBbf]` suffix on a `search`
675        /// rule. The `/s` flag controls anchor advance (match-START vs
676        /// match-END); the eight `StringFlags`-shared letters alter how
677        /// the literal pattern is compared against the file bytes. See
678        /// [`SearchFlags`] for the per-flag semantics.
679        flags: SearchFlags,
680    },
681    /// Control-flow directive (`default`, `clear`, `name`, `use`,
682    /// `indirect`, `offset`).
683    ///
684    /// These magic(5) keywords do not read or compare bytes; they modify
685    /// how a rule set is traversed. All six variants are fully evaluated:
686    /// `default` fires as a fallback when no sibling at the same level
687    /// has matched; `clear` resets that flag; `name`/`use` support
688    /// subroutine definition and invocation; `indirect` re-enters the
689    /// rule set at a resolved offset; `offset` emits the resolved file
690    /// position as `Value::Uint` for printf-style message substitution.
691    /// See [`MetaType`] for the individual variants.
692    ///
693    /// # Examples
694    ///
695    /// ```
696    /// use libmagic_rs::parser::ast::{MetaType, TypeKind};
697    /// let default_rule = TypeKind::Meta(MetaType::Default);
698    /// assert_eq!(default_rule, TypeKind::Meta(MetaType::Default));
699    /// ```
700    Meta(MetaType),
701}
702
703/// Regex modifier flags parsed from the `/[cs]` suffix on a `regex` rule.
704///
705/// The `/l` "line-based window" modifier is **not** represented here; it
706/// lives on [`RegexCount::Lines`] so that the type-level encoding makes
707/// "line count" and "byte count" mutually exclusive. An earlier design
708/// used two separate fields (`line_based: bool` + `count: Option<u32>`)
709/// which admitted the cross-field state `line_based: true, count: None`;
710/// under the current encoding that case is expressed explicitly as
711/// [`RegexCount::Lines(None)`](RegexCount::Lines) -- the `regex/l`
712/// shorthand -- and is behaviorally equivalent to [`RegexCount::Default`]
713/// (both walk the full 8192-byte capped window).
714///
715/// All flags default to `false` via [`RegexFlags::default`], equivalent
716/// to a plain `regex` with no `/c` or `/s` suffix.
717///
718/// # Examples
719///
720/// ```
721/// use libmagic_rs::parser::ast::RegexFlags;
722///
723/// let plain = RegexFlags::default();
724/// assert!(!plain.case_insensitive);
725/// assert!(!plain.start_offset);
726///
727/// let case_and_start = RegexFlags::default()
728///     .with_case_insensitive(true)
729///     .with_start_offset(true);
730/// assert!(case_and_start.case_insensitive);
731/// assert!(case_and_start.start_offset);
732/// ```
733#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
734pub struct RegexFlags {
735    /// `/c` -- case-insensitive matching. When `true`, ASCII letter
736    /// casing is ignored during pattern matching.
737    pub case_insensitive: bool,
738    /// `/s` -- advance the GNU `file` previous-match anchor to the start
739    /// of the matched region instead of its end. Matches libmagic's
740    /// `REGEX_OFFSET_START` flag, which zeros the length contribution in
741    /// `moffset()` for `FILE_REGEX`. Useful for chaining child rules that
742    /// need to re-match from the position where the parent regex began.
743    pub start_offset: bool,
744}
745
746impl RegexFlags {
747    /// Builder-style setter for [`RegexFlags::case_insensitive`] (`/c`).
748    ///
749    /// Chain after [`RegexFlags::default()`] to construct `RegexFlags`
750    /// values without exhaustive struct literals. If a new flag is
751    /// added to `RegexFlags` in the future, callers using the builder
752    /// form keep compiling; callers using struct literals would need
753    /// an update.
754    #[must_use]
755    pub const fn with_case_insensitive(mut self, value: bool) -> Self {
756        self.case_insensitive = value;
757        self
758    }
759
760    /// Builder-style setter for [`RegexFlags::start_offset`] (`/s`).
761    ///
762    /// Chain after [`RegexFlags::default()`] to construct `RegexFlags`
763    /// values without exhaustive struct literals.
764    #[must_use]
765    pub const fn with_start_offset(mut self, value: bool) -> Self {
766        self.start_offset = value;
767        self
768    }
769}
770
771/// String modifier flags parsed from the `/[cCwWtTbf]` suffix on a `string`
772/// rule.
773///
774/// Mirrors libmagic's `STRING_*` flag bits from `src/file.h`. Each flag
775/// alters how `compare_string_with_flags` walks the pattern and buffer in
776/// parallel. The default (all `false`) preserves byte-exact comparison.
777///
778/// **`/c` vs `/C` are asymmetric**: the pattern character controls
779/// direction. With `/c`, only lowercase pattern chars trigger case-folding
780/// (the file byte is `tolower`'d). With `/C`, only uppercase pattern chars
781/// trigger folding (the file byte is `toupper`'d). Mixed-case patterns
782/// behave intuitively: `/c FoO` matches `FoO`, `Foo`, `FOO` but not
783/// `fOO` (the uppercase `F` is literal). See GOTCHAS S6.5 for the
784/// rationale and `src/softmagic.c` for the canonical libmagic contract.
785///
786/// **`/B` is NOT a string flag** -- it is the `pstring` 1-byte length-width
787/// letter (`PSTRING_1_BE`). `string/B` is rejected at parse time. See
788/// GOTCHAS S6.6.
789///
790/// # Examples
791///
792/// ```
793/// use libmagic_rs::parser::ast::StringFlags;
794///
795/// let plain = StringFlags::default();
796/// assert!(!plain.ignore_lowercase);
797///
798/// let case_insensitive = StringFlags::default().with_ignore_lowercase(true);
799/// assert!(case_insensitive.ignore_lowercase);
800///
801/// let compound = StringFlags::default()
802///     .with_ignore_lowercase(true)
803///     .with_compact_optional_whitespace(true);
804/// assert!(compound.ignore_lowercase);
805/// assert!(compound.compact_optional_whitespace);
806/// ```
807#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
808// libmagic's contract is naturally a bitfield: each flag is a distinct
809// magic(5) letter (/c, /C, /w, /W, /t, /T, /b, /f) with its own STRING_*
810// constant in libmagic src/file.h. Flags compose freely (string/cw is
811// /c plus /w; string/wcCtTbf sets all eight). Folding pairs into enums
812// is possible (whitespace: none|optional|required; case: none|lower|upper)
813// but would obscure the libmagic mapping and produce verbose match arms
814// in every consumer. The bool-per-flag layout mirrors `RegexFlags` and
815// the libmagic source -- the clippy lint is overruled by the design.
816#[allow(clippy::struct_excessive_bools)]
817pub struct StringFlags {
818    /// `/W` -- `STRING_COMPACT_WHITESPACE`. Pattern whitespace requires at
819    /// least one whitespace byte in the file, then any further whitespace
820    /// in the file is consumed greedily.
821    pub compact_whitespace: bool,
822    /// `/w` -- `STRING_COMPACT_OPTIONAL_WHITESPACE`. Pattern whitespace
823    /// matches zero or more whitespace bytes in the file.
824    pub compact_optional_whitespace: bool,
825    /// `/c` -- `STRING_IGNORE_LOWERCASE`. When the pattern char is
826    /// lowercase, the file byte is `to_ascii_lowercase`'d before
827    /// comparison. Uppercase pattern chars are compared literally.
828    pub ignore_lowercase: bool,
829    /// `/C` -- `STRING_IGNORE_UPPERCASE`. When the pattern char is
830    /// uppercase, the file byte is `to_ascii_uppercase`'d before
831    /// comparison. Lowercase pattern chars are compared literally.
832    pub ignore_uppercase: bool,
833    /// `/t` -- `STRING_TEXTTEST`. Hint that this rule applies to text
834    /// files. Captured for MIME-output integration; does not currently
835    /// alter comparison.
836    pub text_test: bool,
837    /// `/T` -- `STRING_TRIM`. Trim leading and trailing ASCII whitespace
838    /// from the pattern before comparison. The trim is applied at
839    /// evaluation time (in `read_pattern_match`) so the AST keeps the
840    /// original pattern bytes; the comparison function receives the
841    /// trimmed slice.
842    pub trim: bool,
843    /// `/b` -- `STRING_BINTEST`. Hint that this rule applies to binary
844    /// files. Captured for MIME-output integration; does not currently
845    /// alter comparison.
846    pub bin_test: bool,
847    /// `/f` -- `STRING_FULL_WORD`. Post-match check that the byte after
848    /// the matched region is either end-of-buffer or a non-word
849    /// character (ASCII alphanumeric or `_`).
850    pub full_word: bool,
851}
852
853impl StringFlags {
854    /// Returns `true` when every flag is `false` (the byte-exact fast
855    /// path). The evaluator dispatcher uses this to skip the
856    /// parallel-walk comparison when no flags are set.
857    #[must_use]
858    pub const fn is_empty(self) -> bool {
859        !self.compact_whitespace
860            && !self.compact_optional_whitespace
861            && !self.ignore_lowercase
862            && !self.ignore_uppercase
863            && !self.text_test
864            && !self.trim
865            && !self.bin_test
866            && !self.full_word
867    }
868
869    /// Builder-style setter for `compact_whitespace` (`/W`).
870    #[must_use]
871    pub const fn with_compact_whitespace(mut self, value: bool) -> Self {
872        self.compact_whitespace = value;
873        self
874    }
875
876    /// Builder-style setter for `compact_optional_whitespace` (`/w`).
877    #[must_use]
878    pub const fn with_compact_optional_whitespace(mut self, value: bool) -> Self {
879        self.compact_optional_whitespace = value;
880        self
881    }
882
883    /// Builder-style setter for `ignore_lowercase` (`/c`).
884    #[must_use]
885    pub const fn with_ignore_lowercase(mut self, value: bool) -> Self {
886        self.ignore_lowercase = value;
887        self
888    }
889
890    /// Builder-style setter for `ignore_uppercase` (`/C`).
891    #[must_use]
892    pub const fn with_ignore_uppercase(mut self, value: bool) -> Self {
893        self.ignore_uppercase = value;
894        self
895    }
896
897    /// Builder-style setter for `text_test` (`/t`).
898    #[must_use]
899    pub const fn with_text_test(mut self, value: bool) -> Self {
900        self.text_test = value;
901        self
902    }
903
904    /// Builder-style setter for `trim` (`/T`).
905    #[must_use]
906    pub const fn with_trim(mut self, value: bool) -> Self {
907        self.trim = value;
908        self
909    }
910
911    /// Builder-style setter for `bin_test` (`/b`).
912    #[must_use]
913    pub const fn with_bin_test(mut self, value: bool) -> Self {
914        self.bin_test = value;
915        self
916    }
917
918    /// Builder-style setter for `full_word` (`/f`).
919    #[must_use]
920    pub const fn with_full_word(mut self, value: bool) -> Self {
921        self.full_word = value;
922        self
923    }
924}
925
926/// Search modifier flags parsed from the `/[sCcWwTtBbf]` suffix on a
927/// `search` rule.
928///
929/// Mirrors [`StringFlags`] for the eight `STRING_*` letters that alter
930/// the literal-pattern comparison (`/c`, `/C`, `/w`, `/W`, `/t`, `/T`,
931/// `/b`, `/f`), plus a search-only `start_anchor` field for `/s` which
932/// shifts the GNU `file` previous-match anchor to the START of the
933/// matched region. The default (all `false`) preserves byte-exact
934/// comparison and match-END anchor advance.
935///
936/// `SearchFlags` is structurally parallel to `StringFlags`: when one
937/// struct grows a field, the other gains the same field in lockstep
938/// so that [`SearchFlags::to_string_flags`] can keep handing off to
939/// `compare_string_with_flags` without a generic refactor. The
940/// search-only `start_anchor` field has no analog in `string` rules.
941///
942/// **`/c` vs `/C` are asymmetric** in the same way as [`StringFlags`]:
943/// the pattern character controls fold direction. See [`StringFlags`]
944/// and GOTCHAS S6.5 for the rationale.
945///
946/// # Examples
947///
948/// ```
949/// use libmagic_rs::parser::ast::SearchFlags;
950///
951/// let plain = SearchFlags::default();
952/// assert!(!plain.start_anchor);
953/// assert!(plain.is_empty());
954/// assert!(!plain.needs_byte_compare());
955///
956/// let start = SearchFlags::default().with_start_anchor(true);
957/// assert!(start.start_anchor);
958/// assert!(!start.is_empty());
959/// // /s is anchor-only -- does not force the byte-compare slow path.
960/// assert!(!start.needs_byte_compare());
961///
962/// let case = SearchFlags::default().with_ignore_lowercase(true);
963/// assert!(case.needs_byte_compare());
964/// ```
965#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
966// libmagic's contract is naturally a bitfield: each flag is a distinct
967// magic(5) letter with its own STRING_*/SEARCH_* constant in libmagic
968// src/file.h. Flags compose freely (search/cs is /c plus /s; search/sWcT
969// sets four). Folding pairs into enums is possible but would obscure
970// the libmagic mapping and produce verbose match arms in every consumer.
971// The bool-per-flag layout mirrors `StringFlags` and `RegexFlags` and the
972// libmagic source -- the clippy lint is overruled by the design.
973#[allow(clippy::struct_excessive_bools)]
974pub struct SearchFlags {
975    /// `/W` -- `STRING_COMPACT_WHITESPACE`. Pattern whitespace requires at
976    /// least one whitespace byte in the file, then any further whitespace
977    /// in the file is consumed greedily.
978    pub compact_whitespace: bool,
979    /// `/w` -- `STRING_COMPACT_OPTIONAL_WHITESPACE`. Pattern whitespace
980    /// matches zero or more whitespace bytes in the file.
981    pub compact_optional_whitespace: bool,
982    /// `/c` -- `STRING_IGNORE_LOWERCASE`. When the pattern char is
983    /// lowercase, the file byte is `to_ascii_lowercase`'d before
984    /// comparison. Uppercase pattern chars are compared literally.
985    pub ignore_lowercase: bool,
986    /// `/C` -- `STRING_IGNORE_UPPERCASE`. When the pattern char is
987    /// uppercase, the file byte is `to_ascii_uppercase`'d before
988    /// comparison. Lowercase pattern chars are compared literally.
989    pub ignore_uppercase: bool,
990    /// `/t` -- `STRING_TEXTTEST`. Hint that this rule applies to text
991    /// files. Captured for MIME-output integration; does not currently
992    /// alter comparison.
993    pub text_test: bool,
994    /// `/T` -- `STRING_TRIM`. Trim leading and trailing ASCII whitespace
995    /// from the pattern before comparison.
996    pub trim: bool,
997    /// `/b` -- `STRING_BINTEST`. Hint that this rule applies to binary
998    /// files. Captured for MIME-output integration; does not currently
999    /// alter comparison.
1000    pub bin_test: bool,
1001    /// `/f` -- `STRING_FULL_WORD`. Post-match check that the byte after
1002    /// the matched region is either end-of-buffer or a non-word
1003    /// character (ASCII alphanumeric or `_`).
1004    pub full_word: bool,
1005    /// `/s` -- magic(5) "search-start" flag. When `true`, the GNU `file`
1006    /// previous-match anchor advance lands on the match-START index
1007    /// rather than match-END (the default). Mirrors libmagic's
1008    /// `FILE_SEARCH` anchor handling in `src/softmagic.c::moffset`. The
1009    /// dispatch happens in
1010    /// `src/evaluator/types/search.rs::search_bytes_consumed`.
1011    pub start_anchor: bool,
1012}
1013
1014impl SearchFlags {
1015    /// Returns `true` when every flag is `false` (default-constructed).
1016    #[must_use]
1017    pub const fn is_empty(self) -> bool {
1018        !self.compact_whitespace
1019            && !self.compact_optional_whitespace
1020            && !self.ignore_lowercase
1021            && !self.ignore_uppercase
1022            && !self.text_test
1023            && !self.trim
1024            && !self.bin_test
1025            && !self.full_word
1026            && !self.start_anchor
1027    }
1028
1029    /// Returns `true` when any flag alters the literal-pattern
1030    /// comparison, forcing the byte-walk slow path through
1031    /// `compare_string_with_flags`. The anchor-only / metadata-only
1032    /// flags (`/s`, `/t`, `/b`) do **not** trigger byte-compare;
1033    /// they preserve the `memchr::memmem::find` fast path.
1034    #[must_use]
1035    pub const fn needs_byte_compare(self) -> bool {
1036        self.compact_whitespace
1037            || self.compact_optional_whitespace
1038            || self.ignore_lowercase
1039            || self.ignore_uppercase
1040            || self.trim
1041            || self.full_word
1042    }
1043
1044    /// Project the eight shared flag fields onto a [`StringFlags`] for
1045    /// handoff to `compare_string_with_flags`. The search-only
1046    /// `start_anchor` field is dropped (it is anchor-advance policy,
1047    /// not comparison policy).
1048    ///
1049    /// # Examples
1050    ///
1051    /// ```
1052    /// use libmagic_rs::parser::ast::SearchFlags;
1053    ///
1054    /// let sf = SearchFlags::default()
1055    ///     .with_ignore_lowercase(true)
1056    ///     .with_trim(true)
1057    ///     .with_start_anchor(true);
1058    /// let projected = sf.to_string_flags();
1059    /// assert!(projected.ignore_lowercase);
1060    /// assert!(projected.trim);
1061    /// // /s has no analog in StringFlags.
1062    /// ```
1063    #[must_use]
1064    pub const fn to_string_flags(self) -> StringFlags {
1065        StringFlags {
1066            compact_whitespace: self.compact_whitespace,
1067            compact_optional_whitespace: self.compact_optional_whitespace,
1068            ignore_lowercase: self.ignore_lowercase,
1069            ignore_uppercase: self.ignore_uppercase,
1070            text_test: self.text_test,
1071            trim: self.trim,
1072            bin_test: self.bin_test,
1073            full_word: self.full_word,
1074        }
1075    }
1076
1077    /// Builder-style setter for `compact_whitespace` (`/W`).
1078    #[must_use]
1079    pub const fn with_compact_whitespace(mut self, value: bool) -> Self {
1080        self.compact_whitespace = value;
1081        self
1082    }
1083
1084    /// Builder-style setter for `compact_optional_whitespace` (`/w`).
1085    #[must_use]
1086    pub const fn with_compact_optional_whitespace(mut self, value: bool) -> Self {
1087        self.compact_optional_whitespace = value;
1088        self
1089    }
1090
1091    /// Builder-style setter for `ignore_lowercase` (`/c`).
1092    #[must_use]
1093    pub const fn with_ignore_lowercase(mut self, value: bool) -> Self {
1094        self.ignore_lowercase = value;
1095        self
1096    }
1097
1098    /// Builder-style setter for `ignore_uppercase` (`/C`).
1099    #[must_use]
1100    pub const fn with_ignore_uppercase(mut self, value: bool) -> Self {
1101        self.ignore_uppercase = value;
1102        self
1103    }
1104
1105    /// Builder-style setter for `text_test` (`/t`).
1106    #[must_use]
1107    pub const fn with_text_test(mut self, value: bool) -> Self {
1108        self.text_test = value;
1109        self
1110    }
1111
1112    /// Builder-style setter for `trim` (`/T`).
1113    #[must_use]
1114    pub const fn with_trim(mut self, value: bool) -> Self {
1115        self.trim = value;
1116        self
1117    }
1118
1119    /// Builder-style setter for `bin_test` (`/b`).
1120    #[must_use]
1121    pub const fn with_bin_test(mut self, value: bool) -> Self {
1122        self.bin_test = value;
1123        self
1124    }
1125
1126    /// Builder-style setter for `full_word` (`/f`).
1127    #[must_use]
1128    pub const fn with_full_word(mut self, value: bool) -> Self {
1129        self.full_word = value;
1130        self
1131    }
1132
1133    /// Builder-style setter for `start_anchor` (`/s`).
1134    #[must_use]
1135    pub const fn with_start_anchor(mut self, value: bool) -> Self {
1136        self.start_anchor = value;
1137        self
1138    }
1139}
1140
1141/// Scan window specifier for a [`TypeKind::Regex`] rule.
1142///
1143/// Encodes the three mutually-exclusive scan modes in a single enum so
1144/// that the "byte count" and "line count" cases cannot be confused. The
1145/// `regex/l` shorthand (line mode with no explicit count) is represented
1146/// explicitly as [`RegexCount::Lines(None)`](RegexCount::Lines), which
1147/// is behaviorally equivalent to [`RegexCount::Default`] -- both walk
1148/// the full 8192-byte capped window -- but preserves the magic-file
1149/// surface syntax of the original rule. The 8192-byte hard cap
1150/// (matching GNU `file`'s `FILE_REGEX_MAX`) is applied by the evaluator
1151/// on every variant.
1152///
1153/// # Examples
1154///
1155/// ```
1156/// use libmagic_rs::parser::ast::RegexCount;
1157/// use std::num::NonZeroU32;
1158///
1159/// // Plain `regex` (no suffix): default 8192-byte window.
1160/// assert_eq!(RegexCount::default(), RegexCount::Default);
1161///
1162/// // `regex/100`: scan at most 100 bytes.
1163/// let hundred_bytes = RegexCount::Bytes(NonZeroU32::new(100).unwrap());
1164///
1165/// // `regex/1l`: scan the first line.
1166/// let one_line = RegexCount::Lines(NonZeroU32::new(1));
1167///
1168/// // `regex/l`: line-mode with no explicit count (walks terminators
1169/// // to the end of the 8192-byte capped window).
1170/// let unbounded_lines = RegexCount::Lines(None);
1171/// ```
1172#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
1173pub enum RegexCount {
1174    /// No scan bound (plain `regex` with no suffix). Scans the default
1175    /// 8192-byte window from the rule's offset.
1176    #[default]
1177    Default,
1178    /// Byte-bounded scan (`regex/N` with no `/l` flag). The window is
1179    /// `min(n, 8192, remaining_buffer)` bytes long. `NonZeroU32` makes
1180    /// a zero-byte scan unrepresentable.
1181    Bytes(NonZeroU32),
1182    /// Line-bounded scan (`regex/Nl` or `regex/l`). The window walks
1183    /// LF / CRLF / bare CR line terminators from the offset. With
1184    /// `Some(n)`, the walk stops after the Nth terminator (inclusive).
1185    /// With `None` (the `regex/l` shorthand), the walk continues to
1186    /// the end of the 8192-byte capped window. Either way the
1187    /// effective byte window is capped at 8192.
1188    Lines(Option<NonZeroU32>),
1189}
1190
1191impl TypeKind {
1192    /// Returns the bit width of integer types, or `None` for non-integer types (e.g., String).
1193    ///
1194    /// # Examples
1195    ///
1196    /// ```
1197    /// use libmagic_rs::parser::ast::{Endianness, StringFlags, TypeKind};
1198    ///
1199    /// assert_eq!(TypeKind::Byte { signed: false }.bit_width(), Some(8));
1200    /// assert_eq!(TypeKind::Short { endian: Endianness::Native, signed: true }.bit_width(), Some(16));
1201    /// assert_eq!(TypeKind::Long { endian: Endianness::Native, signed: true }.bit_width(), Some(32));
1202    /// assert_eq!(TypeKind::Quad { endian: Endianness::Native, signed: true }.bit_width(), Some(64));
1203    /// assert_eq!(TypeKind::Float { endian: Endianness::Native }.bit_width(), Some(32));
1204    /// assert_eq!(TypeKind::Double { endian: Endianness::Native }.bit_width(), Some(64));
1205    /// assert_eq!(TypeKind::String { max_length: None, flags: StringFlags::default() }.bit_width(), None);
1206    /// ```
1207    #[must_use]
1208    pub const fn bit_width(&self) -> Option<u32> {
1209        match self {
1210            Self::Byte { .. } => Some(8),
1211            Self::Short { .. } => Some(16),
1212            Self::Long { .. } | Self::Float { .. } | Self::Date { .. } => Some(32),
1213            Self::Quad { .. } | Self::Double { .. } | Self::QDate { .. } => Some(64),
1214            Self::String { .. }
1215            | Self::String16 { .. }
1216            | Self::PString { .. }
1217            | Self::Regex { .. }
1218            | Self::Search { .. }
1219            | Self::Meta(_) => None,
1220        }
1221    }
1222}
1223
1224/// Comparison and bitwise operators
1225#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1226#[non_exhaustive]
1227pub enum Operator {
1228    /// Equality comparison (`=` or `==`)
1229    ///
1230    /// # Examples
1231    ///
1232    /// ```
1233    /// use libmagic_rs::parser::ast::Operator;
1234    ///
1235    /// let op = Operator::Equal;
1236    /// assert_eq!(op, Operator::Equal);
1237    /// ```
1238    Equal,
1239    /// Inequality comparison (`!=` or `<>`)
1240    ///
1241    /// # Examples
1242    ///
1243    /// ```
1244    /// use libmagic_rs::parser::ast::Operator;
1245    ///
1246    /// let op = Operator::NotEqual;
1247    /// assert_eq!(op, Operator::NotEqual);
1248    /// ```
1249    NotEqual,
1250    /// Less-than comparison (`<`)
1251    ///
1252    /// # Examples
1253    ///
1254    /// ```
1255    /// use libmagic_rs::parser::ast::Operator;
1256    ///
1257    /// let op = Operator::LessThan;
1258    /// assert_eq!(op, Operator::LessThan);
1259    /// ```
1260    LessThan,
1261    /// Greater-than comparison (`>`)
1262    ///
1263    /// # Examples
1264    ///
1265    /// ```
1266    /// use libmagic_rs::parser::ast::Operator;
1267    ///
1268    /// let op = Operator::GreaterThan;
1269    /// assert_eq!(op, Operator::GreaterThan);
1270    /// ```
1271    GreaterThan,
1272    /// Less-than-or-equal comparison (`<=`)
1273    ///
1274    /// # Examples
1275    ///
1276    /// ```
1277    /// use libmagic_rs::parser::ast::Operator;
1278    ///
1279    /// let op = Operator::LessEqual;
1280    /// assert_eq!(op, Operator::LessEqual);
1281    /// ```
1282    LessEqual,
1283    /// Greater-than-or-equal comparison (`>=`)
1284    ///
1285    /// # Examples
1286    ///
1287    /// ```
1288    /// use libmagic_rs::parser::ast::Operator;
1289    ///
1290    /// let op = Operator::GreaterEqual;
1291    /// assert_eq!(op, Operator::GreaterEqual);
1292    /// ```
1293    GreaterEqual,
1294    /// Bitwise AND operation without mask (`&`)
1295    ///
1296    /// # Examples
1297    ///
1298    /// ```
1299    /// use libmagic_rs::parser::ast::Operator;
1300    ///
1301    /// let op = Operator::BitwiseAnd;
1302    /// assert_eq!(op, Operator::BitwiseAnd);
1303    /// ```
1304    BitwiseAnd,
1305    /// Bitwise AND operation with mask value (`&` with a mask operand)
1306    ///
1307    /// # Examples
1308    ///
1309    /// ```
1310    /// use libmagic_rs::parser::ast::Operator;
1311    ///
1312    /// let op = Operator::BitwiseAndMask(0xFF00);
1313    /// assert_eq!(op, Operator::BitwiseAndMask(0xFF00));
1314    /// ```
1315    BitwiseAndMask(u64),
1316    /// Bitwise XOR operation (`^`)
1317    ///
1318    /// # Examples
1319    ///
1320    /// ```
1321    /// use libmagic_rs::parser::ast::Operator;
1322    ///
1323    /// let op = Operator::BitwiseXor;
1324    /// assert_eq!(op, Operator::BitwiseXor);
1325    /// ```
1326    BitwiseXor,
1327    /// Bitwise NOT/complement operation (`~`)
1328    ///
1329    /// # Examples
1330    ///
1331    /// ```
1332    /// use libmagic_rs::parser::ast::Operator;
1333    ///
1334    /// let op = Operator::BitwiseNot;
1335    /// assert_eq!(op, Operator::BitwiseNot);
1336    /// ```
1337    BitwiseNot,
1338    /// Match any value; condition always succeeds (`x`)
1339    ///
1340    /// # Examples
1341    ///
1342    /// ```
1343    /// use libmagic_rs::parser::ast::Operator;
1344    ///
1345    /// let op = Operator::AnyValue;
1346    /// assert_eq!(op, Operator::AnyValue);
1347    /// ```
1348    AnyValue,
1349}
1350
1351/// Value types for rule matching
1352#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1353#[non_exhaustive]
1354pub enum Value {
1355    /// Unsigned integer value
1356    ///
1357    /// # Examples
1358    ///
1359    /// ```
1360    /// use libmagic_rs::parser::ast::Value;
1361    ///
1362    /// let val = Value::Uint(0xDEAD_BEEF);
1363    /// assert_eq!(val, Value::Uint(0xDEAD_BEEF));
1364    /// ```
1365    Uint(u64),
1366    /// Signed integer value
1367    ///
1368    /// # Examples
1369    ///
1370    /// ```
1371    /// use libmagic_rs::parser::ast::Value;
1372    ///
1373    /// let val = Value::Int(-42);
1374    /// assert_eq!(val, Value::Int(-42));
1375    /// ```
1376    Int(i64),
1377    /// Floating-point value (used for `float` and `double` types)
1378    ///
1379    /// # Examples
1380    ///
1381    /// ```
1382    /// use libmagic_rs::parser::ast::Value;
1383    ///
1384    /// let val = Value::Float(3.14);
1385    /// assert_eq!(val, Value::Float(3.14));
1386    /// ```
1387    Float(f64),
1388    /// Byte sequence
1389    ///
1390    /// # Examples
1391    ///
1392    /// ```
1393    /// use libmagic_rs::parser::ast::Value;
1394    ///
1395    /// let val = Value::Bytes(vec![0x7f, 0x45, 0x4c, 0x46]);
1396    /// assert_eq!(val, Value::Bytes(vec![0x7f, 0x45, 0x4c, 0x46]));
1397    /// ```
1398    Bytes(Vec<u8>),
1399    /// String value
1400    ///
1401    /// # Examples
1402    ///
1403    /// ```
1404    /// use libmagic_rs::parser::ast::Value;
1405    ///
1406    /// let val = Value::String("MZ".to_string());
1407    /// assert_eq!(val, Value::String("MZ".to_string()));
1408    /// ```
1409    String(String),
1410}
1411
1412/// Endianness specification for multi-byte values
1413#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
1414pub enum Endianness {
1415    /// Little-endian byte order (least significant byte first)
1416    ///
1417    /// # Examples
1418    ///
1419    /// ```
1420    /// use libmagic_rs::parser::ast::Endianness;
1421    ///
1422    /// let e = Endianness::Little;
1423    /// assert_eq!(e, Endianness::Little);
1424    /// ```
1425    Little,
1426    /// Big-endian byte order (most significant byte first)
1427    ///
1428    /// # Examples
1429    ///
1430    /// ```
1431    /// use libmagic_rs::parser::ast::Endianness;
1432    ///
1433    /// let e = Endianness::Big;
1434    /// assert_eq!(e, Endianness::Big);
1435    /// ```
1436    Big,
1437    /// Native system byte order (matches target architecture)
1438    ///
1439    /// # Examples
1440    ///
1441    /// ```
1442    /// use libmagic_rs::parser::ast::Endianness;
1443    ///
1444    /// let e = Endianness::Native;
1445    /// assert_eq!(e, Endianness::Native);
1446    /// ```
1447    Native,
1448}
1449
1450/// Strength modifier for magic rules
1451///
1452/// Strength modifiers adjust the default strength calculation for a rule.
1453/// They are specified using the `!:strength` directive in magic files.
1454///
1455/// # Examples
1456///
1457/// ```
1458/// use libmagic_rs::parser::ast::StrengthModifier;
1459///
1460/// let add = StrengthModifier::Add(10);      // !:strength +10
1461/// let sub = StrengthModifier::Subtract(5);  // !:strength -5
1462/// let mul = StrengthModifier::Multiply(2);  // !:strength *2
1463/// let div = StrengthModifier::Divide(2);    // !:strength /2
1464/// let set = StrengthModifier::Set(50);      // !:strength =50
1465/// ```
1466#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
1467pub enum StrengthModifier {
1468    /// Add to the default strength: `!:strength +N`
1469    Add(i32),
1470    /// Subtract from the default strength: `!:strength -N`
1471    Subtract(i32),
1472    /// Multiply the default strength: `!:strength *N`
1473    Multiply(i32),
1474    /// Divide the default strength: `!:strength /N`
1475    Divide(i32),
1476    /// Set strength to an absolute value: `!:strength =N` or `!:strength N`
1477    Set(i32),
1478}
1479
1480/// Arithmetic operation applied to a value read from the file *before* the
1481/// rule's comparison operator is evaluated.
1482///
1483/// magic(5) supports `+`, `-`, `*`, `/`, `%`, `|`, and `^` between the type
1484/// keyword and the comparison value (e.g., `lelong+1 x volume %d` reads a
1485/// long, adds 1, and formats the transformed value into the message).
1486/// Bitwise AND (`&MASK`) is *not* part of this enum because it is already
1487/// represented at the operator level via [`Operator::BitwiseAndMask`].
1488///
1489/// The operand is signed (`i64`) so that subtraction and negative multipliers
1490/// round-trip cleanly. Bitwise ops reinterpret the operand as a `u64` bit
1491/// pattern at evaluation time, matching libmagic's `apprentice.c::mconvert`.
1492#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1493#[non_exhaustive]
1494pub enum ValueTransformOp {
1495    /// Addition (`type+N`).
1496    Add,
1497    /// Subtraction (`type-N`).
1498    Sub,
1499    /// Multiplication (`type*N`).
1500    Mul,
1501    /// Truncating integer division (`type/N`). Division by zero is rejected
1502    /// at evaluation time.
1503    Div,
1504    /// Remainder (`type%N`). Modulo by zero is rejected at evaluation time.
1505    Mod,
1506    /// Bitwise AND (`type&N`).
1507    ///
1508    /// magic(5) `&MASK` was historically encoded at the operator level
1509    /// via [`Operator::BitwiseAndMask`] (which combines mask+equal in
1510    /// one step). That encoding cannot represent rules like `lelong&0xff
1511    /// x %d` (mask + any-value, with the masked value used in format
1512    /// substitution). The parser promotes `&MASK` to this `BitAnd`
1513    /// transform when followed by another operator (`x`, `>`, `!=`, ...)
1514    /// so the read value is masked before comparison and before printf
1515    /// substitution. The legacy `&MASK VALUE` form (mask + implicit
1516    /// equal) keeps using `Operator::BitwiseAndMask` for backwards
1517    /// compatibility.
1518    BitAnd,
1519    /// Bitwise OR (`type|N`).
1520    Or,
1521    /// Bitwise XOR (`type^N`).
1522    Xor,
1523}
1524
1525/// A pre-comparison value transform: `(op, operand)`.
1526///
1527/// Applied to the value read from the file before the rule's comparison
1528/// operator runs. See [`ValueTransformOp`] for the supported operations.
1529///
1530/// # Examples
1531///
1532/// ```
1533/// use libmagic_rs::parser::ast::{ValueTransform, ValueTransformOp};
1534///
1535/// // `lelong+1` -> add 1 to the read value
1536/// let t = ValueTransform { op: ValueTransformOp::Add, operand: 1 };
1537/// assert_eq!(t.op, ValueTransformOp::Add);
1538/// assert_eq!(t.operand, 1);
1539/// ```
1540#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1541pub struct ValueTransform {
1542    /// Operation to apply.
1543    pub op: ValueTransformOp,
1544    /// Operand to combine with the read value.
1545    pub operand: i64,
1546}
1547
1548/// Magic rule representation in the AST
1549#[derive(Debug, Clone, Serialize, Deserialize)]
1550pub struct MagicRule {
1551    /// Offset specification for where to read data
1552    pub offset: OffsetSpec,
1553    /// Type of data to read and interpret
1554    pub typ: TypeKind,
1555    /// Comparison operator to apply
1556    pub op: Operator,
1557    /// Expected value for comparison
1558    pub value: Value,
1559    /// Human-readable message for this rule
1560    pub message: String,
1561    /// Child rules that are evaluated if this rule matches
1562    pub children: Vec<MagicRule>,
1563    /// Indentation level for hierarchical rules
1564    pub level: u32,
1565    /// Optional strength modifier from `!:strength` directive
1566    pub strength_modifier: Option<StrengthModifier>,
1567    /// Optional pre-comparison value transform from a magic-file
1568    /// type-suffix like `lelong+1` or `ulequad/1073741824`. When set,
1569    /// the read value is transformed *before* `op` is evaluated and
1570    /// before the message's `%`-format substitution, so format
1571    /// specifiers see the post-transform number.
1572    ///
1573    /// `#[serde(default)]` keeps existing serialized AST snapshots
1574    /// (which never had this field) round-tripping correctly: missing
1575    /// fields deserialize to `None`, which means "no transform" --
1576    /// the historical behavior.
1577    #[serde(default)]
1578    pub value_transform: Option<ValueTransform>,
1579}
1580
1581/// Validation errors returned by [`MagicRule::validate`].
1582#[derive(Debug, thiserror::Error, PartialEq, Eq)]
1583#[non_exhaustive]
1584pub enum MagicRuleValidationError {
1585    /// Rule message is empty. Messages are user-facing and required
1586    /// for meaningful output.
1587    #[error("rule message must not be empty")]
1588    EmptyMessage,
1589
1590    /// The child rule at `child_index` has `level <= self.level`,
1591    /// violating the "children must nest deeper than the parent"
1592    /// invariant of the hierarchical indentation-based DSL.
1593    #[error(
1594        "child rule at index {child_index} has level {child_level}, \
1595         must be greater than parent level {parent_level}"
1596    )]
1597    InvalidChildLevel {
1598        /// Index of the offending child in `self.children`.
1599        child_index: usize,
1600        /// Level of the child rule.
1601        child_level: u32,
1602        /// Level of the parent rule.
1603        parent_level: u32,
1604    },
1605
1606    /// Rule `level` exceeds the maximum supported depth. The limit is a
1607    /// hardening mechanism against stack overflow during deep recursion;
1608    /// libmagic files in the wild rarely go beyond 10 levels.
1609    #[error("rule level {level} exceeds maximum supported depth {max}")]
1610    LevelTooDeep {
1611        /// The invalid level value.
1612        level: u32,
1613        /// The maximum allowed depth.
1614        max: u32,
1615    },
1616}
1617
1618impl MagicRule {
1619    /// Hard structural ceiling on rule `level`.
1620    ///
1621    /// This is a conservative upper bound enforced by
1622    /// [`MagicRule::validate`] to keep the AST shape sane: real
1623    /// magic files in the wild rarely exceed ~10 levels of nesting,
1624    /// so rejecting rules with `level > 1000` catches obviously
1625    /// pathological input at construction time without constraining
1626    /// any legitimate rule.
1627    ///
1628    /// This ceiling is **independent of** the evaluator's
1629    /// `EvaluationConfig::max_recursion_depth` (default 20), which
1630    /// is the *runtime* recursion guard applied during rule
1631    /// evaluation. The evaluator limit is the first one that fires
1632    /// in practice -- a rule tree with 50 levels passes this
1633    /// structural check but is aborted by the evaluator long before
1634    /// reaching `MAX_LEVEL`. The two limits serve different purposes:
1635    /// `MAX_LEVEL` is an AST-shape sanity check, and
1636    /// `max_recursion_depth` is a per-evaluation resource bound.
1637    pub const MAX_LEVEL: u32 = 1000;
1638
1639    /// Construct a top-level rule with no children and no strength
1640    /// modifier.
1641    ///
1642    /// This is the most common constructor for programmatically building
1643    /// rules outside the parser. To add children, mutate
1644    /// [`MagicRule::children`] directly, or use [`MagicRule::with_children`].
1645    /// To set a strength modifier, use
1646    /// [`MagicRule::with_strength_modifier`].
1647    ///
1648    /// # Examples
1649    ///
1650    /// ```rust
1651    /// use libmagic_rs::{MagicRule, OffsetSpec, Operator, TypeKind, Value};
1652    ///
1653    /// let rule = MagicRule::new(
1654    ///     OffsetSpec::Absolute(0),
1655    ///     TypeKind::Byte { signed: false },
1656    ///     Operator::Equal,
1657    ///     Value::Uint(0x7f),
1658    ///     "ELF magic byte".to_string(),
1659    /// );
1660    /// assert_eq!(rule.level, 0);
1661    /// assert!(rule.children.is_empty());
1662    /// assert!(rule.validate().is_ok());
1663    /// ```
1664    #[must_use]
1665    pub fn new(
1666        offset: OffsetSpec,
1667        typ: TypeKind,
1668        op: Operator,
1669        value: Value,
1670        message: String,
1671    ) -> Self {
1672        Self {
1673            offset,
1674            typ,
1675            op,
1676            value,
1677            message,
1678            children: vec![],
1679            level: 0,
1680            strength_modifier: None,
1681            value_transform: None,
1682        }
1683    }
1684
1685    /// Replace `self.children` with the given children and return the
1686    /// modified rule. Builder-style for chaining.
1687    #[must_use]
1688    pub fn with_children(mut self, children: Vec<MagicRule>) -> Self {
1689        self.children = children;
1690        self
1691    }
1692
1693    /// Set `self.strength_modifier` to the given value and return the
1694    /// modified rule. Builder-style for chaining.
1695    #[must_use]
1696    pub const fn with_strength_modifier(mut self, modifier: StrengthModifier) -> Self {
1697        self.strength_modifier = Some(modifier);
1698        self
1699    }
1700
1701    /// Set `self.level` to the given value and return the modified rule.
1702    /// Builder-style for chaining; typically used only when constructing
1703    /// child rules programmatically.
1704    #[must_use]
1705    pub const fn with_level(mut self, level: u32) -> Self {
1706        self.level = level;
1707        self
1708    }
1709
1710    /// Validate structural invariants of the rule.
1711    ///
1712    /// This checks invariants that the parser enforces automatically but
1713    /// that programmatic constructors (especially via serde deserialize)
1714    /// can violate:
1715    ///
1716    /// * Message must not be empty.
1717    /// * `level` must not exceed [`Self::MAX_LEVEL`].
1718    /// * Every child's `level` must be strictly greater than
1719    ///   `self.level`, and each child must recursively validate.
1720    ///
1721    /// This does *not* validate that `value` is shape-compatible with
1722    /// `typ` (e.g., a `Value::Uint` against a `TypeKind::String`); such
1723    /// mismatches are coerced or rejected by the evaluator at match time.
1724    ///
1725    /// # Errors
1726    ///
1727    /// Returns [`MagicRuleValidationError`] describing the first
1728    /// invariant violation encountered.
1729    ///
1730    /// # Examples
1731    ///
1732    /// ```rust
1733    /// use libmagic_rs::{MagicRule, OffsetSpec, Operator, TypeKind, Value};
1734    ///
1735    /// let rule = MagicRule::new(
1736    ///     OffsetSpec::Absolute(0),
1737    ///     TypeKind::Byte { signed: false },
1738    ///     Operator::Equal,
1739    ///     Value::Uint(0),
1740    ///     "zero byte".to_string(),
1741    /// );
1742    /// assert!(rule.validate().is_ok());
1743    /// ```
1744    pub fn validate(&self) -> Result<(), MagicRuleValidationError> {
1745        if self.message.is_empty() {
1746            return Err(MagicRuleValidationError::EmptyMessage);
1747        }
1748        if self.level > Self::MAX_LEVEL {
1749            return Err(MagicRuleValidationError::LevelTooDeep {
1750                level: self.level,
1751                max: Self::MAX_LEVEL,
1752            });
1753        }
1754        for (child_index, child) in self.children.iter().enumerate() {
1755            if child.level <= self.level {
1756                return Err(MagicRuleValidationError::InvalidChildLevel {
1757                    child_index,
1758                    child_level: child.level,
1759                    parent_level: self.level,
1760                });
1761            }
1762            child.validate()?;
1763        }
1764        Ok(())
1765    }
1766}
1767
1768#[cfg(test)]
1769mod tests {
1770    use super::*;
1771
1772    #[test]
1773    fn test_magic_rule_new_defaults() {
1774        let rule = MagicRule::new(
1775            OffsetSpec::Absolute(0),
1776            TypeKind::Byte { signed: false },
1777            Operator::Equal,
1778            Value::Uint(0x7f),
1779            "ELF".to_string(),
1780        );
1781        assert_eq!(rule.level, 0);
1782        assert!(rule.children.is_empty());
1783        assert!(rule.strength_modifier.is_none());
1784        assert!(rule.validate().is_ok());
1785    }
1786
1787    #[test]
1788    fn test_magic_rule_builder_chain() {
1789        let child = MagicRule::new(
1790            OffsetSpec::Absolute(4),
1791            TypeKind::Byte { signed: false },
1792            Operator::Equal,
1793            Value::Uint(2),
1794            "64-bit".to_string(),
1795        )
1796        .with_level(1);
1797        let parent = MagicRule::new(
1798            OffsetSpec::Absolute(0),
1799            TypeKind::Byte { signed: false },
1800            Operator::Equal,
1801            Value::Uint(0x7f),
1802            "ELF".to_string(),
1803        )
1804        .with_children(vec![child])
1805        .with_strength_modifier(StrengthModifier::Add(10));
1806        assert_eq!(parent.children.len(), 1);
1807        assert_eq!(parent.strength_modifier, Some(StrengthModifier::Add(10)));
1808        assert!(parent.validate().is_ok());
1809    }
1810
1811    #[test]
1812    fn test_magic_rule_validate_empty_message_rejected() {
1813        let rule = MagicRule::new(
1814            OffsetSpec::Absolute(0),
1815            TypeKind::Byte { signed: false },
1816            Operator::Equal,
1817            Value::Uint(0),
1818            String::new(),
1819        );
1820        assert_eq!(rule.validate(), Err(MagicRuleValidationError::EmptyMessage));
1821    }
1822
1823    #[test]
1824    fn test_magic_rule_validate_child_level_must_be_deeper() {
1825        let child_same_level = MagicRule::new(
1826            OffsetSpec::Absolute(4),
1827            TypeKind::Byte { signed: false },
1828            Operator::Equal,
1829            Value::Uint(2),
1830            "child".to_string(),
1831        ); // level = 0, same as parent
1832        let parent = MagicRule::new(
1833            OffsetSpec::Absolute(0),
1834            TypeKind::Byte { signed: false },
1835            Operator::Equal,
1836            Value::Uint(0x7f),
1837            "parent".to_string(),
1838        )
1839        .with_children(vec![child_same_level]);
1840        assert_eq!(
1841            parent.validate(),
1842            Err(MagicRuleValidationError::InvalidChildLevel {
1843                child_index: 0,
1844                child_level: 0,
1845                parent_level: 0,
1846            })
1847        );
1848    }
1849
1850    #[test]
1851    fn test_magic_rule_validate_level_too_deep() {
1852        let rule = MagicRule::new(
1853            OffsetSpec::Absolute(0),
1854            TypeKind::Byte { signed: false },
1855            Operator::Equal,
1856            Value::Uint(0),
1857            "deep".to_string(),
1858        )
1859        .with_level(MagicRule::MAX_LEVEL + 1);
1860        assert_eq!(
1861            rule.validate(),
1862            Err(MagicRuleValidationError::LevelTooDeep {
1863                level: MagicRule::MAX_LEVEL + 1,
1864                max: MagicRule::MAX_LEVEL,
1865            })
1866        );
1867    }
1868
1869    #[test]
1870    fn test_offset_spec_absolute() {
1871        let offset = OffsetSpec::Absolute(42);
1872        assert_eq!(offset, OffsetSpec::Absolute(42));
1873
1874        // Test negative offset
1875        let negative = OffsetSpec::Absolute(-10);
1876        assert_eq!(negative, OffsetSpec::Absolute(-10));
1877    }
1878
1879    #[test]
1880    fn test_offset_spec_indirect() {
1881        let indirect = OffsetSpec::Indirect {
1882            base_offset: 0x20,
1883            base_relative: false,
1884            pointer_type: TypeKind::Long {
1885                endian: Endianness::Little,
1886                signed: false,
1887            },
1888            adjustment: 4,
1889            adjustment_op: IndirectAdjustmentOp::Add,
1890            result_relative: false,
1891            endian: Endianness::Little,
1892        };
1893
1894        match indirect {
1895            OffsetSpec::Indirect {
1896                base_offset,
1897                adjustment,
1898                ..
1899            } => {
1900                assert_eq!(base_offset, 0x20);
1901                assert_eq!(adjustment, 4);
1902            }
1903            _ => panic!("Expected Indirect variant"),
1904        }
1905    }
1906
1907    #[test]
1908    fn test_offset_spec_relative() {
1909        let relative = OffsetSpec::Relative(8);
1910        assert_eq!(relative, OffsetSpec::Relative(8));
1911
1912        // Test negative relative offset
1913        let negative_relative = OffsetSpec::Relative(-4);
1914        assert_eq!(negative_relative, OffsetSpec::Relative(-4));
1915    }
1916
1917    #[test]
1918    fn test_offset_spec_from_end() {
1919        let from_end = OffsetSpec::FromEnd(-16);
1920        assert_eq!(from_end, OffsetSpec::FromEnd(-16));
1921
1922        // Test positive from_end (though unusual)
1923        let positive_from_end = OffsetSpec::FromEnd(8);
1924        assert_eq!(positive_from_end, OffsetSpec::FromEnd(8));
1925    }
1926
1927    #[test]
1928    fn test_offset_spec_debug() {
1929        let offset = OffsetSpec::Absolute(100);
1930        let debug_str = format!("{offset:?}");
1931        assert!(debug_str.contains("Absolute"));
1932        assert!(debug_str.contains("100"));
1933    }
1934
1935    #[test]
1936    fn test_offset_spec_clone() {
1937        let original = OffsetSpec::Indirect {
1938            base_offset: 0x10,
1939            base_relative: false,
1940            pointer_type: TypeKind::Short {
1941                endian: Endianness::Big,
1942                signed: true,
1943            },
1944            adjustment: -2,
1945            adjustment_op: IndirectAdjustmentOp::Add,
1946            result_relative: false,
1947            endian: Endianness::Big,
1948        };
1949
1950        let cloned = original.clone();
1951        assert_eq!(original, cloned);
1952    }
1953
1954    #[test]
1955    fn test_offset_spec_serialization() {
1956        let offset = OffsetSpec::Absolute(42);
1957
1958        // Test JSON serialization
1959        let json = serde_json::to_string(&offset).expect("Failed to serialize");
1960        let deserialized: OffsetSpec = serde_json::from_str(&json).expect("Failed to deserialize");
1961
1962        assert_eq!(offset, deserialized);
1963    }
1964
1965    #[test]
1966    fn test_offset_spec_indirect_serialization() {
1967        let indirect = OffsetSpec::Indirect {
1968            base_offset: 0x100,
1969            base_relative: false,
1970            pointer_type: TypeKind::Long {
1971                endian: Endianness::Native,
1972                signed: false,
1973            },
1974            adjustment: 12,
1975            adjustment_op: IndirectAdjustmentOp::Add,
1976            result_relative: false,
1977            endian: Endianness::Native,
1978        };
1979
1980        // Test JSON serialization for complex variant
1981        let json = serde_json::to_string(&indirect).expect("Failed to serialize");
1982        let deserialized: OffsetSpec = serde_json::from_str(&json).expect("Failed to deserialize");
1983
1984        assert_eq!(indirect, deserialized);
1985    }
1986
1987    #[test]
1988    fn test_all_offset_spec_variants() {
1989        let variants = [
1990            OffsetSpec::Absolute(0),
1991            OffsetSpec::Absolute(-100),
1992            OffsetSpec::Indirect {
1993                base_offset: 0x20,
1994                base_relative: false,
1995                pointer_type: TypeKind::Byte { signed: true },
1996                adjustment: 0,
1997                adjustment_op: IndirectAdjustmentOp::Add,
1998                result_relative: false,
1999                endian: Endianness::Little,
2000            },
2001            OffsetSpec::Relative(50),
2002            OffsetSpec::Relative(-25),
2003            OffsetSpec::FromEnd(-8),
2004            OffsetSpec::FromEnd(4),
2005        ];
2006
2007        // Test that all variants can be created and are distinct
2008        for (i, variant) in variants.iter().enumerate() {
2009            for (j, other) in variants.iter().enumerate() {
2010                if i != j {
2011                    assert_ne!(
2012                        variant, other,
2013                        "Variants at indices {i} and {j} should be different"
2014                    );
2015                }
2016            }
2017        }
2018    }
2019
2020    #[test]
2021    fn test_endianness_variants() {
2022        let endianness_values = vec![Endianness::Little, Endianness::Big, Endianness::Native];
2023
2024        for endian in endianness_values {
2025            let indirect = OffsetSpec::Indirect {
2026                base_offset: 0,
2027                base_relative: false,
2028                pointer_type: TypeKind::Long {
2029                    endian,
2030                    signed: false,
2031                },
2032                adjustment: 0,
2033                adjustment_op: IndirectAdjustmentOp::Add,
2034                result_relative: false,
2035                endian,
2036            };
2037
2038            // Verify the endianness is preserved
2039            match indirect {
2040                OffsetSpec::Indirect {
2041                    endian: actual_endian,
2042                    ..
2043                } => {
2044                    assert_eq!(endian, actual_endian);
2045                }
2046                _ => panic!("Expected Indirect variant"),
2047            }
2048        }
2049    }
2050
2051    // Value enum tests
2052    #[test]
2053    fn test_value_uint() {
2054        let value = Value::Uint(42);
2055        assert_eq!(value, Value::Uint(42));
2056
2057        // Test large values
2058        let large_value = Value::Uint(u64::MAX);
2059        assert_eq!(large_value, Value::Uint(u64::MAX));
2060    }
2061
2062    #[test]
2063    fn test_value_int() {
2064        let positive = Value::Int(100);
2065        assert_eq!(positive, Value::Int(100));
2066
2067        let negative = Value::Int(-50);
2068        assert_eq!(negative, Value::Int(-50));
2069
2070        // Test extreme values
2071        let max_int = Value::Int(i64::MAX);
2072        let min_int = Value::Int(i64::MIN);
2073        assert_eq!(max_int, Value::Int(i64::MAX));
2074        assert_eq!(min_int, Value::Int(i64::MIN));
2075    }
2076
2077    #[test]
2078    fn test_value_bytes() {
2079        let empty_bytes = Value::Bytes(vec![]);
2080        assert_eq!(empty_bytes, Value::Bytes(vec![]));
2081
2082        let some_bytes = Value::Bytes(vec![0x7f, 0x45, 0x4c, 0x46]);
2083        assert_eq!(some_bytes, Value::Bytes(vec![0x7f, 0x45, 0x4c, 0x46]));
2084
2085        // Test that different byte sequences are not equal
2086        let other_bytes = Value::Bytes(vec![0x50, 0x4b, 0x03, 0x04]);
2087        assert_ne!(some_bytes, other_bytes);
2088    }
2089
2090    #[test]
2091    fn test_value_string() {
2092        let empty_string = Value::String(String::new());
2093        assert_eq!(empty_string, Value::String(String::new()));
2094
2095        let hello = Value::String("Hello, World!".to_string());
2096        assert_eq!(hello, Value::String("Hello, World!".to_string()));
2097
2098        // Test Unicode strings
2099        let unicode = Value::String("🦀 Rust".to_string());
2100        assert_eq!(unicode, Value::String("🦀 Rust".to_string()));
2101    }
2102
2103    #[test]
2104    fn test_value_comparison() {
2105        // Test that different value types are not equal
2106        let uint_val = Value::Uint(42);
2107        let int_val = Value::Int(42);
2108        let float_val = Value::Float(42.0);
2109        let bytes_val = Value::Bytes(vec![42]);
2110        let string_val = Value::String("42".to_string());
2111
2112        assert_ne!(uint_val, int_val);
2113        assert_ne!(uint_val, float_val);
2114        assert_ne!(uint_val, bytes_val);
2115        assert_ne!(uint_val, string_val);
2116        assert_ne!(int_val, float_val);
2117        assert_ne!(int_val, bytes_val);
2118        assert_ne!(int_val, string_val);
2119        assert_ne!(float_val, bytes_val);
2120        assert_ne!(float_val, string_val);
2121        assert_ne!(bytes_val, string_val);
2122    }
2123
2124    #[test]
2125    fn test_value_debug() {
2126        let uint_val = Value::Uint(123);
2127        let debug_str = format!("{uint_val:?}");
2128        assert!(debug_str.contains("Uint"));
2129        assert!(debug_str.contains("123"));
2130
2131        let string_val = Value::String("test".to_string());
2132        let debug_str = format!("{string_val:?}");
2133        assert!(debug_str.contains("String"));
2134        assert!(debug_str.contains("test"));
2135    }
2136
2137    #[test]
2138    fn test_value_clone() {
2139        let original = Value::Bytes(vec![1, 2, 3, 4]);
2140        let cloned = original.clone();
2141        assert_eq!(original, cloned);
2142
2143        // Verify they are independent copies
2144        match (original, cloned) {
2145            (Value::Bytes(orig_bytes), Value::Bytes(cloned_bytes)) => {
2146                assert_eq!(orig_bytes, cloned_bytes);
2147                // They should have the same content but be different Vec instances
2148            }
2149            _ => panic!("Expected Bytes variants"),
2150        }
2151    }
2152
2153    #[test]
2154    fn test_value_float() {
2155        let value = Value::Float(3.125);
2156        assert_eq!(value, Value::Float(3.125));
2157
2158        let negative = Value::Float(-1.5);
2159        assert_eq!(negative, Value::Float(-1.5));
2160
2161        let zero = Value::Float(0.0);
2162        assert_eq!(zero, Value::Float(0.0));
2163    }
2164
2165    #[test]
2166    fn test_value_serialization() {
2167        let values = vec![
2168            Value::Uint(42),
2169            Value::Int(-100),
2170            Value::Float(3.125),
2171            Value::Bytes(vec![0x7f, 0x45, 0x4c, 0x46]),
2172            Value::String("ELF executable".to_string()),
2173        ];
2174
2175        for value in values {
2176            // Test JSON serialization
2177            let json = serde_json::to_string(&value).expect("Failed to serialize Value");
2178            let deserialized: Value =
2179                serde_json::from_str(&json).expect("Failed to deserialize Value");
2180            assert_eq!(value, deserialized);
2181        }
2182    }
2183
2184    #[test]
2185    fn test_value_serialization_edge_cases() {
2186        // Test empty collections
2187        let empty_bytes = Value::Bytes(vec![]);
2188        let json = serde_json::to_string(&empty_bytes).expect("Failed to serialize empty bytes");
2189        let deserialized: Value =
2190            serde_json::from_str(&json).expect("Failed to deserialize empty bytes");
2191        assert_eq!(empty_bytes, deserialized);
2192
2193        let empty_string = Value::String(String::new());
2194        let json = serde_json::to_string(&empty_string).expect("Failed to serialize empty string");
2195        let deserialized: Value =
2196            serde_json::from_str(&json).expect("Failed to deserialize empty string");
2197        assert_eq!(empty_string, deserialized);
2198
2199        // Test extreme values
2200        let max_uint = Value::Uint(u64::MAX);
2201        let json = serde_json::to_string(&max_uint).expect("Failed to serialize max uint");
2202        let deserialized: Value =
2203            serde_json::from_str(&json).expect("Failed to deserialize max uint");
2204        assert_eq!(max_uint, deserialized);
2205
2206        let min_int = Value::Int(i64::MIN);
2207        let json = serde_json::to_string(&min_int).expect("Failed to serialize min int");
2208        let deserialized: Value =
2209            serde_json::from_str(&json).expect("Failed to deserialize min int");
2210        assert_eq!(min_int, deserialized);
2211    }
2212
2213    // TypeKind tests
2214    #[test]
2215    fn test_type_kind_byte() {
2216        let byte_type = TypeKind::Byte { signed: true };
2217        assert_eq!(byte_type, TypeKind::Byte { signed: true });
2218    }
2219
2220    #[test]
2221    fn test_type_kind_short() {
2222        let short_little_endian = TypeKind::Short {
2223            endian: Endianness::Little,
2224            signed: false,
2225        };
2226        let short_big_endian = TypeKind::Short {
2227            endian: Endianness::Big,
2228            signed: true,
2229        };
2230
2231        assert_ne!(short_little_endian, short_big_endian);
2232        assert_eq!(short_little_endian, short_little_endian.clone());
2233    }
2234
2235    #[test]
2236    fn test_type_kind_long() {
2237        let long_native = TypeKind::Long {
2238            endian: Endianness::Native,
2239            signed: true,
2240        };
2241
2242        match long_native {
2243            TypeKind::Long { endian, signed } => {
2244                assert_eq!(endian, Endianness::Native);
2245                assert!(signed);
2246            }
2247            _ => panic!("Expected Long variant"),
2248        }
2249    }
2250
2251    #[test]
2252    fn test_type_kind_string() {
2253        let unlimited_string = TypeKind::String {
2254            max_length: None,
2255            flags: StringFlags::default(),
2256        };
2257        let limited_string = TypeKind::String {
2258            max_length: Some(256),
2259            flags: StringFlags::default(),
2260        };
2261
2262        assert_ne!(unlimited_string, limited_string);
2263        assert_eq!(unlimited_string, unlimited_string.clone());
2264    }
2265
2266    #[test]
2267    fn test_type_kind_serialization() {
2268        let types = vec![
2269            TypeKind::Byte { signed: true },
2270            TypeKind::Short {
2271                endian: Endianness::Little,
2272                signed: false,
2273            },
2274            TypeKind::Long {
2275                endian: Endianness::Big,
2276                signed: true,
2277            },
2278            TypeKind::Quad {
2279                endian: Endianness::Little,
2280                signed: false,
2281            },
2282            TypeKind::Quad {
2283                endian: Endianness::Big,
2284                signed: true,
2285            },
2286            TypeKind::Float {
2287                endian: Endianness::Native,
2288            },
2289            TypeKind::Float {
2290                endian: Endianness::Big,
2291            },
2292            TypeKind::Double {
2293                endian: Endianness::Little,
2294            },
2295            TypeKind::Double {
2296                endian: Endianness::Native,
2297            },
2298            TypeKind::Date {
2299                endian: Endianness::Big,
2300                utc: true,
2301            },
2302            TypeKind::Date {
2303                endian: Endianness::Little,
2304                utc: false,
2305            },
2306            TypeKind::QDate {
2307                endian: Endianness::Native,
2308                utc: true,
2309            },
2310            TypeKind::QDate {
2311                endian: Endianness::Big,
2312                utc: false,
2313            },
2314            TypeKind::String {
2315                max_length: None,
2316                flags: StringFlags::default(),
2317            },
2318            TypeKind::String {
2319                max_length: Some(128),
2320                flags: StringFlags::default(),
2321            },
2322            TypeKind::PString {
2323                max_length: None,
2324                length_width: PStringLengthWidth::OneByte,
2325                length_includes_itself: false,
2326            },
2327            TypeKind::PString {
2328                max_length: Some(64),
2329                length_width: PStringLengthWidth::OneByte,
2330                length_includes_itself: false,
2331            },
2332            TypeKind::PString {
2333                max_length: None,
2334                length_width: PStringLengthWidth::TwoByteBE,
2335                length_includes_itself: true,
2336            },
2337            TypeKind::PString {
2338                max_length: Some(128),
2339                length_width: PStringLengthWidth::FourByteLE,
2340                length_includes_itself: false,
2341            },
2342        ];
2343
2344        for typ in types {
2345            let json = serde_json::to_string(&typ).expect("Failed to serialize TypeKind");
2346            let deserialized: TypeKind =
2347                serde_json::from_str(&json).expect("Failed to deserialize TypeKind");
2348            assert_eq!(typ, deserialized);
2349        }
2350    }
2351
2352    // Operator tests
2353    #[test]
2354    fn test_operator_variants() {
2355        let operators = [
2356            Operator::Equal,
2357            Operator::NotEqual,
2358            Operator::BitwiseAnd,
2359            Operator::BitwiseXor,
2360            Operator::BitwiseNot,
2361            Operator::AnyValue,
2362        ];
2363
2364        for (i, op) in operators.iter().enumerate() {
2365            for (j, other) in operators.iter().enumerate() {
2366                if i == j {
2367                    assert_eq!(op, other);
2368                } else {
2369                    assert_ne!(op, other);
2370                }
2371            }
2372        }
2373    }
2374
2375    #[test]
2376    fn test_operator_serialization() {
2377        let operators = vec![
2378            Operator::Equal,
2379            Operator::NotEqual,
2380            Operator::BitwiseAnd,
2381            Operator::BitwiseXor,
2382            Operator::BitwiseNot,
2383            Operator::AnyValue,
2384        ];
2385
2386        for op in operators {
2387            let json = serde_json::to_string(&op).expect("Failed to serialize Operator");
2388            let deserialized: Operator =
2389                serde_json::from_str(&json).expect("Failed to deserialize Operator");
2390            assert_eq!(op, deserialized);
2391        }
2392    }
2393
2394    // MagicRule tests
2395    #[test]
2396    fn test_magic_rule_creation() {
2397        let rule = MagicRule {
2398            offset: OffsetSpec::Absolute(0),
2399            typ: TypeKind::Byte { signed: true },
2400            op: Operator::Equal,
2401            value: Value::Uint(0x7f),
2402            message: "ELF magic".to_string(),
2403            children: vec![],
2404            level: 0,
2405            strength_modifier: None,
2406            value_transform: None,
2407        };
2408
2409        assert_eq!(rule.message, "ELF magic");
2410        assert_eq!(rule.level, 0);
2411        assert!(rule.children.is_empty());
2412    }
2413
2414    #[test]
2415    fn test_magic_rule_with_children() {
2416        let child_rule = MagicRule {
2417            offset: OffsetSpec::Absolute(4),
2418            typ: TypeKind::Byte { signed: true },
2419            op: Operator::Equal,
2420            value: Value::Uint(1),
2421            message: "32-bit".to_string(),
2422            children: vec![],
2423            level: 1,
2424            strength_modifier: None,
2425            value_transform: None,
2426        };
2427
2428        let parent_rule = MagicRule {
2429            offset: OffsetSpec::Absolute(0),
2430            typ: TypeKind::Long {
2431                endian: Endianness::Little,
2432                signed: false,
2433            },
2434            op: Operator::Equal,
2435            value: Value::Bytes(vec![0x7f, 0x45, 0x4c, 0x46]),
2436            message: "ELF executable".to_string(),
2437            children: vec![child_rule],
2438            level: 0,
2439            strength_modifier: None,
2440            value_transform: None,
2441        };
2442
2443        assert_eq!(parent_rule.children.len(), 1);
2444        assert_eq!(parent_rule.children[0].level, 1);
2445        assert_eq!(parent_rule.children[0].message, "32-bit");
2446    }
2447
2448    #[test]
2449    fn test_magic_rule_serialization() {
2450        let rule = MagicRule {
2451            offset: OffsetSpec::Absolute(16),
2452            typ: TypeKind::Short {
2453                endian: Endianness::Little,
2454                signed: false,
2455            },
2456            op: Operator::NotEqual,
2457            value: Value::Uint(0),
2458            message: "Non-zero short value".to_string(),
2459            children: vec![],
2460            level: 2,
2461            strength_modifier: None,
2462            value_transform: None,
2463        };
2464
2465        let json = serde_json::to_string(&rule).expect("Failed to serialize MagicRule");
2466        let deserialized: MagicRule =
2467            serde_json::from_str(&json).expect("Failed to deserialize MagicRule");
2468
2469        assert_eq!(rule.message, deserialized.message);
2470        assert_eq!(rule.level, deserialized.level);
2471        assert_eq!(rule.children.len(), deserialized.children.len());
2472    }
2473
2474    // StrengthModifier tests
2475    #[test]
2476    fn test_strength_modifier_variants() {
2477        let add = StrengthModifier::Add(10);
2478        let sub = StrengthModifier::Subtract(5);
2479        let mul = StrengthModifier::Multiply(2);
2480        let div = StrengthModifier::Divide(2);
2481        let set = StrengthModifier::Set(50);
2482
2483        // Test that each variant has the correct inner value
2484        assert_eq!(add, StrengthModifier::Add(10));
2485        assert_eq!(sub, StrengthModifier::Subtract(5));
2486        assert_eq!(mul, StrengthModifier::Multiply(2));
2487        assert_eq!(div, StrengthModifier::Divide(2));
2488        assert_eq!(set, StrengthModifier::Set(50));
2489
2490        // Test that different variants are not equal
2491        assert_ne!(add, sub);
2492        assert_ne!(mul, div);
2493        assert_ne!(set, add);
2494    }
2495
2496    #[test]
2497    fn test_strength_modifier_negative_values() {
2498        let add_negative = StrengthModifier::Add(-10);
2499        let sub_negative = StrengthModifier::Subtract(-5);
2500        let set_negative = StrengthModifier::Set(-50);
2501
2502        assert_eq!(add_negative, StrengthModifier::Add(-10));
2503        assert_eq!(sub_negative, StrengthModifier::Subtract(-5));
2504        assert_eq!(set_negative, StrengthModifier::Set(-50));
2505    }
2506
2507    #[test]
2508    fn test_strength_modifier_serialization() {
2509        let modifiers = vec![
2510            StrengthModifier::Add(10),
2511            StrengthModifier::Subtract(5),
2512            StrengthModifier::Multiply(2),
2513            StrengthModifier::Divide(3),
2514            StrengthModifier::Set(100),
2515        ];
2516
2517        for modifier in modifiers {
2518            let json =
2519                serde_json::to_string(&modifier).expect("Failed to serialize StrengthModifier");
2520            let deserialized: StrengthModifier =
2521                serde_json::from_str(&json).expect("Failed to deserialize StrengthModifier");
2522            assert_eq!(modifier, deserialized);
2523        }
2524    }
2525
2526    #[test]
2527    fn test_strength_modifier_debug() {
2528        let modifier = StrengthModifier::Add(25);
2529        let debug_str = format!("{modifier:?}");
2530        assert!(debug_str.contains("Add"));
2531        assert!(debug_str.contains("25"));
2532    }
2533
2534    #[test]
2535    fn test_strength_modifier_clone() {
2536        let original = StrengthModifier::Multiply(4);
2537        let cloned = original;
2538        assert_eq!(original, cloned);
2539    }
2540
2541    #[test]
2542    fn test_magic_rule_with_strength_modifier() {
2543        let rule = MagicRule {
2544            offset: OffsetSpec::Absolute(0),
2545            typ: TypeKind::Byte { signed: true },
2546            op: Operator::Equal,
2547            value: Value::Uint(0x7f),
2548            message: "ELF magic".to_string(),
2549            children: vec![],
2550            level: 0,
2551            strength_modifier: Some(StrengthModifier::Add(20)),
2552            value_transform: None,
2553        };
2554
2555        assert_eq!(rule.strength_modifier, Some(StrengthModifier::Add(20)));
2556
2557        // Test serialization with strength_modifier
2558        let json = serde_json::to_string(&rule).expect("Failed to serialize MagicRule");
2559        let deserialized: MagicRule =
2560            serde_json::from_str(&json).expect("Failed to deserialize MagicRule");
2561        assert_eq!(rule.strength_modifier, deserialized.strength_modifier);
2562    }
2563
2564    #[test]
2565    fn test_magic_rule_without_strength_modifier() {
2566        let rule = MagicRule {
2567            offset: OffsetSpec::Absolute(0),
2568            typ: TypeKind::Byte { signed: true },
2569            op: Operator::Equal,
2570            value: Value::Uint(0x7f),
2571            message: "ELF magic".to_string(),
2572            children: vec![],
2573            level: 0,
2574            strength_modifier: None,
2575            value_transform: None,
2576        };
2577
2578        assert_eq!(rule.strength_modifier, None);
2579    }
2580
2581    // MetaType tests
2582    #[test]
2583    fn test_meta_type_variants_debug_clone_eq() {
2584        let cases = [
2585            MetaType::Default,
2586            MetaType::Clear,
2587            MetaType::Indirect,
2588            MetaType::Offset,
2589            MetaType::Name("part2".to_string()),
2590            MetaType::Use("part2".to_string()),
2591        ];
2592
2593        for (i, variant) in cases.iter().enumerate() {
2594            // Debug formatting is non-empty
2595            let debug_str = format!("{variant:?}");
2596            assert!(
2597                !debug_str.is_empty(),
2598                "Debug format must be non-empty for variant at index {i}"
2599            );
2600
2601            // Clone round-trip preserves equality
2602            let cloned = variant.clone();
2603            assert_eq!(
2604                variant, &cloned,
2605                "Clone must preserve equality for variant at index {i}"
2606            );
2607
2608            // Distinct variants are not equal
2609            for (j, other) in cases.iter().enumerate() {
2610                if i == j {
2611                    assert_eq!(variant, other);
2612                } else {
2613                    assert_ne!(
2614                        variant, other,
2615                        "Variants at indices {i} and {j} must differ"
2616                    );
2617                }
2618            }
2619        }
2620    }
2621
2622    #[test]
2623    fn test_meta_type_serde_roundtrip() {
2624        let cases = [
2625            MetaType::Default,
2626            MetaType::Clear,
2627            MetaType::Indirect,
2628            MetaType::Offset,
2629            MetaType::Name("foo".to_string()),
2630            MetaType::Use("bar".to_string()),
2631        ];
2632
2633        for variant in cases {
2634            let json = serde_json::to_string(&variant).expect("serialize MetaType");
2635            let deserialized: MetaType = serde_json::from_str(&json).expect("deserialize MetaType");
2636            assert_eq!(variant, deserialized);
2637        }
2638    }
2639
2640    #[test]
2641    fn test_type_kind_meta_bit_width_is_none() {
2642        let cases = [
2643            MetaType::Default,
2644            MetaType::Clear,
2645            MetaType::Indirect,
2646            MetaType::Offset,
2647            MetaType::Name("x".to_string()),
2648            MetaType::Use("x".to_string()),
2649        ];
2650        for meta in cases {
2651            let kind = TypeKind::Meta(meta);
2652            assert_eq!(
2653                kind.bit_width(),
2654                None,
2655                "TypeKind::Meta must have no bit width: {kind:?}"
2656            );
2657        }
2658    }
2659}