darklua 0.18.0

Transform Lua scripts
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
//! A module that contains the different rules that mutates a Lua/Luau block.
//!
//! Rules are transformations that can be applied to Lua code blocks to modify their structure
//! or behavior while preserving functionality. Each rule implements the [`Rule`] trait and can
//! be configured through properties.

mod append_text_comment;
pub mod bundle;
mod call_parens;
mod compute_expression;
mod configuration_error;
mod convert_index_to_field;
mod convert_luau_number;
mod convert_require;
mod convert_square_root_call;
mod empty_do;
mod filter_early_return;
mod global_function_to_assign;
mod group_local;
mod inject_value;
mod method_def;
mod no_local_function;
mod remove_assertions;
mod remove_attribute;
mod remove_call_match;
mod remove_comments;
mod remove_compound_assign;
mod remove_continue;
mod remove_debug_profiling;
mod remove_floor_division;
mod remove_if_expression;
mod remove_interpolated_string;
mod remove_method_call;
mod remove_nil_declarations;
mod remove_spaces;
mod remove_types;
mod remove_unused_variable;
mod rename_variables;
mod replace_referenced_tokens;
pub(crate) mod require;
mod rule_property;
mod shift_token_line;
mod unused_if_branch;
mod unused_while;

pub use append_text_comment::*;
pub use call_parens::*;
pub use compute_expression::*;
pub use configuration_error::RuleConfigurationError;
pub use convert_index_to_field::*;
pub use convert_luau_number::*;
pub use convert_require::*;
pub use convert_square_root_call::*;
pub use empty_do::*;
pub use filter_early_return::*;
pub use global_function_to_assign::*;
pub use group_local::*;
pub use inject_value::*;
pub use method_def::*;
pub use no_local_function::*;
pub use remove_assertions::*;
pub use remove_attribute::*;
pub use remove_comments::*;
pub use remove_compound_assign::*;
pub use remove_continue::*;
pub use remove_debug_profiling::*;
pub use remove_floor_division::*;
pub use remove_if_expression::*;
pub use remove_interpolated_string::*;
pub use remove_method_call::*;
pub use remove_nil_declarations::*;
pub use remove_spaces::*;
pub use remove_types::*;
pub use remove_unused_variable::*;
pub use rename_variables::*;
pub(crate) use replace_referenced_tokens::*;
pub use require::PathRequireMode;
pub use rule_property::*;
pub(crate) use shift_token_line::*;
pub use unused_if_branch::*;
pub use unused_while::*;

use crate::nodes::Block;
use crate::utils::FilterPattern;
use crate::{DarkluaError, Resources};

use serde::de::{self, MapAccess, Visitor};
use serde::ser::SerializeMap;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::collections::HashMap;
use std::fmt;
use std::path::{Path, PathBuf};
use std::str::FromStr;

const APPLY_TO_FILTER_PROPERTY: &str = "apply_to_files";
const SKIP_FILTER_PROPERTY: &str = "skip_files";

/// A builder for creating a [`Context`] with optional configuration.
///
/// This builder allows for incremental construction of a [`Context`] by adding
/// blocks and project location information before building the final context.
#[derive(Debug, Clone)]
pub struct ContextBuilder<'a, 'resources, 'code> {
    path: PathBuf,
    resources: &'resources Resources,
    original_code: &'code str,
    blocks: HashMap<PathBuf, &'a Block>,
    project_location: Option<PathBuf>,
}

impl<'a, 'resources, 'code> ContextBuilder<'a, 'resources, 'code> {
    /// Creates a new context builder with the specified path, resources, and original code.
    pub fn new(
        path: impl Into<PathBuf>,
        resources: &'resources Resources,
        original_code: &'code str,
    ) -> Self {
        Self {
            path: path.into(),
            resources,
            original_code,
            blocks: Default::default(),
            project_location: None,
        }
    }

    /// Sets the project location for this context.
    pub fn with_project_location(mut self, path: impl Into<PathBuf>) -> Self {
        self.project_location = Some(path.into());
        self
    }

