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
use std::cmp::Ordering;
use std::cmp::PartialOrd;
use std::fmt::Display;
use std::fmt::Formatter;
use std::fmt::Result as FmtResult;
use std::fmt::Write;

use fastobo_derive_internal::FromStr;
use pest::iterators::Pair;

use crate::ast::*;

use crate::error::SyntaxError;
use crate::parser::FromPair;
use crate::syntax::Rule;

/// A clause value binding a property to a value in the relevant entity.
#[derive(Clone, Debug, Hash, Eq, FromStr, PartialEq, Ord)]
pub enum PropertyValue {
    /// A property-value binding where the value is specified with an ID.
    Resource(Box<ResourcePropertyValue>),
    /// A property-value binding where the value is given by a typed literal.
    Literal(Box<LiteralPropertyValue>),
}

impl PropertyValue {
    /// Get the identifier of the declared property annotation.
    pub fn property(&self) -> &RelationIdent {
        use self::PropertyValue::*;
        match self {
            Resource(pv) => pv.property(),
            Literal(pv) => pv.property(),
        }
    }
}

impl Display for PropertyValue {
    fn fmt(&self, f: &mut Formatter) -> FmtResult {
        match self {
            PropertyValue::Resource(pv) => pv.fmt(f),
            PropertyValue::Literal(pv) => pv.fmt(f),
        }
    }
}

impl From<LiteralPropertyValue> for PropertyValue {
    fn from(pv: LiteralPropertyValue) -> Self {
        PropertyValue::Literal(Box::new(pv))
    }
}

impl From<ResourcePropertyValue> for PropertyValue {
    fn from(pv: ResourcePropertyValue) -> Self {
        PropertyValue::Resource(Box::new(pv))
    }
}

impl<'i> FromPair<'i> for PropertyValue {
    const RULE: Rule = Rule::PropertyValue;
    unsafe fn from_pair_unchecked(pair: Pair<'i, Rule>) -> Result<Self, SyntaxError> {
        let inner = pair.into_inner().next().unwrap();
        match inner.as_rule() {
            Rule::LiteralPropertyValue => LiteralPropertyValue::from_pair_unchecked(inner)
                .map(Box::new)
                .map(PropertyValue::Literal),
            Rule::ResourcePropertyValue => ResourcePropertyValue::from_pair_unchecked(inner)
                .map(Box::new)
                .map(PropertyValue::Resource),
            _ => unreachable!(),
        }
    }
}

impl PartialOrd for PropertyValue {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        self.property()
            .cmp(&other.property())
            .then_with(|| self.to_string().cmp(&other.to_string()))
            .into()
    }
}

/// A property-value where the triple target is refered to with an ID.
///
/// This kind of property can be used to declare triples in the OBO document
/// where the property is an annotation property and the target is another
/// element in the semantic graph not necessarily defined as an OBO entity,
/// but for instance with an IDspace mapping:
/// ```rust
/// # extern crate fastobo;
/// # use fastobo::ast::*;
/// let property = RelationIdent::from(PrefixedIdent::new("dc", "creator"));
/// let target = Ident::from(PrefixedIdent::new("ORCID", "0000-0002-3947-4444"));
/// let property_value = ResourcePropertyValue::new(property, target);
/// ```
#[derive(Clone, Debug, Hash, FromStr, PartialOrd, Eq, PartialEq, Ord)]
pub struct ResourcePropertyValue {
    property: RelationIdent,
    target: Ident,
}

impl ResourcePropertyValue {
    pub fn new(property: RelationIdent, target: Ident) -> Self {
        Self { property, target }
    }

    /// Get the identifier of the declared property annotation.
    pub fn property(&self) -> &RelationIdent {
        &self.property
    }

    pub fn property_mut(&mut self) -> &mut RelationIdent {
        &mut self.property
    }

    pub fn target(&self) -> &Ident {
        &self.target
    }

    pub fn target_mut(&mut self) -> &mut Ident {
        &mut self.target
    }
}

impl Display for ResourcePropertyValue {
    fn fmt(&self, f: &mut Formatter) -> FmtResult {
        self.property
            .fmt(f)
            .and(f.write_char(' '))
            .and(self.target.fmt(f))
    }
}

impl<'i> FromPair<'i> for ResourcePropertyValue {
    const RULE: Rule = Rule::ResourcePropertyValue;
    unsafe fn from_pair_unchecked(pair: Pair<'i, Rule>) -> Result<Self, SyntaxError> {
        let mut inner = pair.into_inner();
        let relid = RelationIdent::from_pair_unchecked(inner.next().unwrap())?;
        let id = Ident::from_pair_unchecked(inner.next().unwrap())?;
        Ok(ResourcePropertyValue::new(relid, id))
    }
}

