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
//! Parser for the `@DLM(...)` section.
//!
//! ```text
//! DLMSection  ::= "@DLM(" DLMList? ")"
//! DLMList     ::= DLMModule (","? DLMModule)*
//! DLMModule   ::= ModuleType ("." ModuleSubtype)?
//! ModuleType  ::= "DCompressor" | "DAuditor" | "DEncryptor"
//! ModuleSubtype ::= "gzip" | "bzip2" | "lzma"
//!                 | "diy" | "enhanced"
//!                 | "xor" | "aes128" | "aes256" | "chacha20"
//! ```
//!
//! Commas between modules are optional.

use crate::Compiler::AST::{DLMSection, DLMModule, Position, DLMModuleType, DLMModuleSubtype};
use crate::Compiler::Core::{OperationalSettings, ErrorHandlingStrategy};
use crate::ErrorManager::{ErrorManager, ParseErrorType, DebugConfig};
use crate::Compiler::Core::Tokenizer::{Token, TokenType};
use crate::Compiler::Core::Tokenizer::token::SectionId;

const MAX_ITERATIONS_PER_TOKEN: usize = 3;
const ABSOLUTE_MAX_ITERATIONS: usize = 500_000;
const MAX_STUCK_COUNT: usize = 3;

pub struct DlmSectionParser<'a> {
    tokens: &'a [Token],
    operational_settings: &'a OperationalSettings,
    error_manager: ErrorManager,
    debug_config: DebugConfig,
    position: usize,
    last_position: usize,
    stuck_count: usize,
    iteration_count: usize,
    max_iterations: usize,
    has_encountered_errors: bool,
}

impl<'a> DlmSectionParser<'a> {
    pub fn new(tokens: &'a [Token], operational_settings: &'a OperationalSettings) -> Self {
       Self::new_with_error_manager(tokens,operational_settings,ErrorManager::get_shared_instance())
    }

    pub fn new_with_error_manager(
        tokens: &'a [Token],
        operational_settings: &'a OperationalSettings,
        error_manager: ErrorManager,
    ) -> Self {

        let debug_config = DebugConfig::from_debug_mode(operational_settings.debug_mode);

        let dynamic_limit = tokens.len() * MAX_ITERATIONS_PER_TOKEN;
        let max_iterations = dynamic_limit.min(ABSOLUTE_MAX_ITERATIONS);

        if debug_config.is_enabled {
            error_manager.log_debug(&format!(
                "DLM parser: {} tokens, strategy: {:?}",
                tokens.len(),
                operational_settings.error_handling_strategy
            ));
        }

        DlmSectionParser {
            tokens,
            operational_settings,
            error_manager,
            debug_config,
            position: 0,
            last_position: usize::MAX,
            stuck_count: 0,
            iteration_count: 0,
            max_iterations,
            has_encountered_errors: false,
        }
    }

