bat-cli 0.12.1

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

use std::fs;

pub mod functions;
pub mod sonar_interactive;
pub mod structs;

use regex::Regex;

#[derive(Debug)]
pub struct BatSonarError;

impl fmt::Display for BatSonarError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("Sonar error")
    }
}

impl Error for BatSonarError {}

#[derive(Clone, Debug)]
pub struct BatSonar {
    pub content: String,
    pub result_type: SonarResultType,
    pub results: Vec<SonarResult>,
    open_filters: SonarFilter,
    end_of_open_filters: SonarFilter,
    closure_filters: SonarFilter,
}

impl BatSonar {
    fn new(content: &str, result_type: SonarResultType) -> Self {
        BatSonar {
            content: content.to_string(),
            results: vec![],
            result_type,
            open_filters: SonarFilter::Open(result_type),
            end_of_open_filters: SonarFilter::EndOfOpen(result_type),
            closure_filters: SonarFilter::Closure(result_type),
        }
    }

    pub fn new_scanned(content: &str, result_type: SonarResultType) -> Self {
        let mut new_sonar = BatSonar::new(content, result_type);
        new_sonar.scan_content_to_get_results();
        new_sonar
    }

    pub fn new_from_path(
        path: &str,
        starting_line_content: Option<&str>,
        result_type: SonarResultType,
    ) -> Self {
        let content = fs::read_to_string(path).unwrap();

        let mut new_sonar = BatSonar::new(&content, result_type);

        if let Some(starting_content) = starting_line_content {
            let start_line_index = content
                .lines()
                .position(|line| line.contains(starting_content));
            if let Some(start_line_index) = start_line_index {
                let first_line = content
                    .lines()
                    .find(|line| line.contains(starting_content))
                    .unwrap();
                let trailing_whitespaces = Self::get_trailing_whitespaces(first_line);
                let end_line_index =
                    new_sonar.get_end_line_index(start_line_index, trailing_whitespaces, "");
                if let Some(end_line_index) = end_line_index {
                    let new_content =
                        new_sonar.get_result_content(start_line_index, end_line_index);
                    new_sonar.content = new_content;
                } else {
                    // Could not find closing delimiter; return empty results
                    return new_sonar;
                }
            } else {
                // starting_line_content not found in file; return empty results
                return new_sonar;
            }
        }
        new_sonar.scan_content_to_get_results();
        new_sonar
    }

    /// Creates a BatSonar from a file path using exact line ranges from metadata.
    /// This is more robust than `new_from_path` with string matching — it uses
    /// `start_line_index` and `end_line_index` (1-based) to extract the exact function content.
    pub fn new_from_path_with_lines(
        path: &str,
        start_line: usize,
        end_line: usize,
        result_type: SonarResultType,
    ) -> Self {
        let content = fs::read_to_string(path).unwrap();
        let lines: Vec<&str> = content.lines().collect();

        // Convert from 1-based to 0-based indices
        let start_idx = if start_line > 0 { start_line - 1 } else { 0 };
        let end_idx = end_line.min(lines.len());

        let function_content = lines[start_idx..end_idx].join("\n");
        let mut new_sonar = BatSonar::new(&function_content, result_type);
        new_sonar.scan_content_to_get_results();
        new_sonar
    }

    pub fn scan_content_to_get_results(&mut self) {
        let content_lines = self.content.lines();
        for (line_index, line) in content_lines.enumerate() {
            if self.check_is_opening(line) {
                if self.result_type.test_last_char_is_semicolon() {
                    let last_line_is_semicolon = line.ends_with(';');
                    if last_line_is_semicolon {
                        continue;
                    }
                }
                let trailing_whitespaces = Self::get_trailing_whitespaces(line);
                let start_line_index = line_index;
                let end_line_index =
                    self.get_end_line_index(start_line_index, trailing_whitespaces, line);
                if end_line_index.is_none() {
                    continue;
                }
                let end_line_index = end_line_index.unwrap();
                let result_content = self.get_result_content(start_line_index, end_line_index);
                let mut sonar_result = SonarResult::new(
                    "",
                    &result_content,
                    trailing_whitespaces,
                    self.result_type,
                    start_line_index,
                    end_line_index,
                    true,
                );
                if !sonar_result.is_valid_result() {
                    continue;
                }
                // The context account filter duplicates the accouns starting with #[account(
                if self.result_type == SonarResultType::ContextAccountsNoValidation
                    && !self.results.is_empty()
                {
                    let last_result = self.results.clone();
                    let last_result = last_result.last().unwrap();
                    let last_line = last_result.content.clone();
                    let last_line = last_line.lines().last().unwrap();
                    if last_line == sonar_result.content {
                        continue;
                    }
                }
                sonar_result.format_result();
                self.results.push(sonar_result);
            }
        }
    }

