ruchy 4.2.1

A systems scripting language that transpiles to idiomatic Rust with extreme quality engineering
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
//! API documentation examples and usage guides
//!
//! This module provides comprehensive examples and documentation for the
//! Ruchy compiler API, demonstrating how to integrate Ruchy into applications
//! and build custom tools.
//!
//! # Core API Overview
//!
//! The Ruchy compiler provides several APIs for different use cases:
//!
//! ## High-Level API
//! Simple functions for common operations:
//! - `compile()` - Compile source to Rust code
//! - `run_repl()` - Start interactive REPL
//! - `is_valid_syntax()` - Validate syntax
//!
//! ## Component APIs
//! Direct access to compiler components:
//! - Frontend: Parsing and AST construction
//! - Middleend: Type inference and checking
//! - Backend: Code generation and optimization
//! - Runtime: REPL and actor systems
//!
//! # Usage Patterns
//!
//! ## 1. Simple Compilation
//!
//! For basic source-to-rust compilation:
//!
//! ```rust,no_run
//! use ruchy::compile;
//!
//! let source = "42 + 3";
//! let rust_code = compile(source).expect("Compilation failed");
//! println!("{}", rust_code);
//! ```
//!
//! ## 2. Interactive Development
//!
//! For building interactive tools:
//!
//! ```rust,no_run
//! use ruchy::run_repl;
//!
//! // Use built-in REPL
//! run_repl().expect("REPL failed");
//! ```
//!
//! ## 3. Syntax Validation
//!
//! For editors and IDEs:
//!
//! ```rust
//! use ruchy::{is_valid_syntax, get_parse_error};
//!
//! let code_snippets = vec![
//!     "let x = 42",           // Valid
//!     "if true { 1 }",        // Valid  
//!     "let x = ",             // Invalid
//!     "match { }",            // Invalid
//! ];
//!
//! for snippet in code_snippets {
//!     if is_valid_syntax(snippet) {
//!         println!("✓ Valid: {}", snippet);
//!     } else {
//!         let error = get_parse_error(snippet).unwrap();
//!         println!("✗ Error in '{}': {}", snippet, error);
//!     }
//! }
//! ```
//!
//! ## 4. AST Processing
//!
//! For metaprogramming and code analysis:
//!
//! ```rust,no_run
//! use ruchy::frontend::{Parser, Expr, ExprKind, BinaryOp};
//!
//! let mut parser = Parser::new("1 + 2");
//! let ast = parser.parse().unwrap();
//!
//! // Process the AST as needed
//! match &ast.kind {
//!     ExprKind::Binary { left, op, right } => {
//!         println!("Found binary operation");
//!     }
//!     _ => {}
//! }
//! ```
//!
//! ## 5. Actor System Integration
//!
//! For concurrent applications:
//!
//! ```rust,no_run
//! use ruchy::runtime::ActorSystem;
//!
//! let mut system = ActorSystem::new();
//! // Use actor system for concurrent operations
//! println!("Actor system created");
//! ```
//!
//! ## 6. WebAssembly Compilation
//!
//! For web deployment:
//!
//! ```rust,no_run
//! use ruchy::WasmEmitter;
//! use ruchy::frontend::Parser;
//!
//! let source = "42";
//! let mut parser = Parser::new(source);
//! let ast = parser.parse().unwrap();
//!
//! let mut emitter = WasmEmitter::new();
//! let wasm_bytes = emitter.emit(&ast).unwrap();
//! println!("Generated WASM bytes: {} bytes", wasm_bytes.len());
//! ```
//!
//! # Error Handling
//!
//! All Ruchy APIs use `Result` types for error handling:
//!
//! ```rust
//! use ruchy::compile;
//!
//! match compile("invalid syntax here") {
//!     Ok(code) => println!("Success: {}", code),
//!     Err(error) => {
//!         eprintln!("Compilation failed: {}", error);
//!         
//!         // Check error chain for more details
//!         let mut source = error.source();
//!         while let Some(err) = source {
//!             eprintln!("  caused by: {}", err);
//!             source = err.source();
//!         }
//!     }
//! }
//! ```
//!
//! # Performance Tips
//!
//! ## Parser Reuse
//! Create parser instances once and reuse them:
//!
//! ```rust
//! use ruchy::frontend::Parser;
//!
//! // Example of reusing parsers for better performance
//! let sources = ["42", "true", "3.15"];
//! for source in &sources {
//!     let mut parser = Parser::new(source);
//!     let result = parser.parse();
//!     println!("Parsed {}: {:?}", source, result.is_ok());
//! }
//! ```
//!
//! ## Transpiler Reuse
//! Reuse transpiler instances for better performance:
//!
//! ```rust
//! use ruchy::backend::Transpiler;
//! use ruchy::frontend::Parser;
//!
//! let mut transpiler = Transpiler::new();
//! let expressions = ["42", "true", "\"hello\""];
//!
//! for expr_src in &expressions {
//!     let mut parser = Parser::new(expr_src);
//!     let ast = parser.parse().unwrap();
//!     let code = transpiler.transpile_expr(&ast).unwrap();
//!     println!("{} -> {}", expr_src, code);
//! }
//! ```
//!
//! # Integration Examples
//!
//! ## Jupyter Notebook Integration
//!
//! ```rust,no_run
//! use ruchy::{compile, is_valid_syntax};
//!
//! pub struct RuchyKernel {
//!     // kernel state...
//! }
//!
//! impl RuchyKernel {
//!     pub fn execute_cell(&mut self, source: &str) -> Result<String, String> {
//!         if !is_valid_syntax(source) {
//!             return Err("Invalid syntax".to_string());
//!         }
//!         
//!         match compile(source) {
//!             Ok(rust_code) => {
//!                 // Execute the generated Rust code...
//!                 Ok("Executed successfully".to_string())
//!             }
//!             Err(e) => Err(format!("Compilation error: {}", e))
//!         }
//!     }
//! }
//! ```
//!
//! ## Language Server Protocol
//!
//! ```rust,no_run
//! use ruchy::frontend::Parser;
//!
//! pub struct RuchyLanguageServer {
//!     // LSP state...
//! }
//!
//! impl RuchyLanguageServer {
//!     pub fn validate_document(&mut self, source: &str) -> Vec<String> {
//!         let mut errors = Vec::new();
//!         
//!         // Parse
//!         let mut parser = Parser::new(source);
//!         match parser.parse() {
//!             Ok(_ast) => {
//!                 // AST is valid - could add type checking here
//!             }
//!             Err(e) => errors.push(format!("Parse error: {}", e)),
//!         }
//!         
//!         errors
//!     }
//! }
//! ```
//!
//! # Testing Integration
//!
//! For testing frameworks that need to compile and execute Ruchy code:
//!
//! ```rust
//! use ruchy::compile;
//!
//! #[derive(Debug)]
//! pub struct TestCase {
//!     pub name: String,
//!     pub source: String,
//!     pub expected: String,
//! }
//!
//! pub fn run_test_case(test: &TestCase) -> Result<(), String> {
//!     let rust_code = compile(&test.source)
//!         .map_err(|e| format!("Compilation failed: {}", e))?;
//!     
//!     // In a real implementation, you would compile and execute the Rust code
//!     // and compare the output with test.expected
//!     
//!     println!("Test '{}' passed", test.name);
//!     Ok(())
//! }
//!
//! # fn main() {
//! let test = TestCase {
//!     name: "basic_arithmetic".to_string(),
//!     source: "1 + 2 * 3".to_string(),
//!     expected: "7".to_string(),
//! };
//!
//! match run_test_case(&test) {
//!     Ok(()) => println!("✓ Test passed"),
//!     Err(e) => println!("✗ Test failed: {}", e),
//! }
//! # }
//! ```
//!
//! # Best Practices
//!
//! 1. **Error Handling**: Always handle compilation errors gracefully
//! 2. **Resource Management**: Reuse parser/transpiler instances when possible
//! 3. **Validation**: Check syntax before compilation to provide better UX
//! 4. **Testing**: Write tests for your Ruchy integration code
//! 5. **Documentation**: Document your API usage for future maintenance

