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
//! register validator
//!
//! The [`Validator`] has a generics argument `M`, it is used validate message type,
//! it default is `String`, but when `full` feature is enabled, default is [`Message`].
//! Besides, it can be every types with your idea.
//!
//! if `M1` can be converted to `M2`, then `Validator<M1>` can be
//! converted to `Validator<M2>` with [`map`] method:
//!
//! ```ignore
//! let validator1 = Validator::<M1>::new();
//! let validator2 = validator1.map(M2::from);
//! ```
//! This can integrate built-in [rules] with your application very well.
//!
//! [`Message`]: crate::available::Message
//! [`map`]: Validator::map
//! [rules]: crate::available

use std::{
    collections::{
        hash_map::{IntoIter, Iter, IterMut, Keys},
        HashMap,
    },
    error::Error,
    fmt::Display,
    hash::{Hash, Hasher},
    ops::Index,
};

use crate::{
    rule::{IntoRuleList, RuleList},
    ser::Serializer,
    value::ValueMap,
    Value,
};

pub use field_name::{FieldName, FieldNames};
pub(crate) use field_name::{IntoFieldName, Parser};
pub use message::{IntoMessage, ValidPhrase};
use serde::{Deserialize, Serialize};

mod field_name;
mod lexer;
mod message;
pub mod string;
#[cfg(test)]
mod tests;

/// register a validator
/// ## This is an example:
///
/// ```rust
/// # use serde::{Deserialize, Serialize};
/// # use valitron::{
/// # available::{Required, StartWith, Message},
/// # custom, RuleExt, Validator
/// # };
/// #[derive(Serialize, Debug)]
/// struct Person {
///     introduce: &'static str,
///     age: u8,
///     weight: f32,
/// }
///
/// # fn main() {
/// let validator = Validator::new()
///     .rule("introduce", Required.and(StartWith("I am")))
///     .rule("age", custom(age_range))
///     .message([
///         ("introduce.required", "introduce is required"),
///         (
///             "introduce.start_with",
///             "introduce should be starts with `I am`",
///         ),
///     ]);
///
/// let person = Person {
///     introduce: "hi",
///     age: 18,
///     weight: 20.0,
/// };
///
/// let res = validator.validate(person).unwrap_err();
/// assert!(res.len() == 2);
/// # }
///
/// fn age_range(age: &mut u8) -> Result<(), Message> {
///     if *age >= 25 && *age <= 45 {
///         Ok(())
///     } else {
///         Err("age should be between 25 and 45".into())
///     }
/// }
/// ```
pub type Validator<'v, M> = InnerValidator<M, HashMap<MessageKey<'v>, M>>;

/// # A validator for build messages
/// build message with rule name, field name and value
///
/// *message need to implement [`IntoMessage`]*
///
/// [`IntoMessage`]: message::IntoMessage
pub type ValidatorRefine<M> = InnerValidator<M, ()>;

#[doc(hidden)]
pub struct InnerValidator<M, List> {
    rules: HashMap<FieldNames, RuleList<ValueMap, M>>,
    message: List,
    is_bail: bool,
}