    fn get_result_content(&self, start_line_index: usize, end_line_index: usize) -> String {
        let result_content = self.content.lines().collect::<Vec<_>>()
            [start_line_index..=end_line_index]
            .to_vec()
            .join("\n");
        result_content
    }

    fn get_end_line_index(
        &self,
        start_index: usize,
        trailing_whitespaces: usize,
        starting_line: &str,
    ) -> Option<usize> {
        if (self.result_type == SonarResultType::Validation
            || self.result_type == SonarResultType::Struct
            || self.result_type == SonarResultType::ContextAccountsNoValidation)
            && self.starting_line_contains_closure_filter(starting_line)
        {
            log::debug!("starting_line_contains_closure_filter");
            log::debug!("result_type; {}", self.result_type.to_string());
            log::debug!("starting_line; {}", starting_line);
            return Some(start_index);
        }
        let closing_line_candidates = self.get_closing_lines_candidates(trailing_whitespaces);
        if self.result_type.is_context_accounts_sonar_result_type() {
            let closing_index = self.content.clone().lines().enumerate().position(|line| {
                closing_line_candidates
                    .iter()
                    .any(|candidate| line.1.contains(candidate))
                    && line.0 > start_index
            });
            return closing_index;
        }
        let closing_index = self.content.clone().lines().enumerate().position(|line| {
            closing_line_candidates
                .iter()
                .any(|candidate| line.1 == candidate)
                && line.0 > start_index
        });
        closing_index
    }

    fn starting_line_contains_closure_filter(&self, starting_line: &str) -> bool {
        self.closure_filters
            .get_filters()
            .iter()
            .any(|filter| starting_line.contains(filter))
    }

    fn get_closing_lines_candidates(&self, trailing_whitespaces: usize) -> Vec<String> {
        self.closure_filters
            .get_filters()
            .iter()
            .map(|filter| format!("{}{}", " ".repeat(trailing_whitespaces), filter))
            .collect()
    }

    pub fn get_trailing_whitespaces(line: &str) -> usize {
        let trailing_whitespaces: usize = line
            .chars()
            .take_while(|ch| ch.is_whitespace() && *ch != '\n')
            .map(|ch| ch.len_utf8())
            .sum();
        trailing_whitespaces
    }

    fn check_is_opening(&self, line: &str) -> bool {
        let open_filters = self.open_filters.get_filters();
        let end_of_open_filters = self.end_of_open_filters.get_filters();
        if !open_filters.iter().any(|filter| line.contains(filter)) {
            return false;
        }
        if !end_of_open_filters
            .iter()
            .any(|filter| line.contains(filter))
        {
            return false;
        }
        // Check if open is the preffix of the line
        for filter in open_filters {
            let suffix_strip = line.trim().strip_prefix(filter);
            if suffix_strip.is_some() {
                return true;
            }
        }
        false
    }
}

#[derive(Clone, Debug)]
pub struct SonarResult {
    pub name: String,
    pub content: String,
    pub trailing_whitespaces: usize,
    pub result_type: SonarResultType,
    pub start_line_index: usize,
    pub end_line_index: usize,
    pub is_public: bool,
}