    /// Builds the final context with all configured options.
    pub fn build(self) -> Context<'a, 'resources, 'code> {
        Context {
            path: self.path,
            resources: self.resources,
            original_code: self.original_code,
            blocks: self.blocks,
            project_location: self.project_location,
            dependencies: Default::default(),
        }
    }

    /// Inserts a block into the context with the specified path.
    pub fn insert_block<'block: 'a>(&mut self, path: impl Into<PathBuf>, block: &'block Block) {
        self.blocks.insert(path.into(), block);
    }
}

/// A context that holds data shared across all rules applied to a file.
///
/// The context provides access to resources, file paths, and blocks that may be needed
/// during rule processing.
#[derive(Debug, Clone)]
pub struct Context<'a, 'resources, 'code> {
    path: PathBuf,
    resources: &'resources Resources,
    original_code: &'code str,
    blocks: HashMap<PathBuf, &'a Block>,
    project_location: Option<PathBuf>,
    dependencies: std::cell::RefCell<Vec<PathBuf>>,
}

impl Context<'_, '_, '_> {
    /// Returns the block associated with the given path, if any.
    pub fn block(&self, path: impl AsRef<Path>) -> Option<&Block> {
        self.blocks.get(path.as_ref()).copied()
    }

    /// Returns the path of the current file being processed.
    pub fn current_path(&self) -> &Path {
        self.path.as_ref()
    }

    /// Adds a file dependency to the context.
    ///
    /// This is used to track which files are required by the current file being processed.
    pub fn add_file_dependency(&self, path: PathBuf) {
        if let Ok(mut dependencies) = self.dependencies.try_borrow_mut() {
            log::trace!("add file dependency {}", path.display());
            dependencies.push(path);
        } else {
            log::warn!("unable to submit file dependency (internal error)");
        }
    }

    /// Consumes the context and returns an iterator over all file dependencies.
    pub fn into_dependencies(self) -> impl Iterator<Item = PathBuf> {
        self.dependencies.into_inner().into_iter()
    }

    fn resources(&self) -> &Resources {
        self.resources
    }

    fn original_code(&self) -> &str {
        self.original_code
    }

    fn project_location(&self) -> &Path {
        self.project_location.as_deref().unwrap_or_else(|| {
            let source = self.current_path();
            source.parent().unwrap_or_else(|| {
                log::warn!(
                    "unexpected file path `{}` (unable to extract parent path)",
                    source.display()
                );
                source
            })
        })
    }
}

/// The result type for rule processing operations.
pub type RuleProcessResult = Result<(), String>;

/// Defines an interface for rules that can transform Lua blocks.
///
/// Rules implement this trait to define how they process blocks and how their configuration
/// can be serialized and deserialized.
pub trait Rule: RuleConfiguration + fmt::Debug {
    /// Processes the given block to apply the rule's transformation.
    ///
    /// Returns `Ok(())` if the transformation was successful, or an error message if it failed.
    fn process(&self, block: &mut Block, context: &Context) -> RuleProcessResult;

    /// Returns a list of paths to Lua files that are required to apply this rule.
    ///
    /// These files will be loaded into the context for use during processing.
    fn require_content(&self, _current_source: &Path, _current_block: &Block) -> Vec<PathBuf> {
        Vec::new()
    }
}

/// Defines the configuration interface for rules.
///
/// This trait provides methods for configuring rules through properties and serializing
/// their configuration state.
pub trait RuleConfiguration {
    /// Configures the rule with the given properties.
    ///
    /// Returns an error if the configuration is invalid.
    fn configure(&mut self, properties: RuleProperties) -> Result<(), RuleConfigurationError>;

    /// Returns the unique name of the rule.
    fn get_name(&self) -> &'static str;

    /// Serializes the rule's configuration to properties.
    ///
    /// Only properties that differ from their default values are included.
    fn serialize_to_properties(&self) -> RuleProperties;

    /// Returns whether the rule has any non-default properties.
    fn has_properties(&self) -> bool {
        !self.serialize_to_properties().is_empty()
    }

    fn set_metadata(&mut self, metadata: RuleMetadata);

    fn metadata(&self) -> &RuleMetadata;
}

/// Metadata for a rule.
///
/// This struct contains information about the rule that is used to filter out
/// rules that are not applicable to the current context.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct RuleMetadata {
    apply_to_filters: Vec<FilterPattern>,
    skip_filters: Vec<FilterPattern>,
}

