ast-grep-config 0.43.0

Search and Rewrite code at large scale using precise AST pattern
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
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
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
use crate::GlobalRules;

use crate::check_var::{check_rewriters_in_transform, CheckHint};
use crate::fixer::Fixer;
use crate::label::{get_default_labels, get_labels_from_config, Label, LabelConfig};
use crate::rule::DeserializeEnv;
use crate::rule_core::{RuleCore, RuleCoreError, SerializableRuleCore};

use ast_grep_core::language::Language;
use ast_grep_core::replacer::Replacer;
use ast_grep_core::source::Content;
use ast_grep_core::{Doc, Matcher, NodeMatch};

use schemars::{json_schema, JsonSchema, Schema, SchemaGenerator};
use serde::{Deserialize, Serialize};
use serde_yaml::Error as YamlError;
use serde_yaml::{with::singleton_map_recursive::deserialize, Deserializer};
use thiserror::Error;

use std::borrow::Cow;
use std::collections::HashMap;
use std::ops::{Deref, DerefMut};

#[derive(Serialize, Deserialize, Clone, Default, JsonSchema, Debug)]
#[serde(rename_all = "camelCase")]
pub enum Severity {
  #[default]
  /// A kind reminder for code with potential improvement.
  Hint,
  /// A suggestion that code can be improved or optimized.
  Info,
  /// A warning that code might produce bugs or does not follow best practice.
  Warning,
  /// An error that code produces bugs or has logic errors.
  Error,
  /// Turns off the rule.
  Off,
}

#[derive(Debug, Error)]
pub enum RuleConfigError {
  #[error("Fail to parse yaml as RuleConfig")]
  Yaml(#[from] YamlError),
  #[error("Fail to parse yaml as Rule.")]
  Core(#[from] RuleCoreError),
  #[error("Rewriter rule `{1}` is not configured correctly.")]
  Rewriter(#[source] RuleCoreError, String),
  #[error("Undefined rewriter `{0}` used in transform.")]
  UndefinedRewriter(String),
  #[error("Rewriter rule `{0}` should have `fix`.")]
  NoFixInRewriter(String),
  #[error("Label meta-variable `{0}` must be defined in `rule` or `constraints`.")]
  LabelVariable(String),
  #[error("Rule must specify a set of AST kinds to match. Try adding `kind` rule.")]
  MissingPotentialKinds,
}

#[derive(Serialize, Deserialize, Clone, JsonSchema)]
pub struct SerializableRewriter {
  #[serde(flatten)]
  pub core: SerializableRuleCore,
  /// Unique, descriptive identifier, e.g., no-unused-variable
  pub id: String,
}

#[derive(Serialize, Deserialize, Clone, JsonSchema)]
#[schemars(title = "ast-grep rule")]
pub struct SerializableRuleConfig<L: Language> {
  #[serde(flatten)]
  pub core: SerializableRuleCore,
  /// Unique, descriptive identifier, e.g., no-unused-variable
  #[serde(default)]
  pub id: String,
  /// Specify the language to parse and the file extension to include in matching.
  pub language: L,
  /// Rewrite rules for `rewrite` transformation
  pub rewriters: Option<Vec<SerializableRewriter>>,
  /// Main message highlighting why this rule fired. It should be single line and concise,
  /// but specific enough to be understood without additional context.
  #[serde(default)]
  pub message: String,
  /// Additional notes to elaborate the message and provide potential fix to the issue.
  /// `notes` can contain markdown syntax, but it cannot reference meta-variables.
  pub note: Option<String>,
  /// One of: hint, info, warning, or error
  #[serde(default)]
  pub severity: Severity,
  /// Custom label dictionary to configure reporting. Key is the meta-variable name and
  /// value is the label message and label style.
  pub labels: Option<HashMap<String, LabelConfig>>,
  /// Glob patterns to specify that the rule only applies to matching files
  pub files: Option<Vec<RuleFileGlob>>,
  /// Glob patterns that exclude rules from applying to files
  pub ignores: Option<Vec<RuleFileGlob>>,
  /// Documentation link to this rule
  pub url: Option<String>,
  /// Extra information for the rule
  pub metadata: Option<Metadata>,
}
#[derive(Serialize, Deserialize, Clone, JsonSchema)]
#[serde(untagged)]
pub enum RuleFileGlob {
  /// A glob pattern string
  Glob(String),
  #[serde(rename_all = "camelCase")]
  Config {
    /// A glob pattern string
    glob: String,
    /// Whether the glob matching is case insensitive
    #[serde(default)]
    case_insensitive: bool,
  },
}

/// A trivial wrapper around a HashMap to work around
/// the limitation of `serde_yaml::Value` not implementing `JsonSchema`.
#[derive(Serialize, Deserialize, Clone)]
pub struct Metadata(HashMap<String, serde_yaml::Value>);

impl JsonSchema for Metadata {
  fn schema_name() -> Cow<'static, str> {
    Cow::Borrowed("Metadata")
  }
  fn schema_id() -> Cow<'static, str> {
    Cow::Borrowed("Metadata")
  }
  fn json_schema(_gen: &mut SchemaGenerator) -> Schema {
    json_schema!({
      "type": "object",
      "additionalProperties": true,
      "description": "Additional metadata for the rule, can be used to store extra information."
    })
  }
}

impl<L: Language> SerializableRuleConfig<L> {
  pub fn get_matcher(&self, globals: &GlobalRules) -> Result<RuleCore, RuleConfigError> {
    // every RuleConfig has one rewriters, and the rewriter is shared between sub-rules
    // all RuleConfigs has one common globals
    // every sub-rule has one util
    let env = DeserializeEnv::new(self.language.clone()).with_globals(globals);
    let rule = self.core.get_matcher(env.clone())?;
    self.register_rewriters(&rule, env)?;
    self.check_labels(&rule)?;
    Ok(rule)
  }

