cml-rs 0.4.0

Content Markup Language (CML) v0.2 parser, generator, validator, and embedding store for structured documents
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
//! Hybrid ID generation system for CML elements
//!
//! Generates stable, hierarchical IDs based on document structure position,
//! with content hash validation for change detection.
//!
//! # ID Format Examples
//!
//! ## code:api Profile
//! - Module: `std.vec`
//! - Struct: `std.vec.Vec`
//! - Method: `std.vec.Vec.push`
//! - Function: `std.vec.from_elem`
//!
//! ## legal:constitution Profile
//! - Article: `us.constitution.art.1`
//! - Section: `us.constitution.art.1.sec.8`
//! - Clause: `us.constitution.art.1.sec.8.cl.3`
//! - Amendment: `us.constitution.amendment.14`
//!
//! ## bookstack:wiki Profile
//! - Book: `book-rust-guide`
//! - Chapter: `book-rust-guide.chapter-collections`
//! - Page: `book-rust-guide.chapter-collections.page-vectors`

use sha2::{Digest, Sha256};
use std::fmt;

/// Element ID with content hash validation
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ElementId {
    /// Position-based hierarchical ID
    pub id: String,

    /// SHA-256 hash of element content (hex string)
    pub content_hash: String,
}

impl ElementId {
    /// Create a new element ID with content hash
    pub fn new(id: impl Into<String>, content: &str) -> Self {
        let id = id.into();
        let content_hash = Self::hash_content(content);
        Self { id, content_hash }
    }

    /// Create an element ID without computing hash (use for parent references)
    pub fn from_id(id: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            content_hash: String::new(),
        }
    }

    /// Compute SHA-256 hash of content
    fn hash_content(content: &str) -> String {
        let mut hasher = Sha256::new();
        hasher.update(content.as_bytes());
        format!("sha256:{:x}", hasher.finalize())
    }

    /// Verify that content matches the stored hash
    pub fn verify(&self, content: &str) -> bool {
        if self.content_hash.is_empty() {
            return true; // No hash to verify
        }
        Self::hash_content(content) == self.content_hash
    }

    /// Get just the ID string
    pub fn as_str(&self) -> &str {
        &self.id
    }
}

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

impl From<String> for ElementId {
    fn from(id: String) -> Self {
        Self::from_id(id)
    }
}

impl From<&str> for ElementId {
    fn from(id: &str) -> Self {
        Self::from_id(id)
    }
}

/// ID generator for code:api profile
pub struct CodeIdGenerator {
    namespace: String,
}

impl CodeIdGenerator {
    /// Create a new code ID generator
    pub fn new(namespace: impl Into<String>) -> Self {
        Self {
            namespace: namespace.into(),
        }
    }

    /// Generate module ID: `namespace.module`
    pub fn module_id(&self, module_name: &str, docs: &str) -> ElementId {
        let id = format!("{}.{}", self.namespace, module_name);
        ElementId::new(id, docs)
    }

    /// Generate struct ID: `namespace.module.Struct`
    pub fn struct_id(&self, module_name: &str, struct_name: &str, docs: &str) -> ElementId {
        let id = format!("{}.{}.{}", self.namespace, module_name, struct_name);
        ElementId::new(id, docs)
    }

    /// Generate method ID: `namespace.module.Struct.method`
    pub fn method_id(
        &self,
        module_name: &str,
        struct_name: &str,
        method_name: &str,
        signature: &str,
        docs: &str,
    ) -> ElementId {
        let id = format!(
            "{}.{}.{}.{}",
            self.namespace, module_name, struct_name, method_name
        );
        // Hash includes signature for overload detection
        let content = format!("{}\n{}", signature, docs);
        ElementId::new(id, &content)
    }

    /// Generate function ID: `namespace.module.function`
    pub fn function_id(&self, module_name: &str, function_name: &str, docs: &str) -> ElementId {
        let id = format!("{}.{}.{}", self.namespace, module_name, function_name);
        ElementId::new(id, docs)
    }

    /// Generate enum ID: `namespace.module.Enum`
    pub fn enum_id(&self, module_name: &str, enum_name: &str, docs: &str) -> ElementId {
        let id = format!("{}.{}.{}", self.namespace, module_name, enum_name);
        ElementId::new(id, docs)
    }

