relateby-pattern 0.4.2

Core pattern data structures
Documentation
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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
//! Subject type definition
//!
//! This module provides the Subject type and related types (Symbol, Value, RangeValue, PropertyRecord)
//! for use as pattern values in `Pattern<Subject>`.

use std::fmt;

/// Symbol identifier that uniquely identifies the subject.
///
/// A `Symbol` is a wrapper around a `String` that represents an identifier.
/// In gram notation, symbols appear before labels and properties.
///
/// # Examples
///
/// ```rust
/// use pattern_core::Symbol;
///
/// let symbol = Symbol("n".to_string());
/// assert_eq!(symbol.0, "n");
/// ```
#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Symbol(pub String);

impl fmt::Debug for Symbol {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("Symbol").field(&self.0).finish()
    }
}

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

impl From<&str> for Symbol {
    fn from(s: &str) -> Self {
        Symbol(s.to_string())
    }
}

impl From<String> for Symbol {
    fn from(s: String) -> Self {
        Symbol(s)
    }
}

/// Range value for numeric ranges (lower and upper bounds, both optional).
///
/// Used in `Value::VRange` to represent numeric ranges with optional bounds.
///
/// Note: This type only implements `PartialEq`, not `Eq`, because `f64` doesn't implement `Eq`
/// (due to NaN != NaN).
///
/// # Examples
///
/// ```rust
/// use pattern_core::RangeValue;
///
/// // Closed range: 1.0 to 10.0
/// let range1 = RangeValue {
///     lower: Some(1.0),
///     upper: Some(10.0),
/// };
///
/// // Lower bound only: 1.0 to infinity
/// let range2 = RangeValue {
///     lower: Some(1.0),
///     upper: None,
/// };
///
/// // Upper bound only: negative infinity to 10.0
/// let range3 = RangeValue {
///     lower: None,
///     upper: Some(10.0),
/// };
/// ```
#[derive(Clone, PartialEq)]
pub struct RangeValue {
    /// Lower bound of the range (inclusive), `None` means unbounded below
    pub lower: Option<f64>,
    /// Upper bound of the range (inclusive), `None` means unbounded above
    pub upper: Option<f64>,
}

impl fmt::Debug for RangeValue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("RangeValue")
            .field("lower", &self.lower)
            .field("upper", &self.upper)
            .finish()
    }
}

impl fmt::Display for RangeValue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match (self.lower, self.upper) {
            (Some(lower), Some(upper)) => write!(f, "{}..{}", lower, upper),
            (Some(lower), None) => write!(f, "{}..", lower),
            (None, Some(upper)) => write!(f, "..{}", upper),
            (None, None) => write!(f, ".."),
        }
    }
}

/// Property value types for Subject properties.
///
/// `Value` is an enum that represents rich value types that can be stored in Subject properties.
/// It supports standard types (integers, decimals, booleans, strings, symbols) and extended types
/// (tagged strings, arrays, maps, ranges, measurements).
///
/// Note: This type only implements `PartialEq`, not `Eq`, because it contains `RangeValue`
/// which uses `f64` (`f64` doesn't implement `Eq` due to NaN != NaN).
///
/// # Examples
///
/// ```rust
/// use pattern_core::Value;
///
/// // Standard types
/// let int_val = Value::VInteger(42);
/// let decimal_val = Value::VDecimal(3.14);
/// let bool_val = Value::VBoolean(true);
/// let string_val = Value::VString("hello".to_string());
/// let symbol_val = Value::VSymbol("sym".to_string());
///
/// // Extended types
/// let tagged = Value::VTaggedString {
///     tag: "type".to_string(),
///     content: "value".to_string(),
/// };
/// let array = Value::VArray(vec![
///     Value::VInteger(1),
///     Value::VInteger(2),
/// ]);
/// ```
#[derive(Clone, PartialEq)]
pub enum Value {
    /// Integer value (i64)
    VInteger(i64),
    /// Decimal value (f64)
    VDecimal(f64),
    /// Boolean value
    VBoolean(bool),
    /// String value
    VString(String),
    /// Symbol value (string identifier)
    VSymbol(String),
    /// Tagged string with a type tag and content
    VTaggedString {
        /// The type tag
        tag: String,
        /// The string content
        content: String,
    },
    /// Array of values
    VArray(Vec<Value>),
    /// Map from string keys to values
    VMap(std::collections::HashMap<String, Value>),
    /// Numeric range value
    VRange(RangeValue),
    /// Measurement with unit and numeric value (e.g., "5kg" -> unit="kg", value=5.0)
    VMeasurement {
        /// The unit string (e.g., "kg", "m", "s")
        unit: String,
        /// The numeric value
        value: f64,
    },
}