  fn check_labels(&self, rule: &RuleCore) -> Result<(), RuleConfigError> {
    let Some(labels) = &self.labels else {
      return Ok(());
    };
    // labels var must be vars with node, transform var cannot be used
    let vars = rule.defined_node_vars();
    for var in labels.keys() {
      if !vars.contains(var.as_str()) {
        return Err(RuleConfigError::LabelVariable(var.clone()));
      }
    }
    Ok(())
  }

  fn register_rewriters(
    &self,
    rule: &RuleCore,
    env: DeserializeEnv<L>,
  ) -> Result<(), RuleConfigError> {
    let Some(ser) = &self.rewriters else {
      return Ok(());
    };
    let reg = &env.registration;
    let vars = rule.defined_vars();
    for val in ser {
      if val.core.fix.is_none() {
        return Err(RuleConfigError::NoFixInRewriter(val.id.clone()));
      }
      let rewriter = val
        .core
        .get_matcher_with_hint(env.clone(), CheckHint::Rewriter(&vars))
        .map_err(|e| RuleConfigError::Rewriter(e, val.id.clone()))?;
      reg.insert_rewriter(&val.id, rewriter);
    }
    check_rewriters_in_transform(rule, reg.get_rewriters())?;
    Ok(())
  }
}

impl<L: Language> Deref for SerializableRuleConfig<L> {
  type Target = SerializableRuleCore;
  fn deref(&self) -> &Self::Target {
    &self.core
  }
}

impl<L: Language> DerefMut for SerializableRuleConfig<L> {
  fn deref_mut(&mut self) -> &mut Self::Target {
    &mut self.core
  }
}

pub struct RuleConfig<L: Language> {
  inner: SerializableRuleConfig<L>,
  pub matcher: RuleCore,
}

impl<L: Language> RuleConfig<L> {
  pub fn try_from(
    inner: SerializableRuleConfig<L>,
    globals: &GlobalRules,
  ) -> Result<Self, RuleConfigError> {
    let matcher = inner.get_matcher(globals)?;
    if matcher.potential_kinds().is_none() {
      return Err(RuleConfigError::MissingPotentialKinds);
    }
    Ok(Self { inner, matcher })
  }

  pub fn deserialize<'de>(
    deserializer: Deserializer<'de>,
    globals: &GlobalRules,
  ) -> Result<Self, RuleConfigError>
  where
    L: Deserialize<'de>,
  {
    let inner: SerializableRuleConfig<L> = deserialize(deserializer)?;
    Self::try_from(inner, globals)
  }

