windjammer 0.48.0

A simple language inspired by Go, Ruby, and Elixir that transpiles to Rust - 80% of Rust's power with 20% of the complexity
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
501
502
503
504
# Automatic Reference Insertion Design

## Problem

**Current Behavior**:
```windjammer
fn double(x: int) -> int {  // Analyzer infers: x: &i64
    x * 2
}

fn main() {
    let result = double(5)  // Generates: double(5)
}
```

**Generated Rust**:
```rust
fn double(x: &i64) -> i64 {  // ✅ Correct
    x * 2
}

fn main() {
    let result = double(5);  // ❌ Error: expected &i64, found integer
}
```

**Root Cause**: Code generator doesn't know that `double` expects `&i64`, so it doesn't insert `&` at call site.

---

## Solution Architecture

### Three-Component System

```
┌─────────────┐
│  Analyzer   │ → Infers ownership for all functions
└──────┬──────┘
       │ FunctionSignatures { name → [param ownership] }
┌─────────────┐
│  Registry   │ → Stores inferred signatures
└──────┬──────┘
       │ Lookup during codegen
┌─────────────┐
│  CodeGen    │ → Inserts & or &mut at call sites
└─────────────┘
```

### Component 1: Enhanced Analyzer Output

**Current**:
```rust
pub struct AnalyzedFunction {
    pub decl: FunctionDecl,
    pub inferred_ownership: HashMap<String, OwnershipMode>,  // param name → mode
}
```

**Needed**:
```rust
pub struct FunctionSignature {
    pub name: String,
    pub param_ownership: Vec<OwnershipMode>,  // Positional ownership modes
    pub return_ownership: OwnershipMode,
}

pub struct AnalysisResult {
    pub functions: Vec<AnalyzedFunction>,
    pub signatures: HashMap<String, FunctionSignature>,  // NEW: name → signature
}
```

### Component 2: Signature Registry

**Purpose**: Global lookup table for function signatures

```rust
pub struct SignatureRegistry {
    signatures: HashMap<String, FunctionSignature>,
}

impl SignatureRegistry {
    pub fn new() -> Self {
        // Pre-populate with stdlib functions
        let mut registry = SignatureRegistry {
            signatures: HashMap::new(),
        };
        
        // Add known functions
        registry.add_builtin("println", vec![OwnershipMode::Borrowed]);
        registry.add_builtin("format", vec![OwnershipMode::Borrowed]);
        
        registry
    }
    
    pub fn add_function(&mut self, name: String, sig: FunctionSignature) {
        self.signatures.insert(name, sig);
    }
    
    pub fn get_signature(&self, name: &str) -> Option<&FunctionSignature> {
        self.signatures.get(name)
    }
}
```

### Component 3: Smart Call Site Generation

**Current**:
```rust
Expression::Call { function, arguments } => {
    let func_str = self.generate_expression(function);
    let args: Vec<String> = arguments.iter()
        .map(|(_label, arg)| self.generate_expression(arg))
        .collect();
    format!("{}({})", func_str, args.join(", "))
}
```

**Enhanced**:
```rust
Expression::Call { function, arguments } => {
    let func_name = self.extract_function_name(function);
    let func_str = self.generate_expression(function);
    
    // Look up signature
    let signature = self.signature_registry.get_signature(&func_name);
    
    let args: Vec<String> = arguments.iter().enumerate()
        .map(|(i, (_label, arg))| {
            let arg_str = self.generate_expression(arg);
            
            // Check if this parameter expects a borrow
            if let Some(sig) = signature {
                if let Some(&ownership) = sig.param_ownership.get(i) {
                    match ownership {
                        OwnershipMode::Borrowed => {
                            // Check if arg is already a reference
                            if !self.is_reference_expression(arg) {
                                return format!("&{}", arg_str);
                            }
                        }
                        OwnershipMode::MutBorrowed => {
                            if !self.is_reference_expression(arg) {
                                return format!("&mut {}", arg_str);
                            }
                        }
                        OwnershipMode::Owned => {
                            // No change needed
                        }
                    }
                }
            }
            
            arg_str
        })
        .collect();
    
    format!("{}({})", func_str, args.join(", "))
}
```