    pub fn parse_section(&mut self) -> Option<DLMSection> {
        let section_start_pos = Position::from_token(self.current());
        self.reset_parse_state();

        let mut modules = Vec::with_capacity(usize::max(2, self.tokens.len() / 10));

        if !self.match_and_consume_symbol('(') {
            let current = self.current().clone();
            self.report_error(ParseErrorType::MissingToken, "Expected '(' to start DLM section", &current);
            if self.should_halt_section() {
                return self.partial_or_none(section_start_pos);
            }
            if !self.recover_to_symbol('(', 10) {
                return self.partial_or_none(section_start_pos);
            }
        }

        if self.is_current_symbol(')') {
            self.advance();
            return Some(DLMSection::new(modules, section_start_pos));
        }

        while !self.is_at_end() && !self.is_current_symbol(')') && !self.should_terminate_loop() {
            self.track_progress();

            if self.is_stuck() {
                if !self.force_advance() {
                    break;
                }
                continue;
            }

            match self.parse_dlm_module() {
                Some(module) => {
                    if self.debug_config.is_enabled {
                        self.error_manager.log_debug(&format!("DLM: parsed module '{}'", module));
                    }
                    modules.push(module);
                }
                None => {
                    if self.should_halt_section() {
                        return self.partial_or_none(section_start_pos);
                    }
                    if self.operational_settings.error_handling_strategy == ErrorHandlingStrategy::Recover {
                        if !self.recover_to_next_module() {
                            self.ensure_progress();
                        }
                    } else {
                        self.ensure_progress();
                    }
                }
            }

            // Commas between modules are optional.
            if self.is_current_symbol(',') {
                self.advance();
            } else if self.is_current_symbol(')') {
                break;
            } else if !self.is_at_end() && !self.could_be_module_type() {
                let current = self.current().clone();
                let msg = format!(
                    "Expected ',' or ')' after DLM module, found {}",
                    current.get_token_value()
                );
                self.report_error(ParseErrorType::UnexpectedToken, &msg, &current);
                if self.should_halt_section() {
                    return self.partial_or_none(section_start_pos);
                }
                if self.operational_settings.error_handling_strategy == ErrorHandlingStrategy::Recover {
                    if !self.recover_to_next_module() {
                        self.ensure_progress();
                    }
                } else {
                    self.ensure_progress();
                }
            }
        }

        if !self.match_and_consume_symbol(')') {
            let current = self.current().clone();
            self.report_error(ParseErrorType::MissingToken, "Expected ')' to close DLM section", &current);
            if self.should_halt_section() {
                return self.partial_or_none(section_start_pos);
            }
        }

        if self.debug_config.is_enabled {
            self.error_manager.log_debug(&format!(
                "DLM section done: {} modules, errors: {}",
                modules.len(),
                self.has_encountered_errors
            ));
        }

        Some(DLMSection::new(modules, section_start_pos))
    }

    fn parse_dlm_module(&mut self) -> Option<DLMModule> {
        let module_start_pos = Position::from_token(self.current());

        let type_name = self.parse_identifier_or_keyword("Expected DLM module type (DCompressor, DAuditor, DEncryptor)")?;

        let module_type = match type_name.as_str() {
            "DCompressor" => DLMModuleType::DCompressor,
            "DAuditor"    => DLMModuleType::DAuditor,
            "DEncryptor"  => DLMModuleType::DEncryptor,
            _             => DLMModuleType::ParseError,
        };

        let mut subtype = None;

        if self.is_current_symbol('.') {
            self.advance();

            match self.parse_identifier_or_keyword("Expected DLM module subtype after '.'") {
                Some(name) => {
                    let parsed = match name.as_str() {
                        "gzip"     => DLMModuleSubtype::Gzip,
                        "bzip2"    => DLMModuleSubtype::Bzip2,
                        "lzma"     => DLMModuleSubtype::Lzma,
                        "diy"      => DLMModuleSubtype::Diy,
                        "enhanced" => DLMModuleSubtype::Enhanced,
                        "xor"      => DLMModuleSubtype::Xor,
                        "aes128"   => DLMModuleSubtype::Aes128,
                        "aes256"   => DLMModuleSubtype::Aes256,
                        "chacha20" => DLMModuleSubtype::Chacha20,
                        _          => DLMModuleSubtype::ParseError,
                    };
                    subtype = Some(parsed);
                }
                None => {
                    if self.should_halt_section() {
                        return None;
                    }
                }
            }
        }

        Some(DLMModule::new(module_type, subtype, module_start_pos))
    }

    fn parse_identifier_or_keyword(&mut self, context: &str) -> Option<String> {
        match &self.current().token_type {
            TokenType::Identifier(id) => {
                let name = id.clone();
                self.advance();
                Some(name)
            }
            TokenType::Keyword(k) => {
                let name = k.to_string();
                self.advance();
                Some(name)
            }
            _ => {
                let current = self.current().clone();
                self.report_error(ParseErrorType::UnexpectedToken, context, &current);
                None
            }
        }
    }

    #[inline]
    fn could_be_module_type(&self) -> bool {
        matches!(
            &self.current().token_type,
            TokenType::Identifier(_) | TokenType::Keyword(_)
        )
    }