  pub fn get_message<D>(&self, node: &NodeMatch<D>) -> String
  where
    D: Doc,
  {
    let env = self.matcher.get_env(self.language.clone());
    let parsed = Fixer::with_transform(&self.message, &env, &self.transform).expect("should work");
    let bytes = parsed.generate_replacement(node);
    <D::Source as Content>::encode_bytes(&bytes).to_string()
  }
  pub fn get_fixer(&self) -> Result<Vec<Fixer>, RuleConfigError> {
    if let Some(fix) = &self.fix {
      let env = self.matcher.get_env(self.language.clone());
      let parsed = Fixer::parse(fix, &env, &self.transform).map_err(RuleCoreError::Fixer)?;
      Ok(parsed)
    } else {
      Ok(vec![])
    }
  }
  pub fn get_labels<'t, D: Doc>(&self, node: &NodeMatch<'t, D>) -> Vec<Label<'_, 't, D>> {
    if let Some(labels_config) = &self.labels {
      get_labels_from_config(labels_config, node)
    } else {
      get_default_labels(node)
    }
  }
}
impl<L: Language> Deref for RuleConfig<L> {
  type Target = SerializableRuleConfig<L>;
  fn deref(&self) -> &Self::Target {
    &self.inner
  }
}

impl<L: Language> DerefMut for RuleConfig<L> {
  fn deref_mut(&mut self) -> &mut Self::Target {
    &mut self.inner
  }
}

#[cfg(test)]
mod test {
  use super::*;
  use crate::from_str;
  use crate::test::TypeScript;
  use crate::{SerializableGlobalRule, SerializableRule};
  use ast_grep_core::tree_sitter::LanguageExt;

  fn ts_rule_config(rule: SerializableRule) -> SerializableRuleConfig<TypeScript> {
    let core = SerializableRuleCore {
      rule,
      constraints: None,
      transform: None,
      utils: None,
      fix: None,
    };
    SerializableRuleConfig {
      core,
      id: "".into(),
      language: TypeScript::Tsx,
      rewriters: None,
      message: "".into(),
      note: None,
      severity: Severity::Hint,
      labels: None,
      files: None,
      ignores: None,
      url: None,
      metadata: None,
    }
  }

  fn ts_global_rules(yaml: &str) -> GlobalRules {
    let globals: Vec<SerializableGlobalRule<TypeScript>> =
      from_str(yaml).expect("should parse globals");
    DeserializeEnv::parse_global_utils(globals).expect("should parse global rules")
  }

  #[test]
  fn test_rule_message() {
    let globals = GlobalRules::default();
    let rule = from_str("pattern: class $A {}").expect("cannot parse rule");
    let mut config = ts_rule_config(rule);
    config.id = "test".into();
    config.message = "Found $A".into();
    let config = RuleConfig::try_from(config, &Default::default()).expect("should work");
    let grep = TypeScript::Tsx.ast_grep("class TestClass {}");
    let node_match = grep
      .root()
      .find(config.get_matcher(&globals).unwrap())
      .expect("should find match");
    assert_eq!(config.get_message(&node_match), "Found TestClass");
  }

  #[test]
  fn test_augmented_rule() {
    let globals = GlobalRules::default();
    let rule = from_str(
      "
pattern: console.log($A)
inside:
  stopBy: end
  pattern: function test() { $$$ }
",
    )
    .expect("should parse");
    let config = ts_rule_config(rule);
    let grep = TypeScript::Tsx.ast_grep("console.log(1)");
    let matcher = config.get_matcher(&globals).unwrap();
    assert!(grep.root().find(&matcher).is_none());
    let grep = TypeScript::Tsx.ast_grep("function test() { console.log(1) }");
    assert!(grep.root().find(&matcher).is_some());
  }

  #[test]
  fn test_multiple_augment_rule() {
    let globals = GlobalRules::default();
    let rule = from_str(
      "
pattern: console.log($A)
inside:
  stopBy: end
  pattern: function test() { $$$ }
has:
  stopBy: end
  pattern: '123'
",
    )
    .expect("should parse");
    let config = ts_rule_config(rule);
    let grep = TypeScript::Tsx.ast_grep("function test() { console.log(1) }");
    let matcher = config.get_matcher(&globals).unwrap();
    assert!(grep.root().find(&matcher).is_none());
    let grep = TypeScript::Tsx.ast_grep("function test() { console.log(123) }");
    assert!(grep.root().find(&matcher).is_some());
  }