impl SonarResult {
    pub fn new(
        name: &str,
        content: &str,
        trailing_whitespaces: usize,
        result_type: SonarResultType,
        start_line_index: usize,
        end_line_index: usize,
        is_public: bool,
    ) -> Self {
        SonarResult {
            name: name.to_string(),
            content: content.to_string(),
            trailing_whitespaces,
            result_type,
            start_line_index,
            end_line_index,
            is_public,
        }
    }

    pub fn is_valid_result(&self) -> bool {
        match self.result_type {
            SonarResultType::IfValidation => self.is_valid_if_validation(),
            _ => true,
        }
    }

    pub fn format_result(&mut self) {
        match self.result_type {
            SonarResultType::Function => self.get_name(),
            SonarResultType::Struct => self.get_name(),
            SonarResultType::Enum => self.get_name(),
            SonarResultType::Module => self.get_name(),
            SonarResultType::Trait => self.get_name(),
            SonarResultType::TraitImpl => self.get_name(),
            SonarResultType::ContextAccountsNoValidation => {
                self.get_name();
                self.format_ca_no_validations()
            }
            _ => {}
        }
    }

    fn get_name(&mut self) {
        match self.result_type {
            SonarResultType::Function
            | SonarResultType::Struct
            | SonarResultType::Module
            | SonarResultType::Enum => {
                // Try syn first
                if let Some((name, is_public)) = self.try_syn_get_name() {
                    self.name = name;
                    self.is_public = is_public;
                    return;
                }
                // Fallback to string splitting
                let first_line = self.content.clone();
                let first_line = first_line.lines().next().unwrap();
                let mut first_line_tokenized = first_line.trim().split(' ');
                let is_public = first_line_tokenized.next().unwrap().contains("pub");
                if is_public {
                    first_line_tokenized.next().unwrap();
                }
                let name_candidate = first_line_tokenized.next().unwrap();
                let name = name_candidate
                    .split('<')
                    .next()
                    .unwrap()
                    .split('(')
                    .next()
                    .unwrap();
                self.name = name.to_string();
                self.is_public = is_public;
            }
            SonarResultType::Trait => {
                if let Some((name, is_public)) = self.try_syn_get_name() {
                    self.name = name;
                    self.is_public = is_public;
                    return;
                }
                // Fallback
                let first_line = self.content.clone();
                let first_line = first_line.lines().next().unwrap();
                let mut first_line_tokenized = first_line.trim().split(' ');
                let is_public = first_line_tokenized.next().unwrap().contains("pub");
                if is_public {
                    first_line_tokenized.next().unwrap();
                }
                let name_candidate = first_line_tokenized.next().unwrap();
                let name = name_candidate
                    .split('<')
                    .next()
                    .unwrap()
                    .split(':')
                    .next()
                    .unwrap()
                    .split('{')
                    .next()
                    .unwrap();
                self.name = name.to_string();
                self.is_public = is_public;
                log::debug!("name: {}", name);
                log::debug!("is_public: {}", is_public);
            }
            SonarResultType::TraitImpl => {
                // Try syn first
                if let Ok(item_impl) = syn::parse_str::<syn::ItemImpl>(&self.content) {
                    use quote::ToTokens;
                    let self_ty = item_impl.self_ty.to_token_stream().to_string();
                    let name = if let Some((_, trait_path, _)) = &item_impl.trait_ {
                        let trait_name = trait_path.to_token_stream().to_string();
                        let normalized_trait =
                            crate::batbelt::parser::function_parser::normalize_generic_type(
                                &trait_name,
                            );
                        let normalized_self =
                            crate::batbelt::parser::function_parser::normalize_generic_type(
                                &self_ty,
                            );
                        format!("{} for {}", normalized_trait, normalized_self)
                    } else {
                        crate::batbelt::parser::function_parser::normalize_generic_type(&self_ty)
                    };
                    self.name = name.clone();
                    log::debug!("name (syn): {}", name);
                    return;
                }
                // Fallback
                let first_line = self.content.clone();
                let first_line = first_line.lines().next().unwrap();
                let lifetime_regex = Regex::new(r"&*'+[A-Za-z0-9:]+[, ]*").unwrap();
                let name = lifetime_regex
                    .replace_all(first_line, "")
                    .trim()
                    .to_string()
                    .replace("<>", "")
                    .trim_start_matches("impl")
                    .trim()
                    .trim_end_matches(" {")
                    .to_string();
                self.name = name.clone();
                log::debug!("name: {}", name);
            }
            _ => {}
        }
    }