    fn report_error(&mut self, error_type: ParseErrorType, message: &str, token: &Token) {
        self.has_encountered_errors = true;
        let source_line = self.reconstruct_source_line(token);
        self.error_manager.add_parse_error(
            error_type,
            message.to_string(),
            token.line,
            token.column,
            None,
            source_line,
        );
    }

    #[inline]
    fn should_halt_section(&self) -> bool {
        self.operational_settings.error_handling_strategy == ErrorHandlingStrategy::Halt
            && self.has_encountered_errors
    }

    fn partial_or_none(&self, start_pos: Position) -> Option<DLMSection> {
        if self.operational_settings.error_handling_strategy == ErrorHandlingStrategy::Halt {
            None
        } else {
            Some(DLMSection::new(Vec::new(), start_pos))
        }
    }

    fn recover_to_symbol(&mut self, symbol: char, max_steps: usize) -> bool {
        if self.operational_settings.error_handling_strategy != ErrorHandlingStrategy::Recover {
            return false;
        }
        for _ in 0..max_steps {
            if self.is_at_end() {
                return false;
            }
            if self.is_current_symbol(symbol) {
                self.advance();
                return true;
            }
            self.advance();
        }
        false
    }

    fn recover_to_next_module(&mut self) -> bool {
        if self.operational_settings.error_handling_strategy != ErrorHandlingStrategy::Recover {
            return false;
        }
        for _ in 0..50 {
            if self.is_at_end() || self.is_current_symbol(',') || self.is_current_symbol(')') {
                return true;
            }
            if self.could_be_module_type() {
                return true;
            }
            self.advance();
        }
        false
    }

    #[inline]
    fn current(&self) -> &Token {
        static EOF: Token = Token {
            token_type: TokenType::EndOfFile,
            line: 1,
            column: 1,
            section: SectionId::None,
        };
        self.tokens.get(self.position).unwrap_or(&EOF)
    }

    #[inline]
    fn is_at_end(&self) -> bool {
        self.position >= self.tokens.len()
            || matches!(self.current().token_type, TokenType::EndOfFile)
    }

    #[inline]
    fn advance(&mut self) {
        if self.position < self.tokens.len() {
            self.position += 1;
        }
    }

    #[inline]
    fn is_current_symbol(&self, symbol: char) -> bool {
        matches!(&self.current().token_type, TokenType::Symbol(s) if *s == symbol)
    }

    #[inline]
    fn match_and_consume_symbol(&mut self, symbol: char) -> bool {
        if self.is_current_symbol(symbol) {
            self.advance();
            true
        } else {
            false
        }
    }

    fn reconstruct_source_line(&self, token: &Token) -> Option<String> {
        let mut source = String::new();
        let mut col = 0usize;
        for t in self.tokens.iter().filter(|t| t.line == token.line) {
            while col < t.column {
                source.push(' ');
                col += 1;
            }
            let v = t.get_token_value();
            col += v.len();
            source.push_str(&v);
        }
        if source.is_empty() { None } else { Some(source) }
    }

    fn reset_parse_state(&mut self) {
        self.last_position = usize::MAX;
        self.stuck_count = 0;
        self.iteration_count = 0;
        self.has_encountered_errors = false;
    }

    fn track_progress(&mut self) {
        self.iteration_count += 1;
        if self.position == self.last_position {
            self.stuck_count += 1;
        } else {
            self.last_position = self.position;
            self.stuck_count = 0;
        }
    }

    #[inline]
    fn is_stuck(&self) -> bool {
        self.stuck_count >= MAX_STUCK_COUNT
    }

    fn should_terminate_loop(&self) -> bool {
        if self.iteration_count >= self.max_iterations {
            self.error_manager.log_error(&format!(
                "DLM parser exceeded {} iterations — possible infinite loop",
                self.max_iterations
            ));
            return true;
        }
        false
    }

    fn force_advance(&mut self) -> bool {
        if self.is_at_end() {
            return false;
        }
        self.advance();
        self.stuck_count = 0;
        true
    }

    #[inline]
    fn ensure_progress(&mut self) {
        if !self.is_at_end() {
            self.advance();
        }
    }
}