impl RuleMetadata {
    pub fn with_apply_to_filter(mut self, filter: String) -> Result<Self, DarkluaError> {
        self.push_apply_to_filter(filter)?;
        Ok(self)
    }

    pub fn push_apply_to_filter(&mut self, filter: String) -> Result<(), DarkluaError> {
        let pattern = FilterPattern::new(filter)?;
        self.apply_to_filters.push(pattern);
        Ok(())
    }

    pub fn with_skip_filter(mut self, filter: String) -> Result<Self, DarkluaError> {
        self.push_skip_filter(filter)?;
        Ok(self)
    }

    pub fn push_skip_filter(&mut self, filter: String) -> Result<(), DarkluaError> {
        let pattern = FilterPattern::new(filter)?;
        self.skip_filters.push(pattern);
        Ok(())
    }

    pub(crate) fn should_apply(&self, path: &Path) -> bool {
        if !self.apply_to_filters.is_empty()
            && self.apply_to_filters.iter().all(|f| !f.matches(path))
        {
            return false;
        }

        if !self.skip_filters.is_empty() && self.skip_filters.iter().any(|f| f.matches(path)) {
            return false;
        }

        true
    }
}

/// A trait for rules that are guaranteed to succeed without errors.
///
/// Rules implementing this trait can be automatically converted to the `Rule` trait
/// with error handling.
pub trait FlawlessRule {
    /// Processes the block without the possibility of failure.
    fn flawless_process(&self, block: &mut Block, context: &Context);
}

impl<T: FlawlessRule + RuleConfiguration + fmt::Debug> Rule for T {
    fn process(&self, block: &mut Block, context: &Context) -> RuleProcessResult {
        self.flawless_process(block, context);
        Ok(())
    }
}

/// Returns the default set of rules that preserve code functionality.
///
/// These rules are guaranteed to maintain the original behavior of the code
/// while performing their transformations.
pub fn get_default_rules() -> Vec<Box<dyn Rule>> {
    vec![
        Box::<RemoveSpaces>::default(),
        Box::<RemoveComments>::default(),
        Box::<ComputeExpression>::default(),
        Box::<RemoveUnusedIfBranch>::default(),
        Box::<RemoveUnusedWhile>::default(),
        Box::<FilterAfterEarlyReturn>::default(),
        Box::<RemoveEmptyDo>::default(),
        Box::<RemoveUnusedVariable>::default(),
        Box::<RemoveMethodDefinition>::default(),
        Box::<ConvertIndexToField>::default(),
        Box::<RemoveNilDeclaration>::default(),
        Box::<RenameVariables>::default(),
        Box::<RemoveFunctionCallParens>::default(),
    ]
}

/// Returns a list of all available rule names.
///
/// This includes both default and optional rules that can be used for code transformation.
pub fn get_all_rule_names() -> Vec<&'static str> {
    vec![
        APPEND_TEXT_COMMENT_RULE_NAME,
        COMPUTE_EXPRESSIONS_RULE_NAME,
        CONVERT_FUNCTION_TO_ASSIGNMENT_RULE_NAME,
        CONVERT_INDEX_TO_FIELD_RULE_NAME,
        CONVERT_LOCAL_FUNCTION_TO_ASSIGN_RULE_NAME,
        CONVERT_LUAU_NUMBER_RULE_NAME,
        CONVERT_REQUIRE_RULE_NAME,
        CONVERT_SQUARE_ROOT_CALL_RULE_NAME,
        FILTER_AFTER_EARLY_RETURN_RULE_NAME,
        GROUP_LOCAL_ASSIGNMENT_RULE_NAME,
        INJECT_GLOBAL_VALUE_RULE_NAME,
        REMOVE_ASSERTIONS_RULE_NAME,
        REMOVE_ATTRIBUTE_RULE_NAME,
        REMOVE_COMMENTS_RULE_NAME,
        REMOVE_COMPOUND_ASSIGNMENT_RULE_NAME,
        REMOVE_DEBUG_PROFILING_RULE_NAME,
        REMOVE_EMPTY_DO_RULE_NAME,
        REMOVE_FLOOR_DIVISION_RULE_NAME,
        REMOVE_FUNCTION_CALL_PARENS_RULE_NAME,
        REMOVE_INTERPOLATED_STRING_RULE_NAME,
        REMOVE_METHOD_CALL_RULE_NAME,
        REMOVE_METHOD_DEFINITION_RULE_NAME,
        REMOVE_NIL_DECLARATION_RULE_NAME,
        REMOVE_SPACES_RULE_NAME,
        REMOVE_TYPES_RULE_NAME,
        REMOVE_UNUSED_IF_BRANCH_RULE_NAME,
        REMOVE_UNUSED_VARIABLE_RULE_NAME,
        REMOVE_UNUSED_WHILE_RULE_NAME,
        RENAME_VARIABLES_RULE_NAME,
        REMOVE_IF_EXPRESSION_RULE_NAME,
        REMOVE_CONTINUE_RULE_NAME,
    ]
}