  #[test]
  fn test_rule_env() {
    let globals = GlobalRules::default();
    let rule = from_str(
      "
all:
  - pattern: console.log($A)
  - inside:
      stopBy: end
      pattern: function $B() {$$$}
",
    )
    .expect("should parse");
    let config = ts_rule_config(rule);
    let grep = TypeScript::Tsx.ast_grep("function test() { console.log(1) }");
    let node_match = grep
      .root()
      .find(config.get_matcher(&globals).unwrap())
      .expect("should found");
    let env = node_match.get_env();
    let a = env.get_match("A").expect("should exist").text();
    assert_eq!(a, "1");
    let b = env.get_match("B").expect("should exist").text();
    assert_eq!(b, "test");
  }

  #[test]
  fn test_parameterized_global_rule_exports_argument_env_only() {
    let globals = ts_global_rules(
      r"
- id: global-rule
  arguments: [export-var]
  language: Tsx
  rule:
    pattern: Some($A)
    matches: export-var
",
    );
    let rule = from_str(
      r"
matches:
  global-rule:
    export-var:
      pattern: $EXP
",
    )
    .expect("should parse");
    let config = ts_rule_config(rule);
    let grep = TypeScript::Tsx.ast_grep("let value = Some(123)");
    let node_match = grep
      .root()
      .find(config.get_matcher(&globals).unwrap())
      .expect("should found");
    let env = node_match.get_env();
    let exp = env.get_match("EXP").expect("should export argument").text();
    assert_eq!(exp, "Some(123)");
    assert!(env.get_match("A").is_none());
  }

  #[test]
  fn test_parameterized_global_rule_does_not_interfere_with_same_name_local_var() {
    let globals = ts_global_rules(
      r"
- id: global-rule
  arguments: [export-var]
  language: Tsx
  rule:
    pattern: Some($A)
    matches: export-var
",
    );
    let rule = from_str(
      r"
all:
  - pattern: $A
  - matches:
      global-rule:
        export-var:
          pattern: $EXP
",
    )
    .expect("should parse");
    let config = ts_rule_config(rule);
    let grep = TypeScript::Tsx.ast_grep("Some(123)");
    let node_match = grep
      .root()
      .find(config.get_matcher(&globals).unwrap())
      .expect("should found");
    let env = node_match.get_env();
    let a = env.get_match("A").expect("should keep local A").text();
    assert_eq!(a, "Some(123)");
    let exp = env.get_match("EXP").expect("should export argument").text();
    assert_eq!(exp, "Some(123)");
  }

  #[test]
  fn test_parameterized_global_rule_metavar_does_not_affect_yaml_rule_matching() {
    let globals = ts_global_rules(
      r"
- id: global-rule
  arguments: [export-var]
  language: Tsx
  rule:
    pattern: Some($A)
    matches: export-var
",
    );
    let rule = from_str(
      r"
all:
  - pattern: wrapper($A)
  - has:
      stopBy: end
      matches:
        global-rule:
          export-var:
            pattern: $EXP
",
    )
    .expect("should parse");
    let config = ts_rule_config(rule);
    let grep = TypeScript::Tsx.ast_grep("wrapper(Some(123))");
    let node_match = grep
      .root()
      .find(config.get_matcher(&globals).unwrap())
      .expect("should found");
    let env = node_match.get_env();
    let a = env.get_match("A").expect("should keep yaml A").text();
    assert_eq!(a, "Some(123)");
    let exp = env.get_match("EXP").expect("should export argument").text();
    assert_eq!(exp, "Some(123)");
  }