    /// Tries to extract name and visibility using syn.
    /// Works for Function, Struct, Module, Enum, Trait.
    fn try_syn_get_name(&self) -> Option<(String, bool)> {
        // Try parsing as different syn items based on result_type
        match self.result_type {
            SonarResultType::Function => {
                if let Ok(item_fn) = syn::parse_str::<syn::ItemFn>(&self.content) {
                    let is_public = matches!(item_fn.vis, syn::Visibility::Public(_));
                    return Some((item_fn.sig.ident.to_string(), is_public));
                }
            }
            SonarResultType::Struct => {
                if let Ok(item_struct) = syn::parse_str::<syn::ItemStruct>(&self.content) {
                    let is_public = matches!(item_struct.vis, syn::Visibility::Public(_));
                    return Some((item_struct.ident.to_string(), is_public));
                }
            }
            SonarResultType::Enum => {
                if let Ok(item_enum) = syn::parse_str::<syn::ItemEnum>(&self.content) {
                    let is_public = matches!(item_enum.vis, syn::Visibility::Public(_));
                    return Some((item_enum.ident.to_string(), is_public));
                }
            }
            SonarResultType::Module => {
                if let Ok(item_mod) = syn::parse_str::<syn::ItemMod>(&self.content) {
                    let is_public = matches!(item_mod.vis, syn::Visibility::Public(_));
                    return Some((item_mod.ident.to_string(), is_public));
                }
            }
            SonarResultType::Trait => {
                if let Ok(item_trait) = syn::parse_str::<syn::ItemTrait>(&self.content) {
                    let is_public = matches!(item_trait.vis, syn::Visibility::Public(_));
                    return Some((item_trait.ident.to_string(), is_public));
                }
            }
            _ => {}
        }
        None
    }

    fn format_ca_no_validations(&mut self) {
        let content = self.content.clone();
        if !content.contains("#[account(") {
            return;
        }
        // single line, only filter the first line
        if content.lines().count() == 2 {
            let first_line = content.lines().next().unwrap();
            let first_line_formatted = first_line
                .trim_start()
                .trim_start_matches("#[account(")
                .trim_end_matches(")]");
            let first_line_tokenized = first_line_formatted.split(',');
            let first_line_filtered = first_line_tokenized
                .filter(|token| {
                    !self
                        .result_type
                        .get_context_accounts_only_validations_filters()
                        .iter()
                        .any(|filter| token.contains(filter))
                })
                .collect::<Vec<_>>();
            let last_line = content.lines().last().unwrap();
            if first_line_filtered.is_empty() {
                self.content = last_line.to_string();
            } else {
                let result_filtered = first_line_filtered.join(",");
                self.content = format!(
                    "{}#[account({})]\n{}",
                    " ".repeat(self.trailing_whitespaces),
                    result_filtered,
                    last_line
                )
            }
        } else {
            // multiline account
            let ca_filters = self
                .result_type
                .get_context_accounts_only_validations_filters();
            let lines_count = content.lines().count();
            // remove first and last line
            let filtered_lines = content.lines().collect::<Vec<_>>()[1..lines_count - 1]
                .to_vec()
                .join("\n")
                .split(",\n")
                .filter(|line| {
                    !ca_filters.iter().any(|filter| line.contains(filter)) && line.trim() != ")]"
                })
                .map(|line| line.trim_end_matches(")]").to_string())
                .collect::<Vec<String>>();
            let first_line = content.lines().next().unwrap();
            let last_line = content.lines().last().unwrap();
            if filtered_lines.is_empty() {
                self.content = last_line.to_string();
            } else if filtered_lines.len() == 1 {
                // only 1 line, convert multiline to single line
                let formatted_content = format!(
                    "{}{})]\n{}",
                    first_line.trim_end_matches('\n'),
                    filtered_lines[0].trim().trim_end_matches('\n'),
                    last_line
                );
                self.content = formatted_content
            } else {
                let filtered_lines = filtered_lines.join(",\n");
                let formatted_content = format!(
                    "{}\n{})]\n{}",
                    first_line,
                    filtered_lines,
                    // " ".repeat(self.trailing_whitespaces),
                    last_line
                );
                self.content = formatted_content
            }
        }
    }