    /// Generate trait ID: `namespace.module.Trait`
    pub fn trait_id(&self, module_name: &str, trait_name: &str, docs: &str) -> ElementId {
        let id = format!("{}.{}.{}", self.namespace, module_name, trait_name);
        ElementId::new(id, docs)
    }
}

/// ID generator for legal:constitution profile
pub struct LegalIdGenerator {
    document_id: String,
}

impl LegalIdGenerator {
    /// Create a new legal ID generator
    pub fn new(document_id: impl Into<String>) -> Self {
        Self {
            document_id: document_id.into(),
        }
    }

    /// Generate article ID: `document.art.{num}`
    pub fn article_id(&self, article_num: &str, content: &str) -> ElementId {
        let id = format!(
            "{}.art.{}",
            self.document_id,
            Self::normalize_num(article_num)
        );
        ElementId::new(id, content)
    }

    /// Generate section ID: `document.art.{num}.sec.{num}`
    pub fn section_id(&self, article_num: &str, section_num: &str, content: &str) -> ElementId {
        let id = format!(
            "{}.art.{}.sec.{}",
            self.document_id,
            Self::normalize_num(article_num),
            Self::normalize_num(section_num)
        );
        ElementId::new(id, content)
    }

    /// Generate clause ID: `document.art.{num}.sec.{num}.cl.{num}`
    pub fn clause_id(
        &self,
        article_num: &str,
        section_num: &str,
        clause_num: &str,
        content: &str,
    ) -> ElementId {
        let id = format!(
            "{}.art.{}.sec.{}.cl.{}",
            self.document_id,
            Self::normalize_num(article_num),
            Self::normalize_num(section_num),
            Self::normalize_num(clause_num)
        );
        ElementId::new(id, content)
    }

    /// Generate paragraph ID: `document.art.{num}.sec.{num}.cl.{num}.para.{letter}`
    pub fn paragraph_id(
        &self,
        article_num: &str,
        section_num: &str,
        clause_num: &str,
        para_num: &str,
        content: &str,
    ) -> ElementId {
        let id = format!(
            "{}.art.{}.sec.{}.cl.{}.para.{}",
            self.document_id,
            Self::normalize_num(article_num),
            Self::normalize_num(section_num),
            Self::normalize_num(clause_num),
            Self::normalize_num(para_num)
        );
        ElementId::new(id, content)
    }

    /// Generate amendment ID: `document.amendment.{num}`
    pub fn amendment_id(&self, amendment_num: &str, content: &str) -> ElementId {
        let id = format!(
            "{}.amendment.{}",
            self.document_id,
            Self::normalize_num(amendment_num)
        );
        ElementId::new(id, content)
    }

    /// Normalize numbering (Roman numerals, letters, etc. to lowercase)
    fn normalize_num(num: &str) -> String {
        num.trim().to_lowercase().replace(' ', "-")
    }
}

/// ID generator for bookstack:wiki profile
pub struct BookstackIdGenerator;

impl BookstackIdGenerator {
    /// Create a new bookstack ID generator
    pub fn new() -> Self {
        Self
    }

    /// Generate book ID: `book-{slug}`
    pub fn book_id(title: &str, description: &str) -> ElementId {
        let slug = Self::slugify(title);
        let id = format!("book-{}", slug);
        ElementId::new(id, &format!("{}\n{}", title, description))
    }

    /// Generate chapter ID: `book-{slug}.chapter-{slug}`
    pub fn chapter_id(book_slug: &str, chapter_title: &str, content: &str) -> ElementId {
        let chapter_slug = Self::slugify(chapter_title);
        let id = format!("{}.chapter-{}", book_slug, chapter_slug);
        ElementId::new(id, content)
    }

    /// Generate page ID: `book-{slug}.chapter-{slug}.page-{slug}`
    pub fn page_id(
        book_slug: &str,
        chapter_slug: &str,
        page_title: &str,
        content: &str,
    ) -> ElementId {
        let page_slug = Self::slugify(page_title);
        let id = format!("{}.{}.page-{}", book_slug, chapter_slug, page_slug);
        ElementId::new(id, content)
    }

    /// Generate shelf ID: `shelf-{slug}`
    pub fn shelf_id(name: &str, description: &str) -> ElementId {
        let slug = Self::slugify(name);
        let id = format!("shelf-{}", slug);
        ElementId::new(id, &format!("{}\n{}", name, description))
    }

