rustleaf 0.1.0

A simple programming language interpreter written in Rust
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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
# 13. Documentation Comments and Docstrings

RustLeaf provides a comprehensive documentation system using Rust-style documentation comments and docstrings. Documentation can be attached to functions, classes, modules, and variables, and is accessible at runtime for dynamic introspection. This chapter defines the documentation syntax, format conventions, and runtime access mechanisms.

### 13.1. Overview

**Documentation Types:**
- **Documentation comments**: `///` for single-line, `/** */` for multi-line
- **Docstrings**: Located above declarations, not inside function bodies
- **Runtime access**: Documentation available via reflection functions
- **Markdown support**: Rich formatting with Markdown syntax
- **Structured format**: Support for `@param`, `@returns`, `@example` tags

**Documentation Targets:**
- Functions and methods
- Classes and their members
- Modules (file-level)
- Variables and constants
- Type definitions

### 13.2. Documentation Comment Syntax

Documentation comments use Rust-style syntax with special comment markers.

**Single-line Documentation Comments:**
```
/// This is a single-line documentation comment
/// It can span multiple lines by repeating the marker
fn documented_function() {
    // Implementation
}
```

**Multi-line Documentation Comments:**
```
/**
 * This is a multi-line documentation comment
 * It can contain rich formatting and examples
 * 
 * @param x The input value
 * @returns The processed result
 */
fn complex_function(x) {
    // Implementation
}
```

**Mixed Documentation:**
```
/// Brief description of the function
/**
 * Extended description with more details
 * and formatting options.
 */
fn mixed_docs_function() {
    // Implementation
}
```

### 13.3. Docstring Syntax

Docstrings use Rust-style placement above declarations rather than inside function bodies.

**Function Docstrings:**
```
/// Calculates the factorial of a number
/// 
/// @param n The number to calculate factorial for
/// @returns The factorial result
/// @example
/// ```
/// factorial(5)  // Returns 120
/// factorial(0)  // Returns 1
/// ```
fn factorial(n) {
    if n <= 1 {
        1
    } else {
        n * factorial(n - 1)
    }
}
```

**Class Docstrings:**
```
/// Represents a point in 2D space
/// 
/// This class provides basic geometric operations
/// for working with 2D coordinates.
/// 
/// @example
/// ```
/// var p = Point.new(3, 4)
/// print(p.distance_to_origin())  // 5.0
/// ```
class Point {
    /// The x-coordinate of the point
    var x;
    
    /// The y-coordinate of the point  
    var y;
    
    /// Creates a new point with given coordinates
    /// 
    /// @param x The x-coordinate
    /// @param y The y-coordinate
    /// @returns A new Point instance
    static fn new(x, y) {
        var p = Point();
        p.x = x;
        p.y = y;
        p
    }
    
    /// Calculates the distance from this point to the origin
    /// 
    /// @returns The Euclidean distance to (0, 0)
    fn distance_to_origin() {
        (self.x * self.x + self.y * self.y) ** 0.5
    }
}
```

### 13.4. Function Docstrings

Function documentation supports structured tags for parameters, return values, and examples.

**Basic Function Documentation:**
```
/// Adds two numbers together
/// 
/// @param a The first number
/// @param b The second number
/// @returns The sum of a and b
fn add(a, b) {
    a + b
}
```

**Complex Function Documentation:**
```
/// Processes a list of items with a transformation function
/// 
/// This function applies the given transformation to each item
/// in the input list and returns a new list with the results.
/// The original list is not modified.
/// 
/// @param items The list of items to process
/// @param transform_fn The function to apply to each item
/// @returns A new list with transformed items
/// 
/// @example
/// ```
/// var numbers = [1, 2, 3]
/// var doubled = process_items(numbers, |x| x * 2)
/// print(doubled)  // [2, 4, 6]
/// ```
/// 
/// @example
/// ```
/// var words = ["hello", "world"]
/// var upper = process_items(words, |s| s.upper())
/// print(upper)  // ["HELLO", "WORLD"]
/// ```
fn process_items(items, transform_fn) {
    items.map(transform_fn)
}
```

**Function with Default Parameters:**
```
/// Creates a range of numbers
/// 
/// @param start The starting number (inclusive)
/// @param end The ending number (exclusive)  
/// @param step The step size (default: 1)
/// @returns A list of numbers in the specified range
/// 
/// @example
/// ```
/// create_range(0, 5)     // [0, 1, 2, 3, 4]
/// create_range(1, 10, 2) // [1, 3, 5, 7, 9]
/// ```
fn create_range(start, end, step = 1) {
    range(start, end, step)
}
```

### 13.5. Module Docstrings

Module-level documentation appears at the top of files to describe the module's purpose and contents.

**Module Documentation:**
```
/// Mathematical utility functions
/// 
/// This module provides common mathematical operations
/// and constants for use throughout the application.
/// 
/// @example
/// ```
/// use math_utils::{PI, circle_area}
/// 
/// var area = circle_area(5.0)
/// print("Area: ${area}")
/// ```