impl<M> Validator<'_, M> {
    pub fn new() -> Self {
        Self::default()
    }

    /// run validate without modifiable
    pub fn validate<T>(self, data: T) -> Result<(), ValidatorError<M>>
    where
        T: Serialize,
    {
        let value = data.serialize(Serializer).unwrap();

        debug_assert!(self.exist_field(&value));

        let mut value_map = ValueMap::new(value);

        self.inner_validate(&mut value_map).ok()
    }

    /// run validate with modifiable
    pub fn validate_mut<'de, T>(self, data: T) -> Result<T, ValidatorError<M>>
    where
        T: Serialize + serde::de::Deserialize<'de>,
    {
        let value = data.serialize(Serializer).unwrap();

        debug_assert!(self.exist_field(&value));

        let mut value_map = ValueMap::new(value);

        self.inner_validate(&mut value_map)
            .ok()
            .map(|_| T::deserialize(value_map.value()).unwrap())
    }

    fn inner_validate(self, value_map: &mut ValueMap) -> ValidatorError<M> {
        fn handle_msg<M>(
            rules: RuleList<ValueMap, M>,
            value_map: &mut ValueMap,
            message: &mut HashMap<MessageKey<'_>, M>,
        ) -> Vec<M> {
            rules
                .call(value_map)
                .into_iter()
                .map(|(rule, msg)| {
                    message
                        .remove(&MessageKey::new(value_map.as_index().clone(), rule))
                        .unwrap_or(msg)
                })
                .collect()
        }
        self.iter_validate(value_map, handle_msg)
    }

    fn exit_message(&self, MessageKey { fields, rule }: &MessageKey) -> bool {
        debug_assert!(
            self.rule_get(fields).is_some(),
            "the field \"{}\" not found in validator",
            fields.as_str()
        );

        debug_assert!(
            self.rule_get(fields).unwrap().contains(rule),
            "rule \"{rule}\" is not found in rules"
        );

        true
    }
}

impl<M> ValidatorRefine<M> {
    pub fn new() -> Self {
        Self::default()
    }

    /// run validate without modifiable
    pub fn validate<T, M2>(self, data: T) -> Result<(), ValidatorError<M2>>
    where
        T: Serialize,
        M2: IntoMessage,
    {
        let value = data.serialize(Serializer).unwrap();

        debug_assert!(self.exist_field(&value));

        let mut value_map = ValueMap::new(value);

        self.inner_validate(&mut value_map).ok()
    }

    /// run validate with modifiable
    pub fn validate_mut<'de, T, M2>(self, data: T) -> Result<T, ValidatorError<M2>>
    where
        T: Serialize + serde::de::Deserialize<'de>,
        M2: IntoMessage,
    {
        let value = data.serialize(Serializer).unwrap();

        debug_assert!(self.exist_field(&value));

        let mut value_map = ValueMap::new(value);

        self.inner_validate(&mut value_map)
            .ok()
            .map(|_| T::deserialize(value_map.value()).unwrap())
    }

    /// inner creating message by field name and current value.
    fn inner_validate<M2>(self, value_map: &mut ValueMap) -> ValidatorError<M2>
    where
        M2: IntoMessage,
    {
        self.iter_validate(value_map, |rules, data, _| rules.call_gen_message(data))
    }
}