  #[test]
  fn test_parameterized_global_rule_argument_vars_do_not_conflict_with_internal_vars() {
    let globals = ts_global_rules(
      r"
- id: global-rule
  arguments: [export-var]
  language: Tsx
  rule:
    pattern: Some($A)
    matches: export-var
",
    );
    let rule = from_str(
      r"
matches:
  global-rule:
    export-var:
      pattern: $A
",
    )
    .expect("should parse");
    let config = ts_rule_config(rule);
    let grep = TypeScript::Tsx.ast_grep("Some(123)");
    let node_match = grep
      .root()
      .find(config.get_matcher(&globals).unwrap())
      .expect("should found");
    let env = node_match.get_env();
    let a = env.get_match("A").expect("should export caller A").text();
    assert_eq!(a, "Some(123)");
  }

  #[test]
  fn test_local_util_metavar_does_affect_yaml_rule_matching() {
    let rule: SerializableRuleConfig<TypeScript> = from_str(
      r"
id: test
language: Tsx
rule:
  all:
    - pattern: $A
    - matches: local-rule
utils:
  local-rule:
    pattern: Some($A)
",
    )
    .expect("should parse");
    let rule = RuleConfig::try_from(rule, &Default::default()).expect("should work");
    let grep = TypeScript::Tsx.ast_grep("Some(123)");
    assert!(grep.root().find(&rule.matcher).is_none());
  }

  #[test]
  fn test_transform() {
    let globals = GlobalRules::default();
    let rule = from_str("pattern: console.log($A)").expect("should parse");
    let mut config = ts_rule_config(rule);
    let transform = from_str(
      "
B:
  substring:
    source: $A
    startChar: 1
    endChar: -1
",
    )
    .expect("should parse");
    config.transform = Some(transform);
    let grep = TypeScript::Tsx.ast_grep("function test() { console.log(123) }");
    let node_match = grep
      .root()
      .find(config.get_matcher(&globals).unwrap())
      .expect("should found");
    let env = node_match.get_env();
    let a = env.get_match("A").expect("should exist").text();
    assert_eq!(a, "123");
    let b = env.get_transformed("B").expect("should exist");
    assert_eq!(b, b"2");
  }

  fn get_matches_config() -> SerializableRuleConfig<TypeScript> {
    let rule = from_str(
      "
matches: test-rule
",
    )
    .unwrap();
    let utils = from_str(
      "
test-rule:
  pattern: some($A)
",
    )
    .unwrap();
    let mut ret = ts_rule_config(rule);
    ret.utils = Some(utils);
    ret
  }

  #[test]
  fn test_utils_rule() {
    let globals = GlobalRules::default();
    let config = get_matches_config();
    let matcher = config.get_matcher(&globals).unwrap();
    let grep = TypeScript::Tsx.ast_grep("some(123)");
    assert!(grep.root().find(&matcher).is_some());
    let grep = TypeScript::Tsx.ast_grep("some()");
    assert!(grep.root().find(&matcher).is_none());
  }
  #[test]
  fn test_get_fixer() {
    let globals = GlobalRules::default();
    let mut config = get_matches_config();
    config.fix = Some(from_str("string!!").unwrap());
    let rule = RuleConfig::try_from(config, &globals).unwrap();
    let fixer = rule.get_fixer().unwrap().remove(0);
    let grep = TypeScript::Tsx.ast_grep("some(123)");
    let nm = grep.root().find(&rule.matcher).unwrap();
    let replacement = fixer.generate_replacement(&nm);
    assert_eq!(String::from_utf8_lossy(&replacement), "string!!");
  }

  #[test]
  fn test_add_rewriters() {
    let rule: SerializableRuleConfig<TypeScript> = from_str(
      r"
id: test
rule: {pattern: 'a = $A'}
language: Tsx
transform:
  B:
    rewrite:
      rewriters: [re]
      source: $A
rewriters:
- id: re
  rule: {kind: number}
  fix: yjsnp
    ",
    )
    .expect("should parse");
    let rule = RuleConfig::try_from(rule, &Default::default()).expect("work");
    let grep = TypeScript::Tsx.ast_grep("a = 123");
    let nm = grep.root().find(&rule.matcher).unwrap();
    let b = nm.get_env().get_transformed("B").expect("should have");
    assert_eq!(String::from_utf8_lossy(b), "yjsnp");
  }