impl fmt::Debug for Value {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Value::VInteger(i) => f.debug_tuple("VInteger").field(i).finish(),
            Value::VDecimal(d) => f.debug_tuple("VDecimal").field(d).finish(),
            Value::VBoolean(b) => f.debug_tuple("VBoolean").field(b).finish(),
            Value::VString(s) => f.debug_tuple("VString").field(s).finish(),
            Value::VSymbol(s) => f.debug_tuple("VSymbol").field(s).finish(),
            Value::VTaggedString { tag, content } => f
                .debug_struct("VTaggedString")
                .field("tag", tag)
                .field("content", content)
                .finish(),
            Value::VArray(arr) => f.debug_list().entries(arr).finish(),
            Value::VMap(map) => f.debug_map().entries(map.iter()).finish(),
            Value::VRange(r) => f.debug_tuple("VRange").field(r).finish(),
            Value::VMeasurement { unit, value } => f
                .debug_struct("VMeasurement")
                .field("unit", unit)
                .field("value", value)
                .finish(),
        }
    }
}

impl fmt::Display for Value {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Value::VInteger(i) => write!(f, "{}", i),
            Value::VDecimal(d) => write!(f, "{}", d),
            Value::VBoolean(b) => write!(f, "{}", b),
            Value::VString(s) => write!(f, "\"{}\"", s),
            Value::VSymbol(s) => write!(f, "{}", s),
            Value::VTaggedString { tag, content } => write!(f, "{}:{}", tag, content),
            Value::VArray(arr) => {
                write!(f, "[")?;
                for (i, item) in arr.iter().enumerate() {
                    if i > 0 {
                        write!(f, ", ")?;
                    }
                    write!(f, "{}", item)?;
                }
                write!(f, "]")
            }
            Value::VMap(map) => {
                write!(f, "{{")?;
                let mut first = true;
                for (k, v) in map.iter() {
                    if !first {
                        write!(f, ", ")?;
                    }
                    first = false;
                    write!(f, "{}: {}", k, v)?;
                }
                write!(f, "}}")
            }
            Value::VRange(r) => write!(f, "{}", r),
            Value::VMeasurement { unit, value } => write!(f, "{}{}", value, unit),
        }
    }
}

/// Property record type alias.
///
/// A `PropertyRecord` is a map from string keys to `Value` types, storing
/// structured data about a Subject.
///
/// # Examples
///
/// ```rust
/// use pattern_core::{PropertyRecord, Value};
/// use std::collections::HashMap;
///
/// let mut props: PropertyRecord = HashMap::new();
/// props.insert("name".to_string(), Value::VString("Alice".to_string()));
/// props.insert("age".to_string(), Value::VInteger(30));
/// ```
pub type PropertyRecord = std::collections::HashMap<String, Value>;

/// Self-descriptive object with identity, labels, and properties.
///
/// `Subject` is designed to be the primary content type for patterns
/// (i.e., `Pattern<Subject>` will be the common use case).
///
/// A Subject contains:
/// - **Identity**: A required symbol identifier that uniquely identifies the subject
/// - **Labels**: A set of label strings that categorize or classify the subject
/// - **Properties**: A key-value map storing properties with rich value types
///
/// Note: This type only implements `PartialEq`, not `Eq`, because it contains `Value`
/// which uses `f64` (`f64` doesn't implement `Eq` due to NaN != NaN).
///
/// # Examples
///
/// ```rust
/// use pattern_core::{Subject, Symbol, Value};
/// use std::collections::{HashSet, HashMap};
///
/// let subject = Subject {
///     identity: Symbol("n".to_string()),
///     labels: {
///         let mut s = HashSet::new();
///         s.insert("Person".to_string());
///         s
///     },
///     properties: {
///         let mut m = HashMap::new();
///         m.insert("name".to_string(), Value::VString("Alice".to_string()));
///         m.insert("age".to_string(), Value::VInteger(30));
///         m
///     },
/// };
/// ```
///
/// # Usage with Pattern
///
/// ```rust
/// use pattern_core::{Pattern, Subject, Symbol};
/// use std::collections::HashSet;
///
/// let subject = Subject {
///     identity: Symbol("n".to_string()),
///     labels: HashSet::new(),
///     properties: std::collections::HashMap::new(),
/// };
///
/// let pattern: Pattern<Subject> = Pattern {
///     value: subject,
///     elements: vec![],
/// };
/// ```
#[derive(Clone, PartialEq)]
pub struct Subject {
    /// Symbol identifier that uniquely identifies the subject.
    ///
    /// The identity is always required. In gram notation, identities appear
    /// before labels and properties.
    pub identity: Symbol,

    /// Set of label strings that categorize or classify the subject.
    ///
    /// Labels provide classification information. The set can be empty (no labels)
    /// or contain one or more unique labels. In gram notation, labels are prefixed
    /// with `:` or `::` and appear after the identity and before properties.
    pub labels: std::collections::HashSet<String>,