/// The mathematical constant π
pub var PI = 3.14159265359;

/// Calculates the area of a circle
/// 
/// @param radius The radius of the circle
/// @returns The area of the circle
pub fn circle_area(radius) {
    PI * radius * radius
}

/// Calculates the circumference of a circle
/// 
/// @param radius The radius of the circle
/// @returns The circumference of the circle  
pub fn circle_circumference(radius) {
    2 * PI * radius
}
```

### 13.6. Variable and Constant Docstrings

Variables and constants can be documented for API clarity.

**Variable Documentation:**
```
/// The default timeout for network operations (in seconds)
var DEFAULT_TIMEOUT = 30;

/// Configuration options for the application
var CONFIG = {
    /// The server host address
    host: "localhost",
    
    /// The server port number
    port: 8080,
    
    /// Whether to enable debug logging
    debug: false
};

/// List of supported file extensions
pub var SUPPORTED_EXTENSIONS = [".txt", ".md", ".rs"];
```

**Class Member Documentation:**
```
class DatabaseConnection {
    /// The connection string used to connect to the database
    var connection_string;
    
    /// Whether the connection is currently active
    var is_connected = false;
    
    /// The maximum number of retry attempts
    var max_retries = 3;
}
```

### 13.7. Object and Type Docstrings

Classes and their members support hierarchical documentation.

**Class with Comprehensive Documentation:**
```
/// A configuration management system
/// 
/// This class provides a structured way to manage application
/// configuration with support for nested values, defaults,
/// and environment variable overrides.
/// 
/// @example
/// ```
/// var config = ConfigManager.new("app.json")
/// config.set("database.host", "localhost")
/// var host = config.get("database.host", "default")
/// ```
class ConfigManager {
    /// The path to the configuration file
    var config_path;
    
    /// The loaded configuration data
    var data = {};
    
    /// Creates a new configuration manager
    /// 
    /// @param path The path to the configuration file
    /// @returns A new ConfigManager instance
    static fn new(path) {
        var manager = ConfigManager();
        manager.config_path = path;
        manager.load();
        manager
    }
    
    /// Loads configuration from the file
    /// 
    /// Reads the configuration file and parses it as JSON.
    /// If the file doesn't exist, starts with empty configuration.
    fn load() {
        // Implementation details...
    }
    
    /// Gets a configuration value
    /// 
    /// Retrieves a value from the configuration using dot notation
    /// for nested keys. Returns the default value if the key is not found.
    /// 
    /// @param key The configuration key (supports dot notation)
    /// @param default_value The value to return if key is not found
    /// @returns The configuration value or default
    /// 
    /// @example
    /// ```
    /// config.get("database.host")           // "localhost"
    /// config.get("missing.key", "default")  // "default"
    /// ```
    fn get(key, default_value = null) {
        // Implementation details...
    }
    