    /// Convert title to URL-safe slug
    fn slugify(text: &str) -> String {
        let slug = text
            .to_lowercase()
            .chars()
            .map(|c| {
                if c.is_alphanumeric() {
                    c
                } else if c.is_whitespace() || c == '-' || c == '_' {
                    '-'
                } else {
                    ' ' // Will be filtered out
                }
            })
            .collect::<String>()
            .split_whitespace()
            .collect::<Vec<_>>()
            .join("-");

        // Remove consecutive dashes
        let mut result = String::new();
        let mut last_was_dash = false;
        for c in slug.chars() {
            if c == '-' {
                if !last_was_dash {
                    result.push(c);
                    last_was_dash = true;
                }
            } else {
                result.push(c);
                last_was_dash = false;
            }
        }
        result.trim_matches('-').to_string()
    }
}

impl Default for BookstackIdGenerator {
    fn default() -> Self {
        Self::new()
    }
}

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

    #[test]
    fn test_element_id_creation() {
        let id = ElementId::new("std.vec.Vec.push", "Pushes an item onto the vector");
        assert_eq!(id.id, "std.vec.Vec.push");
        assert!(id.content_hash.starts_with("sha256:"));
        assert!(id.verify("Pushes an item onto the vector"));
        assert!(!id.verify("Different content"));
    }

    #[test]
    fn test_code_id_generator() {
        let gen = CodeIdGenerator::new("std");

        let module_id = gen.module_id("vec", "Vector module documentation");
        assert_eq!(module_id.id, "std.vec");

        let struct_id = gen.struct_id("vec", "Vec", "A contiguous growable array");
        assert_eq!(struct_id.id, "std.vec.Vec");

        let method_id = gen.method_id(
            "vec",
            "Vec",
            "push",
            "pub fn push(&mut self, value: T)",
            "Pushes an item",
        );
        assert_eq!(method_id.id, "std.vec.Vec.push");
    }

    #[test]
    fn test_legal_id_generator() {
        let gen = LegalIdGenerator::new("us.constitution");

        let article_id = gen.article_id("I", "Article I content");
        assert_eq!(article_id.id, "us.constitution.art.i");

        let section_id = gen.section_id("I", "8", "Section 8 content");
        assert_eq!(section_id.id, "us.constitution.art.i.sec.8");

        let clause_id = gen.clause_id("I", "8", "3", "Commerce Clause");
        assert_eq!(clause_id.id, "us.constitution.art.i.sec.8.cl.3");

        let amendment_id = gen.amendment_id("XIV", "Amendment XIV content");
        assert_eq!(amendment_id.id, "us.constitution.amendment.xiv");
    }

    #[test]
    fn test_bookstack_id_generator() {
        let book_id =
            BookstackIdGenerator::book_id("Rust Programming Guide", "A comprehensive guide");
        assert_eq!(book_id.id, "book-rust-programming-guide");

        let chapter_id = BookstackIdGenerator::chapter_id(
            "book-rust-guide",
            "Getting Started",
            "Chapter content",
        );
        assert_eq!(chapter_id.id, "book-rust-guide.chapter-getting-started");

        let page_id = BookstackIdGenerator::page_id(
            "book-rust-guide",
            "chapter-getting-started",
            "Installation & Setup",
            "Page content",
        );
        assert_eq!(
            page_id.id,
            "book-rust-guide.chapter-getting-started.page-installation-setup"
        );
    }

    #[test]
    fn test_slugify() {
        assert_eq!(BookstackIdGenerator::slugify("Hello World"), "hello-world");
        assert_eq!(
            BookstackIdGenerator::slugify("C++ Programming"),
            "c-programming"
        );
        assert_eq!(
            BookstackIdGenerator::slugify("Multiple   Spaces"),
            "multiple-spaces"
        );
        assert_eq!(BookstackIdGenerator::slugify("Trim-Dashes-"), "trim-dashes");
    }

    #[test]
    fn test_content_hash_deterministic() {
        let id1 = ElementId::new("test", "Same content");
        let id2 = ElementId::new("test", "Same content");
        assert_eq!(id1.content_hash, id2.content_hash);

        let id3 = ElementId::new("test", "Different content");
        assert_ne!(id1.content_hash, id3.content_hash);
    }
}