sphinx-ultra 0.3.0

High-performance Rust-based Sphinx documentation builder for large codebases
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
use crate::domains::{
    CrossReference, DomainObject, DomainValidator, ReferenceType, ReferenceValidationResult,
};
use crate::error::BuildError;
/// RST Domain Implementation
///
/// Handles RST-specific objects and references like :doc:, :ref:, etc.
use std::collections::HashMap;

/// RST domain validator for document and section references
pub struct RstDomain {
    /// Documents registered in this domain
    documents: HashMap<String, DomainObject>,
    /// Sections registered in this domain
    sections: HashMap<String, DomainObject>,
}

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

impl RstDomain {
    /// Create a new RST domain
    pub fn new() -> Self {
        Self {
            documents: HashMap::new(),
            sections: HashMap::new(),
        }
    }

    /// Register a document
    pub fn register_document(
        &mut self,
        docname: String,
        title: String,
        location: crate::domains::ReferenceLocation,
    ) -> Result<(), BuildError> {
        let object = DomainObject {
            id: format!("doc:{}", docname),
            name: docname.clone(),
            object_type: "document".to_string(),
            domain: "rst".to_string(),
            definition_location: location,
            qualified_name: docname.clone(),
            metadata: {
                let mut meta = HashMap::new();
                meta.insert("title".to_string(), title);
                meta
            },
            signature: None,
            docstring: None,
        };

        self.documents.insert(docname, object);
        Ok(())
    }

    /// Register a section (for :ref: targets)
    pub fn register_section(
        &mut self,
        label: String,
        title: String,
        docname: String,
        location: crate::domains::ReferenceLocation,
    ) -> Result<(), BuildError> {
        let qualified_name = format!("{}#{}", docname, label);
        let object = DomainObject {
            id: format!("ref:{}", label),
            name: label.clone(),
            object_type: "section".to_string(),
            domain: "rst".to_string(),
            definition_location: location,
            qualified_name: qualified_name.clone(),
            metadata: {
                let mut meta = HashMap::new();
                meta.insert("title".to_string(), title);
                meta.insert("docname".to_string(), docname);
                meta
            },
            signature: None,
            docstring: None,
        };

        self.sections.insert(label, object);
        Ok(())
    }

    /// Register a figure or table label
    pub fn register_label(
        &mut self,
        label: String,
        label_type: String, // "figure", "table", "code-block", etc.
        title: Option<String>,
        docname: String,
        location: crate::domains::ReferenceLocation,
    ) -> Result<(), BuildError> {
        let qualified_name = format!("{}#{}", docname, label);
        let object = DomainObject {
            id: format!("{}:{}", label_type, label),
            name: label.clone(),
            object_type: label_type,
            domain: "rst".to_string(),
            definition_location: location,
            qualified_name: qualified_name.clone(),
            metadata: {
                let mut meta = HashMap::new();
                if let Some(title) = title {
                    meta.insert("title".to_string(), title);
                }
                meta.insert("docname".to_string(), docname);
                meta
            },
            signature: None,
            docstring: None,
        };

        self.sections.insert(label, object);
        Ok(())
    }

    /// Find suggestions for a broken reference
    fn find_suggestions(&self, target: &str, ref_type: &ReferenceType) -> Vec<String> {
        let mut suggestions = Vec::new();

        let objects = match ref_type {
            ReferenceType::Document => &self.documents,
            ReferenceType::Section => &self.sections,
            _ => &self.sections, // Default to sections for other types
        };

        // Look for similar names
        for (key, obj) in objects {
            // Exact match on key
            if key.contains(target) || target.contains(key) {
                suggestions.push(key.clone());
            }
            // Title match
            if let Some(title) = obj.metadata.get("title") {
                if title.to_lowercase().contains(&target.to_lowercase()) {
                    suggestions.push(key.clone());
                }
            }
        }

        suggestions.sort();
        suggestions.dedup();
        suggestions.truncate(5); // Limit to 5 suggestions

        suggestions
    }
}

impl DomainValidator for RstDomain {
    fn domain_name(&self) -> &str {
        "rst"
    }

    fn supported_reference_types(&self) -> Vec<ReferenceType> {
        vec![
            ReferenceType::Document,
            ReferenceType::Section,
            ReferenceType::Custom("numref".to_string()),
        ]
    }

    fn register_object(&mut self, object: DomainObject) -> Result<(), BuildError> {
        match object.object_type.as_str() {
            "document" => {
                self.documents.insert(object.name.clone(), object);
            }
            "section" | "figure" | "table" | "code-block" => {
                self.sections.insert(object.name.clone(), object);
            }
            _ => {
                return Err(BuildError::ValidationError(format!(
                    "Unknown RST object type: {}",
                    object.object_type
                )));
            }
        }
        Ok(())
    }

    fn resolve_reference(&self, reference: &CrossReference) -> Option<DomainObject> {
        match reference.ref_type {
            ReferenceType::Document => {
                // For documents, target might include .rst extension or not
                let target = reference.target.trim_end_matches(".rst");
                self.documents
                    .get(target)
                    .cloned()
                    .or_else(|| self.documents.get(&reference.target).cloned())
            }
            ReferenceType::Section => self.sections.get(&reference.target).cloned(),
            _ => {
                // Try sections first, then documents
                self.sections
                    .get(&reference.target)
                    .cloned()
                    .or_else(|| self.documents.get(&reference.target).cloned())
            }
        }
    }