---

## Implementation Steps

### Step 1: Modify Analyzer to Build Signature Registry

```rust
// src/analyzer.rs
impl Analyzer {
    pub fn analyze_program(
        &mut self,
        program: &Program
    ) -> (Vec<AnalyzedFunction>, SignatureRegistry) {
        let mut analyzed = Vec::new();
        let mut registry = SignatureRegistry::new();
        
        // Analyze each function
        for item in &program.items {
            if let Item::Function(func) = item {
                let analyzed_func = self.analyze_function(func);
                
                // Build signature from analysis
                let signature = self.build_signature(&analyzed_func);
                registry.add_function(func.name.clone(), signature);
                
                analyzed.push(analyzed_func);
            }
        }
        
        (analyzed, registry)
    }
    
    fn build_signature(&self, func: &AnalyzedFunction) -> FunctionSignature {
        let param_ownership: Vec<OwnershipMode> = func.decl.parameters
            .iter()
            .map(|param| {
                func.inferred_ownership
                    .get(&param.name)
                    .cloned()
                    .unwrap_or(OwnershipMode::Owned)
            })
            .collect();
        
        FunctionSignature {
            name: func.decl.name.clone(),
            param_ownership,
            return_ownership: OwnershipMode::Owned, // For now
        }
    }
}
```

### Step 2: Pass Registry to CodeGen

```rust
// src/main.rs
fn build_project(path: &str) -> Result<(), Box<dyn std::error::Error>> {
    // ... parse ...
    
    // Analyze with signature extraction
    let (analyzed_functions, signature_registry) = analyzer.analyze_program(&program);
    
    // Generate code with registry
    let mut codegen = CodeGenerator::new(signature_registry);
    let rust_code = codegen.generate_program(&program, &analyzed_functions);
    
    // ... write output ...
}
```

### Step 3: Update CodeGenerator

```rust
// src/codegen.rs
pub struct CodeGenerator {
    indent_level: usize,
    signature_registry: SignatureRegistry,  // NEW
}

impl CodeGenerator {
    pub fn new(registry: SignatureRegistry) -> Self {
        CodeGenerator {
            indent_level: 0,
            signature_registry: registry,
        }
    }
    
    fn generate_expression(&mut self, expr: &Expression) -> String {
        match expr {
            Expression::Call { function, arguments } => {
                self.generate_call(function, arguments)
            }
            // ... other cases ...
        }
    }
    
    fn generate_call(
        &mut self,
        function: &Expression,
        arguments: &[(Option<String>, Expression)]
    ) -> String {
        // Extract function name
        let func_name = match function {
            Expression::Identifier(name) => name.clone(),
            Expression::FieldAccess { field, .. } => field.clone(),
            _ => String::new(), // Method calls, etc.
        };
        
        let func_str = self.generate_expression(function);
        
        // Look up signature
        let signature = self.signature_registry.get_signature(&func_name);
        
        // Generate arguments with automatic referencing
        let args: Vec<String> = arguments.iter().enumerate()
            .map(|(i, (_label, arg))| {
                self.generate_argument(arg, signature, i)
            })
            .collect();
        
        format!("{}({})", func_str, args.join(", "))
    }
    
    fn generate_argument(
        &mut self,
        arg: &Expression,
        signature: Option<&FunctionSignature>,
        position: usize
    ) -> String {
        let arg_str = self.generate_expression(arg);
        
        // Check if we need to insert a reference
        if let Some(sig) = signature {
            if let Some(&ownership) = sig.param_ownership.get(position) {
                match ownership {
                    OwnershipMode::Borrowed => {
                        // Insert & if not already a reference
                        if !self.is_reference_expr(arg) {
                            return format!("&{}", arg_str);
                        }
                    }
                    OwnershipMode::MutBorrowed => {
                        if !self.is_reference_expr(arg) {
                            return format!("&mut {}", arg_str);
                        }
                    }
                    OwnershipMode::Owned => {
                        // May need to clone or move
                    }
                }
            }
        }
        
        arg_str
    }
    
    fn is_reference_expr(&self, expr: &Expression) -> bool {
        matches!(
            expr,
            Expression::Unary { op: UnaryOp::Ref, .. }
        )
    }
}
```

