1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
// MIT License
//
// Copyright (c) 2021 Ferhat Geçdoğan All Rights Reserved.
// Distributed under the terms of the MIT License.
//
//
use {
    crate::{
        ast::{
            EliteKeywords,

            EliteASTForFunctions,
            EliteASTForSpecificTargets,

            EliteASTIfFunctions,

            EliteASTUseArguments,
            EliteASTUseFunctions,

            EliteAST,
            EliteDataTree,
            EliteDataInfos,

            ast_helpers
        },

        logger::{*},

        VALID_VERSIONS,
        VERSION
    },
};


pub struct EliteParser {
    pub(crate) init_ast : EliteAST,
    pub(crate) data_tree: EliteDataTree
}

impl EliteParser {
    pub fn parse_tokens(&mut self, tokens: &Vec<String>) {
        let mut __matched_type           = EliteKeywords       ::Undefined;
        let mut last_matched_function    = EliteASTForFunctions::Undefined;
        let mut last_matched_if_function = EliteASTIfFunctions ::Undefined;

        let mut is_variable                     = false;
        let mut is_defined                      = false;

        let mut is_for                          = false;
        let mut is_for_argument                 = false;

        let mut is_if                           = false;
        let mut is_if_function                  = false;

        let mut is_print                        = false;
        let mut is_newline                      = false;

        let mut is_use                          = false;
        let mut is_use_argument                 = false;

        let mut is_required_version             = false;
        let mut is_required_version_initializer = false;

        let mut is_data_initializer             = false;

        // Used by argument() and specific()
        let mut is_main_os                      = true ;

        let mut is_use_add_source               = false;
        let mut is_use_add_argument             = false;

        let mut count_end_of_function: u32            = 0    ;

        let mut variable_name                  = String::new();
        let mut variable_data                  = String::new();

        let mut first_if_argument              = String::new();
        let mut second_if_argument             = String::new();

        let mut use_add_source_argument        = String::new();

        let mut use_current_function           = String::new();

        for token in tokens {
            if token.is_empty() { continue; }

            let mut token = self.init_ast.to(token.trim());

            if is_defined {
                token = self.token_get(token.to_owned());

                is_defined = false;
            }
            else if crate::tokenizer::elite_tokenizer::is_variable(&token.as_str()) {
                is_defined = true;

                continue;
            }

            __matched_type = *self.init_ast.match_types(&token);

            match __matched_type {
                EliteKeywords::Set => {
                    is_variable = true;

                    continue;
                },
                EliteKeywords::As => {
                    if is_variable {
                        is_data_initializer             = true;

                        continue;
                    }

                    if is_required_version {
                        is_required_version_initializer = true;

                        continue;
                    }
                },
                EliteKeywords::For => {
                    is_for = true;

                    continue;
                },
                EliteKeywords::Print => {
                    is_print = true;

                    continue;
                },
                EliteKeywords::Println => {
                    is_print = true;
                    is_newline = true;

                    continue;
                },
                EliteKeywords::Use => {
                    is_use = true;

                    continue;
                },
                EliteKeywords::If  => {
                    is_if = true;

                    continue;
                },
                EliteKeywords::RequiredVersion => {
                    is_required_version = true;

                    continue;
                },

                // Ignoring them.
                EliteKeywords::LeftParenthese |
                EliteKeywords::RightParenthese => {},

                EliteKeywords::LeftSqBracket   => {
                    if is_main_os  {
                        count_end_of_function += 1;
                    }

                    continue;
                },
                EliteKeywords::RightSqBracket  => {
                    if count_end_of_function == 0 {
                        elite_logger::log(EliteLogType::Error,
                                          "right-sq-bracket",
                                          "unmatched bracket");
                    }

                    if is_main_os {
                        count_end_of_function -= 1;
                    }
                    else {
                        is_main_os = true;
                    }

                    if count_end_of_function == 0 {
                        is_main_os       = false;
                    }

                    continue;
                },
                _ => {
                    if !is_main_os {
                        is_newline      = false;
                        is_print        = false;
                        is_use          = false;
                        is_use_argument = false;

                        continue;
                    }

                    if crate::tokenizer::elite_tokenizer::is_data(&token.as_str()) {
                        let mut __data   = String::new();
                        let mut __format = String::new();

                        let mut is_formatter = false;

                        for character in token.chars() {
                            if is_formatter {
                                if character == '}' {
                                    is_formatter = false;

                                    __data.push_str(self.token_get(__format.clone()).as_str());

                                    __format.clear();

                                    continue;
                                }

                                __format.push(character);

                                continue;
                            }

                            if character == '{' {
                                is_formatter = true;

                                continue;
                            }

                            __data.push(character);

                            continue;
                        }

                        token = __data;
                    }

                    if is_if {
                        if token.is_empty() { continue; }

                        if is_if_function {
                            if first_if_argument.is_empty() {
                                first_if_argument = crate::ast::ast_helpers::extract_argument(&token);

                                continue;
                            }

                            if second_if_argument.is_empty() {
                                second_if_argument = crate::ast::ast_helpers::extract_argument(&token);
                            }

                            match last_matched_if_function {
                                EliteASTIfFunctions::Eq |
                                EliteASTIfFunctions::UnEq => {
                                    is_main_os = self.ast_parse_if_function(variable_name.clone(),
                                                                            crate::ast::ast_helpers::extract_argument(&first_if_argument.clone()),
                                                                            crate::ast::ast_helpers::extract_argument(&second_if_argument.clone()));
                                },
                                _ => {
                                    elite_logger::log(EliteLogType::Error,
                                                      &token,
                                                      "syntax error, \
                                                        undefined if function");
                                }
                            }

                            is_if          = false;
                            is_if_function = false;

                            first_if_argument .clear();
                            second_if_argument.clear();

                            continue;
                        }

                        if self.init_ast.match_if_functions(&token) != &EliteASTIfFunctions::Undefined {
                            is_if_function = true;

                            last_matched_if_function = *self.init_ast.match_if_functions(&token);

                            variable_name   = token.clone();
                        }
                        else {
                            elite_logger::log(EliteLogType::Error,
                                        &token, "syntax error, undefined if function");
                        }

                        continue;
                    }

                    if is_use {
                        // All 'use' functions are takes 1 argument
                        // add_source is excepted, it's requires 2 argument.
                        if is_use_add_source {
                            if is_use_add_argument {
                                let token = ast_helpers::extract_argument(&token);

                                match self.init_ast.match_use_functions(&use_current_function) {
                                    EliteASTUseFunctions::AddSource => {
                                        if !std::path::Path::new(&token).exists() {
                                            elite_logger::log(EliteLogType::Warning,
                                                              &token,  "source file is not exist");
                                        }

                                        self.token_append(use_add_source_argument.clone(),
                                                          ast_helpers::extract_argument(&token),
                                                          ' ');
                                    },
                                    EliteASTUseFunctions::Append    => {
                                        self.token_append(use_add_source_argument.clone(),
                                                          ast_helpers::extract_argument(&token),
                                                          Default::default());
                                    }
                                    _ => {}
                                }


                                is_use_add_source   = false;
                                is_use_add_argument = false;

                                use_add_source_argument.clear();

                                continue;
                            }

                            use_add_source_argument = token.clone();

                            is_use_add_argument     = true;

                            continue;
                        }

                        match self.init_ast.match_use_functions(&token).clone() {
                            EliteASTUseFunctions::AddSource |
                            EliteASTUseFunctions::Append     => {
                                is_use_add_source = true;

                                use_current_function = token.clone();

                                continue;
                            },
                            _ => {
                                is_use_add_source = false;

                                use_current_function = token.clone();
                            }
                        }

                        if is_use_argument {
                            let token: &String = &ast_helpers::extract_argument(&token);

                            for argument in &self.init_ast.ast_for_use_arguments.clone() {
                                if argument == token {
                                    self.ast_parse_use(token.to_string());
                                }
                            }

                            if token.is_empty() { continue; }


                            self.ast_parse_use_function(variable_data.clone(),
                                                        ast_helpers::extract_argument(token));


                            is_use = false;
                            is_use_argument = false;

                            continue;
                        }

                        for function in &self.init_ast.ast_for_use {
                            if function == &token {
                                is_use_argument = true;
                                variable_data = function.clone();

                                continue;
                            }
                        }
                    }

                    // Built-in regular print function.
                    if is_print {
                        print!("{}",
                               ast_helpers::extract_argument(&ast_helpers::extract_argument(&token)));

                        is_print = false;

                        if is_newline {
                            println!();

                            is_newline = false;
                        }

                        continue;
                    }

                    // for signal("...")
                    if is_for {
                        if is_for_argument {
                            let token = &(ast_helpers::extract_argument(&token));

                            match last_matched_function {
                                EliteASTForFunctions::Specific |
                                EliteASTForFunctions::Argument |
                                EliteASTForFunctions::Exists   => {
                                    is_main_os = self.ast_parse_for_functions(variable_name.clone(),
                                                                              ast_helpers::extract_argument(token));
                                },
                                _ => {
                                    self.ast_parse_for_functions(variable_name.clone(),
                                                                 ast_helpers::extract_argument(token));
                                }
                            }

                            is_for = false;
                            is_for_argument = false;

                            variable_name.clear();

                            continue;
                        }

                        if self.init_ast.match_for_functions(&token) != &EliteASTForFunctions::Undefined {
                            is_for_argument = true;
                            last_matched_function = *self.init_ast.match_for_functions(&token);

                            variable_name   = token.clone();
                        }

                        continue;
                    }

                    if is_required_version {
                        if is_required_version_initializer {
                            if crate::tokenizer::elite_tokenizer::is_data(&token.as_str()) {
                                elite_logger::log(EliteLogType::Error,
                                                  "string_notation", &*format!(
                                                      "required_version must be used with \
                                                      float literal, \
                                                      not string. \
                                                      use {} instead of \"{data}\"",
                                                            data = ast_helpers::extract_argument(&token)));
                            }

                            is_required_version             = false;
                            is_required_version_initializer = false;

                            let version       = token.parse::<f32>().unwrap();
                            let mut is_valid = false;

                            for __version in VALID_VERSIONS {
                                // Valid version
                                if __version == &version {
                                    if version > VERSION {
                                        elite_logger::log(EliteLogType::Info,
                                                          "required_version",
                                                          &*format!("required {} or latest version",
                                                                    token));

                                        std::process::exit(1);
                                    }

                                    is_valid = true;

                                    break;
                                }
                            }

                            if !is_valid {
                                elite_logger::log(EliteLogType::Error,
                                                  "invalid_version",
                                                  &*format!("invalid version: {}, \
                                                        for latest valid version: {}",
                                                            version,
                                                            VALID_VERSIONS.last().unwrap()));
                            }
                        }
                    }

                    if is_variable {
                        if is_data_initializer {
                            is_variable         = false;
                            is_data_initializer = false;

                            self.token_set(variable_name.clone(),
                                           ast_helpers::extract_argument(&token));

                            variable_name.clear();

                            continue;
                        }

                        variable_name = token.clone();
                        continue;
                    }
                }
            }
        }
    }