    /// Sets a configuration value
    /// 
    /// @param key The configuration key (supports dot notation)
    /// @param value The value to set
    /// @returns Self for method chaining
    fn set(key, value) {
        // Implementation details...
        self
    }
}
```

### 13.8. Docstring Format Conventions

**Markdown Formatting:**
Documentation supports Markdown for rich formatting.

```
/// # Math Utilities
/// 
/// This module provides **essential** mathematical functions:
/// 
/// - Basic arithmetic operations
/// - Trigonometric functions  
/// - Statistical calculations
/// 
/// ## Usage
/// 
/// ```rustleaf
/// use math::{sin, cos, mean}
/// 
/// var angle = PI / 4
/// var x = cos(angle)
/// var y = sin(angle)
/// 
/// var numbers = [1, 2, 3, 4, 5]
/// var average = mean(numbers)
/// ```
/// 
/// > **Note**: All angle parameters are in radians.
```

**Structured Tags:**
```
/// Brief description of the function
/// 
/// Longer description with multiple paragraphs
/// explaining the behavior and use cases.
/// 
/// @param name description
/// @param name description (optional)
/// @returns description
/// @throws ErrorType description of when this error occurs
/// @example
/// ```
/// code example
/// ```
/// @see related_function
/// @since version 1.2.0
/// @deprecated Use new_function instead
```

### 13.9. Runtime Access to Docstrings

Documentation is accessible at runtime for dynamic introspection and tooling.

**Documentation Access Functions:**
```
/// Gets the documentation for a function
/// 
/// @param function_ref The function to get documentation for
/// @returns The documentation string or null if not documented
fn get_doc(function_ref) {
    // Implementation provided by runtime
}

/// Gets documentation for a class
/// 
/// @param class_ref The class to get documentation for  
/// @returns The class documentation or null
fn get_class_doc(class_ref) {
    // Implementation provided by runtime
}

/// Gets documentation for a specific method
/// 
/// @param class_ref The class containing the method
/// @param method_name The name of the method
/// @returns The method documentation or null
fn get_method_doc(class_ref, method_name) {
    // Implementation provided by runtime
}
```

**Runtime Documentation Examples:**
```
/// Calculates the square of a number
/// 
/// @param x The number to square
/// @returns The square of x
fn square(x) {
    x * x
}

// Access documentation at runtime
var doc = get_doc(square)
print(doc)
// Output: "Calculates the square of a number\n\n@param x The number to square\n@returns The square of x"

// Documentation for classes
var class_doc = get_class_doc(Point)
print(class_doc)
// Output: "Represents a point in 2D space\n\nThis class provides basic geometric operations..."

// Documentation for methods
var method_doc = get_method_doc(Point, "distance_to_origin")
print(method_doc)
// Output: "Calculates the distance from this point to the origin..."
```

### 13.10. Tooling Integration

Documentation integrates with development tools for enhanced developer experience.

**IDE Integration:**
- Hover tooltips show formatted documentation
- Auto-completion includes parameter information
- Quick documentation lookup with keyboard shortcuts
- Inline parameter hints during function calls

**Documentation Generation:**
- Export documentation to HTML/Markdown formats
- Generate API reference documentation
- Extract examples for testing
- Validate documentation completeness

**Linting and Validation:**
- Warn about undocumented public functions
- Validate `@param` tags match function parameters
- Check that `@returns` is present for non-void functions
- Verify example code syntax

**Example Tool Usage:**
```
/// Validates an email address
/// 
/// @param email The email address to validate
/// @returns True if the email is valid, false otherwise
/// 
/// @example
/// ```
/// validate_email("user@example.com")  // true
/// validate_email("invalid-email")     // false
/// ```
fn validate_email(email) {
    // Implementation
}

// IDE shows on hover:
// validate_email(email)
// 
// Validates an email address
// 
// Parameters:
//   email - The email address to validate
// 
// Returns:
//   True if the email is valid, false otherwise
```

**Documentation Coverage:**
```bash