impl FromStr for Box<dyn Rule> {
    type Err = String;

    fn from_str(string: &str) -> Result<Self, Self::Err> {
        let rule: Box<dyn Rule> = match string {
            APPEND_TEXT_COMMENT_RULE_NAME => Box::<AppendTextComment>::default(),
            COMPUTE_EXPRESSIONS_RULE_NAME => Box::<ComputeExpression>::default(),
            CONVERT_FUNCTION_TO_ASSIGNMENT_RULE_NAME => Box::<ConvertFunctionToAssign>::default(),
            CONVERT_INDEX_TO_FIELD_RULE_NAME => Box::<ConvertIndexToField>::default(),
            CONVERT_LOCAL_FUNCTION_TO_ASSIGN_RULE_NAME => {
                Box::<ConvertLocalFunctionToAssign>::default()
            }
            CONVERT_LUAU_NUMBER_RULE_NAME => Box::<ConvertLuauNumber>::default(),
            CONVERT_REQUIRE_RULE_NAME => Box::<ConvertRequire>::default(),
            CONVERT_SQUARE_ROOT_CALL_RULE_NAME => Box::<ConvertSquareRootCall>::default(),
            FILTER_AFTER_EARLY_RETURN_RULE_NAME => Box::<FilterAfterEarlyReturn>::default(),
            GROUP_LOCAL_ASSIGNMENT_RULE_NAME => Box::<GroupLocalAssignment>::default(),
            INJECT_GLOBAL_VALUE_RULE_NAME => Box::<InjectGlobalValue>::default(),
            REMOVE_ASSERTIONS_RULE_NAME => Box::<RemoveAssertions>::default(),
            REMOVE_ATTRIBUTE_RULE_NAME => Box::<RemoveAttribute>::default(),
            REMOVE_COMMENTS_RULE_NAME => Box::<RemoveComments>::default(),
            REMOVE_COMPOUND_ASSIGNMENT_RULE_NAME => Box::<RemoveCompoundAssignment>::default(),
            REMOVE_DEBUG_PROFILING_RULE_NAME => Box::<RemoveDebugProfiling>::default(),
            REMOVE_EMPTY_DO_RULE_NAME => Box::<RemoveEmptyDo>::default(),
            REMOVE_FLOOR_DIVISION_RULE_NAME => Box::<RemoveFloorDivision>::default(),
            REMOVE_FUNCTION_CALL_PARENS_RULE_NAME => Box::<RemoveFunctionCallParens>::default(),
            REMOVE_INTERPOLATED_STRING_RULE_NAME => Box::<RemoveInterpolatedString>::default(),
            REMOVE_METHOD_CALL_RULE_NAME => Box::<RemoveMethodCall>::default(),
            REMOVE_METHOD_DEFINITION_RULE_NAME => Box::<RemoveMethodDefinition>::default(),
            REMOVE_NIL_DECLARATION_RULE_NAME => Box::<RemoveNilDeclaration>::default(),
            REMOVE_SPACES_RULE_NAME => Box::<RemoveSpaces>::default(),
            REMOVE_TYPES_RULE_NAME => Box::<RemoveTypes>::default(),
            REMOVE_UNUSED_IF_BRANCH_RULE_NAME => Box::<RemoveUnusedIfBranch>::default(),
            REMOVE_UNUSED_VARIABLE_RULE_NAME => Box::<RemoveUnusedVariable>::default(),
            REMOVE_UNUSED_WHILE_RULE_NAME => Box::<RemoveUnusedWhile>::default(),
            RENAME_VARIABLES_RULE_NAME => Box::<RenameVariables>::default(),
            REMOVE_IF_EXPRESSION_RULE_NAME => Box::<RemoveIfExpression>::default(),
            REMOVE_CONTINUE_RULE_NAME => Box::<RemoveContinue>::default(),
            _ => return Err(format!("invalid rule name: {}", string)),
        };

        Ok(rule)
    }
}