    pub fn ast_parse_for_functions(&mut self, function: String, argument: String) -> bool {
        match self.init_ast.match_for_functions(&function) {
            EliteASTForFunctions::Signal => {
                // TODO: Signal parser.
                false
            },
            EliteASTForFunctions::Specific => {
                self.ast_parse_for_specific_target(argument)
            },
            EliteASTForFunctions::Argument => {
                self.is_same_arg(&argument)
            },
            EliteASTForFunctions::Exists   => {
                self.is_exists(&argument)
            },
            _ => {
                elite_logger::log(EliteLogType::Error,
                                  &function,
                                  "syntax error, undefined for function");
                false
            }
        }
    }

    pub fn ast_parse_for_specific_target(&mut self, target: String) -> bool {
        match self.init_ast.match_for_specific_targets(&target) {
            // EliteASTForSpecificTargets::Windows => {
            //
            // },
            // EliteASTForSpecificTargets::macOS => {
            //
            // },
            // EliteASTForSpecificTargets::iOS => {
            //
            // },
            // EliteASTForSpecificTargets::Linux => {
            //
            // },
            // EliteASTForSpecificTargets::Android => {
            //
            // },
            // EliteASTForSpecificTargets::FreeBSD => {
            //
            // },
            // EliteASTForSpecificTargets::DragonFly => {
            //
            // },
            // EliteASTForSpecificTargets::Bitrig => {
            //
            // },
            // EliteASTForSpecificTargets ::OpenBSD => {
            //
            // },
            // EliteASTForSpecificTargets::NetBSD => {
            //
            // },
            EliteASTForSpecificTargets::Undefined => {
                elite_logger::log(EliteLogType::Error,
                                  &target,
                                  "undefined os target");

                false
            },
            _ => {
                return self.is_same(&target);
            }
        }
    }