    /// Key-value property map storing structured data about the subject.
    ///
    /// Properties store attributes and metadata. The property record can be empty
    /// (no properties) or contain any number of key-value pairs. In gram notation,
    /// properties appear in curly braces: `{name:"Alice", age:30}`.
    pub properties: PropertyRecord,
}

impl fmt::Debug for Subject {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Subject")
            .field("identity", &self.identity)
            .field("labels", &self.labels)
            .field("properties", &self.properties)
            .finish()
    }
}

impl fmt::Display for Subject {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.identity)?;

        if !self.labels.is_empty() {
            write!(f, ":")?;
            let mut labels_vec: Vec<_> = self.labels.iter().collect();
            labels_vec.sort();
            for (i, label) in labels_vec.iter().enumerate() {
                if i > 0 {
                    write!(f, "::")?;
                }
                write!(f, "{}", label)?;
            }
        }

        if !self.properties.is_empty() {
            write!(f, " {{")?;
            let mut props_vec: Vec<_> = self.properties.iter().collect();
            props_vec.sort_by_key(|(k, _)| *k);
            for (i, (key, value)) in props_vec.iter().enumerate() {
                if i > 0 {
                    write!(f, ", ")?;
                }
                write!(f, "{}: {}", key, value)?;
            }
            write!(f, "}}")?;
        }

        Ok(())
    }
}

impl Subject {
    /// Creates an identity-only Subject with no labels or properties.
    ///
    /// Useful as a reference handle when passing to methods that accept `&Subject`
    /// and only need the identity (e.g., `add_relationship` source/target args).
    ///
    /// # Examples
    ///
    /// ```rust
    /// use pattern_core::Subject;
    ///
    /// let mut g = pattern_core::graph::StandardGraph::new();
    /// let alice = Subject::build("alice").label("Person").done();
    /// let bob   = Subject::build("bob").label("Person").done();
    /// g.add_node(alice.clone());
    /// g.add_node(bob.clone());
    /// g.add_relationship(Subject::build("r1").label("KNOWS").done(), &alice, &bob);
    ///
    /// // When you only have an ID string, use from_id as a lightweight reference:
    /// g.add_relationship(
    ///     Subject::build("r2").label("KNOWS").done(),
    ///     &Subject::from_id("alice"),
    ///     &Subject::from_id("bob"),
    /// );
    /// ```
    pub fn from_id(identity: impl Into<String>) -> Subject {
        Subject {
            identity: Symbol(identity.into()),
            labels: std::collections::HashSet::new(),
            properties: std::collections::HashMap::new(),
        }
    }

    /// Creates a SubjectBuilder with the given identity.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use pattern_core::Subject;
    ///
    /// let subject = Subject::build("alice")
    ///     .label("Person")
    ///     .property("name", "Alice")
    ///     .done();
    /// assert_eq!(subject.identity.0, "alice");
    /// assert!(subject.labels.contains("Person"));
    /// ```
    pub fn build(identity: impl Into<String>) -> SubjectBuilder {
        SubjectBuilder {
            identity: Symbol(identity.into()),
            labels: std::collections::HashSet::new(),
            properties: PropertyRecord::new(),
        }
    }
}

/// Fluent builder for constructing Subject values.
///
/// Created via `Subject::build(identity)`. Chain `.label()` and `.property()`
/// calls, then finalize with `.done()` or use `Into<Subject>`.
pub struct SubjectBuilder {
    identity: Symbol,
    labels: std::collections::HashSet<String>,
    properties: PropertyRecord,
}

impl SubjectBuilder {
    /// Adds a label to the subject being built.
    pub fn label(mut self, label: impl Into<String>) -> Self {
        self.labels.insert(label.into());
        self
    }

    /// Adds a property to the subject being built.
    pub fn property(mut self, key: impl Into<String>, value: impl Into<Value>) -> Self {
        self.properties.insert(key.into(), value.into());
        self
    }

    /// Finalizes the builder and returns the constructed Subject.
    pub fn done(self) -> Subject {
        Subject {
            identity: self.identity,
            labels: self.labels,
            properties: self.properties,
        }
    }
}

impl From<SubjectBuilder> for Subject {
    fn from(builder: SubjectBuilder) -> Self {
        builder.done()
    }
}

// ============================================================================
// Value conversion implementations
// ============================================================================

impl From<i64> for Value {
    fn from(v: i64) -> Self {
        Value::VInteger(v)
    }
}

impl From<i32> for Value {
    fn from(v: i32) -> Self {
        Value::VInteger(v as i64)
    }
}

impl From<f64> for Value {
    fn from(v: f64) -> Self {
        Value::VDecimal(v)
    }
}

impl From<bool> for Value {
    fn from(v: bool) -> Self {
        Value::VBoolean(v)
    }
}

impl From<String> for Value {
    fn from(v: String) -> Self {
        Value::VString(v)
    }
}

impl From<&str> for Value {
    fn from(v: &str) -> Self {
        Value::VString(v.to_string())
    }
}