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
use itertools::*;
use std::{cmp, fmt};

/// Identifier in EXPRESS language must be one of scopes described in
/// "Table 9 – Scope and identifier defining items"
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum ScopeType {
    Entity,
    Alias,
    Function,
    Procedure,
    Query,
    Repeat,
    Rule,
    Schema,
    SubType,
    Type,
}

/// Scope declaration
///
/// Partial Order
/// --------------
/// Scope is partially ordered in terms of the sub-scope relation:
///
/// ```
/// # use espr::ir::*;
/// let root = Scope::root();
/// let schema = root.pushed(ScopeType::Schema, "schema");
/// assert!(root > schema); // schema scope is sub-scope of root scope
/// ```
///
/// Be sure that this is not total order:
///
/// ```
/// # use espr::ir::*;
/// let root = Scope::root();
/// let schema1 = root.pushed(ScopeType::Schema, "schema1");
/// let schema2 = root.pushed(ScopeType::Schema, "schema2");
///
/// // schema1 and schema2 are both sub-scope of root,
/// assert!(root > schema1);
/// assert!(root > schema2);
///
/// // but they are independent. Comparison always returns false:
/// assert!(!(schema1 <= schema2));
/// assert!(!(schema1 >= schema2));
/// ```
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct Scope(Vec<(ScopeType, String)>);

// Custom debug output like: `schema.entity`
impl fmt::Display for Scope {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0.iter().map(|(_ty, name)| name).join("."))
    }
}

// Custom debug output like: `Scope(schema[Schema].entity[Entity])`
impl fmt::Debug for Scope {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Scope(")?;
        for (i, (ty, name)) in self.0.iter().enumerate() {
            if i != 0 {
                write!(f, ".")?;
            }
            write!(f, "{}[{:?}]", name, ty)?;
        }
        write!(f, ")")?;
        Ok(())
    }
}

impl PartialOrd for Scope {
    fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
        for (lhs, rhs) in self.0.iter().zip(other.0.iter()) {
            if lhs != rhs {
                return None;
            }
        }
        if self.0.len() == other.0.len() {
            Some(cmp::Ordering::Equal)
        } else if self.0.len() > other.0.len() {
            Some(cmp::Ordering::Less)
        } else {
            Some(cmp::Ordering::Greater)
        }
    }
}

macro_rules! add_scope {
    ($f:ident, $ty:ident) => {
        #[doc = stringify!(Add $ty scope)]
        pub fn $f(&self, name: &str) -> Self {
            self.pushed(ScopeType::$ty, name)
        }
    };
}

impl Scope {
    pub fn root() -> Self {
        Self(Vec::new())
    }

    pub fn pushed(&self, ty: ScopeType, name: &str) -> Self {
        let mut new = self.clone();
        new.0.push((ty, name.to_string()));
        new
    }

    add_scope!(entity, Entity);
    add_scope!(alias, Alias);
    add_scope!(function, Function);
    add_scope!(procedure, Procedure);
    add_scope!(query, Query);
    add_scope!(repeat, Repeat);
    add_scope!(rule, Rule);
    add_scope!(schema, Schema);
    add_scope!(subtype, SubType);
    add_scope!(r#type, Type);

    /// Pop the last scope
    ///
    /// Returns `None` when `self` is root.
    pub fn popped(&self) -> Option<Self> {
        let mut new = self.clone();
        let _current = new.0.pop()?;
        Some(new)
    }
}

#[derive(Clone, PartialEq, Eq, Hash)]
pub struct Path {
    pub scope: Scope,
    pub ty: ScopeType,
    pub name: String,
}

impl fmt::Display for Path {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}.{}", self.scope, self.name)
    }
}

impl fmt::Debug for Path {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:?}.{}[{:?}]", self.scope, self.name, self.ty)
    }
}

macro_rules! new_path {
    ($f:ident, $ty:ident) => {
        #[doc = stringify!(Add $ty scope)]
        pub fn $f(scope: &Scope, name: &str) -> Self {
            Path::new(scope, ScopeType::$ty, name)
        }
    };
}

impl Path {
    pub fn new(scope: &Scope, ty: ScopeType, name: &str) -> Self {
        Path {
            scope: scope.clone(),
            ty,
            name: name.to_string(),
        }
    }

    new_path!(entity, Entity);
    new_path!(alias, Alias);
    new_path!(function, Function);
    new_path!(procedure, Procedure);
    new_path!(query, Query);
    new_path!(repeat, Repeat);
    new_path!(rule, Rule);
    new_path!(schema, Schema);
    new_path!(subtype, SubType);
    new_path!(r#type, Type);
}

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

    #[test]
    fn scope() {
        let root = Scope::root();
        assert_eq!(format!("{}", root), "");

        let schema = root.pushed(ScopeType::Schema, "schema1");
        assert_eq!(format!("{}", schema), "schema1");
        assert_eq!(format!("{:?}", schema), "Scope(schema1[Schema])");

        let entity = schema.pushed(ScopeType::Entity, "entity1");
        assert_eq!(format!("{}", entity), "schema1.entity1");
        assert_eq!(
            format!("{:?}", entity),
            "Scope(schema1[Schema].entity1[Entity])"
        );
    }
}