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
//! Compile `serde_yaml`'s representation into a compiled schema that then can be used in `Generator`, using `compile` function.
use yaml_merge_keys::merge_keys_serde;

use crate::dsl::schema::deserialization::deserialize_root;
use crate::dsl::schema::DocumentRoot;

pub fn compile(schema: serde_yaml::Value) -> Result<CompiledSchema, CompilationError> {
    let schema = merge_keys_serde(schema)?;
    let schema = deserialize_root::<serde_yaml::Error>(&schema)?;
    Ok(CompiledSchema::with(schema))
}

pub struct CompiledSchema {
    schema: DocumentRoot,
}

#[derive(Debug)]
pub struct CompilationError {
    message: String,
}

impl CompilationError {
    pub fn with_message(message: &str) -> CompilationError {
        CompilationError {
            message: message.to_string(),
        }
    }
}

impl From<serde_yaml::Error> for CompilationError {
    fn from(source: serde_yaml::Error) -> Self {
        CompilationError {
            message: source.to_string(),
        }
    }
}

impl From<yaml_merge_keys::Error> for CompilationError {
    fn from(source: yaml_merge_keys::Error) -> Self {
        CompilationError {
            message: source.to_string(),
        }
    }
}

impl CompiledSchema {
    pub fn with(schema: DocumentRoot) -> CompiledSchema {
        CompiledSchema { schema }
    }

    pub fn compiled(self) -> DocumentRoot {
        self.schema
    }
}