    fn validate_reference(&self, reference: &CrossReference) -> ReferenceValidationResult {
        if let Some(target_object) = self.resolve_reference(reference) {
            ReferenceValidationResult {
                reference: reference.clone(),
                is_valid: true,
                target_object: Some(target_object),
                error_message: None,
                suggestions: Vec::new(),
            }
        } else {
            let suggestions = self.find_suggestions(&reference.target, &reference.ref_type);
            let error_message = match reference.ref_type {
                ReferenceType::Document => {
                    if suggestions.is_empty() {
                        format!("Document '{}' not found", reference.target)
                    } else {
                        format!(
                            "Document '{}' not found. Did you mean: {}?",
                            reference.target,
                            suggestions.join(", ")
                        )
                    }
                }
                ReferenceType::Section => {
                    if suggestions.is_empty() {
                        format!("Section label '{}' not found", reference.target)
                    } else {
                        format!(
                            "Section label '{}' not found. Did you mean: {}?",
                            reference.target,
                            suggestions.join(", ")
                        )
                    }
                }
                _ => {
                    if suggestions.is_empty() {
                        format!("Reference target '{}' not found", reference.target)
                    } else {
                        format!(
                            "Reference target '{}' not found. Did you mean: {}?",
                            reference.target,
                            suggestions.join(", ")
                        )
                    }
                }
            };

            ReferenceValidationResult {
                reference: reference.clone(),
                is_valid: false,
                target_object: None,
                error_message: Some(error_message),
                suggestions,
            }
        }
    }

    fn get_all_objects(&self) -> Vec<&DomainObject> {
        let mut objects = Vec::new();
        objects.extend(self.documents.values());
        objects.extend(self.sections.values());
        objects
    }

    fn clear_objects(&mut self) {
        self.documents.clear();
        self.sections.clear();
    }
}

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

    fn create_test_location() -> ReferenceLocation {
        ReferenceLocation {
            docname: "test.rst".to_string(),
            lineno: Some(10),
            column: Some(5),
            source_path: Some("test.rst".to_string()),
        }
    }

    #[test]
    fn test_rst_domain_creation() {
        let domain = RstDomain::new();
        assert_eq!(domain.domain_name(), "rst");
        assert!(domain
            .supported_reference_types()
            .contains(&ReferenceType::Document));
        assert!(domain
            .supported_reference_types()
            .contains(&ReferenceType::Section));
    }

    #[test]
    fn test_register_document() {
        let mut domain = RstDomain::new();

        let result = domain.register_document(
            "index".to_string(),
            "Home Page".to_string(),
            create_test_location(),
        );

        assert!(result.is_ok());
        assert_eq!(domain.documents.len(), 1);

        let doc = domain.documents.get("index").unwrap();
        assert_eq!(doc.name, "index");
        assert_eq!(doc.object_type, "document");
        assert_eq!(doc.metadata.get("title"), Some(&"Home Page".to_string()));
    }

    #[test]
    fn test_register_section() {
        let mut domain = RstDomain::new();

        let result = domain.register_section(
            "introduction".to_string(),
            "Introduction".to_string(),
            "index".to_string(),
            create_test_location(),
        );

        assert!(result.is_ok());
        assert_eq!(domain.sections.len(), 1);

        let section = domain.sections.get("introduction").unwrap();
        assert_eq!(section.name, "introduction");
        assert_eq!(section.object_type, "section");
        assert_eq!(
            section.metadata.get("title"),
            Some(&"Introduction".to_string())
        );
        assert_eq!(section.metadata.get("docname"), Some(&"index".to_string()));
    }

    #[test]
    fn test_document_reference_validation() {
        let mut domain = RstDomain::new();

        domain
            .register_document(
                "getting-started".to_string(),
                "Getting Started".to_string(),
                create_test_location(),
            )
            .unwrap();

        // Valid reference
        let valid_ref = CrossReference {
            ref_type: ReferenceType::Document,
            target: "getting-started".to_string(),
            display_text: None,
            source_location: create_test_location(),
            is_external: false,
        };

        let result = domain.validate_reference(&valid_ref);
        assert!(result.is_valid);
        assert!(result.target_object.is_some());

        // Valid reference with .rst extension
        let valid_ref_ext = CrossReference {
            ref_type: ReferenceType::Document,
            target: "getting-started.rst".to_string(),
            display_text: None,
            source_location: create_test_location(),
            is_external: false,
        };

        let result = domain.validate_reference(&valid_ref_ext);
        assert!(result.is_valid);

        // Invalid reference
        let invalid_ref = CrossReference {
            ref_type: ReferenceType::Document,
            target: "nonexistent".to_string(),
            display_text: None,
            source_location: create_test_location(),
            is_external: false,
        };

        let result = domain.validate_reference(&invalid_ref);
        assert!(!result.is_valid);
        assert!(result.error_message.is_some());
    }

    #[test]
    fn test_section_reference_validation() {
        let mut domain = RstDomain::new();

        domain
            .register_section(
                "api-reference".to_string(),
                "API Reference".to_string(),
                "api".to_string(),
                create_test_location(),
            )
            .unwrap();

        // Valid reference
        let valid_ref = CrossReference {
            ref_type: ReferenceType::Section,
            target: "api-reference".to_string(),
            display_text: None,
            source_location: create_test_location(),
            is_external: false,
        };

        let result = domain.validate_reference(&valid_ref);
        assert!(result.is_valid);
        assert!(result.target_object.is_some());

        // Invalid reference with suggestions
        let invalid_ref = CrossReference {
            ref_type: ReferenceType::Section,
            target: "api".to_string(), // Close but not exact
            display_text: None,
            source_location: create_test_location(),
            is_external: false,
        };

        let result = domain.validate_reference(&invalid_ref);
        assert!(!result.is_valid);
        assert!(!result.suggestions.is_empty());
    }
}