impl<'v, M> Validator<'v, M> {
    /// Custom validate error message
    ///
    /// Every rule has a default message, the method should be replace it with your need.
    ///
    /// parameter list item format:
    /// `(field_name.rule_name, message)`
    ///
    /// e.g: `("name.required", "name is required")`
    ///
    /// # Panic
    ///
    /// When field or rule is not existing ,this will panic
    pub fn message<const N: usize, Msg>(mut self, list: [(&'v str, Msg); N]) -> Self
    where
        Msg: Into<M>,
    {
        self.message.extend(list.map(|(key_str, v)| {
            let msg_key = crate::panic_on_err!(field_name::parse_message(key_str));

            debug_assert!(self.exit_message(&msg_key));

            (msg_key, v.into())
        }));
        self
    }

    /// # convert `Validator<M1>` to `Validator<M2>`
    ///
    /// Using build-in rules and returning custom validator message type is able:
    /// ```rust
    /// # use valitron::{Validator, available::{Message, MessageKind, Required}};
    /// let validator = Validator::new()
    ///     .rule("introduce", Required)
    ///     .map(MyError::from)
    ///     .message([("introduce.required", MyError::IntroduceRequired)]);
    ///
    /// enum MyError {
    ///     IntroduceRequired,
    ///     NotReset,
    /// }
    ///
    /// impl From<Message> for MyError {
    ///     fn from(val: Message) -> Self {
    ///         match val.kind() {
    ///             MessageKind::Required => MyError::NotReset,
    ///             // ...
    ///             # _ => unreachable!(),
    ///         }
    ///     }
    /// }
    /// ```
    #[must_use]
    pub fn map<M2>(self, f: fn(message: M) -> M2) -> Validator<'v, M2>
    where
        M: 'static,
        M2: 'static,
    {
        Validator {
            rules: self
                .rules
                .into_iter()
                .map(|(field, list)| (field, list.map(f)))
                .collect(),
            message: self
                .message
                .into_iter()
                .map(|(key, msg)| (key, f(msg)))
                .collect(),
            is_bail: self.is_bail,
        }
    }
}

impl<M, List> Default for InnerValidator<M, List>
where
    List: Default,
{
    fn default() -> Self {
        Self {
            rules: HashMap::new(),
            message: List::default(),
            is_bail: false,
        }
    }
}

impl<M, List> Clone for InnerValidator<M, List>
where
    List: Clone,
{
    fn clone(&self) -> Self {
        Self {
            rules: self.rules.clone(),
            message: self.message.clone(),
            is_bail: self.is_bail,
        }
    }
}

impl<M, List> InnerValidator<M, List> {
    /// # Register rules
    ///
    /// **Feild support multiple formats:**
    /// - `field1` used to matching struct field
    /// - `0`,`1`.. used to matching tuple item or tuple struct field
    /// - `[0]`,`[1]` used to matching array item
    /// - `[foo]` used to matching struct variant, e.g. `enum Foo{ Color { r: u8, g: u8, b: u8 } }`
    ///
    /// fields support nest:
    /// - `field1.0`
    /// - `0.color`
    /// - `[12].1`
    /// - `foo.1[color]`
    /// - more combine
    ///
    /// fields's BNF:
    /// ```bnf
    /// fields                 ::= <tuple_index>
    ///                          | <array_index>
    ///                          | <ident>
    ///                          | <struct_variant_index>
    ///                          | <fields> '.' <tuple_index>
    ///                          | <fields> '.' <ident>
    ///                          | <fields> <array_index>
    ///                          | <fields> <struct_variant_index>
    /// tuple_index            ::= <u8>
    /// array_index            ::= '[' <usize> ']'
    /// struct_variant_index   ::= '[' <ident> ']'
    /// ```
    ///
    /// **Rule also support multiple formats:**
    /// - `RuleFoo`
    /// - `RuleFoo.and(RuleBar)` combineable
    /// - `custom(handler)` closure usage
    /// - `RuleFoo.custom(handler)` type and closure
    /// - `custom(handler).and(RuleFoo)` closure and type
    /// - `RuleFoo.and(RuleBar).bail()` when first validate error, immediately return error with one message.
    ///
    /// *Available Rules*
    /// - [`Required`]
    /// - [`StartWith`]
    /// - [`Confirm`]
    /// - [`Trim`]
    /// - [`Range`]
    /// - customizable
    ///
    /// # Panic
    ///
    /// - Field format error will be panic
    /// - Invalid rule name will be panic
    ///
    /// [`Required`]: crate::available::required
    /// [`StartWith`]: crate::available::start_with
    /// [`Confirm`]: crate::available::confirm
    /// [`Trim`]: crate::available::trim
    /// [`Range`]: crate::available::range
    pub fn rule<F, R>(mut self, field: F, rule: R) -> Self
    where
        F: IntoFieldName,
        R: IntoRuleList<ValueMap, M>,
    {
        let names = crate::panic_on_err!(field.into_field());
        let mut rules = rule.into_list();

        debug_assert!(rules.valid_name(), "invalid rule name");

        self.rules
            .entry(names)
            .and_modify(|list| list.merge(&mut rules))
            .or_insert(rules);
        self
    }

    /// when first validate error is encountered, right away return Err(message).
    pub fn bail(mut self) -> Self {
        self.is_bail = true;
        self
    }

    fn exist_field(&self, value: &Value) -> bool {
        for (field, _) in self.rules.iter() {
            if value.get_with_names(field).is_none() {
                panic!("field `{}` is not found", field.as_str());
            }
        }

        true
    }

    #[inline(always)]
    fn rule_get(&self, names: &FieldNames) -> Option<&RuleList<ValueMap, M>> {
        self.rules.get(names)
    }

    fn iter_validate<F, T>(self, value_map: &mut ValueMap, handle_msg: F) -> ValidatorError<T>
    where
        F: Fn(RuleList<ValueMap, M>, &mut ValueMap, &mut List) -> Vec<T>,
    {
        let mut resp_message = ValidatorError::with_capacity(self.rules.len());

        let Self {
            rules,
            mut message,
            is_bail,
        } = self;

        for (mut names, mut rules) in rules.into_iter() {
            if is_bail {
                rules.set_bail();
            }

            value_map.index(names);

            let field_msg = handle_msg(rules, value_map, &mut message);

            names = value_map.take_index();

            resp_message.push(names, field_msg);

            if is_bail && !resp_message.is_empty() {
                resp_message.shrink_to(1);
                return resp_message;
            }
        }

        resp_message.shrink_to_fit();

        resp_message
    }

    #[cfg(test)]
    pub(crate) fn get_message(&self) -> &List {
        &self.message
    }
}

impl<M> From<Validator<'_, M>> for ValidatorRefine<M> {
    fn from(value: Validator<'_, M>) -> Self {
        let Validator { rules, is_bail, .. } = value;
        Self {
            rules,
            message: (),
            is_bail,
        }
    }
}

/// validateable for more types
pub trait Validatable<V, E> {
    /// if not change value
    fn validate(&self, validator: V) -> Result<(), E>;

    /// if need to change value, e.g. `trim`
    fn validate_mut<'de>(self, validator: V) -> Result<Self, E>
    where
        Self: Deserialize<'de>;
}

impl<T, M> Validatable<Validator<'_, M>, ValidatorError<M>> for T
where
    T: Serialize,
    M: 'static,
{
    fn validate(&self, validator: Validator<M>) -> Result<(), ValidatorError<M>> {
        validator.validate(self)
    }

    fn validate_mut<'de>(self, validator: Validator<M>) -> Result<Self, ValidatorError<M>>
    where
        Self: Deserialize<'de>,
    {
        validator.validate_mut(self)
    }
}

impl<T, M, M2> Validatable<ValidatorRefine<M>, ValidatorError<M2>> for T
where
    T: Serialize,
    M: 'static,
    M2: IntoMessage,
{
    fn validate(&self, validator: ValidatorRefine<M>) -> Result<(), ValidatorError<M2>> {
        validator.validate(self)
    }

    fn validate_mut<'de>(self, validator: ValidatorRefine<M>) -> Result<Self, ValidatorError<M2>>
    where
        Self: Deserialize<'de>,
    {
        validator.validate_mut(self)
    }
}

/// store validate error message
pub type ValidatorError<M> = InnerValidatorError<FieldNames, M>;

pub struct InnerValidatorError<F, M> {
    message: HashMap<F, Vec<M>>,
}

impl<F: Clone, M: Clone> Clone for InnerValidatorError<F, M> {
    fn clone(&self) -> Self {
        Self {
            message: self.message.clone(),
        }
    }
}

impl<F: Hash + Eq, M: PartialEq> PartialEq for InnerValidatorError<F, M> {
    fn eq(&self, other: &Self) -> bool {
        self.message == other.message
    }
}

impl<M, F> std::fmt::Debug for InnerValidatorError<F, M>
where
    M: std::fmt::Debug,
    F: std::fmt::Debug,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ValidatorError")
            .field("message", &self.message)
            .finish()
    }
}