    fn is_valid_if_validation(&self) -> bool {
        let bat_sonar = BatSonar::new_scanned(&self.content, SonarResultType::Validation);
        !bat_sonar.results.is_empty()
    }
}

#[derive(Clone, Debug, Copy, PartialEq, Default, strum_macros::Display, strum_macros::EnumIter)]
pub enum SonarResultType {
    #[default]
    Function,
    Struct,
    Module,
    Enum,
    If,
    IfValidation,
    Validation,
    Trait,
    TraitImpl,
    ContextAccountsNoValidation,
}

impl SonarResultType {
    pub fn get_context_accounts_sonar_result_types(&self) -> Vec<SonarResultType> {
        vec![SonarResultType::ContextAccountsNoValidation]
    }

    pub fn is_context_accounts_sonar_result_type(&self) -> bool {
        self.get_context_accounts_sonar_result_types()
            .iter()
            .any(|ca_type| self == ca_type)
    }

    fn get_context_accounts_only_validations_filters(&self) -> Vec<&'static str> {
        vec![
            "has_one",
            "constraint",
            "zero",
            "owner",
            "token::mint",
            "token::authority",
            "associated_token::mint",
            "associated_token::authority",
            "address",
        ]
    }

    fn test_last_char_is_semicolon(&self) -> bool {
        [SonarResultType::Function].contains(self)
    }
}

#[derive(Clone, Debug, PartialEq)]
pub enum SonarFilter {
    Open(SonarResultType),
    EndOfOpen(SonarResultType),
    Closure(SonarResultType),
}

impl SonarFilter {
    pub fn get_filters(&self) -> Vec<&str> {
        match self {
            SonarFilter::Open(SonarResultType::Function) => vec!["fn", "pub fn", "pub(crate) fn"],
            SonarFilter::EndOfOpen(SonarResultType::Function) => vec!["("],
            SonarFilter::Closure(SonarResultType::Function) => vec!["}"],
            SonarFilter::Open(SonarResultType::Struct) => vec!["struct", "pub struct"],
            SonarFilter::EndOfOpen(SonarResultType::Struct) => vec!["{", ";"],
            SonarFilter::Closure(SonarResultType::Struct) => vec!["}", ";"],
            SonarFilter::Open(SonarResultType::Enum) => vec!["enum", "pub enum"],
            SonarFilter::EndOfOpen(SonarResultType::Enum) => vec!["{", ";"],
            SonarFilter::Closure(SonarResultType::Enum) => vec!["}", ";"],
            SonarFilter::Open(SonarResultType::Trait) => vec!["trait", "pub trait"],
            SonarFilter::EndOfOpen(SonarResultType::Trait) => vec!["{", ";"],
            SonarFilter::Closure(SonarResultType::Trait) => vec!["}", ";"],
            SonarFilter::Open(SonarResultType::TraitImpl) => vec!["impl"],
            SonarFilter::EndOfOpen(SonarResultType::TraitImpl) => vec!["{", ";"],
            SonarFilter::Closure(SonarResultType::TraitImpl) => vec!["}", ";"],
            SonarFilter::Open(SonarResultType::Module) => vec!["mod", "pub mod"],
            SonarFilter::EndOfOpen(SonarResultType::Module) => vec!["{"],
            SonarFilter::Closure(SonarResultType::Module) => vec!["}"],
            SonarFilter::Open(SonarResultType::If) => vec!["if"],
            SonarFilter::EndOfOpen(SonarResultType::If) => vec!["{"],
            SonarFilter::Closure(SonarResultType::If) => vec!["}"],
            SonarFilter::Open(SonarResultType::IfValidation) => vec!["if"],
            SonarFilter::EndOfOpen(SonarResultType::IfValidation) => vec!["{"],
            SonarFilter::Closure(SonarResultType::IfValidation) => vec!["}"],
            SonarFilter::Open(SonarResultType::Validation) => {
                vec!["require", "valid", "assert", "verify"]
            }
            SonarFilter::EndOfOpen(SonarResultType::Validation) => vec!["("],
            SonarFilter::Closure(SonarResultType::Validation) => vec![");", ")?;", ")"],
            SonarFilter::Open(SonarResultType::ContextAccountsNoValidation) => {
                vec!["pub", "#[account"]
            }
            SonarFilter::EndOfOpen(SonarResultType::ContextAccountsNoValidation) => vec!["(", ">,"],
            SonarFilter::Closure(SonarResultType::ContextAccountsNoValidation) => vec!["pub", "}"],
        }
    }
}