  #[test]
  fn test_rewriters_access_utils() {
    let rule: SerializableRuleConfig<TypeScript> = from_str(
      r"
id: test
rule: {pattern: 'a = $A'}
language: Tsx
utils:
  num: { kind: number }
transform:
  B:
    rewrite:
      rewriters: [re]
      source: $A
rewriters:
- id: re
  rule: {matches: num, pattern: $NOT}
  fix: yjsnp
    ",
    )
    .expect("should parse");
    let rule = RuleConfig::try_from(rule, &Default::default()).expect("work");
    let grep = TypeScript::Tsx.ast_grep("a = 456");
    let nm = grep.root().find(&rule.matcher).unwrap();
    let b = nm.get_env().get_transformed("B").expect("should have");
    assert!(nm.get_env().get_match("NOT").is_none());
    assert_eq!(String::from_utf8_lossy(b), "yjsnp");
  }

  #[test]
  fn test_rewriter_utils_should_not_pollute_registration() {
    let rule: SerializableRuleConfig<TypeScript> = from_str(
      r"
id: test
rule: {matches: num}
language: Tsx
transform:
  B:
    rewrite:
      rewriters: [re]
      source: $B
rewriters:
- id: re
  rule: {matches: num}
  fix: yjsnp
  utils:
    num: { kind: number }
    ",
    )
    .expect("should parse");
    let ret = RuleConfig::try_from(rule, &Default::default());
    assert!(matches!(ret, Err(RuleConfigError::Core(_))));
  }

  #[test]
  fn test_rewriter_should_have_fix() {
    let rule: SerializableRuleConfig<TypeScript> = from_str(
      r"
id: test
rule: {kind: number}
language: Tsx
rewriters:
- id: wrong
  rule: {matches: num}",
    )
    .expect("should parse");
    let ret = RuleConfig::try_from(rule, &Default::default());
    match ret {
      Err(RuleConfigError::NoFixInRewriter(name)) => assert_eq!(name, "wrong"),
      _ => panic!("unexpected error"),
    }
  }

  #[test]
  fn test_utils_in_rewriter_should_work() {
    let rule: SerializableRuleConfig<TypeScript> = from_str(
      r"
id: test
rule: {pattern: 'a = $A'}
language: Tsx
transform:
  B:
    rewrite:
      rewriters: [re]
      source: $A
rewriters:
- id: re
  rule: {matches: num}
  fix: yjsnp
  utils:
    num: { kind: number }
    ",
    )
    .expect("should parse");
    let rule = RuleConfig::try_from(rule, &Default::default()).expect("work");
    let grep = TypeScript::Tsx.ast_grep("a = 114514");
    let nm = grep.root().find(&rule.matcher).unwrap();
    let b = nm.get_env().get_transformed("B").expect("should have");
    assert_eq!(String::from_utf8_lossy(b), "yjsnp");
  }

  #[test]
  fn test_use_rewriter_recursive() {
    let rule: SerializableRuleConfig<TypeScript> = from_str(
      r"
id: test
rule: {pattern: 'a = $A'}
language: Tsx
transform:
  B: { rewrite: { rewriters: [re], source: $A } }
rewriters:
- id: handle-num
  rule: {regex: '114'}
  fix: '1919810'
- id: re
  rule: {kind: number, pattern: $A}
  transform:
    B: { rewrite: { rewriters: [handle-num], source: $A } }
  fix: $B
    ",
    )
    .expect("should parse");
    let rule = RuleConfig::try_from(rule, &Default::default()).expect("work");
    let grep = TypeScript::Tsx.ast_grep("a = 114514");
    let nm = grep.root().find(&rule.matcher).unwrap();
    let b = nm.get_env().get_transformed("B").expect("should have");
    assert_eq!(String::from_utf8_lossy(b), "1919810");
  }

  fn make_undefined_error(src: &str) -> String {
    let rule: SerializableRuleConfig<TypeScript> = from_str(src).expect("should parse");
    let err = RuleConfig::try_from(rule, &Default::default());
    match err {
      Err(RuleConfigError::UndefinedRewriter(name)) => name,
      _ => panic!("unexpected parsing result"),
    }
  }