impl Serialize for dyn Rule {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let properties = self.serialize_to_properties();
        let property_count = properties.len();
        let rule_name = self.get_name();

        if property_count == 0 {
            serializer.serialize_str(rule_name)
        } else {
            let mut map = serializer.serialize_map(Some(property_count + 1))?;

            map.serialize_entry("rule", rule_name)?;

            let metadata = self.metadata();

            if !metadata.apply_to_filters.is_empty() {
                let filters = metadata
                    .apply_to_filters
                    .iter()
                    .map(|f| f.original())
                    .collect::<Vec<_>>();

                if filters.len() == 1 {
                    map.serialize_entry(APPLY_TO_FILTER_PROPERTY, &filters[0])?;
                } else {
                    map.serialize_entry(APPLY_TO_FILTER_PROPERTY, &filters)?;
                }
            }

            if !metadata.apply_to_filters.is_empty() {
                let filters = metadata
                    .skip_filters
                    .iter()
                    .map(|f| f.original())
                    .collect::<Vec<_>>();

                if filters.len() == 1 {
                    map.serialize_entry(SKIP_FILTER_PROPERTY, &filters[0])?;
                } else {
                    map.serialize_entry(SKIP_FILTER_PROPERTY, &filters)?;
                }
            }

            let mut ordered: Vec<(String, RulePropertyValue)> = properties.into_iter().collect();

            ordered.sort_by(|a, b| a.0.cmp(&b.0));

            for (key, value) in ordered {
                map.serialize_entry(&key, &value)?;
            }

            map.end()
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
enum OneOrMany<T> {
    One(T),
    Many(Vec<T>),
}

impl<T> OneOrMany<T> {
    fn into_vec(self) -> Vec<T> {
        match self {
            OneOrMany::One(value) => vec![value],
            OneOrMany::Many(values) => values,
        }
    }
}

impl<'de> Deserialize<'de> for Box<dyn Rule> {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Box<dyn Rule>, D::Error> {
        struct StringOrStruct;

        impl<'de> Visitor<'de> for StringOrStruct {
            type Value = Box<dyn Rule>;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("rule name or rule object")
            }

            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                let mut rule: Self::Value = FromStr::from_str(value).map_err(de::Error::custom)?;

                rule.configure(RuleProperties::new())
                    .map_err(de::Error::custom)?;

                Ok(rule)
            }

            fn visit_map<M>(self, mut map: M) -> Result<Self::Value, M::Error>
            where
                M: MapAccess<'de>,
            {
                let mut rule_name: Option<String> = None;
                let mut properties = HashMap::new();
                let mut only_patterns: Option<Vec<_>> = None;
                let mut skip_patterns: Option<Vec<_>> = None;

                while let Some(key) = map.next_key::<String>()? {
                    match key.as_str() {
                        "rule" => {
                            if rule_name.is_none() {
                                rule_name = Some(map.next_value::<String>()?);
                            } else {
                                return Err(de::Error::duplicate_field("rule"));
                            }
                        }
                        APPLY_TO_FILTER_PROPERTY => {
                            if only_patterns.is_none() {
                                let value =
                                    map.next_value::<OneOrMany<FilterPattern>>()?.into_vec();

                                only_patterns = Some(value);
                            } else {
                                return Err(de::Error::duplicate_field(APPLY_TO_FILTER_PROPERTY));
                            }
                        }
                        SKIP_FILTER_PROPERTY => {
                            if skip_patterns.is_none() {
                                let value =
                                    map.next_value::<OneOrMany<FilterPattern>>()?.into_vec();

                                skip_patterns = Some(value);
                            } else {
                                return Err(de::Error::duplicate_field(SKIP_FILTER_PROPERTY));
                            }
                        }
                        property => {
                            let value = map.next_value::<RulePropertyValue>()?;

                            if properties.insert(property.to_owned(), value).is_some() {
                                return Err(de::Error::custom(format!(
                                    "duplicate field {} in rule object",
                                    property
                                )));
                            }
                        }
                    }
                }

                if let Some(rule_name) = rule_name {
                    let mut rule: Self::Value =
                        FromStr::from_str(&rule_name).map_err(de::Error::custom)?;

                    rule.configure(properties).map_err(de::Error::custom)?;

                    let metadata = RuleMetadata {
                        apply_to_filters: only_patterns.unwrap_or_default(),
                        skip_filters: skip_patterns.unwrap_or_default(),
                    };
                    rule.set_metadata(metadata);

                    Ok(rule)
                } else {
                    Err(de::Error::missing_field("rule"))
                }
            }
        }

        deserializer.deserialize_any(StringOrStruct)
    }
}

