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
//! Directive & Role Validation System Example
//!
//! This example demonstrates the comprehensive directive and role validation system,
//! showing how to validate RST content, detect errors and warnings, and get suggestions
//! for fixing issues.

use sphinx_ultra::directives::validation::{
    DirectiveValidationResult, DirectiveValidationSystem, RoleValidationResult,
    StatisticalDirectiveRoleParser,
};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    println!("Sphinx Ultra - Directive & Role Validation System Example");
    println!("=========================================================");
    println!();

    // Create a validation system with built-in validators
    let mut validation_system = DirectiveValidationSystem::new();

    println!("✅ Initialized directive and role validation system");
    println!(
        "📋 Registered {} directives and {} roles",
        validation_system
            .directive_registry()
            .get_registered_directives()
            .len(),
        validation_system
            .role_registry()
            .get_registered_roles()
            .len()
    );
    println!();

    // Sample RST content with various directives and roles
    let sample_content = r#"
Getting Started Guide
=====================

Welcome to our documentation! This guide shows various Sphinx directives and roles.

.. note:: 
   This is an important note about the setup process.
   Make sure to read this carefully.

Installation
------------

First, download the :download:`installer.exe` file from our website.

.. code-block:: python
   :linenos:
   :caption: Example Python code

   def hello_world():
       print("Hello, world!")
       return True

.. warning::
   Be careful when running this command!

Advanced Configuration
----------------------

See the :doc:`configuration` guide for details. You can also refer to 
:ref:`advanced-settings` for more options.

For keyboard shortcuts, use :kbd:`Ctrl+C` to copy and :kbd:`Ctrl+V` to paste.

.. figure:: architecture.png
   :width: 500px
   :alt: System architecture diagram
   :align: center

   This figure shows the overall system architecture.

Mathematical expressions can be written as :math:`x = \frac{a + b}{c}`.

.. admonition:: Custom Note
   :class: tip

   This is a custom admonition with additional styling.

Common Issues
-------------

.. literalinclude:: examples/config.py
   :language: python
   :lines: 1-20
   :emphasize-lines: 5,10

For more help, see :doc:`troubleshooting` or contact support.

Problematic Examples
--------------------

.. note::

.. code-block::
   
   print("No language specified")

.. image::

See :doc:`` and :ref:``.

Download :download:`nonexistent` file.

.. unknowndirective:: test

Use :unknownrole:`something` here.

.. math::

.. figure:: image.png
   :width: invalid-width
   :align: invalid-alignment

.. toctree::
   :maxdepth: not-a-number