#[test]
fn test_get_functions() {
    let expected_second_function = "        pub fn create_game_2<'info>(
        ) -> Result<()> {
            handle_create_game_2(&ctx, key_index, free_create)
        }"
    .to_string();
    let expected_first_function = format!(
        "{}\n{}\n{}\n{}",
        "       pub fn create_game_1<'info>() -> Result<()> {",
        expected_second_function,
        "           handle_create_game_1(&ctx, key_index, free_create)",
        "       }"
    );
    let expected_third_function = "        pub fn create_fleet(
            sector: [i64; 2],
        ) -> Result<()> {
            handle_create_fleet(&ctx, key_index, stats.into(), sector)
        }"
    .to_string();

    let content = format!("{}\n\n{}", expected_first_function, expected_third_function);
    let mut bat_sonar = BatSonar::new_scanned(&content, SonarResultType::Function);
    bat_sonar.scan_content_to_get_results();
    let first_result = bat_sonar.results[0].clone();
    let second_result = bat_sonar.results[1].clone();
    let third_result = bat_sonar.results[2].clone();
    assert_eq!(first_result.content, expected_first_function);
    assert_eq!(first_result.name, "create_game_1");
    assert_eq!(second_result.content, expected_second_function);
    assert_eq!(second_result.name, "create_game_2");
    assert_eq!(third_result.content, expected_third_function);
    assert_eq!(third_result.name, "create_fleet");
}

