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
# 10. Modules

RustLeaf provides a module system for organizing code into reusable components. Modules enable namespace management, visibility control, and code separation. This chapter defines module declaration, import/export semantics, path resolution, and dependency management.

### 10.1. Module System Overview

**Design Principles:**
- File-based modules (one module per file)
- Explicit visibility with `pub` keyword
- Path-based import system with `use` statements
- Runtime circular dependency detection
- No module caching (modules imported fresh each time)

**Module Structure:**
```
project/
├── main.rustleaf           // Entry point
├── utils.rustleaf          // Module: utils
├── math/
│   ├── geometry.rustleaf   // Module: math::geometry
│   └── algebra.rustleaf    // Module: math::algebra
└── graphics/
    ├── shapes/
    │   └── circle.rustleaf // Module: graphics::shapes::circle
    └── colors.rustleaf     // Module: graphics::colors
```

### 10.2. Import Statements

Import statements use the `use` keyword to bring items from other modules into scope.

**Basic Import Syntax:**
```
use module_path;                    // Import module
use module_path::item;              // Import specific item
use module_path::{item1, item2};    // Import multiple items
use module_path::*;                 // Import all public items (discouraged)
```

**Path Resolution:**
- **Relative paths**: `use utils::math` (relative to current module's directory)
- **Parent paths**: `use super::sibling_module` (parent directory)

**Import Examples:**
```
// File: graphics/renderer.rustleaf

// Import from project root
use math::geometry::Point;
use math::algebra::{Vector, Matrix};

// Import from parent directory
use super::colors::{RED, GREEN, BLUE};

// Import from same directory (just use the name)
use effects::Shader;

// Import from root explicitly
use root::utils::Logger;

// Multiple imports
use math::geometry::{Point, Line, Circle};

// Import all (discouraged)
use math::constants::*;
```

### 10.3. Export Functions

Exports use the `pub` keyword to make items visible outside the current module.

**Visibility Levels:**
- **Private** (default): Only accessible within the current module
- **Public** (`pub`): Accessible from other modules that import this module

**Export Syntax:**
```
// Public function
pub fn public_function() { }

// Private function (default)
fn private_function() { }

// Public variable
pub var PUBLIC_CONSTANT = 42;

// Private variable (default)
var private_data = [];

// Public class
pub class PublicClass {
    pub var public_field;     // Public field
    var private_field;        // Private field
    
    pub fn public_method() { } // Public method
    fn private_method() { }    // Private method
}

// Private class (default)
class PrivateClass { }
```

**Module Example:**
```
// File: math/geometry.rustleaf

// Public exports - available to importers
pub class Point {
    pub var x;
    pub var y;
    
    pub static fn new(x, y) {
        var p = Point()
        p.x = x
        p.y = y
        p
    }
    
    pub fn distance_to(other) {
        var dx = self.x - other.x
        var dy = self.y - other.y
        sqrt(dx * dx + dy * dy)
    }
    
    // Private method - only accessible within this module
    fn validate() {
        if type(self.x) != "float" or type(self.y) != "float" {
            raise("Point coordinates must be numbers")
        }
    }
}

pub fn distance(p1, p2) {
    p1.distance_to(p2)
}

pub var ORIGIN = Point.new(0.0, 0.0);

// Private helper - not accessible from other modules
fn sqrt(x) {
    x ** 0.5
}

var cache = {};  // Private module variable
```

**Usage:**
```
// File: main.rustleaf
use math::geometry::{Point, distance, ORIGIN};

var p1 = Point.new(3.0, 4.0)
var p2 = Point.new(0.0, 0.0)

print(distance(p1, ORIGIN))     // OK - public function
print(p1.distance_to(p2))       // OK - public method
// print(p1.validate())         // Error - private method
// var c = cache                // Error - private variable
```

### 10.4. Module Resolution

Module paths are resolved based on the filesystem structure and special keywords.

**Resolution Rules:**
1. **Relative paths** resolve from current module's directory (default)
2. **Parent paths** start with `super::` to access parent directory

**Path Resolution Algorithm:**
```
use path::to::module
1. If path starts with "super::" → resolve relative to parent directory of current module
2. Otherwise → resolve relative to current module's directory
```

**Exact Path Lookup:**
- Module paths are resolved to exactly one file location
- No directory searching or fallback paths
- If the computed `.rustleaf` file doesn't exist, import fails with error
- No standard library search paths or module discovery

**Examples:**
```
// Project structure:
// project/
// ├── main.rustleaf
// ├── utils.rustleaf  
// ├── graphics/
// │   ├── renderer.rustleaf
// │   └── shapes/
// │       └── circle.rustleaf
// └── math/
//     └── geometry.rustleaf

// File: project/graphics/renderer.rustleaf (current module)

use shapes::circle                 // → project/graphics/shapes/circle.rustleaf
use super::utils                   // → project/utils.rustleaf  
use super::math::geometry          // → project/math/geometry.rustleaf

// File: project/math/geometry.rustleaf (current module)

use super::utils                   // → project/utils.rustleaf
use super::graphics::renderer      // → project/graphics/renderer.rustleaf
```

**Module File Mapping:**
- `use shapes::circle``shapes/circle.rustleaf` (relative to current module)
- `use super::utils``../utils.rustleaf` (parent directory)
- `use super::math::geometry``../math/geometry.rustleaf` (parent, then relative)

### 10.5. Module Loading

Modules are loaded and executed when first imported.

**Loading Behavior:**
- Each module file is executed once when first imported during program execution
- Multiple imports of the same module return the same module instance
- Module-level code runs during first import (initialization)
- No persistent file caching - modules are re-loaded fresh on each program run
- Circular dependencies cause runtime errors

**Module Initialization:**
```
// File: database.rustleaf

// Module-level initialization code
print("Loading database module...")

var connection_pool = [];
var default_config = {
    host: "localhost",
    port: 5432,
    timeout: 30
};

// Initialize connection pool
for i in range(0, 10) {
    connection_pool.append(create_connection(default_config))
}

print("Database module loaded with ${connection_pool.length} connections")

// Public API
pub fn get_connection() {
    if connection_pool.length > 0 {
        connection_pool.pop()
    } else {
        create_connection(default_config)
    }
}

pub fn release_connection(conn) {
    connection_pool.append(conn)
}

// Private helper
fn create_connection(config) {
    // Implementation details...
    {host: config.host, port: config.port, active: true}
}
```

**Import Execution:**
```
// File: main.rustleaf
print("Starting application...")

use database  // This triggers database.rustleaf execution
// Output: "Loading database module..."
//         "Database module loaded with 10 connections"

var conn = database.get_connection()
print("Got connection: ${conn}")
```

**Module Instance Consistency:**
```
// File: main.rustleaf
use database::{get_connection};
get_connection();  // Uses one connection

use database::{get_connection as get_conn2};  
get_conn2();       // Uses another connection from SAME module instance

print("Connections left: ${database.connection_pool.length}");  // 8
```

### 10.6. Module Scope

Each module has its own scope separate from other modules.

**Scope Rules:**
- Module-level variables are private by default
- Only `pub` items are accessible from other modules
- Imported items are available in the importing module's scope
- No global namespace pollution

**Scope Isolation:**
```
// File: module_a.rustleaf
var private_var = "A's private data"
pub var public_var = "A's public data"

pub fn get_private() {
    private_var  // OK - same module
}

// File: module_b.rustleaf  
var private_var = "B's private data"  // Different from A's private_var
pub var public_var = "B's public data"

use module_a

pub fn test() {
    print(module_a.public_var)     // OK - public
    print(module_a.get_private())  // OK - returns A's private data
    // print(module_a.private_var) // Error - not public
    
    print(private_var)             // "B's private data" - local scope
}
```

**Import Scope:**
```
// File: graphics.rustleaf
use math::geometry::Point
use math::algebra::{Vector, Matrix}
use utils::*

// Point, Vector, Matrix, and all utils items are now in scope
pub fn render_scene() {
    var origin = Point.new(0, 0)     // Point from math::geometry
    var transform = Matrix.identity() // Matrix from math::algebra
    log("Rendering...")              // log from utils (via *)
}
```

**Standard Library Scope:**
All standard library functions and types are available globally without explicit import:
```
// These are always available:
print("Hello")           // Built-in function
var x = type(42)         // Built-in function  
var list = [1, 2, 3]     // Built-in type
var dict = {a: 1}        // Built-in type

// No need for:
// use std::io::print
// use std::types::type
```

**Circular Dependency Detection:**
The runtime maintains an import stack to detect circular dependencies during module loading. Detection happens at import time, not at function call time.

```
// File: module_a.rustleaf
use module_b  // ← Circular dependency!

pub fn a_function() {
    module_b.b_function()
}

// File: module_b.rustleaf  
use module_a  // ← Circular dependency!

pub fn b_function() {
    module_a.a_function()
}

// Runtime execution:
// 1. Start loading module_a
// 2. Import stack: [module_a]
// 3. module_a imports module_b
// 4. Import stack: [module_a, module_b]  
// 5. module_b imports module_a
// 6. module_a already in stack → Runtime error!

// Runtime error:
// "Circular dependency detected: module_a → module_b → module_a"
```

**Resolution:**
```
// File: shared.rustleaf
pub fn shared_function() {
    "shared logic"
}

// File: module_a.rustleaf
use shared

pub fn a_function() {
    shared.shared_function() + " from A"
}

// File: module_b.rustleaf
use shared
use module_a  // OK - no circularity

pub fn b_function() {
    module_a.a_function() + " via B"
}
```