#[cfg(test)]
mod tests {

    // Sprint 12: API documentation tests

    #[test]
    fn test_module_documentation_exists() {
        // This test verifies that the module has documentation
        // The fact this compiles proves the module exists
        let module_doc = "API documentation examples and usage guides";
        assert!(module_doc.contains("API"));
    }

    #[test]
    fn test_usage_pattern_sections() {
        // Verify key sections are documented
        let sections = [
            "Simple Compilation",
            "Interactive Development",
            "Syntax Validation",
            "AST Processing",
        ];

        for section in &sections {
            // This is a meta-test ensuring documentation structure
            assert!(!section.is_empty());
        }
    }

    #[test]
    fn test_api_overview_sections() {
        // Verify API overview sections
        let apis = ["High-Level API", "Component APIs"];

        for api in &apis {
            assert!(!api.is_empty());
        }
    }

    #[test]
    fn test_best_practices_documented() {
        // Verify best practices are documented
        let practices = [
            "Error Handling",
            "Resource Management",
            "Validation",
            "Testing",
            "Documentation",
        ];

        for practice in &practices {
            assert!(!practice.is_empty());
        }
    }

    #[test]
    fn test_example_code_snippets() {
        // Verify example snippets are provided
        let examples = [
            "use ruchy::compile;",
            "use ruchy::run_repl;",
            "use ruchy::{is_valid_syntax, get_parse_error};",
        ];

        for example in &examples {
            // Meta-test: examples should be non-empty
            assert!(!example.is_empty());
        }
    }

    #[test]
    fn test_integration_example_sections() {
        let sections = ["Jupyter Notebook Integration", "Language Server Protocol"];
        for section in &sections {
            assert!(!section.is_empty());
        }
    }

    #[test]
    fn test_performance_tips_documented() {
        let tips = ["Parser Reuse", "Transpiler Reuse"];
        for tip in &tips {
            assert!(!tip.is_empty());
        }
    }

    #[test]
    fn test_error_handling_documented() {
        let error_handling = "All Ruchy APIs use Result types";
        assert!(error_handling.contains("Result"));
    }

    #[test]
    fn test_webassembly_section_exists() {
        let wasm_section = "WebAssembly Compilation";
        assert!(wasm_section.contains("WebAssembly"));
    }

    #[test]
    fn test_actor_system_section_exists() {
        let actor_section = "Actor System Integration";
        assert!(actor_section.contains("Actor"));
    }

    #[test]
    fn test_testing_integration_section() {
        let testing_section = "Testing Integration";
        assert!(testing_section.contains("Testing"));
    }

    #[test]
    fn test_code_examples_contain_ruchy_imports() {
        let imports = [
            "use ruchy::compile",
            "use ruchy::frontend::Parser",
            "use ruchy::backend::Transpiler",
        ];
        for import in &imports {
            assert!(import.starts_with("use ruchy"));
        }
    }

    #[test]
    fn test_module_level_doc_attributes() {
        // Verifies key module docs concepts exist
        let concepts = ["Frontend", "Middleend", "Backend", "Runtime"];
        for concept in &concepts {
            assert!(!concept.is_empty());
        }
    }

    #[test]
    fn test_validation_api_documented() {
        let validation_apis = ["is_valid_syntax", "get_parse_error"];
        for api in &validation_apis {
            assert!(api.contains("valid") || api.contains("error"));
        }
    }
}