    pub fn ast_parse_if_function(&mut self, function: String,  argument_1: String, argument_2: String) -> bool {
        match self.init_ast.match_if_functions(&function) {
            EliteASTIfFunctions::Eq => {
                self.is_same_argument(&argument_1, &argument_2)
            },
            EliteASTIfFunctions::UnEq => {
                self.is_not_same_argument(&argument_1, &argument_2)
            },
            EliteASTIfFunctions::Undefined => {
                false
            }
        }
    }

    pub fn ast_parse_use_function(&mut self, function: String, argument: String) {
        match self.init_ast.match_use_functions(&function) {
            EliteASTUseFunctions::Signal => {
                self.ast_parse_use(argument);
            },
            EliteASTUseFunctions::Exec => {
                let mut command = String::new();

                for character in argument.split(' ').collect::<Vec<_>>().get(0).unwrap().chars() {
                    if character != '"' || character != ' ' {
                        command.push(character);

                        continue;
                    }

                    break;
                }

                if argument.contains(' ') {
                    let mut arguments: Vec<&str> = argument.split(' ').collect();

                    arguments.remove(0);

                    std::process::Command::new(command.clone())
                        .args(arguments)
                        .status()
                        .expect(format!("{} command failed to execute!", command.to_owned()).as_str());
                }
                else {
                    std::process::Command::new(command.clone())
                        .status()
                        .expect(format!("{} command failed to execute!", command.to_owned()).as_str());
                }
            }
            _ => {
                elite_logger::log(EliteLogType::Error,
                                  &function,
                                  "syntax error, undefined use function");
            }
        }
    }

