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
// String expression analysis utilities
//
// This module provides functions for analyzing string-related expressions:
// - Collecting string concatenation parts
// - Detecting string literals in expressions

use crate::parser::{BinaryOp, Expression, Literal};

/// Collects all parts of a string concatenation chain
///
/// For expressions like `"a" + "b" + "c"`, this returns `["a", "b", "c"]`.
/// For non-concatenation expressions, returns the expression itself as a single element.
///
/// # Examples
/// ```
/// // "hello" + "world" → ["hello", "world"]
/// // "a" + variable → ["a", variable]
/// // a * b → [a * b] (not a concatenation)
/// ```
pub fn collect_concat_parts<'ast>(expr: &Expression<'ast>) -> Vec<Expression<'ast>> {
    let mut parts = Vec::new();
    collect_concat_parts_recursive(expr, &mut parts);
    parts
}

/// Recursively collect string concatenation parts
fn collect_concat_parts_recursive<'ast>(
    expr: &Expression<'ast>,
    parts: &mut Vec<Expression<'ast>>,
) {
    match expr {
        Expression::Binary {
            left,
            op: BinaryOp::Add,
            right,
            ..
        } => {
            // Recursively collect parts from both sides of the + operator
            collect_concat_parts_recursive(left, parts);
            collect_concat_parts_recursive(right, parts);
        }
        _ => {
            // Not an addition, treat as a single part
            parts.push(expr.clone());
        }
    }
}

/// Collects string concatenation parts into a mutable Vec (static version for use without `self`)
///
/// This is the same as `collect_concat_parts` but uses a mutable reference
/// instead of returning a Vec, avoiding unnecessary allocation in some contexts.
pub fn collect_concat_parts_static<'ast>(
    expr: &Expression<'ast>,
    parts: &mut Vec<Expression<'ast>>,
) {
    collect_concat_parts_recursive(expr, parts);
}

/// Checks if an expression contains a string literal (recursively)
///
/// This is useful for detecting string operations that might need special handling.
///
/// # Examples
/// ```
/// // "hello" → true
/// // 42 → false
/// // "hello" + variable → true
/// // variable + "world" → true
/// // a + b → false
/// ```
pub fn contains_string_literal(expr: &Expression) -> bool {
    match expr {
        Expression::Literal {
            value: Literal::String(_),
            ..
        } => true,
        Expression::Binary { left, right, .. } => {
            // Recursively check both sides
            contains_string_literal(left) || contains_string_literal(right)
        }
        _ => false,
    }
}

/// Checks if an expression produces a String (not &str)
///
/// Detects expressions that return owned String values like:
/// - `format!("hello")`  
/// - `obj.to_string()`
/// - `s.to_owned()`
/// - `String::from("text")`
/// - Blocks that end in String-producing expressions
///
/// # Examples
/// ```
/// // format!() → true
/// // .to_string() → true
/// // String::from() → true
/// // .len() → false
/// ```
pub fn expression_produces_string(expr: &Expression) -> bool {
    use crate::parser::Statement;
    match expr {
        // Macro invocations like format!(...) produce String
        Expression::MacroInvocation { name, .. } => {
            // format!, concat!, and write!-like macros produce String
            matches!(name.as_str(), "format" | "concat" | "format_args" | "write")
        }
        // Function calls like String::from, format() without !
        Expression::Call { function, .. } => {
            if let Expression::Identifier { name, .. } = &**function {
                name == "format" || name == "String" || name == "to_string"
            } else if let Expression::FieldAccess { field, .. } = &**function {
                field == "from" || field == "to_string"
            } else {
                false
            }
        }
        // Method calls like .to_string()
        Expression::MethodCall { method, .. } => method == "to_string" || method == "to_owned",
        // Blocks - check last statement for String-producing expression
        Expression::Block { statements, .. } => {
            if let Some(last) = statements.last() {
                match last {
                    Statement::Expression { expr, .. } => expression_produces_string(expr),
                    // If statements - check if branches return String
                    Statement::If {
                        then_block,
                        else_block,
                        ..
                    } => {
                        // Check if then branch produces String
                        let then_produces_string = then_block.last().is_some_and(|s| {
                            if let Statement::Expression { expr, .. } = s {
                                expression_produces_string(expr)
                            } else {
                                false
                            }
                        });
                        // Check else branch if present
                        let else_produces_string = else_block.as_ref().is_some_and(|block| {
                            block.last().is_some_and(|s| {
                                if let Statement::Expression { expr, .. } = s {
                                    expression_produces_string(expr)
                                } else {
                                    false
                                }
                            })
                        });
                        then_produces_string || else_produces_string
                    }
                    _ => false,
                }
            } else {
                false
            }
        }
        _ => false,
    }
}