  #[test]
  fn test_undefined_rewriter() {
    let undefined = make_undefined_error(
      r"
id: test
rule: {pattern: 'a = $A'}
language: Tsx
transform:
  B: { rewrite: { rewriters: [not-defined], source: $A } }
rewriters:
- id: re
  rule: {kind: number, pattern: $A}
  fix: hah
    ",
    );
    assert_eq!(undefined, "not-defined");
  }
  #[test]
  fn test_wrong_rewriter() {
    let rule: SerializableRuleConfig<TypeScript> = from_str(
      r"
id: test
rule: {pattern: 'a = $A'}
language: Tsx
rewriters:
- id: wrong
  rule: {kind: '114'}
  fix: '1919810'
    ",
    )
    .expect("should parse");
    let ret = RuleConfig::try_from(rule, &Default::default());
    match ret {
      Err(RuleConfigError::Rewriter(_, name)) => assert_eq!(name, "wrong"),
      _ => panic!("unexpected error"),
    }
  }

  #[test]
  fn test_undefined_rewriter_in_transform() {
    let undefined = make_undefined_error(
      r"
id: test
rule: {pattern: 'a = $A'}
language: Tsx
transform:
  B: { rewrite: { rewriters: [re], source: $A } }
rewriters:
- id: re
  rule: {kind: number, pattern: $A}
  transform:
    C: { rewrite: { rewriters: [nested-undefined], source: $A } }
  fix: hah
    ",
    );
    assert_eq!(undefined, "nested-undefined");
  }

  #[test]
  fn test_rewriter_use_upper_var() {
    let src = r"
id: test
rule: {pattern: '$B = $A'}
language: Tsx
transform:
  D: { rewrite: { rewriters: [re], source: $A } }
rewriters:
- id: re
  rule: {kind: number, pattern: $C}
  fix: $B.$C
    ";
    let rule: SerializableRuleConfig<TypeScript> = from_str(src).expect("should parse");
    let ret = RuleConfig::try_from(rule, &Default::default());
    assert!(ret.is_ok());
  }

  #[test]
  fn test_rewriter_use_undefined_var() {
    let src = r"
id: test
rule: {pattern: '$B = $A'}
language: Tsx
transform:
  B: { rewrite: { rewriters: [re], source: $A } }
rewriters:
- id: re
  rule: {kind: number, pattern: $C}
  fix: $D.$C
    ";
    let rule: SerializableRuleConfig<TypeScript> = from_str(src).expect("should parse");
    let ret = RuleConfig::try_from(rule, &Default::default());
    assert!(ret.is_err());
  }

  #[test]
  fn test_get_message_transform() {
    let src = r"
id: test-rule
language: Tsx
rule: { kind: string, pattern: $ARG }
transform:
  TEST: { replace: { replace: 'a', by: 'b', source: $ARG, } }
message: $TEST
    ";
    let rule: SerializableRuleConfig<TypeScript> = from_str(src).expect("should parse");
    let rule = RuleConfig::try_from(rule, &Default::default()).expect("should work");
    let grep = TypeScript::Tsx.ast_grep("a = '123'");
    let nm = grep.root().find(&rule.matcher).unwrap();
    assert_eq!(rule.get_message(&nm), "'123'");
  }

  #[test]
  fn test_get_message_transform_string() {
    let src = r"
id: test-rule
language: Tsx
rule: { kind: string, pattern: $ARG }
transform:
  TEST: replace($ARG, replace=a, by=b)
message: $TEST
    ";
    let rule: SerializableRuleConfig<TypeScript> = from_str(src).expect("should parse");
    let rule = RuleConfig::try_from(rule, &Default::default()).expect("should work");
    let grep = TypeScript::Tsx.ast_grep("a = '123'");
    let nm = grep.root().find(&rule.matcher).unwrap();
    assert_eq!(rule.get_message(&nm), "'123'");
  }

  #[test]
  fn test_complex_metadata() {
    let src = r"
id: test-rule
language: Tsx
rule: { kind: string }
metadata:
  test: [1, 2, 3]
  ";
    let rule: SerializableRuleConfig<TypeScript> = from_str(src).expect("should parse");
    let rule = RuleConfig::try_from(rule, &Default::default()).expect("should work");
    let grep = TypeScript::Tsx.ast_grep("a = '123'");
    let nm = grep.root().find(&rule.matcher);
    assert!(nm.is_some());
  }