---

## Edge Cases

### Case 1: Already Borrowed Argument
```windjammer
let x = 5
let result = double(&x)  // User explicitly passes &
```

**Solution**: Check if expression is already `UnaryOp::Ref`, don't add another `&`

### Case 2: Method Calls
```windjammer
let text = "hello"
text.len()  // self is already borrowed
```

**Solution**: Method receivers are handled separately, don't auto-reference

### Case 3: Pipe Operator
```windjammer
5 |> double  // Should become double(&5)
```

**Solution**: Pipe operator creates Call expression, goes through same logic

### Case 4: Variables vs Literals
```windjammer
double(5)      // Needs &5
double(x)      // Needs &x
double(x + 1)  // Needs &(x + 1)... complex!
```

**Solution**: For complex expressions, may need temp variable:
```rust
let _tmp = x + 1;
double(&_tmp)
```

### Case 5: Unknown Functions (External Crates)
```windjammer
external_func(x)  // Don't know signature
```

**Solution**: 
- Default to no auto-referencing for unknown functions
- User must be explicit: `external_func(&x)`
- Or: use type inference from Rust compilation errors (future)

---

## Testing Strategy

### Test 1: Basic Auto-Reference
```windjammer
fn double(x: int) -> int { x * 2 }
fn main() {
    let result = double(5)  // Should generate: double(&5)
}
```

### Test 2: Mutable Borrow
```windjammer
fn increment(x: int) { x += 1 }  // Infers &mut
fn main() {
    let mut x = 5
    increment(x)  // Should generate: increment(&mut x)
}
```

### Test 3: Ownership Transfer
```windjammer
fn consume(x: int) -> int { x }  // Infers owned (returned)
fn main() {
    let x = 5
    let y = consume(x)  // Should generate: consume(x) - no &
}
```

### Test 4: Pipe Operator
```windjammer
fn double(x: int) -> int { x * 2 }
fn main() {
    let result = 5 |> double  // Should generate: double(&5)
}
```

### Test 5: Complex Expressions
```windjammer
fn process(x: int) { println!("{}", x) }
fn main() {
    process(5 + 10)  // Should generate: process(&(5 + 10)) or temp var
}
```

---

## Performance Considerations

**Overhead**:
- HashMap lookups for every function call during codegen
- ~O(1) per call, negligible impact

**Memory**:
- SignatureRegistry size: ~few KB for typical programs
- Acceptable overhead

**Optimization**:
- Cache signature lookups
- Use interned strings for function names

---

## Migration Strategy

### Phase 1: Implement Core (Now)
- Basic auto-reference for simple cases
- Test with hello_world example

### Phase 2: Handle Edge Cases (v0.2)
- Complex expressions
- Method calls
- External functions

### Phase 3: Optimization (v0.3)
- Performance tuning
- Better heuristics
- User control (opt-out)

---

## User Control (Future)

Allow users to opt-out of auto-referencing:
```windjammer
@no_auto_ref
fn my_function() {
    // Manual control over references
}
```

Or mark specific functions:
```windjammer
@explicit_refs
fn external_api_call(x: &int) {
    // Must pass &x explicitly
}
```

---

## Success Criteria

**Must Work**:
- ✅ Basic function calls with inferred borrows
- ✅ Pipe operator with auto-reference
- ✅ Both & and &mut insertion

**Should Work**:
- ✅ Method calls (self parameters)
- ✅ Complex expressions
- ✅ Nested function calls

**Nice to Have**:
- ✅ Optimization for common patterns
- ✅ User override controls
- ✅ IDE hints showing inserted references

---

*Status: Design Complete*  
*Priority: P0 (Blocker)*  
*Estimated Effort: 2-3 days*  
*Next Step: Implement Step 1 (Analyzer changes)*