    pub fn ast_parse_use(&mut self, argument: String) {
        match self.init_ast.match_use_arguments(&argument) {
            EliteASTUseArguments::Exit => {
                std::process::exit(0);
            },
            _ => {
                if argument != "start" {
                    elite_logger::log(EliteLogType::Error,
                                      &format!("{}", argument),
                                      "syntax error, undefined use function");
                }
            }
        }
    }

    // Syntax rule:
    // use {VARIABLE_NAME} as {data}
    pub fn token_set(&mut self, variable: String, data: String) {
        // Check is variable exists.
        for (_index, variable_list) in self.data_tree.variable_list.iter().enumerate() {
            if variable_list.__name == variable {
                self.data_tree.variable_list[_index].__data = data.clone();

                return;
            }
        }

        self.data_tree.variable_list.push(
                EliteDataInfos {
                    __type: EliteKeywords::Set,
                    __name: variable,
                    __data: data
                }
        );
    }

    pub fn token_get(&self, variable: String) -> String {
        for variable_list in self.data_tree.variable_list.iter() {
            if variable == variable_list.__name {
                if variable_list.__type != EliteKeywords::Undefined { return String::from(variable_list.__data.clone()); }
            }
        }

        self.init_ast.to("")
    }

    pub fn token_append(&mut self, variable: String, argument: String, delimiter: char) {
        for (_index, variable_list) in self.data_tree.variable_list.iter().enumerate() {
            if variable_list.__name == variable {
                self.data_tree.variable_list[_index].__data.push_str(
                    format!("{}{}", delimiter, argument).as_str());
                return;
            }
        }
    }

    pub fn is_exists(&self, path: &String) -> bool {
        return if std::path::Path::new(path).exists() {
            true
        } else { false };
    }

    pub fn is_same_arg(&self, argument: &String) -> bool {
        let __argument: Vec<_> = std::env::args().collect();

        return if __argument.last().unwrap() == argument {
            true
        } else { false };
    }

    pub fn is_same(&self, target: &String) -> bool {
        return if std::env::consts::OS == target || std::env::consts::ARCH == target {
            true
        } else { false };
    }

    pub fn is_same_argument(&self, argument_1: &String, argument_2: &String) -> bool {
        return if argument_1 == argument_2 {
            true
        } else { false };
    }

    pub fn is_not_same_argument(&self, argument_1: &String, argument_2: &String) -> bool {
        return if argument_1 != argument_2 {
            true
        } else { false };
    }
}