/// A property-value binding where the value is given by a typed literal.
///
/// This kind of property can be used to add additional annotations to an entity
/// where the annotation value is not an entity itself but a typed value such
/// as a string (of type `xsd:string`), a date (`xsd:date`), etc.
#[derive(Clone, Debug, Hash, FromStr, PartialOrd, Eq, PartialEq, Ord)]
pub struct LiteralPropertyValue {
    property: RelationIdent,
    literal: QuotedString,
    datatype: Ident,
}

impl LiteralPropertyValue {
    pub fn new(property: RelationIdent, literal: QuotedString, datatype: Ident) -> Self {
        Self {
            property,
            literal,
            datatype,
        }
    }

    /// Get the identifier of the declared property annotation.
    pub fn property(&self) -> &RelationIdent {
        &self.property
    }

    pub fn property_mut(&mut self) -> &mut RelationIdent {
        &mut self.property
    }

    pub fn literal(&self) -> &QuotedString {
        &self.literal
    }

    pub fn literal_mut(&mut self) -> &mut QuotedString {
        &mut self.literal
    }

    pub fn datatype(&self) -> &Ident {
        &self.datatype
    }

    pub fn datatype_mut(&mut self) -> &mut Ident {
        &mut self.datatype
    }
}

impl Display for LiteralPropertyValue {
    fn fmt(&self, f: &mut Formatter) -> FmtResult {
        self.property
            .fmt(f)
            .and(f.write_char(' '))
            .and(self.literal.fmt(f))
            .and(f.write_char(' '))
            .and(self.datatype.fmt(f))
    }
}

impl<'i> FromPair<'i> for LiteralPropertyValue {
    const RULE: Rule = Rule::LiteralPropertyValue;
    unsafe fn from_pair_unchecked(pair: Pair<'i, Rule>) -> Result<Self, SyntaxError> {
        let mut inner = pair.into_inner();

        let relid = RelationIdent::from_pair_unchecked(inner.next().unwrap())?;
        let second = inner.next().unwrap();
        let datatype = Ident::from_pair_unchecked(inner.next().unwrap())?;
        let desc = match second.as_rule() {
            Rule::QuotedString => QuotedString::from_pair_unchecked(second)?,
            Rule::UnquotedPropertyValueTarget => QuotedString::new(second.as_str().to_string()),
            _ => unreachable!(),
        };

        Ok(LiteralPropertyValue::new(relid, desc, datatype))
    }
}

#[cfg(test)]
mod tests {

    use super::*;
    use pretty_assertions::assert_eq;
    use std::str::FromStr;

    #[test]
    fn from_str() {
        let actual = PropertyValue::from_str("married_to heather").unwrap();
        let expected = PropertyValue::from(ResourcePropertyValue::new(
            RelationIdent::from(UnprefixedIdent::new(String::from("married_to"))),
            Ident::from(UnprefixedIdent::new(String::from("heather"))),
        ));
        assert_eq!(actual, expected);

        let actual = PropertyValue::from_str("shoe_size \"8\" xsd:positiveInteger").unwrap();
        let expected = PropertyValue::from(LiteralPropertyValue::new(
            RelationIdent::from(UnprefixedIdent::new(String::from("shoe_size"))),
            QuotedString::new(String::from("8")),
            Ident::from(PrefixedIdent::new("xsd", "positiveInteger")),
        ));
        assert_eq!(actual, expected);
    }

    #[test]
    fn partial_cmp() {
        let l1 = PropertyValue::from_str("engaged_to heather").unwrap();
        let r1 = PropertyValue::from_str("married_to heather").unwrap();
        assert!(l1 < r1);

        let l2 = PropertyValue::from_str("married_to ashley").unwrap();
        let r2 = PropertyValue::from_str("married_to heather").unwrap();
        assert!(l2 < r2);

        let l3 = PropertyValue::from_str("has_kids \"8\" xsd:positiveInteger").unwrap();
        let r3 = PropertyValue::from_str("married_to heather").unwrap();
        assert!(l3 < r3);

        let l4 = PropertyValue::from_str("has_kid \"true\" xsd:boolean").unwrap();
        let r4 = PropertyValue::from_str("has_kid jenny").unwrap();
        assert!(l4 < r4);
    }
}