impl<M> Index<&str> for ValidatorError<M> {
    type Output = Vec<M>;

    fn index(&self, index: &str) -> &Self::Output {
        self.message
            .get(&(index.into()))
            .expect("this field is not found")
    }
}
impl<M> Index<&str> for InnerValidatorError<String, M> {
    type Output = Vec<M>;

    fn index(&self, index: &str) -> &Self::Output {
        self.message.get(index).expect("this field is not found")
    }
}

impl<F, M> Serialize for InnerValidatorError<F, M>
where
    F: serde::Serialize,
    M: serde::Serialize,
{
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        self.message.serialize(serializer)
    }
}

impl<F, M> Display for InnerValidatorError<F, M> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        "validate error".fmt(f)
    }
}

impl<F, M> Error for InnerValidatorError<F, M>
where
    M: std::fmt::Debug,
    F: std::fmt::Debug,
{
}

impl<F, M> InnerValidatorError<F, M>
where
    F: Eq + Hash,
{
    pub fn new() -> Self {
        Self {
            message: HashMap::new(),
        }
    }
    fn with_capacity(capacity: usize) -> Self {
        Self {
            message: HashMap::with_capacity(capacity),
        }
    }
    fn shrink_to_fit(&mut self) {
        self.message.shrink_to_fit()
    }

    fn shrink_to(&mut self, min_capacity: usize) {
        self.message.shrink_to(min_capacity)
    }

    /// `ValidatorError<M1>` convert to `ValidatorError<M2>`
    pub fn map<M2>(self, f: fn(M) -> M2) -> InnerValidatorError<F, M2> {
        InnerValidatorError {
            message: self
                .message
                .into_iter()
                .map(|(name, msg)| (name, msg.into_iter().map(f).collect()))
                .collect(),
        }
    }

    pub fn is_empty(&self) -> bool {
        self.message.is_empty()
    }

    pub fn is_ok(&self) -> bool {
        self.is_empty()
    }

    pub fn len(&self) -> usize {
        self.message.len()
    }

    /// total length of the message
    pub fn total(&self) -> usize {
        self.message.values().map(|msg| msg.len()).sum()
    }

    fn ok(self) -> Result<(), Self> {
        if self.message.is_empty() {
            Ok(())
        } else {
            Err(self)
        }
    }
}
impl<M> ValidatorError<M> {
    fn push(&mut self, field_name: FieldNames, message: Vec<M>) {
        if !message.is_empty() {
            self.message.insert(field_name, message);
        }
    }