/// Checks if an expression contains .as_str() call (recursively)
///
/// This is useful for detecting when string conversion should be suppressed
/// because the user explicitly wants a &str.
///
/// # Examples
/// ```
/// // s.as_str() → true
/// // s.trim().as_str() → true (nested)
/// // obj.field.as_str() → true (field access)
/// // s.to_string() → false
/// ```
pub fn expression_has_as_str(expr: &Expression) -> bool {
    match expr {
        Expression::MethodCall { method, object, .. } => {
            super::rust_stdlib_annotations::is_strip_redundant(method)
                || expression_has_as_str(object)
        }
        Expression::Block { statements, .. } => block_has_as_str(statements),
        Expression::FieldAccess { object, .. } => expression_has_as_str(object),
        _ => false,
    }
}

/// Checks if a statement contains .as_str() call
///
/// Recursively checks the statement and any nested statements (like in if/else).
///
/// # Examples
/// ```
/// // let x = s.as_str(); → true
/// // return s.as_str(); → true
/// // if true { s.as_str() } → true
/// ```
pub fn statement_has_as_str(stmt: &crate::parser::Statement) -> bool {
    use crate::parser::Statement;
    match stmt {
        Statement::Expression { expr, .. } => expression_has_as_str(expr),
        Statement::Return {
            value: Some(expr), ..
        } => expression_has_as_str(expr),
        Statement::If {
            then_block,
            else_block,
            ..
        } => {
            block_has_as_str(then_block) || else_block.as_ref().is_some_and(|b| block_has_as_str(b))
        }
        _ => false,
    }
}

/// Checks if a block of statements contains .as_str() call
///
/// Returns true if any statement in the block contains .as_str().
///
/// # Examples
/// ```
/// // { s.as_str(); } → true
/// // { let x = 1; s.as_str(); } → true
/// // {} → false
/// ```
pub fn block_has_as_str<'ast>(stmts: &[&'ast crate::parser::Statement<'ast>]) -> bool {
    stmts.iter().any(|s| statement_has_as_str(s))
}

// =============================================================================
// Explicit Reference Detection (for String Conversion Suppression)
// =============================================================================

/// Check if a block's LAST expression (return value) is an explicit reference
///
/// Used to suppress string literal conversion when one if-else branch returns
/// an explicit ref (&self.field, &var, etc.)
///
/// # Examples
/// ```
/// // { &x } → true
/// // { let y = 1; &x } → true
/// // { x } → false
/// // {} → false
/// ```
pub fn block_has_explicit_ref<'ast>(stmts: &[&'ast crate::parser::Statement<'ast>]) -> bool {
    use crate::parser::Statement;
    if stmts.is_empty() {
        return false;
    }

    // Only check the LAST statement (the return value of the block)
    if let Some(last_stmt) = stmts.last() {
        match last_stmt {
            Statement::Expression { expr, .. } => expression_is_explicit_ref(expr),
            Statement::Return {
                value: Some(expr), ..
            } => expression_is_explicit_ref(expr),
            _ => false,
        }
    } else {
        false
    }
}

/// Check if an expression is an explicit reference (&expr)
///
/// Returns true for &x, &self.field, etc.
/// Recursively checks blocks.
///
/// # Examples
/// ```
/// // &x → true
/// // &self.field → true
/// // { &x } → true (recursive)
/// // x → false
/// ```
pub fn expression_is_explicit_ref(expr: &Expression) -> bool {
    match expr {
        Expression::Unary {
            op: crate::parser::UnaryOp::Ref,
            ..
        } => true,
        Expression::Block { statements, .. } => block_has_explicit_ref(statements),
        _ => false,
    }
}
#[cfg(test)]
mod tests {
    use super::*;
    use crate::source_map::Location;
    use crate::test_utils::test_alloc_expr;
    use std::path::PathBuf;