fn verify_no_rule_properties(properties: &RuleProperties) -> Result<(), RuleConfigurationError> {
    if let Some((key, _value)) = properties.iter().next() {
        return Err(RuleConfigurationError::UnexpectedProperty(key.to_owned()));
    }
    Ok(())
}

fn verify_required_properties(
    properties: &RuleProperties,
    names: &[&str],
) -> Result<(), RuleConfigurationError> {
    for name in names.iter() {
        if !properties.contains_key(*name) {
            return Err(RuleConfigurationError::MissingProperty(name.to_string()));
        }
    }
    Ok(())
}

fn verify_required_any_properties(
    properties: &RuleProperties,
    names: &[&str],
) -> Result<(), RuleConfigurationError> {
    if names.iter().any(|name| properties.contains_key(*name)) {
        Ok(())
    } else {
        Err(RuleConfigurationError::MissingAnyProperty(
            names.iter().map(ToString::to_string).collect(),
        ))
    }
}

fn verify_property_collisions(
    properties: &RuleProperties,
    names: &[&str],
) -> Result<(), RuleConfigurationError> {
    let mut exists: Option<&str> = None;
    for name in names.iter() {
        if properties.contains_key(*name) {
            if let Some(existing_name) = &exists {
                return Err(RuleConfigurationError::PropertyCollision(vec![
                    existing_name.to_string(),
                    name.to_string(),
                ]));
            } else {
                exists = Some(*name);
            }
        }
    }
    Ok(())
}

#[cfg(test)]
mod test {
    use super::*;

    use insta::assert_json_snapshot;

    #[test]
    fn snapshot_default_rules() {
        let rules = get_default_rules();

        assert_json_snapshot!("default_rules", rules);
    }

    #[test]
    fn snapshot_all_rules() {
        let rule_names = get_all_rule_names();

        assert_json_snapshot!("all_rule_names", rule_names);
    }

    #[test]
    fn verify_no_rule_properties_is_ok_when_empty() {
        let empty_properties = RuleProperties::default();

        assert_eq!(verify_no_rule_properties(&empty_properties), Ok(()));
    }

    #[test]
    fn verify_no_rule_properties_is_unexpected_rule_err() {
        let mut properties = RuleProperties::default();
        let some_rule_name = "rule name";
        properties.insert(some_rule_name.to_owned(), RulePropertyValue::None);

        assert_eq!(
            verify_no_rule_properties(&properties),
            Err(RuleConfigurationError::UnexpectedProperty(
                some_rule_name.to_owned()
            ))
        );
    }

    #[test]
    fn get_all_rule_names_are_deserializable() {
        for name in get_all_rule_names() {
            let rule: Result<Box<dyn Rule>, _> = name.parse();
            assert!(rule.is_ok(), "unable to deserialize `{}`", name);
        }
    }

    #[test]
    fn get_all_rule_names_are_serializable() {
        for name in get_all_rule_names() {
            let rule: Box<dyn Rule> = name
                .parse()
                .unwrap_or_else(|_| panic!("unable to deserialize `{}`", name));
            assert!(json5::to_string(&rule).is_ok());
        }
    }
}