dixscript 1.0.0

Config, code, and encryption in one file — a data interchange format with compile-time functions, AES-256/ChaCha20 built-in, and cross-platform FFI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
//! Decodes binary format to DixScript AST values

use std::io::{Read, Result as IoResult};
use crate::Compiler::AST::{Value, Position, ObjectProperty};
use crate::ErrorManager::ErrorManager;
use super::binary_format::ValueTypeTag;
use super::binary_serialization_context::BinarySerializationContext;
use super::binary_serialization_error::BinarySerializationError;

/// Decodes binary format to AST values with type tag validation.
/// Context is passed per-call rather than stored — safe to use from parallel tasks.
pub struct ValueDecoder {
    error_manager: ErrorManager,
}

impl ValueDecoder {
    pub fn new() -> Self {
        Self::new_with_error_manager(ErrorManager::get_shared_instance())
    }

    pub fn new_with_error_manager(error_manager: ErrorManager) -> Self {
        ValueDecoder { error_manager }
    }

    // =========================================================================
    // MAIN DECODE ENTRY POINT
    // =========================================================================

    /// Decode any value from binary.
    /// Format: [Type Tag: 1 byte][Value Data: variable]
    pub fn decode_value<R: Read>(
        &mut self,
        reader:  &mut R,
        context: &mut BinarySerializationContext,
    ) -> IoResult<Value> {
        let mut tag_buf = [0u8; 1];
        reader.read_exact(&mut tag_buf)?;
        let type_tag = ValueTypeTag::from_u8(tag_buf[0]).ok_or_else(|| {
            std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                BinarySerializationError::invalid_type_tag(tag_buf[0], context.get_current_scope()),
            )
        })?;

        let value = match type_tag {
            ValueTypeTag::Int32     => self.decode_int32(reader, context)?,
            ValueTypeTag::Int64     => self.decode_int64(reader, context)?,
            ValueTypeTag::Float32   => self.decode_float32(reader, context)?,
            ValueTypeTag::Float64   => self.decode_float64(reader, context)?,
            ValueTypeTag::String    => self.decode_string(reader, context)?,
            ValueTypeTag::Bool      => self.decode_bool(reader, context)?,
            ValueTypeTag::Null      => self.decode_null(context)?,
            ValueTypeTag::Array     => self.decode_array(reader, context)?,
            ValueTypeTag::Object    => self.decode_object(reader, context)?,
            ValueTypeTag::Tuple     => self.decode_tuple(reader, context)?,
            ValueTypeTag::Date      => self.decode_date(reader, context)?,
            ValueTypeTag::Timestamp => self.decode_timestamp(reader, context)?,
            ValueTypeTag::Hex       => self.decode_hex(reader, context)?,
            ValueTypeTag::Blob      => self.decode_blob(reader, context)?,
            ValueTypeTag::Regex     => self.decode_regex(reader, context)?,
            ValueTypeTag::Enum      => self.decode_enum(reader, context)?,
            ValueTypeTag::Invalid   => {
                return Err(std::io::Error::new(
                    std::io::ErrorKind::InvalidData,
                    BinarySerializationError::new(
                        crate::ErrorManager::ErrorTypes::BinarySerializationErrorType::UnsupportedType,
                        "Encountered InvalidType tag (0xFF) during decode",
                        context.get_current_scope(),
                    ),
                ));
            }
        };

