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
use super::{AllowedType, Attribute};
use crate::definition::Type;
use crate::error::{Error, ValidationError};
use crate::validator::{Context, DocumentPath, State};

use std::collections::HashSet;

#[derive(Debug)]
pub struct PointerPath {
    name: String,
    ptr: String,
}

impl PointerPath {
    pub fn new(state: &mut State, mut path: DocumentPath, ctx: &Context) -> Result<Self, Error> {
        let obj = ctx.raw_definition();

        match Type::new(obj, path.clone())? {
            Type::Pointer => (),
            typ => return Err(Error::ForbiddenType { path, typ }),
        };

        let ptr = match obj.get(ctx.name().as_str()) {
            Some(ptr_path) => match ptr_path.as_str() {
                Some(path) => path,
                None => {
                    path.add(ctx.name().as_str());
                    return Err(Error::InvalidValue {
                        path,
                        value: ptr_path.clone(),
                    });
                }
            },
            None => {
                return Err(Error::MissingAttribute {
                    path,
                    attr: ctx.name(),
                })
            }
        };

        state.add_unresolved_pointer(ptr.to_string(), ctx.ptr());

        Ok(PointerPath {
            name: ctx.name(),
            ptr: ptr.to_string(),
        })
    }

    pub fn allowed_types() -> HashSet<AllowedType> {
        let mut set = HashSet::<AllowedType>::new();
        set.insert(AllowedType::new(Type::Pointer, true));
        set
    }

    pub fn build(
        state: &mut State,
        path: DocumentPath,
        ctx: &Context,
    ) -> Result<Box<Attribute>, Error> {
        Ok(Box::new(PointerPath::new(state, path, ctx)?))
    }
}

impl Attribute for PointerPath {
    fn validate(
        &self,
        state: &State,
        path: Vec<String>,
        input: &serde_json::Value,
    ) -> Result<(), ValidationError> {
        let def = match state.get_definition(self.ptr.as_str()) {
            Some(def) => def,
            None => return Err(ValidationError::UndefinedDefinition),
        };

        def.validate(state, input, path)?;

        Ok(())
    }
}