"#;

    println!("📄 Parsing sample RST content...");

    // Parse the content to extract directives and roles
    let mut parser = StatisticalDirectiveRoleParser::new("getting-started.rst".to_string());
    let (directives, roles) = parser.parse_with_statistics(sample_content);

    let parse_stats = parser.statistics();
    println!(
        "🔍 Found {} directives and {} roles:",
        parse_stats.directive_count, parse_stats.role_count
    );

    // Display found directives
    for (i, directive) in directives.iter().enumerate() {
        println!(
            "  {}. {} -> '{}' (line {}, {} args, {} options)",
            i + 1,
            directive.name,
            directive.arguments.join(" "),
            directive.location.line,
            directive.arguments.len(),
            directive.options.len()
        );
    }

    // Display found roles
    for (i, role) in roles.iter().enumerate() {
        println!(
            "  {}. {} -> '{}' (line {}{})",
            i + 1 + directives.len(),
            role.name,
            role.target,
            role.location.line,
            if role.display_text.is_some() {
                " with display text"
            } else {
                ""
            }
        );
    }
    println!();

    println!("🔍 Validating directives and roles...");
    println!();

    // Track validation issues
    let mut valid_count = 0;
    let mut warning_count = 0;
    let mut error_count = 0;
    let mut unknown_count = 0;
    let mut issues = Vec::new();

    // Validate all directives
    for directive in &directives {
        let result = validation_system.validate_directive(directive);

        match &result {
            DirectiveValidationResult::Valid => {
                valid_count += 1;
                println!(
                    "✅ VALID: {} directive '{}' (line {})",
                    directive.name,
                    directive.arguments.join(" "),
                    directive.location.line
                );
            }
            DirectiveValidationResult::Warning(msg) => {
                warning_count += 1;
                println!(
                    "⚠️  WARNING: {} directive '{}' (line {})",
                    directive.name,
                    directive.arguments.join(" "),
                    directive.location.line
                );
                println!("    Issue: {}", msg);
                issues.push(format!(
                    "Directive '{}' at line {}: {}",
                    directive.name, directive.location.line, msg
                ));
            }
            DirectiveValidationResult::Error(msg) => {
                error_count += 1;
                println!(
                    "❌ ERROR: {} directive '{}' (line {})",
                    directive.name,
                    directive.arguments.join(" "),
                    directive.location.line
                );
                println!("    Error: {}", msg);
                issues.push(format!(
                    "Directive '{}' at line {}: {}",
                    directive.name, directive.location.line, msg
                ));
            }
            DirectiveValidationResult::Unknown => {
                unknown_count += 1;
                println!(
                    "❓ UNKNOWN: {} directive '{}' (line {})",
                    directive.name,
                    directive.arguments.join(" "),
                    directive.location.line
                );

                // Get suggestions for unknown directives
                let suggestions = validation_system.get_directive_suggestions(directive);
                if !suggestions.is_empty() {
                    println!("    Suggestions: {}", suggestions.join("; "));
                }
                issues.push(format!(
                    "Unknown directive '{}' at line {}",
                    directive.name, directive.location.line
                ));
            }
        }
    }

    println!();

    // Validate all roles
    for role in &roles {
        let result = validation_system.validate_role(role);

        match &result {
            RoleValidationResult::Valid => {
                valid_count += 1;
                println!(
                    "✅ VALID: {} role '{}' (line {})",
                    role.name, role.target, role.location.line
                );
            }
            RoleValidationResult::Warning(msg) => {
                warning_count += 1;
                println!(
                    "⚠️  WARNING: {} role '{}' (line {})",
                    role.name, role.target, role.location.line
                );
                println!("    Issue: {}", msg);
                issues.push(format!(
                    "Role '{}' at line {}: {}",
                    role.name, role.location.line, msg
                ));
            }
            RoleValidationResult::Error(msg) => {
                error_count += 1;
                println!(
                    "❌ ERROR: {} role '{}' (line {})",
                    role.name, role.target, role.location.line
                );
                println!("    Error: {}", msg);
                issues.push(format!(
                    "Role '{}' at line {}: {}",
                    role.name, role.location.line, msg
                ));
            }
            RoleValidationResult::Unknown => {
                unknown_count += 1;
                println!(
                    "❓ UNKNOWN: {} role '{}' (line {})",
                    role.name, role.target, role.location.line
                );

                // Get suggestions for unknown roles
                let suggestions = validation_system.get_role_suggestions(role);
                if !suggestions.is_empty() {
                    println!("    Suggestions: {}", suggestions.join("; "));
                }
                issues.push(format!(
                    "Unknown role '{}' at line {}",
                    role.name, role.location.line
                ));
            }
        }
    }

    println!();
    println!("📊 Validation Summary");
    println!("==================");
    let total_items = directives.len() + roles.len();
    println!("Total items: {}", total_items);
    println!(
        "Valid: {} ({:.1}%)",
        valid_count,
        valid_count as f64 / total_items as f64 * 100.0
    );
    println!(
        "Warnings: {} ({:.1}%)",
        warning_count,
        warning_count as f64 / total_items as f64 * 100.0
    );
    println!(
        "Errors: {} ({:.1}%)",
        error_count,
        error_count as f64 / total_items as f64 * 100.0
    );
    println!(
        "Unknown: {} ({:.1}%)",
        unknown_count,
        unknown_count as f64 / total_items as f64 * 100.0
    );
    println!();

    // Display detailed statistics
    println!("📈 Detailed Statistics");
    println!("=====================");
    let stats = validation_system.statistics();
    println!("{}", stats);

    // Parse statistics
    println!("📊 Parser Statistics");
    println!("===================");
    println!("Lines processed: {}", parse_stats.lines_processed);
    println!("Items found: {}", parse_stats.total_items());
    println!();

    println!("Directives by type:");
    for (directive_type, count) in &parse_stats.directives_by_type {
        println!("  {}: {}", directive_type, count);
    }
    println!();

    println!("Roles by type:");
    for (role_type, count) in &parse_stats.roles_by_type {
        println!("  {}: {}", role_type, count);
    }
    println!();

    // Show issues summary
    if !issues.is_empty() {
        println!("🚨 Issues Found");
        println!("===============");
        for (i, issue) in issues.iter().enumerate() {
            println!("{}. {}", i + 1, issue);
        }
        println!();
    }

    // Demonstrate directive suggestions
    println!("💡 Suggestion Examples");
    println!("=====================");

    // Create some problematic directives to show suggestions
    let problematic_directives = vec![
        ("note", vec![], std::collections::HashMap::new(), ""), // Note without content
        (
            "code-block",
            vec![],
            std::collections::HashMap::new(),
            "print('test')",
        ), // Code block without language
        ("image", vec![], std::collections::HashMap::new(), ""), // Image without path
    ];

    for (name, args, options, content) in problematic_directives {
        let directive = sphinx_ultra::directives::validation::ParsedDirective {
            name: name.to_string(),
            arguments: args,
            options,
            content: content.to_string(),
            location: sphinx_ultra::directives::validation::SourceLocation {
                file: "example.rst".to_string(),
                line: 1,
                column: 1,
            },
        };

        let suggestions = validation_system.get_directive_suggestions(&directive);
        if !suggestions.is_empty() {
            println!("Directive '{}': {}", name, suggestions.join("; "));
        }
    }

    println!();
    println!("🎉 Directive and role validation completed successfully!");

    let success_rate = valid_count as f64 / total_items as f64 * 100.0;
    println!("Overall success rate: {:.1}%", success_rate);

    if error_count > 0 || unknown_count > 0 {
        println!(
            "⚠️  Please fix the {} error(s) and {} unknown item(s) before building.",
            error_count, unknown_count
        );
        std::process::exit(1);
    } else if warning_count > 0 {
        println!(
            "⚠️  Consider addressing the {} warning(s) to improve documentation quality.",
            warning_count
        );
    } else {
        println!("✅ All directives and roles are valid!");
    }

    Ok(())
}