Skip to main content

sklears_core/
api_data_structures.rs

1//! Core Data Structures for API Reference Generation
2//!
3//! This module contains all the data structures used by the API reference generator,
4//! including trait information, type definitions, code examples, and interactive
5//! documentation components.
6
7use crate::api_generator_config::{GeneratorConfig, PlaygroundConfig};
8use crate::error::{Result, SklearsError};
9use serde::{Deserialize, Serialize};
10use std::collections::HashMap;
11use std::time::Duration;
12
13// ================================================================================================
14// CORE API REFERENCE STRUCTURES
15// ================================================================================================
16
17/// Complete API reference for a crate
18#[derive(Debug, Clone, Serialize, Deserialize)]
19pub struct ApiReference {
20    /// Name of the crate
21    pub crate_name: String,
22    /// Version of the crate
23    pub version: String,
24    /// Analyzed traits
25    pub traits: Vec<TraitInfo>,
26    /// Extracted type information
27    pub types: Vec<TypeInfo>,
28    /// Code examples
29    pub examples: Vec<CodeExample>,
30    /// Cross-references between API elements
31    pub cross_references: HashMap<String, Vec<String>>,
32    /// Generation metadata
33    pub metadata: ApiMetadata,
34}
35
36impl ApiReference {
37    /// Convert to JSON representation
38    pub fn to_json(&self) -> Result<String> {
39        serde_json::to_string_pretty(self)
40            .map_err(|e| SklearsError::InvalidInput(format!("JSON serialization failed: {}", e)))
41    }
42
43    /// Convert to HTML representation
44    pub fn to_html(&self) -> Result<String> {
45        let mut html = String::new();
46        html.push_str(&format!(
47            "<html><head><title>API Reference - {}</title></head><body>",
48            self.crate_name
49        ));
50        html.push_str(&format!("<h1>API Reference for {}</h1>", self.crate_name));
51
52        // Traits section
53        if !self.traits.is_empty() {
54            html.push_str("<h2>Traits</h2>");
55            for trait_info in &self.traits {
56                html.push_str(&format!("<h3>{}</h3>", trait_info.name));
57                html.push_str(&format!("<p>{}</p>", trait_info.description));
58
59                if !trait_info.methods.is_empty() {
60                    html.push_str("<h4>Methods</h4><ul>");
61                    for method in &trait_info.methods {
62                        html.push_str(&format!(
63                            "<li><code>{}</code> - {}</li>",
64                            method.signature, method.description
65                        ));
66                    }
67                    html.push_str("</ul>");
68                }
69            }
70        }
71
72        // Types section
73        if !self.types.is_empty() {
74            html.push_str("<h2>Types</h2>");
75            for type_info in &self.types {
76                html.push_str(&format!("<h3>{}</h3>", type_info.name));
77                html.push_str(&format!("<p>{}</p>", type_info.description));
78            }
79        }
80
81        // Examples section
82        if !self.examples.is_empty() {
83            html.push_str("<h2>Examples</h2>");
84            for example in &self.examples {
85                html.push_str(&format!("<h3>{}</h3>", example.title));
86                html.push_str(&format!("<p>{}</p>", example.description));
87                html.push_str(&format!(
88                    "<pre><code class=\"{}\">{}</code></pre>",
89                    example.language, example.code
90                ));
91            }
92        }
93
94        html.push_str("</body></html>");
95        Ok(html)
96    }
97
98    /// Convert to Markdown representation
99    pub fn to_markdown(&self) -> Result<String> {
100        let mut md = String::new();
101        md.push_str(&format!("# API Reference - {}\n\n", self.crate_name));
102        md.push_str(&format!("Version: {}\n\n", self.version));
103
104        // Traits section
105        if !self.traits.is_empty() {
106            md.push_str("## Traits\n\n");
107            for trait_info in &self.traits {
108                md.push_str(&format!("### {}\n\n", trait_info.name));
109                md.push_str(&format!("{}\n\n", trait_info.description));
110
111                if !trait_info.methods.is_empty() {
112                    md.push_str("#### Methods\n\n");
113                    for method in &trait_info.methods {
114                        md.push_str(&format!(
115                            "- `{}` - {}\n",
116                            method.signature, method.description
117                        ));
118                    }
119                    md.push('\n');
120                }
121            }
122        }
123
124        // Types section
125        if !self.types.is_empty() {
126            md.push_str("## Types\n\n");
127            for type_info in &self.types {
128                md.push_str(&format!("### {}\n\n", type_info.name));
129                md.push_str(&format!("{}\n\n", type_info.description));
130            }
131        }
132
133        // Examples section
134        if !self.examples.is_empty() {
135            md.push_str("## Examples\n\n");
136            for example in &self.examples {
137                md.push_str(&format!("### {}\n\n", example.title));
138                md.push_str(&format!("{}\n\n", example.description));
139                md.push_str(&format!(
140                    "```{}\n{}\n```\n\n",
141                    example.language, example.code
142                ));
143            }
144        }
145
146        Ok(md)
147    }
148
149    /// Generate interactive playground HTML
150    pub fn to_interactive(&self) -> Result<String> {
151        let mut html = String::new();
152        html.push_str("<!DOCTYPE html><html><head>");
153        html.push_str("<title>Interactive API Reference</title>");
154        html.push_str(
155            "<script src=\"https://unpkg.com/@webassembly/wasi-sdk@0.11.0/bin/wasm-ld\"></script>",
156        );
157        html.push_str("</head><body>");
158        html.push_str(&format!(
159            "<h1>Interactive Reference - {}</h1>",
160            self.crate_name
161        ));
162        html.push_str("<div id=\"playground\">");
163        html.push_str("<textarea id=\"code-editor\" rows=\"20\" cols=\"80\">");
164
165        // Add a sample example
166        if let Some(example) = self.examples.first() {
167            html.push_str(&example.code);
168        } else {
169            html.push_str(
170                "// Write your code here\nfn main() {\n    println!(\"Hello, sklears!\");\n}",
171            );
172        }
173
174        html.push_str("</textarea>");
175        html.push_str("<br><button onclick=\"runCode()\">Run Code</button>");
176        html.push_str("<div id=\"output\"></div>");
177        html.push_str("</div>");
178        html.push_str("<script>");
179        html.push_str("function runCode() {");
180        html.push_str("  const code = document.getElementById('code-editor').value;");
181        html.push_str(
182            "  document.getElementById('output').innerHTML = 'Code execution would happen here';",
183        );
184        html.push('}');
185        html.push_str("</script>");
186        html.push_str("</body></html>");
187
188        Ok(html)
189    }
190}
191
192/// Information about a crate
193#[derive(Debug, Clone)]
194#[allow(dead_code)]
195pub struct CrateInfo {
196    pub name: String,
197    pub version: String,
198    pub description: String,
199    pub modules: Vec<String>,
200    pub dependencies: Vec<String>,
201}
202
203/// Metadata about the API reference generation
204#[derive(Debug, Clone, Serialize, Deserialize)]
205pub struct ApiMetadata {
206    /// When the reference was generated
207    pub generation_time: String,
208    /// Version of the generator tool
209    pub generator_version: String,
210    /// Version of the crate being documented
211    pub crate_version: String,
212    /// Rust version used
213    pub rust_version: String,
214    /// Configuration used for generation
215    pub config: GeneratorConfig,
216}
217
218impl Default for ApiMetadata {
219    fn default() -> Self {
220        Self {
221            generation_time: chrono::Utc::now().to_string(),
222            generator_version: env!("CARGO_PKG_VERSION").to_string(),
223            crate_version: "unknown".to_string(),
224            rust_version: env!("CARGO_PKG_RUST_VERSION").to_string(),
225            config: GeneratorConfig::default(),
226        }
227    }
228}
229
230// ================================================================================================
231// TRAIT-RELATED STRUCTURES
232// ================================================================================================
233
234/// Information about a trait
235#[derive(Debug, Clone, Serialize, Deserialize, Default)]
236pub struct TraitInfo {
237    /// Name of the trait
238    pub name: String,
239    /// Documentation description
240    pub description: String,
241    /// Full path to the trait
242    pub path: String,
243    /// Generic parameters
244    pub generics: Vec<String>,
245    /// Associated types
246    pub associated_types: Vec<AssociatedType>,
247    /// Methods defined in the trait
248    pub methods: Vec<MethodInfo>,
249    /// Supertraits (traits this trait extends)
250    pub supertraits: Vec<String>,
251    /// Implementations found
252    pub implementations: Vec<String>,
253}
254
255/// Information about an associated type
256#[derive(Debug, Clone, Serialize, Deserialize, Default)]
257pub struct AssociatedType {
258    /// Name of the associated type
259    pub name: String,
260    /// Documentation for the associated type
261    pub description: String,
262    /// Bounds on the associated type
263    pub bounds: Vec<String>,
264}
265
266/// Information about a method
267#[derive(Debug, Clone, Serialize, Deserialize, Default)]
268pub struct MethodInfo {
269    /// Name of the method
270    pub name: String,
271    /// Full signature of the method
272    pub signature: String,
273    /// Documentation description
274    pub description: String,
275    /// Parameters of the method
276    pub parameters: Vec<ParameterInfo>,
277    /// Return type
278    pub return_type: String,
279    /// Whether the method is required or has a default implementation
280    pub required: bool,
281}
282
283/// Information about a method parameter
284#[derive(Debug, Clone, Serialize, Deserialize, Default)]
285pub struct ParameterInfo {
286    /// Name of the parameter
287    pub name: String,
288    /// Type of the parameter
289    pub param_type: String,
290    /// Documentation for the parameter
291    pub description: String,
292    /// Whether the parameter is optional
293    pub optional: bool,
294}
295
296// ================================================================================================
297// TYPE-RELATED STRUCTURES
298// ================================================================================================
299
300/// Information about a type
301#[derive(Debug, Clone, Serialize, Deserialize)]
302pub struct TypeInfo {
303    /// Name of the type
304    pub name: String,
305    /// Documentation description
306    pub description: String,
307    /// Full path to the type
308    pub path: String,
309    /// Kind of type (struct, enum, union, etc.)
310    pub kind: TypeKind,
311    /// Generic parameters
312    pub generics: Vec<String>,
313    /// Fields (for structs) or variants (for enums)
314    pub fields: Vec<FieldInfo>,
315    /// Trait implementations
316    pub trait_impls: Vec<String>,
317}
318
319/// Kind of type definition
320#[derive(Debug, Clone, Serialize, Deserialize)]
321pub enum TypeKind {
322    Struct,
323    Enum,
324    Union,
325    TypeAlias,
326    Trait,
327}
328
329/// Information about a field or enum variant
330#[derive(Debug, Clone, Serialize, Deserialize)]
331pub struct FieldInfo {
332    /// Name of the field
333    pub name: String,
334    /// Type of the field
335    pub field_type: String,
336    /// Documentation for the field
337    pub description: String,
338    /// Visibility of the field
339    pub visibility: Visibility,
340}
341
342/// Visibility levels
343#[derive(Debug, Clone, Serialize, Deserialize)]
344pub enum Visibility {
345    Public,
346    Private,
347    Restricted(String),
348}
349
350impl std::fmt::Display for Visibility {
351    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
352        match self {
353            Visibility::Public => write!(f, "public"),
354            Visibility::Private => write!(f, "private"),
355            Visibility::Restricted(path) => write!(f, "restricted({path})"),
356        }
357    }
358}
359
360// ================================================================================================
361// EXAMPLE-RELATED STRUCTURES
362// ================================================================================================
363
364/// Code example extracted from documentation
365#[derive(Debug, Clone, Serialize, Deserialize)]
366pub struct CodeExample {
367    /// Title of the example
368    pub title: String,
369    /// Description of what the example demonstrates
370    pub description: String,
371    /// The actual code
372    pub code: String,
373    /// Programming language (usually "rust")
374    pub language: String,
375    /// Whether this example can be executed
376    pub runnable: bool,
377    /// Expected output when run
378    pub expected_output: Option<String>,
379}
380
381/// Result of code execution
382#[derive(Debug, Clone, Serialize, Deserialize)]
383pub struct ExecutionResult {
384    /// Standard output
385    pub stdout: String,
386    /// Standard error
387    pub stderr: String,
388    /// Exit code
389    pub exit_code: i32,
390    /// Time taken to execute
391    pub execution_time: Duration,
392    /// Memory used during execution
393    pub memory_used: usize,
394    /// Raw output data
395    pub output: String,
396}
397
398// ================================================================================================
399// INTERACTIVE DOCUMENTATION STRUCTURES
400// ================================================================================================
401
402/// Interactive documentation with live examples and features
403#[derive(Debug, Clone, Serialize, Deserialize)]
404pub struct InteractiveDocumentation {
405    /// Base API reference
406    pub api_reference: ApiReference,
407    /// Live executable examples
408    pub live_examples: Vec<LiveCodeExample>,
409    /// Searchable index
410    pub searchable_index: SearchIndex,
411    /// Interactive tutorials
412    pub interactive_tutorials: Vec<InteractiveTutorial>,
413    /// Visualizations
414    pub visualizations: Vec<ApiVisualization>,
415    /// Playground configuration
416    pub playground_config: PlaygroundConfig,
417}
418
419/// Live code example with execution capabilities
420#[derive(Debug, Clone, Serialize, Deserialize)]
421pub struct LiveCodeExample {
422    /// Original code example
423    pub original_example: CodeExample,
424    /// Execution result
425    pub execution_result: ExecutionResult,
426    /// Interactive UI elements
427    pub interactive_elements: Vec<InteractiveElement>,
428    /// Visualization of the example
429    pub visualization: ExampleVisualization,
430    /// Whether the code can be edited
431    pub editable: bool,
432    /// Whether to provide real-time feedback
433    pub real_time_feedback: bool,
434}
435
436/// Interactive element for examples
437#[derive(Debug, Clone, Serialize, Deserialize)]
438pub struct InteractiveElement {
439    /// Type of interactive element
440    pub element_type: InteractiveElementType,
441    /// Unique identifier
442    pub id: String,
443    /// Display label
444    pub label: String,
445    /// Action to perform
446    pub action: String,
447    /// Target for the action
448    pub target: String,
449}
450
451/// Types of interactive elements
452#[derive(Debug, Clone, Serialize, Deserialize)]
453pub enum InteractiveElementType {
454    Button,
455    Slider,
456    Toggle,
457    Input,
458    Dropdown,
459}
460
461/// Visualization for code examples
462#[derive(Debug, Clone, Serialize, Deserialize)]
463pub struct ExampleVisualization {
464    /// Type of visualization
465    pub visualization_type: VisualizationType,
466    /// Data to visualize
467    pub data: String,
468    /// Whether visualization is interactive
469    pub interactive: bool,
470    /// Whether to update in real-time
471    pub real_time_updates: bool,
472    /// Visualization configuration
473    pub config: VisualizationConfig,
474}
475
476/// Types of visualizations
477#[derive(Debug, Clone, Serialize, Deserialize)]
478pub enum VisualizationType {
479    FlowChart,
480    Graph,
481    Timeline,
482    Tree,
483    Network,
484    Chart,
485}
486
487/// Configuration for visualizations
488#[derive(Debug, Clone, Serialize, Deserialize)]
489pub struct VisualizationConfig {
490    /// Width in pixels
491    pub width: u32,
492    /// Height in pixels
493    pub height: u32,
494    /// Theme name
495    pub theme: String,
496    /// Whether animations are enabled
497    pub animation_enabled: bool,
498}
499
500/// Interactive tutorial
501#[derive(Debug, Clone, Serialize, Deserialize)]
502pub struct InteractiveTutorial {
503    /// Tutorial title
504    pub title: String,
505    /// Tutorial description
506    pub description: String,
507    /// Tutorial steps
508    pub steps: Vec<TutorialStep>,
509    /// Difficulty level
510    pub difficulty: TutorialDifficulty,
511    /// Estimated completion time
512    pub estimated_time: Duration,
513}
514
515/// Individual tutorial step
516#[derive(Debug, Clone, Serialize, Deserialize)]
517pub struct TutorialStep {
518    /// Step title
519    pub title: String,
520    /// Step content
521    pub content: String,
522    /// Code example for this step
523    pub code_example: Option<CodeExample>,
524    /// Interactive elements for this step
525    pub interactive_elements: Vec<InteractiveElement>,
526    /// Expected outcome
527    pub expected_outcome: String,
528}
529
530/// Tutorial difficulty levels
531#[derive(Debug, Clone, Serialize, Deserialize)]
532pub enum TutorialDifficulty {
533    Beginner,
534    Intermediate,
535    Advanced,
536    Expert,
537}
538
539/// API visualization
540#[derive(Debug, Clone, Serialize, Deserialize)]
541pub struct ApiVisualization {
542    /// Visualization title
543    pub title: String,
544    /// Visualization type
545    pub visualization_type: VisualizationType,
546    /// Data to visualize
547    pub data: ApiVisualizationData,
548    /// Configuration
549    pub config: VisualizationConfig,
550}
551
552/// Data for API visualizations
553#[derive(Debug, Clone, Serialize, Deserialize)]
554pub struct ApiVisualizationData {
555    /// Nodes in the visualization
556    pub nodes: Vec<VisualizationNode>,
557    /// Edges between nodes
558    pub edges: Vec<VisualizationEdge>,
559    /// Metadata
560    pub metadata: HashMap<String, String>,
561}
562
563/// Node in a visualization
564#[derive(Debug, Clone, Serialize, Deserialize)]
565pub struct VisualizationNode {
566    /// Node ID
567    pub id: String,
568    /// Node label
569    pub label: String,
570    /// Node type
571    pub node_type: String,
572    /// Node properties
573    pub properties: HashMap<String, String>,
574}
575
576/// Edge in a visualization
577#[derive(Debug, Clone, Serialize, Deserialize)]
578pub struct VisualizationEdge {
579    /// Source node ID
580    pub source: String,
581    /// Target node ID
582    pub target: String,
583    /// Edge label
584    pub label: String,
585    /// Edge type
586    pub edge_type: String,
587    /// Edge properties
588    pub properties: HashMap<String, String>,
589}
590
591// ================================================================================================
592// WEBASSEMBLY PLAYGROUND STRUCTURES
593// ================================================================================================
594
595/// WebAssembly playground configuration
596#[derive(Debug, Clone, Serialize, Deserialize)]
597pub struct WasmPlayground {
598    /// HTML template for the playground
599    pub html_template: String,
600    /// JavaScript code for WASM bindings
601    pub javascript_code: String,
602    /// CSS styling for the playground
603    pub css_styling: String,
604    /// Rust code template
605    pub rust_code: String,
606    /// Build instructions
607    pub build_instructions: Vec<String>,
608}
609
610/// WASM binding for Rust code
611#[derive(Debug, Clone, Serialize, Deserialize)]
612pub struct WasmBinding {
613    /// Rust name
614    pub rust_name: String,
615    /// JavaScript wrapper name
616    pub js_name: String,
617    /// Available methods
618    pub methods: Vec<WasmMethod>,
619    /// Usage examples
620    pub examples: Vec<String>,
621}
622
623/// WASM method binding
624#[derive(Debug, Clone, Serialize, Deserialize)]
625pub struct WasmMethod {
626    /// Method name
627    pub name: String,
628    /// JavaScript signature
629    pub js_signature: String,
630    /// Method description
631    pub description: String,
632}
633
634/// UI component for interactive features
635#[derive(Debug, Clone, Serialize, Deserialize)]
636pub struct UIComponent {
637    /// Component name
638    pub name: String,
639    /// Component type
640    pub component_type: UIComponentType,
641    /// Component properties
642    pub props: Vec<(String, String)>,
643    /// HTML template
644    pub template: String,
645}
646
647/// Types of UI components
648#[derive(Debug, Clone, Serialize, Deserialize)]
649pub enum UIComponentType {
650    CodeEditor,
651    OutputPanel,
652    ApiExplorer,
653    ExampleGallery,
654    SearchBox,
655    NavigationMenu,
656}
657
658// ================================================================================================
659// SEARCH AND INDEXING STRUCTURES
660// ================================================================================================
661
662/// Search index for API elements
663#[derive(Debug, Clone, Serialize, Deserialize)]
664pub struct SearchIndex {
665    /// Indexed items
666    pub items: Vec<SearchItem>,
667    /// Search metadata
668    pub metadata: SearchMetadata,
669}
670
671impl SearchIndex {
672    /// Create a new empty search index
673    pub fn new() -> Self {
674        Self {
675            items: Vec::new(),
676            metadata: SearchMetadata::default(),
677        }
678    }
679
680    /// Add an item to the search index
681    pub fn add_item(&mut self, item: SearchItem) -> Result<()> {
682        self.items.push(item);
683        self.metadata.total_items += 1;
684        Ok(())
685    }
686
687    /// Search for items matching a query
688    pub fn search(&self, query: &str) -> Vec<&SearchItem> {
689        self.items
690            .iter()
691            .filter(|item| {
692                item.name.to_lowercase().contains(&query.to_lowercase())
693                    || item
694                        .description
695                        .to_lowercase()
696                        .contains(&query.to_lowercase())
697                    || item
698                        .keywords
699                        .iter()
700                        .any(|keyword| keyword.to_lowercase().contains(&query.to_lowercase()))
701            })
702            .collect()
703    }
704}
705
706impl Default for SearchIndex {
707    fn default() -> Self {
708        Self::new()
709    }
710}
711
712/// Individual search item
713#[derive(Debug, Clone, Serialize, Deserialize)]
714pub struct SearchItem {
715    /// Item name
716    pub name: String,
717    /// Type of item
718    pub item_type: SearchItemType,
719    /// Item description
720    pub description: String,
721    /// Path to the item
722    pub path: String,
723    /// Search keywords
724    pub keywords: Vec<String>,
725    /// Relevance score
726    pub relevance_score: f64,
727}
728
729/// Types of searchable items
730#[derive(Debug, Clone, Serialize, Deserialize)]
731pub enum SearchItemType {
732    Trait,
733    Type,
734    Method,
735    Function,
736    Example,
737    Tutorial,
738    Documentation,
739}
740
741/// Search metadata
742#[derive(Debug, Clone, Serialize, Deserialize)]
743pub struct SearchMetadata {
744    /// Total number of indexed items
745    pub total_items: usize,
746    /// Index creation time
747    pub created_at: String,
748    /// Last update time
749    pub updated_at: String,
750    /// Index version
751    pub version: String,
752}
753
754impl Default for SearchMetadata {
755    fn default() -> Self {
756        let now = chrono::Utc::now().to_string();
757        Self {
758            total_items: 0,
759            created_at: now.clone(),
760            updated_at: now,
761            version: "1.0.0".to_string(),
762        }
763    }
764}
765
766/// Enhanced search index with multiple search engines
767#[derive(Debug, Clone, Serialize, Deserialize)]
768pub struct EnhancedSearchIndex {
769    /// Semantic search engine
770    pub semantic_search: SemanticSearchEngine,
771    /// Type-based search engine
772    pub type_based_search: TypeSearchEngine,
773    /// Usage pattern search engine
774    pub usage_pattern_search: UsagePatternSearchEngine,
775    /// Similarity search engine
776    pub similarity_search: SimilaritySearchEngine,
777    /// Auto-complete engine
778    pub auto_complete_engine: AutoCompleteEngine,
779    /// Search analytics
780    pub search_analytics: SearchAnalytics,
781}
782
783/// Semantic search engine
784#[derive(Debug, Clone, Serialize, Deserialize)]
785pub struct SemanticSearchEngine {
786    /// Semantic index
787    pub index: HashMap<String, Vec<f64>>,
788    /// Search model configuration
789    pub model_config: SemanticModelConfig,
790}
791
792impl SemanticSearchEngine {
793    /// Create a new semantic search engine
794    pub fn new() -> Self {
795        Self {
796            index: HashMap::new(),
797            model_config: SemanticModelConfig::default(),
798        }
799    }
800
801    /// Index a trait semantically
802    pub fn index_trait(&mut self, trait_info: &TraitInfo) -> Result<()> {
803        // In a real implementation, this would use NLP models to create embeddings
804        let embedding = vec![0.0; 128]; // Placeholder embedding
805        self.index.insert(trait_info.name.clone(), embedding);
806        Ok(())
807    }
808
809    /// Index an example semantically
810    pub fn index_example(&mut self, example: &CodeExample) -> Result<()> {
811        // In a real implementation, this would analyze code semantics
812        let embedding = vec![0.0; 128]; // Placeholder embedding
813        self.index.insert(example.title.clone(), embedding);
814        Ok(())
815    }
816}
817
818impl Default for SemanticSearchEngine {
819    fn default() -> Self {
820        Self::new()
821    }
822}
823
824/// Configuration for semantic search models
825#[derive(Debug, Clone, Serialize, Deserialize)]
826pub struct SemanticModelConfig {
827    /// Model name
828    pub model_name: String,
829    /// Embedding dimension
830    pub embedding_dim: usize,
831    /// Similarity threshold
832    pub similarity_threshold: f64,
833}
834
835impl Default for SemanticModelConfig {
836    fn default() -> Self {
837        Self {
838            model_name: "sentence-transformers/all-MiniLM-L6-v2".to_string(),
839            embedding_dim: 384,
840            similarity_threshold: 0.7,
841        }
842    }
843}
844
845/// Type-based search engine
846#[derive(Debug, Clone, Serialize, Deserialize)]
847pub struct TypeSearchEngine {
848    /// Type signatures index
849    pub signatures: HashMap<String, TypeSignature>,
850    /// Type compatibility matrix
851    pub compatibility_matrix: HashMap<String, Vec<String>>,
852}
853
854impl TypeSearchEngine {
855    /// Create a new type search engine
856    pub fn new() -> Self {
857        Self {
858            signatures: HashMap::new(),
859            compatibility_matrix: HashMap::new(),
860        }
861    }
862
863    /// Index trait signatures
864    pub fn index_trait_signatures(&mut self, trait_info: &TraitInfo) -> Result<()> {
865        for method in &trait_info.methods {
866            self.signatures.insert(
867                method.name.clone(),
868                TypeSignature {
869                    signature: method.signature.clone(),
870                    return_type: method.return_type.clone(),
871                    parameters: method.parameters.clone(),
872                },
873            );
874        }
875        Ok(())
876    }
877
878    /// Index type definition
879    pub fn index_type_definition(&mut self, type_info: &TypeInfo) -> Result<()> {
880        // Index type compatibility information
881        self.compatibility_matrix
882            .insert(type_info.name.clone(), type_info.trait_impls.clone());
883        Ok(())
884    }
885}
886
887impl Default for TypeSearchEngine {
888    fn default() -> Self {
889        Self::new()
890    }
891}
892
893/// Type signature information
894#[derive(Debug, Clone, Serialize, Deserialize)]
895pub struct TypeSignature {
896    /// Full signature
897    pub signature: String,
898    /// Return type
899    pub return_type: String,
900    /// Parameters
901    pub parameters: Vec<ParameterInfo>,
902}
903
904/// Usage pattern search engine
905#[derive(Debug, Clone, Serialize, Deserialize)]
906pub struct UsagePatternSearchEngine {
907    /// Pattern index
908    pub patterns: HashMap<String, UsagePattern>,
909    /// Pattern frequency
910    pub frequency: HashMap<String, usize>,
911}
912
913impl UsagePatternSearchEngine {
914    /// Create a new usage pattern search engine
915    pub fn new() -> Self {
916        Self {
917            patterns: HashMap::new(),
918            frequency: HashMap::new(),
919        }
920    }
921
922    /// Index usage patterns from examples
923    pub fn index_usage_patterns(&mut self, example: &CodeExample) -> Result<()> {
924        // Analyze code patterns
925        let pattern = UsagePattern {
926            pattern_type: PatternType::FunctionCall,
927            code_snippet: example.code.clone(),
928            frequency: 1,
929            confidence: 0.8,
930        };
931        self.patterns.insert(example.title.clone(), pattern);
932        Ok(())
933    }
934}
935
936impl Default for UsagePatternSearchEngine {
937    fn default() -> Self {
938        Self::new()
939    }
940}
941
942/// Usage pattern information
943#[derive(Debug, Clone, Serialize, Deserialize)]
944pub struct UsagePattern {
945    /// Type of pattern
946    pub pattern_type: PatternType,
947    /// Code snippet
948    pub code_snippet: String,
949    /// Pattern frequency
950    pub frequency: usize,
951    /// Confidence score
952    pub confidence: f64,
953}
954
955/// Types of usage patterns
956#[derive(Debug, Clone, Serialize, Deserialize)]
957pub enum PatternType {
958    FunctionCall,
959    MethodChaining,
960    ErrorHandling,
961    Initialization,
962    Configuration,
963}
964
965/// Similarity search engine
966#[derive(Debug, Clone, Serialize, Deserialize)]
967pub struct SimilaritySearchEngine {
968    /// Similarity matrix
969    pub similarity_matrix: HashMap<String, HashMap<String, f64>>,
970    /// Similarity algorithms
971    pub algorithms: Vec<SimilarityAlgorithm>,
972}
973
974impl SimilaritySearchEngine {
975    /// Create a new similarity search engine
976    pub fn new() -> Self {
977        Self {
978            similarity_matrix: HashMap::new(),
979            algorithms: vec![SimilarityAlgorithm::Cosine, SimilarityAlgorithm::Jaccard],
980        }
981    }
982
983    /// Index trait similarities
984    pub fn index_trait_similarities(&mut self, trait_info: &TraitInfo) -> Result<()> {
985        // Calculate similarities with other traits
986        let similarities = HashMap::new(); // Placeholder
987        self.similarity_matrix
988            .insert(trait_info.name.clone(), similarities);
989        Ok(())
990    }
991}
992
993impl Default for SimilaritySearchEngine {
994    fn default() -> Self {
995        Self::new()
996    }
997}
998
999/// Similarity algorithms
1000#[derive(Debug, Clone, Serialize, Deserialize)]
1001pub enum SimilarityAlgorithm {
1002    Cosine,
1003    Jaccard,
1004    Euclidean,
1005    Manhattan,
1006}
1007
1008/// Auto-complete engine
1009#[derive(Debug, Clone, Serialize, Deserialize)]
1010pub struct AutoCompleteEngine {
1011    /// Completion trie
1012    pub completions: HashMap<String, CompletionNode>,
1013    /// Completion statistics
1014    pub stats: CompletionStats,
1015}
1016
1017impl AutoCompleteEngine {
1018    /// Create a new auto-complete engine
1019    pub fn new() -> Self {
1020        Self {
1021            completions: HashMap::new(),
1022            stats: CompletionStats::default(),
1023        }
1024    }
1025
1026    /// Add a completion
1027    pub fn add_completion(&mut self, text: &str, completion_type: CompletionType) -> Result<()> {
1028        let node = CompletionNode {
1029            text: text.to_string(),
1030            completion_type,
1031            frequency: 1,
1032            score: 1.0,
1033        };
1034        self.completions.insert(text.to_string(), node);
1035        self.stats.total_completions += 1;
1036        Ok(())
1037    }
1038
1039    /// Get completions for a prefix
1040    pub fn get_completions(&self, prefix: &str) -> Vec<&CompletionNode> {
1041        self.completions
1042            .values()
1043            .filter(|node| node.text.starts_with(prefix))
1044            .collect()
1045    }
1046}
1047
1048impl Default for AutoCompleteEngine {
1049    fn default() -> Self {
1050        Self::new()
1051    }
1052}
1053
1054/// Completion node
1055#[derive(Debug, Clone, Serialize, Deserialize)]
1056pub struct CompletionNode {
1057    /// Completion text
1058    pub text: String,
1059    /// Type of completion
1060    pub completion_type: CompletionType,
1061    /// Usage frequency
1062    pub frequency: usize,
1063    /// Relevance score
1064    pub score: f64,
1065}
1066
1067/// Types of completions
1068#[derive(Debug, Clone, Serialize, Deserialize)]
1069pub enum CompletionType {
1070    Trait,
1071    Type,
1072    Method,
1073    Function,
1074    Variable,
1075    Keyword,
1076}
1077
1078/// Completion statistics
1079#[derive(Debug, Clone, Serialize, Deserialize)]
1080pub struct CompletionStats {
1081    /// Total number of completions
1082    pub total_completions: usize,
1083    /// Most used completions
1084    pub popular_completions: Vec<String>,
1085    /// Completion accuracy
1086    pub accuracy: f64,
1087}
1088
1089impl Default for CompletionStats {
1090    fn default() -> Self {
1091        Self {
1092            total_completions: 0,
1093            popular_completions: Vec::new(),
1094            accuracy: 0.0,
1095        }
1096    }
1097}
1098
1099/// Search analytics
1100#[derive(Debug, Clone, Serialize, Deserialize)]
1101pub struct SearchAnalytics {
1102    /// Search queries performed
1103    pub query_count: usize,
1104    /// Most popular queries
1105    pub popular_queries: Vec<String>,
1106    /// Search performance metrics
1107    pub performance_metrics: SearchPerformanceMetrics,
1108}
1109
1110impl SearchAnalytics {
1111    /// Create new search analytics
1112    pub fn new() -> Self {
1113        Self {
1114            query_count: 0,
1115            popular_queries: Vec::new(),
1116            performance_metrics: SearchPerformanceMetrics::default(),
1117        }
1118    }
1119}
1120
1121impl Default for SearchAnalytics {
1122    fn default() -> Self {
1123        Self::new()
1124    }
1125}
1126
1127/// Search performance metrics
1128#[derive(Debug, Clone, Serialize, Deserialize)]
1129pub struct SearchPerformanceMetrics {
1130    /// Average search time in milliseconds
1131    pub avg_search_time_ms: f64,
1132    /// Search success rate
1133    pub success_rate: f64,
1134    /// Index size in bytes
1135    pub index_size_bytes: usize,
1136}
1137
1138impl Default for SearchPerformanceMetrics {
1139    fn default() -> Self {
1140        Self {
1141            avg_search_time_ms: 0.0,
1142            success_rate: 0.0,
1143            index_size_bytes: 0,
1144        }
1145    }
1146}
1147
1148// ================================================================================================
1149// TUTORIAL SYSTEM STRUCTURES
1150// ================================================================================================
1151
1152/// Template for generating tutorials
1153#[derive(Debug, Clone, Serialize, Deserialize)]
1154pub struct TutorialTemplate {
1155    /// Template name
1156    pub name: String,
1157    /// Template content
1158    pub content: String,
1159    /// Template variables
1160    pub variables: HashMap<String, String>,
1161    /// Required API elements
1162    pub required_elements: Vec<String>,
1163}
1164
1165// ================================================================================================
1166// TESTS
1167// ================================================================================================
1168
1169#[allow(non_snake_case)]
1170#[cfg(test)]
1171mod tests {
1172    use super::*;
1173
1174    #[test]
1175    fn test_api_reference_creation() {
1176        let api_ref = ApiReference {
1177            crate_name: "test-crate".to_string(),
1178            version: "1.0.0".to_string(),
1179            traits: Vec::new(),
1180            types: Vec::new(),
1181            examples: Vec::new(),
1182            cross_references: HashMap::new(),
1183            metadata: ApiMetadata::default(),
1184        };
1185
1186        assert_eq!(api_ref.crate_name, "test-crate");
1187        assert_eq!(api_ref.version, "1.0.0");
1188    }
1189
1190    #[test]
1191    fn test_search_index() {
1192        let mut index = SearchIndex::new();
1193        let item = SearchItem {
1194            name: "TestTrait".to_string(),
1195            item_type: SearchItemType::Trait,
1196            description: "A test trait".to_string(),
1197            path: "test::TestTrait".to_string(),
1198            keywords: vec!["test".to_string(), "trait".to_string()],
1199            relevance_score: 1.0,
1200        };
1201
1202        index.add_item(item).expect("add_item should succeed");
1203        assert_eq!(index.items.len(), 1);
1204        assert_eq!(index.metadata.total_items, 1);
1205
1206        let results = index.search("test");
1207        assert_eq!(results.len(), 1);
1208        assert_eq!(results[0].name, "TestTrait");
1209    }
1210
1211    #[test]
1212    fn test_trait_info_default() {
1213        let trait_info = TraitInfo::default();
1214        assert!(trait_info.name.is_empty());
1215        assert!(trait_info.methods.is_empty());
1216        assert!(trait_info.associated_types.is_empty());
1217    }
1218
1219    #[test]
1220    fn test_code_example() {
1221        let example = CodeExample {
1222            title: "Basic Usage".to_string(),
1223            description: "Shows basic usage".to_string(),
1224            code: "fn main() {}".to_string(),
1225            language: "rust".to_string(),
1226            runnable: true,
1227            expected_output: Some("Success".to_string()),
1228        };
1229
1230        assert_eq!(example.title, "Basic Usage");
1231        assert!(example.runnable);
1232    }
1233
1234    #[test]
1235    fn test_auto_complete_engine() {
1236        let mut engine = AutoCompleteEngine::new();
1237        engine
1238            .add_completion("TestTrait", CompletionType::Trait)
1239            .expect("expected valid value");
1240        engine
1241            .add_completion("TestType", CompletionType::Type)
1242            .expect("expected valid value");
1243
1244        let completions = engine.get_completions("Test");
1245        assert_eq!(completions.len(), 2);
1246
1247        let completions = engine.get_completions("TestT");
1248        assert_eq!(completions.len(), 2);
1249
1250        let completions = engine.get_completions("TestTr");
1251        assert_eq!(completions.len(), 1);
1252        assert_eq!(completions[0].text, "TestTrait");
1253    }
1254
1255    #[test]
1256    fn test_serialization() {
1257        let example = CodeExample {
1258            title: "Test".to_string(),
1259            description: "Test example".to_string(),
1260            code: "println!(\"Hello\");".to_string(),
1261            language: "rust".to_string(),
1262            runnable: true,
1263            expected_output: None,
1264        };
1265
1266        let serialized = serde_json::to_string(&example).unwrap_or_default();
1267        let deserialized: CodeExample =
1268            serde_json::from_str(&serialized).expect("valid JSON operation");
1269
1270        assert_eq!(example.title, deserialized.title);
1271        assert_eq!(example.code, deserialized.code);
1272    }
1273
1274    #[test]
1275    fn test_visibility_display() {
1276        assert_eq!(Visibility::Public.to_string(), "public");
1277        assert_eq!(Visibility::Private.to_string(), "private");
1278        assert_eq!(
1279            Visibility::Restricted("crate".to_string()).to_string(),
1280            "restricted(crate)"
1281        );
1282    }
1283}