    pub fn get<K: IntoFieldName>(&self, key: K) -> Option<&Vec<M>> {
        let k = key.into_field().ok()?;
        self.message.get(&k)
    }

    pub fn get_key_value<K: IntoFieldName>(&self, key: K) -> Option<(&FieldNames, &Vec<M>)> {
        let k = key.into_field().ok()?;
        self.message.get_key_value(&k)
    }

    pub fn contains_key<K: IntoFieldName>(&self, key: K) -> bool {
        match key.into_field() {
            Ok(k) => self.message.contains_key(&k),
            Err(_) => false,
        }
    }

    pub fn keys(&self) -> Keys<'_, FieldNames, Vec<M>> {
        self.message.keys()
    }

    pub fn iter(&self) -> Iter<'_, FieldNames, Vec<M>> {
        self.message.iter()
    }

    pub fn iter_mut(&mut self) -> IterMut<'_, FieldNames, Vec<M>> {
        self.message.iter_mut()
    }
}

impl<'a, F, M> IntoIterator for &'a mut InnerValidatorError<F, M> {
    type Item = (&'a F, &'a mut Vec<M>);
    type IntoIter = IterMut<'a, F, Vec<M>>;
    fn into_iter(self) -> Self::IntoIter {
        self.message.iter_mut()
    }
}

impl<F, M> IntoIterator for InnerValidatorError<F, M> {
    type Item = (F, Vec<M>);
    type IntoIter = IntoIter<F, Vec<M>>;
    fn into_iter(self) -> Self::IntoIter {
        self.message.into_iter()
    }
}

#[derive(Debug, PartialEq, Eq, Clone)]
pub struct MessageKey<'key> {
    fields: FieldNames,
    rule: &'key str,
}

impl Hash for MessageKey<'_> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.fields.hash(state);
        self.rule.hash(state);
    }
}

impl<'key> MessageKey<'key> {
    pub(crate) fn new(fields: FieldNames, rule: &'key str) -> Self {
        Self { fields, rule }
    }
}

#[test]
#[cfg(feature = "full")]
fn test_refine() {
    use crate::available::Required;
    let _ = ValidatorRefine::new().rule("foo", Required);
}