#[test]
fn test_get_structs() {
    let expected_first_struct = "            pub struct StructName {
                handle_create_game_2(&ctx, key_index, free_create)
            }"
    .to_string();
    let expected_first_function = format!(
        "{}\n{}\n{}\n{}",
        "       pub fn create_game_1<'info>() -> Result<()> {",
        expected_first_struct,
        "           handle_create_game_1(&ctx, key_index, free_create)",
        "       }"
    );
    let expected_second_struct = "        struct create_fleet {
            sector: [i64; 2],
        ) -> Result<()> {
            handle_create_fleet(&ctx, key_index, stats.into(), sector)
        }"
    .to_string();

    let content = format!("{}\n\n{}", expected_first_function, expected_second_struct);
    let mut bat_sonar = BatSonar::new_scanned(&content, SonarResultType::Struct);
    bat_sonar.scan_content_to_get_results();
    let first_result = bat_sonar.results[0].clone();
    let second_result = bat_sonar.results[1].clone();
    assert_eq!(first_result.content, expected_first_struct);
    assert_eq!(first_result.name, "StructName");
    assert_eq!(second_result.content, expected_second_struct);
    assert_eq!(second_result.name, "create_fleet");
}
#[test]
fn test_get_enums() {
    let expected_first_enum = "            pub enum StructName {
                handle_create_game_2(&ctx, key_index, free_create)
            }"
    .to_string();
    let expected_first_function = format!(
        "{}\n{}\n{}\n{}",
        "       pub fn create_game_1<'info>() -> Result<()> {",
        expected_first_enum,
        "           handle_create_game_1(&ctx, key_index, free_create)",
        "       }"
    );
    let expected_second_enum = "        enum create_fleet {
            sector: [i64; 2],
        ) -> Result<()> {
            handle_create_fleet(&ctx, key_index, stats.into(), sector)
        }"
    .to_string();

    let content = format!("{}\n\n{}", expected_first_function, expected_second_enum);
    let mut bat_sonar = BatSonar::new_scanned(&content, SonarResultType::Enum);
    bat_sonar.scan_content_to_get_results();
    let first_result = bat_sonar.results[0].clone();
    let second_result = bat_sonar.results[1].clone();
    assert_eq!(first_result.content, expected_first_enum);
    assert_eq!(first_result.name, "StructName");
    assert_eq!(second_result.content, expected_second_enum);
    assert_eq!(second_result.name, "create_fleet");
}
#[test]
fn test_get_modules() {
    let expected_first_mod = "            pub mod modName {
                handle_create_game_2(&ctx, key_index, free_create)
            }"
    .to_string();
    let expected_first_function = format!(
        "{}\n{}\n{}\n{}",
        "       pub fn create_game_1<'info>() -> Result<()> {",
        expected_first_mod,
        "           handle_create_game_1(&ctx, key_index, free_create)",
        "       }"
    );
    let expected_second_mod = "        mod create_fleet {
            sector: [i64; 2],
        ) -> Result<()> {
            handle_create_fleet(&ctx, key_index, stats.into(), sector)
        }"
    .to_string();

    let content = format!("{}\n\n{}", expected_first_function, expected_second_mod);
    let bat_sonar = BatSonar::new_scanned(&content, SonarResultType::Module);
    let first_result = bat_sonar.results[0].clone();
    let second_result = bat_sonar.results[1].clone();
    assert_eq!(first_result.content, expected_first_mod);
    assert_eq!(first_result.name, "modName");
    assert_eq!(second_result.content, expected_second_mod);
    assert_eq!(second_result.name, "create_fleet");
}

#[test]
fn test_get_function_body() {
    // let function_signature = "pub fn cancel_impulse<'info>(ctx: Context<'_, '_, '_, 'info, CancelImpulse<'info>>, key_index: Option<u16>)";
    let function = "pub fn cancel_impulse<'info>()->Result<String, String> { body }";
    let body = function.split('{').collect::<Vec<_>>()[1]
        .split('}')
        .next()
        .unwrap();
    println!("body {:#?}", body)
}
#[test]
fn test_get_if() {
    let test_text = "
    if thing > 1 {
        thing is correct
    } else if {
        thing might not be correct
    } else {
        thing is cool
    }

    this is not an if, even knowing i'm writing if {
        and it looks like an if
    }

    if the_if_dont_get_else {
        and is detected
    }
    ";
    let bat_sonar = BatSonar::new_scanned(test_text, SonarResultType::If);
    println!("sonar \n{:#?}", bat_sonar);
}
#[test]
fn test_get_validation() {
    let test_text = "
    require_eq!(
        this is a valid require
    );

    require_eq!(
        this is not a valid require
    );
    ";
    let bat_sonar = BatSonar::new_scanned(test_text, SonarResultType::Validation);
    println!("sonar \n{:#?}", bat_sonar);
}
#[test]
fn test_get_context_accounts_no_validations() {
    let test_text = "
    #[derive(Accounts, Debug)]
    pub struct thing<'info> {
        pub acc_1: Signer<'info>,
    
        #[account(has_one = thing)]
        pub acc_2: AccountLoader<'info, Pf>,
    
        #[account(mut)]
        pub acc_3: Signer<'info>,
    
        #[account(
            mut,
            has_one = thing,
        )]
        pub acc_4: AccountLoader<'info, Rc>,
    
        #[account(
            has_one = thing,
        )]
        pub acc_5: AccountLoader<'info, A>,
    
        pub acc_6: Account<'info, Mint>,
    
        pub acc_7: Program<'info, B>,
    }
    ";
    let bat_sonar = BatSonar::new_scanned(test_text, SonarResultType::ContextAccountsNoValidation);
    assert_eq!(bat_sonar.results.len(), 7, "incorrect results length");
}