        context.statistics.increment_value_count(type_tag);
        Ok(value)
    }

    // =========================================================================
    // PRIMITIVE TYPE DECODERS
    // =========================================================================

    /// Decode Int32: [4 bytes little-endian]
    fn decode_int32<R: Read>(
        &mut self,
        reader:   &mut R,
        _context: &mut BinarySerializationContext,
    ) -> IoResult<Value> {
        let mut buf = [0u8; 4];
        reader.read_exact(&mut buf)?;
        Ok(Value::Integer { value: i32::from_le_bytes(buf), position: Position::UNKNOWN })
    }

    /// Decode Int64 (Long): [8 bytes little-endian]
    fn decode_int64<R: Read>(
        &mut self,
        reader:   &mut R,
        _context: &mut BinarySerializationContext,
    ) -> IoResult<Value> {
        let mut buf = [0u8; 8];
        reader.read_exact(&mut buf)?;
        Ok(Value::Long { value: i64::from_le_bytes(buf), position: Position::UNKNOWN })
    }

    /// Decode Float32: [4 bytes IEEE 754]
    fn decode_float32<R: Read>(
        &mut self,
        reader:   &mut R,
        _context: &mut BinarySerializationContext,
    ) -> IoResult<Value> {
        let mut buf = [0u8; 4];
        reader.read_exact(&mut buf)?;
        Ok(Value::Float { value: f32::from_le_bytes(buf), position: Position::UNKNOWN })
    }

    /// Decode Float64: [8 bytes IEEE 754]
    fn decode_float64<R: Read>(
        &mut self,
        reader:   &mut R,
        _context: &mut BinarySerializationContext,
    ) -> IoResult<Value> {
        let mut buf = [0u8; 8];
        reader.read_exact(&mut buf)?;
        Ok(Value::Double { value: f64::from_le_bytes(buf), position: Position::UNKNOWN })
    }

    /// Decode String: [Length: 4 bytes][UTF-8 bytes]
    fn decode_string<R: Read>(
        &mut self,
        reader:  &mut R,
        context: &mut BinarySerializationContext,
    ) -> IoResult<Value> {
        let mut len_buf = [0u8; 4];
        reader.read_exact(&mut len_buf)?;
        let length = i32::from_le_bytes(len_buf) as usize;
        context.validate_string_length(length)
            .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
        let mut bytes = vec![0u8; length];
        reader.read_exact(&mut bytes)?;
        let value = String::from_utf8(bytes)
            .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
        Ok(Value::String { value, position: Position::UNKNOWN })
    }

    /// Decode Bool: [1 byte: 0x00 or 0x01]
    fn decode_bool<R: Read>(
        &mut self,
        reader:   &mut R,
        _context: &mut BinarySerializationContext,
    ) -> IoResult<Value> {
        let mut buf = [0u8; 1];
        reader.read_exact(&mut buf)?;
        Ok(Value::Boolean { value: buf[0] != 0x00, position: Position::UNKNOWN })
    }

    /// Decode Null: (no payload)
    fn decode_null(&mut self, _context: &mut BinarySerializationContext) -> IoResult<Value> {
        Ok(Value::Null { position: Position::UNKNOWN })
    }

    // =========================================================================
    // COMPLEX TYPE DECODERS
    // =========================================================================

    /// Decode Array: [Count: 4 bytes][Element Type: 1 byte][Values...]
    fn decode_array<R: Read>(
        &mut self,
        reader:  &mut R,
        context: &mut BinarySerializationContext,
    ) -> IoResult<Value> {
        context.enter_nested("Array")
            .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;

        let mut count_buf = [0u8; 4];
        reader.read_exact(&mut count_buf)?;
        let count = i32::from_le_bytes(count_buf) as usize;
        context.validate_array_length(count)
            .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;

        // Element type byte — metadata only, actual type comes from each value's tag
        let mut _type_buf = [0u8; 1];
        reader.read_exact(&mut _type_buf)?;

        let mut values = Vec::with_capacity(count);
        for _ in 0..count {
            values.push(self.decode_value(reader, context)?);
        }

        context.exit_nested()
            .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
        Ok(Value::Array { values, position: Position::UNKNOWN })
    }

    /// Decode Object: [Count: 4 bytes][Key-Value pairs...]
    fn decode_object<R: Read>(
        &mut self,
        reader:  &mut R,
        context: &mut BinarySerializationContext,
    ) -> IoResult<Value> {
        context.enter_nested("Object")
            .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;

        let mut count_buf = [0u8; 4];
        reader.read_exact(&mut count_buf)?;
        let count = i32::from_le_bytes(count_buf) as usize;
        context.validate_object_property_count(count)
            .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;

        let mut properties = Vec::with_capacity(count);
        for _ in 0..count {
            let mut key_len_buf = [0u8; 4];
            reader.read_exact(&mut key_len_buf)?;
            let key_length = i32::from_le_bytes(key_len_buf) as usize;
            let mut key_bytes = vec![0u8; key_length];
            reader.read_exact(&mut key_bytes)?;
            let key = String::from_utf8(key_bytes)
                .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
            let value = self.decode_value(reader, context)?;
            properties.push(ObjectProperty::new(key, value, Position::UNKNOWN));
        }

        context.exit_nested()
            .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
        Ok(Value::Object { properties, position: Position::UNKNOWN })
    }

    /// Decode Tuple: [Count: 1 byte (1-6)][Values...]
    fn decode_tuple<R: Read>(
        &mut self,
        reader:  &mut R,
        context: &mut BinarySerializationContext,
    ) -> IoResult<Value> {
        context.enter_nested("Tuple")
            .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;

        let mut count_buf = [0u8; 1];
        reader.read_exact(&mut count_buf)?;
        let count = count_buf[0] as usize;
        if !(1..=6).contains(&count) {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                format!("Invalid tuple count: {} (must be 1-6)", count),
            ));
        }

        let mut arguments = Vec::with_capacity(count);
        for _ in 0..count {
            arguments.push(self.decode_value(reader, context)?);
        }

        context.exit_nested()
            .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
        Ok(Value::PrefixedConstructor {
            prefix:    "t".to_string(),
            arguments,
            position:  Position::UNKNOWN,
        })
    }

    // =========================================================================
    // TEMPORAL TYPE DECODERS
    // =========================================================================

    /// Decode Date: [8 bytes ticks since epoch]
    fn decode_date<R: Read>(
        &mut self,
        reader:   &mut R,
        _context: &mut BinarySerializationContext,
    ) -> IoResult<Value> {
        let mut buf = [0u8; 8];
        reader.read_exact(&mut buf)?;
        let ticks   = i64::from_le_bytes(buf);
        let seconds = ticks / 10_000_000;
        use chrono::{DateTime, Utc};
        let datetime = DateTime::<Utc>::from_timestamp(seconds, 0)
            .ok_or_else(|| std::io::Error::new(
                std::io::ErrorKind::InvalidData, "Invalid date timestamp",
            ))?;
        Ok(Value::Date { value: datetime.format("%Y-%m-%d").to_string(), position: Position::UNKNOWN })
    }

    /// Decode Timestamp: [8 bytes ticks since epoch]
    fn decode_timestamp<R: Read>(
        &mut self,
        reader:   &mut R,
        _context: &mut BinarySerializationContext,
    ) -> IoResult<Value> {
        let mut buf = [0u8; 8];
        reader.read_exact(&mut buf)?;
        let ticks   = i64::from_le_bytes(buf);
        let seconds = ticks / 10_000_000;
        use chrono::{DateTime, Utc};
        let datetime = DateTime::<Utc>::from_timestamp(seconds, 0)
            .ok_or_else(|| std::io::Error::new(
                std::io::ErrorKind::InvalidData, "Invalid timestamp",
            ))?;
        Ok(Value::Timestamp { value: datetime.to_rfc3339(), position: Position::UNKNOWN })
    }

    // =========================================================================
    // SPECIAL TYPE DECODERS
    // =========================================================================

    /// Decode Hex Color: [4 bytes RGBA]
    fn decode_hex<R: Read>(
        &mut self,
        reader:   &mut R,
        _context: &mut BinarySerializationContext,
    ) -> IoResult<Value> {
        let mut buf = [0u8; 4];
        reader.read_exact(&mut buf)?;
        let (r, g, b, a) = (buf[0], buf[1], buf[2], buf[3]);
        Ok(Value::HexColor {
            value:    format!("#{:02X}{:02X}{:02X}{:02X}", r, g, b, a),
            position: Position::UNKNOWN,
        })
    }

    /// Decode Blob: [Encoding: 1][Length: 4][Data bytes]
    fn decode_blob<R: Read>(
        &mut self,
        reader:  &mut R,
        context: &mut BinarySerializationContext,
    ) -> IoResult<Value> {
        let mut _encoding_buf = [0u8; 1];
        reader.read_exact(&mut _encoding_buf)?;
        let mut len_buf = [0u8; 4];
        reader.read_exact(&mut len_buf)?;
        let length = i32::from_le_bytes(len_buf) as usize;
        context.validate_string_length(length)
            .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
        let mut bytes = vec![0u8; length];
        reader.read_exact(&mut bytes)?;
        let data = String::from_utf8(bytes)
            .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
        Ok(Value::PrefixedConstructor {
            prefix:    "b".to_string(),
            arguments: vec![Value::String { value: data, position: Position::UNKNOWN }],
            position:  Position::UNKNOWN,
        })
    }

    /// Decode Regex: [Length: 4][Pattern UTF-8 bytes]
    fn decode_regex<R: Read>(
        &mut self,
        reader:  &mut R,
        context: &mut BinarySerializationContext,
    ) -> IoResult<Value> {
        let mut len_buf = [0u8; 4];
        reader.read_exact(&mut len_buf)?;
        let length = i32::from_le_bytes(len_buf) as usize;
        context.validate_string_length(length)
            .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
        let mut bytes = vec![0u8; length];
        reader.read_exact(&mut bytes)?;
        let pattern = String::from_utf8(bytes)
            .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
        regex::Regex::new(&pattern).map_err(|e| std::io::Error::new(
            std::io::ErrorKind::InvalidData,
            format!("Invalid regex pattern: {}", e),
        ))?;
        Ok(Value::PrefixedConstructor {
            prefix:    "r".to_string(),
            arguments: vec![Value::String { value: pattern, position: Position::UNKNOWN }],
            position:  Position::UNKNOWN,
        })
    }

    /// Decode Enum: [enum_name: 4-byte len + UTF-8][field_name: 4-byte len + UTF-8][4-byte i32 resolved value]
    ///
    /// Reconstructs a real `Value::EnumValue` AST node — the exact shape the
    /// parser already produces for a literal `Enum.FIELD` reference — so
    /// `DixData::from_ast`'s existing `ast_value_to_dix_value` branch builds a
    /// proper `DixValue::Enum` from decoded binary data with no changes needed
    /// on that side. The resolved i32 travels alongside the names on the wire
    /// (see `encode_enum` in value_encoder.rs) since data_section_reader.rs has
    /// no access to the @ENUMS table at decode time — self-contained, no
    /// cross-section lookup required.
    fn decode_enum<R: Read>(
        &mut self,
        reader:  &mut R,
        context: &mut BinarySerializationContext,
    ) -> IoResult<Value> {
        let read_len_prefixed_string = |reader: &mut R, context: &mut BinarySerializationContext| -> IoResult<String> {
            let mut len_buf = [0u8; 4];
            reader.read_exact(&mut len_buf)?;
            let length = i32::from_le_bytes(len_buf) as usize;
            context.validate_string_length(length)
                .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
            let mut bytes = vec![0u8; length];
            reader.read_exact(&mut bytes)?;
            String::from_utf8(bytes)
                .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))
        };

        let enum_name  = read_len_prefixed_string(reader, context)?;
        let field_name = read_len_prefixed_string(reader, context)?;

        // The resolved i32 isn't carried by Value::EnumValue itself (that AST
        // node only has enum_name/value/position — see Compiler/AST/values.rs).
        // We still need to consume these 4 bytes off the wire since we wrote
        // them (see encode_enum); the resolved int is redundant here because
        // from_ast re-derives it from @ENUMS via enum_name+field_name anyway,
        // the same way it does for a freshly-parsed source file.
        let mut resolved_buf = [0u8; 4];
        reader.read_exact(&mut resolved_buf)?;

        Ok(Value::EnumValue { enum_name, value: field_name, position: Position::UNKNOWN })
    }
}

impl Default for ValueDecoder {
    fn default() -> Self { Self::new() }
            }