Skip to main content

zz_validator/
ast.rs

1use std::collections::HashMap;
2
3/// -----------------------------
4/// AST
5/// -----------------------------
6#[derive(Debug, Clone, PartialEq)]
7pub enum FieldType {
8    String,
9    Int,
10    Float,
11    Bool,
12    Object,
13    Array,
14    Email, // 新增
15    Uri, // 新增
16    Uuid, // 新增
17    Ip,
18    Mac,
19    Date,
20    DateTime,
21    Time,
22    Timestamp,
23    Color,
24    Hostname,
25    Slug,
26    Hex,
27    Base64,
28    Password,
29    Token,
30}
31
32#[derive(Debug, Clone)]
33pub enum Constraint {
34    Range {
35        min: Value,
36        max: Value,
37        min_inclusive: bool,
38        max_inclusive: bool,
39    },
40    Regex(String),
41}
42
43#[derive(Debug, Clone)]
44pub struct Constraints {
45    pub items: Vec<Constraint>,
46}
47
48/// -----------------------------
49/// Value
50/// -----------------------------
51#[derive(Debug, Clone, PartialEq)]
52pub enum Value {
53    String(String),
54    Int(i64),
55    Float(f64),
56    Bool(bool),
57    Object(HashMap<String, Value>),
58    Array(Vec<Value>),
59}
60
61impl Value {
62    pub fn as_str(&self) -> Option<&str> {
63        if let Value::String(s) = self { Some(s) } else { None }
64    }
65    pub fn as_int(&self) -> Option<i64> {
66        if let Value::Int(i) = self { Some(*i) } else { None }
67    }
68    pub fn as_float(&self) -> Option<f64> {
69        if let Value::Float(f) = self { Some(*f) } else { None }
70    }
71    pub fn as_bool(&self) -> Option<bool> {
72        if let Value::Bool(b) = self { Some(*b) } else { None }
73    }
74    pub fn as_object(&self) -> Option<&HashMap<String, Value>> {
75        if let Value::Object(m) = self { Some(m) } else { None }
76    }
77    pub fn as_object_mut(&mut self) -> Option<&mut HashMap<String, Value>> {
78        if let Value::Object(m) = self { Some(m) } else { None }
79    }
80    pub fn as_array(&self) -> Option<&Vec<Value>> {
81        if let Value::Array(a) = self { Some(a) } else { None }
82    }
83    pub fn as_array_mut(&mut self) -> Option<&mut Vec<Value>> {
84        if let Value::Array(a) = self { Some(a) } else { None }
85    }
86}
87
88#[derive(Debug, Clone)]
89pub struct FieldRule {
90    pub field: String,
91    pub field_type: FieldType,
92    pub required: bool,
93    pub default: Option<Value>,
94    pub enum_values: Option<Vec<Value>>,
95    pub union_types: Option<Vec<FieldType>>,
96    pub constraints: Option<Constraints>,
97    pub rule: Option<Box<FieldRule>>,
98    pub children: Option<Vec<FieldRule>>,
99    pub is_array: bool,
100}