  #[test]
  fn test_label() {
    let src = r"
id: test-rule
language: Tsx
rule: { pattern: Some($A) }
labels:
  A: { style: primary, message: 'var label' }
  ";
    let rule: SerializableRuleConfig<TypeScript> = from_str(src).expect("should parse");
    let ret = RuleConfig::try_from(rule, &Default::default());
    assert!(ret.is_ok());
    let src = r"
id: test-rule
language: Tsx
rule: { pattern: Some($A) }
labels:
  B: { style: primary, message: 'var label' }
  ";
    let rule: SerializableRuleConfig<TypeScript> = from_str(src).expect("should parse");
    let ret = RuleConfig::try_from(rule, &Default::default());
    assert!(matches!(ret, Err(RuleConfigError::LabelVariable(_))));
  }

  #[test]
  fn test_file_glob_simple_string() {
    let src = r"
id: test-rule
language: Tsx
rule: { kind: string }
files:
  - '*.ts'
  - 'src/**/*.tsx'
  ";
    let rule: SerializableRuleConfig<TypeScript> = from_str(src).expect("should parse");
    assert!(rule.files.is_some());
    let files = rule.files.as_ref().unwrap();
    assert_eq!(files.len(), 2);
    assert!(matches!(files[0], RuleFileGlob::Glob(_)));
    assert!(matches!(files[1], RuleFileGlob::Glob(_)));
  }

  #[test]
  fn test_file_glob_case_insensitive() {
    let src = r"
id: test-rule
language: Tsx
rule: { kind: string }
files:
  - glob: '*.ts'
    caseInsensitive: true
  - glob: 'README.md'
    caseInsensitive: true
  ";
    let rule: SerializableRuleConfig<TypeScript> = from_str(src).expect("should parse");
    assert!(rule.files.is_some());
    let files = rule.files.as_ref().unwrap();
    assert_eq!(files.len(), 2);
    match &files[0] {
      RuleFileGlob::Config {
        glob,
        case_insensitive,
      } => {
        assert_eq!(glob, "*.ts");
        assert!(case_insensitive);
      }
      _ => panic!("Expected Config variant"),
    }
    match &files[1] {
      RuleFileGlob::Config {
        glob,
        case_insensitive,
      } => {
        assert_eq!(glob, "README.md");
        assert!(case_insensitive);
      }
      _ => panic!("Expected Config variant"),
    }
  }

  #[test]
  fn test_file_glob_case_sensitive() {
    let src = r"
id: test-rule
language: Tsx
rule: { kind: string }
files:
  - glob: '*.ts'
    caseInsensitive: false
  ";
    let rule: SerializableRuleConfig<TypeScript> = from_str(src).expect("should parse");
    assert!(rule.files.is_some());
    let files = rule.files.as_ref().unwrap();
    assert_eq!(files.len(), 1);
    match &files[0] {
      RuleFileGlob::Config {
        glob,
        case_insensitive,
      } => {
        assert_eq!(glob, "*.ts");
        assert!(!case_insensitive);
      }
      _ => panic!("Expected Config variant"),
    }
  }

  #[test]
  fn test_file_glob_mixed_formats() {
    let src = r"
id: test-rule
language: Tsx
rule: { kind: string }
files:
  - '*.ts'
  - glob: 'README.md'
    caseInsensitive: true
  - 'src/**/*.tsx'
ignores:
  - 'test/**'
  - glob: 'BUILD'
    caseInsensitive: true
  ";
    let rule: SerializableRuleConfig<TypeScript> = from_str(src).expect("should parse");

    assert!(rule.files.is_some());
    let files = rule.files.as_ref().unwrap();
    assert_eq!(files.len(), 3);
    assert!(matches!(files[0], RuleFileGlob::Glob(_)));
    assert!(matches!(files[1], RuleFileGlob::Config { .. }));
    assert!(matches!(files[2], RuleFileGlob::Glob(_)));

    assert!(rule.ignores.is_some());
    let ignores = rule.ignores.as_ref().unwrap();
    assert_eq!(ignores.len(), 2);
    assert!(matches!(ignores[0], RuleFileGlob::Glob(_)));
    assert!(matches!(ignores[1], RuleFileGlob::Config { .. }));
  }
}