    fn test_loc() -> Location {
        Location {
            file: PathBuf::from(""),
            line: 0,
            column: 0,
        }
    }

    #[test]
    fn test_collect_single_expression() {
        let expr = Expression::Identifier {
            name: "x".to_string(),
            location: Some(test_loc()),
        };

        let parts = collect_concat_parts(&expr);
        assert_eq!(parts.len(), 1);
    }

    #[test]
    fn test_collect_nested_concatenation() {
        // ("a" + "b") + ("c" + "d")
        let a = Expression::Literal {
            value: Literal::String("a".to_string()),
            location: Some(test_loc()),
        };
        let b = Expression::Literal {
            value: Literal::String("b".to_string()),
            location: Some(test_loc()),
        };
        let c = Expression::Literal {
            value: Literal::String("c".to_string()),
            location: Some(test_loc()),
        };
        let d = Expression::Literal {
            value: Literal::String("d".to_string()),
            location: Some(test_loc()),
        };

        let a_ref = test_alloc_expr(a);
        let b_ref = test_alloc_expr(b);
        let c_ref = test_alloc_expr(c);
        let d_ref = test_alloc_expr(d);

        let ab = test_alloc_expr(Expression::Binary {
            left: a_ref,
            op: BinaryOp::Add,
            right: b_ref,
            location: Some(test_loc()),
        });
        let cd = test_alloc_expr(Expression::Binary {
            left: c_ref,
            op: BinaryOp::Add,
            right: d_ref,
            location: Some(test_loc()),
        });
        let expr = Expression::Binary {
            left: ab,
            op: BinaryOp::Add,
            right: cd,
            location: Some(test_loc()),
        };

        let parts = collect_concat_parts(&expr);
        assert_eq!(parts.len(), 4); // Should flatten to ["a", "b", "c", "d"]
    }

    #[test]
    fn test_contains_string_in_nested_expression() {
        // ((a + b) * c) + "hello"
        let a = test_alloc_expr(Expression::Identifier {
            name: "a".to_string(),
            location: Some(test_loc()),
        });
        let b = test_alloc_expr(Expression::Identifier {
            name: "b".to_string(),
            location: Some(test_loc()),
        });
        let c = test_alloc_expr(Expression::Identifier {
            name: "c".to_string(),
            location: Some(test_loc()),
        });
        let hello = test_alloc_expr(Expression::Literal {
            value: Literal::String("hello".to_string()),
            location: Some(test_loc()),
        });

        let ab = test_alloc_expr(Expression::Binary {
            left: a,
            op: BinaryOp::Add,
            right: b,
            location: Some(test_loc()),
        });
        let ab_mul_c = test_alloc_expr(Expression::Binary {
            left: ab,
            op: BinaryOp::Mul,
            right: c,
            location: Some(test_loc()),
        });
        let expr = Expression::Binary {
            left: ab_mul_c,
            op: BinaryOp::Add,
            right: hello,
            location: Some(test_loc()),
        };

        assert!(contains_string_literal(&expr));
    }

    #[test]
    fn test_no_string_in_complex_expression() {
        // (a + b) * (c - d)
        let a = test_alloc_expr(Expression::Identifier {
            name: "a".to_string(),
            location: Some(test_loc()),
        });
        let b = test_alloc_expr(Expression::Identifier {
            name: "b".to_string(),
            location: Some(test_loc()),
        });
        let c = test_alloc_expr(Expression::Identifier {
            name: "c".to_string(),
            location: Some(test_loc()),
        });
        let d = test_alloc_expr(Expression::Identifier {
            name: "d".to_string(),
            location: Some(test_loc()),
        });

        let ab = test_alloc_expr(Expression::Binary {
            left: a,
            op: BinaryOp::Add,
            right: b,
            location: Some(test_loc()),
        });
        let cd = test_alloc_expr(Expression::Binary {
            left: c,
            op: BinaryOp::Sub,
            right: d,
            location: Some(test_loc()),
        });
        let expr = Expression::Binary {
            left: ab,
            op: BinaryOp::Mul,
            right: cd,
            location: Some(test_loc()),
        };

        assert!(!contains_string_literal(&expr));
    }
}