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
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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
//! String Body Conversion Module
//!
//! This module handles transpilation of function bodies that need to return String,
//! including proper `.to_string()` wrapping and string literal handling.
//!
//! **EXTREME TDD Round 73**: Extracted from statements.rs for modularization.

use super::Transpiler;
use crate::frontend::ast::{Expr, ExprKind, Literal, MatchArm, TypeKind};
use anyhow::Result;
use proc_macro2::TokenStream;
use quote::{format_ident, quote};

impl Transpiler {
    /// Generate body tokens with `.to_string()` wrapper on last expression
    /// Complexity: 10 (at Toyota Way limit)
    pub(crate) fn generate_body_tokens_with_string_conversion_impl(
        &self,
        body: &Expr,
        is_async: bool,
    ) -> Result<TokenStream> {
        if is_async {
            return self.generate_async_string_body(body);
        }

        match &body.kind {
            ExprKind::Block(exprs) if exprs.len() > 1 => {
                self.convert_multi_expr_block_to_string(exprs)
            }
            ExprKind::Block(exprs) if exprs.len() == 1 => {
                self.convert_single_expr_block_to_string(&exprs[0])
            }
            ExprKind::Match { expr, arms } => {
                self.transpile_match_with_string_arms_impl(expr, arms)
            }
            _ => {
                let body_tokens = self.transpile_expr(body)?;
                Ok(quote! { (#body_tokens).to_string() })
            }
        }
    }

    /// Generate async body with string conversion
    fn generate_async_string_body(&self, body: &Expr) -> Result<TokenStream> {
        let mut async_transpiler = Transpiler::new();
        async_transpiler.in_async_context = true;
        let body_tokens = async_transpiler.transpile_expr(body)?;
        Ok(quote! { (#body_tokens).to_string() })
    }

    /// Convert multi-expression block to String
    fn convert_multi_expr_block_to_string(&self, exprs: &[Expr]) -> Result<TokenStream> {
        let mut statements = Vec::new();
        for (i, expr) in exprs.iter().enumerate() {
            let expr_tokens = self.transpile_expr(expr)?;
            let is_let = matches!(
                &expr.kind,
                ExprKind::Let { .. } | ExprKind::LetPattern { .. }
            );

            if i < exprs.len() - 1 {
                if is_let {
                    statements.push(expr_tokens);
                } else {
                    statements.push(quote! { #expr_tokens; });
                }
            } else {
                statements.push(quote! { (#expr_tokens).to_string() });
            }
        }
        Ok(quote! { { #(#statements)* } })
    }

    /// Convert single-expression block to String
    fn convert_single_expr_block_to_string(&self, expr: &Expr) -> Result<TokenStream> {
        match &expr.kind {
            ExprKind::Let {
                name,
                type_annotation,
                value,
                body: let_body,
                is_mutable,
                ..
            } => self.convert_let_body_to_string(
                name,
                type_annotation.as_ref(),
                value,
                let_body,
                *is_mutable,
            ),
            ExprKind::Match { expr, arms } => {
                self.transpile_match_with_string_arms_impl(expr, arms)
            }
            _ => {
                let expr_tokens = self.transpile_expr(expr)?;
                Ok(quote! { (#expr_tokens).to_string() })
            }
        }
    }

    /// Convert let binding body to String
    fn convert_let_body_to_string(
        &self,
        name: &str,
        type_annotation: Option<&crate::frontend::ast::Type>,
        value: &Expr,
        let_body: &Expr,
        is_mutable: bool,
    ) -> Result<TokenStream> {
        let name_ident = format_ident!("{}", name);
        let is_mutable_var = self.check_mutability(name, is_mutable, let_body);
        let value_tokens =
            self.convert_value_for_string_context(name, value, type_annotation, is_mutable_var)?;
        let let_body_tokens = self.transpile_expr(let_body)?;

        let mutability = if is_mutable_var {
            quote! { mut }
        } else {
            quote! {}
        };

        let type_annotation_tokens = if let Some(ty) = &type_annotation {
            let ty_tokens = self.transpile_type(ty)?;
            quote! { : #ty_tokens }
        } else {
            quote! {}
        };

        Ok(quote! {
            {
                let #mutability #name_ident #type_annotation_tokens = #value_tokens;
                (#let_body_tokens).to_string()
            }
        })
    }

    /// Check if variable needs mutability
    fn check_mutability(&self, name: &str, is_mutable: bool, body: &Expr) -> bool {
        is_mutable
            || self.mutable_vars.contains(name)
            || super::mutation_detection::is_variable_mutated(name, body)
    }

    /// Convert value expression for string context
    fn convert_value_for_string_context(
        &self,
        name: &str,
        value: &Expr,
        type_annotation: Option<&crate::frontend::ast::Type>,
        is_mutable_var: bool,
    ) -> Result<TokenStream> {
        match (&value.kind, type_annotation) {
            // String literal with String type annotation
            (ExprKind::Literal(Literal::String(s)), Some(type_ann)) if matches!(&type_ann.kind, TypeKind::Named(n) if n == "String") =>
            {
                self.string_vars.borrow_mut().insert(name.to_string());
                Ok(quote! { #s.to_string() })
            }
            // Mutable string literal without type annotation
            (ExprKind::Literal(Literal::String(s)), None) if is_mutable_var => {
                self.string_vars.borrow_mut().insert(name.to_string());
                Ok(quote! { String::from(#s) })
            }
            // Array with List type annotation
            (ExprKind::List(_), Some(type_ann)) if matches!(&type_ann.kind, TypeKind::List(_)) => {
                let list_tokens = self.transpile_expr(value)?;
                Ok(quote! { #list_tokens.to_vec() })
            }
            // Function call - track in string_vars
            (ExprKind::Call { .. }, _) => {
                self.string_vars.borrow_mut().insert(name.to_string());
                self.transpile_expr(value)
            }
            _ => self.transpile_expr(value),
        }
    }

    /// Transpile match expression with string literal arm conversion
    pub(crate) fn transpile_match_with_string_arms_impl(
        &self,
        expr: &Expr,
        arms: &[MatchArm],
    ) -> Result<TokenStream> {
        let expr_tokens = self.transpile_expr(expr)?;
        let arm_tokens = self.convert_match_arms_to_string(arms)?;

        Ok(quote! {
            match #expr_tokens {
                #(#arm_tokens,)*
            }
        })
    }

    /// Convert match arms to string
    fn convert_match_arms_to_string(&self, arms: &[MatchArm]) -> Result<Vec<TokenStream>> {
        let mut arm_tokens = Vec::new();

        for arm in arms {
            let pattern_tokens = self.transpile_pattern(&arm.pattern)?;
            let body_tokens = self.convert_arm_body_to_string(&arm.body)?;

            if let Some(guard_expr) = &arm.guard {
                let guard_tokens = self.transpile_expr(guard_expr)?;
                arm_tokens.push(quote! {
                    #pattern_tokens if #guard_tokens => #body_tokens
                });
            } else {
                arm_tokens.push(quote! {
                    #pattern_tokens => #body_tokens
                });
            }
        }

        Ok(arm_tokens)
    }

    /// Convert arm body to string (adding `.to_string()` for literals)
    fn convert_arm_body_to_string(&self, body: &Expr) -> Result<TokenStream> {
        match &body.kind {
            ExprKind::Literal(Literal::String(s)) => Ok(quote! { #s.to_string() }),
            _ => self.transpile_expr(body),
        }
    }
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use crate::frontend::ast::{Pattern, Span, Type};

    fn make_transpiler() -> Transpiler {
        Transpiler::new()
    }

    fn make_expr(kind: ExprKind) -> Expr {
        Expr {
            kind,
            span: Span::default(),
            attributes: vec![],
            leading_comments: vec![],
            trailing_comment: None,
        }
    }

    fn int_expr(n: i64) -> Expr {
        make_expr(ExprKind::Literal(Literal::Integer(n, None)))
    }

    fn string_expr(s: &str) -> Expr {
        make_expr(ExprKind::Literal(Literal::String(s.to_string())))
    }

    fn ident_expr(name: &str) -> Expr {
        make_expr(ExprKind::Identifier(name.to_string()))
    }

    fn make_match_arm(pattern: Pattern, body: Expr) -> MatchArm {
        MatchArm {
            pattern,
            guard: None,
            body: Box::new(body),
            span: Span::default(),
        }
    }

    fn make_type(type_name: &str) -> Type {
        Type {
            kind: TypeKind::Named(type_name.to_string()),
            span: Span::default(),
        }
    }

    // ========================================================================
    // generate_body_tokens_with_string_conversion_impl tests
    // ========================================================================

    #[test]
    fn test_simple_expression_to_string() {
        let transpiler = make_transpiler();
        let body = int_expr(42);
        let result = transpiler
            .generate_body_tokens_with_string_conversion_impl(&body, false)
            .unwrap();
        let result_str = result.to_string();
        assert!(result_str.contains("42"));
        assert!(result_str.contains("to_string"));
    }

    #[test]
    fn test_async_body_to_string() {
        let transpiler = make_transpiler();
        let body = int_expr(42);
        let result = transpiler
            .generate_body_tokens_with_string_conversion_impl(&body, true)
            .unwrap();
        let result_str = result.to_string();
        assert!(result_str.contains("42"));
        assert!(result_str.contains("to_string"));
    }

    #[test]
    fn test_block_multiple_exprs_to_string() {
        let transpiler = make_transpiler();
        let body = make_expr(ExprKind::Block(vec![ident_expr("a"), int_expr(42)]));
        let result = transpiler
            .generate_body_tokens_with_string_conversion_impl(&body, false)
            .unwrap();
        let result_str = result.to_string();
        assert!(result_str.contains("a"));
        assert!(result_str.contains(";"));
        assert!(result_str.contains("to_string"));
    }

    #[test]
    fn test_block_single_expr_to_string() {
        let transpiler = make_transpiler();
        let body = make_expr(ExprKind::Block(vec![int_expr(99)]));
        let result = transpiler
            .generate_body_tokens_with_string_conversion_impl(&body, false)
            .unwrap();
        let result_str = result.to_string();
        assert!(result_str.contains("99"));
        assert!(result_str.contains("to_string"));
    }

    // ========================================================================
    // convert_multi_expr_block_to_string tests
    // ========================================================================

    #[test]
    fn test_multi_expr_block_semicolons() {
        let transpiler = make_transpiler();
        let exprs = vec![ident_expr("x"), ident_expr("y"), int_expr(10)];
        let result = transpiler
            .convert_multi_expr_block_to_string(&exprs)
            .unwrap();
        let result_str = result.to_string();
        assert!(result_str.contains("x"));
        assert!(result_str.contains("y"));
        assert!(result_str.contains(";"));
        assert!(result_str.contains("to_string"));
    }

    #[test]
    fn test_multi_expr_block_with_let() {
        let transpiler = make_transpiler();
        let let_expr = make_expr(ExprKind::Let {
            name: "x".to_string(),
            type_annotation: None,
            value: Box::new(int_expr(1)),
            body: Box::new(ident_expr("x")),
            is_mutable: false,
            else_block: None,
        });
        let exprs = vec![let_expr, int_expr(42)];
        let result = transpiler
            .convert_multi_expr_block_to_string(&exprs)
            .unwrap();
        assert!(result.to_string().contains("to_string"));
    }

    // ========================================================================
    // transpile_match_with_string_arms_impl tests
    // ========================================================================

    #[test]
    fn test_match_with_string_literal_arms() {
        let transpiler = make_transpiler();
        let expr = ident_expr("x");
        let arms = vec![
            make_match_arm(
                Pattern::Literal(Literal::Integer(1, None)),
                string_expr("one"),
            ),
            make_match_arm(Pattern::Wildcard, string_expr("other")),
        ];
        let result = transpiler
            .transpile_match_with_string_arms_impl(&expr, &arms)
            .unwrap();
        let result_str = result.to_string();
        assert!(result_str.contains("match"));
        assert!(result_str.contains("to_string"));
    }

    #[test]
    fn test_match_with_non_string_arms() {
        let transpiler = make_transpiler();
        let expr = ident_expr("x");
        let arms = vec![
            make_match_arm(Pattern::Literal(Literal::Integer(1, None)), int_expr(10)),
            make_match_arm(Pattern::Wildcard, int_expr(0)),
        ];
        let result = transpiler
            .transpile_match_with_string_arms_impl(&expr, &arms)
            .unwrap();
        let result_str = result.to_string();
        assert!(result_str.contains("match"));
        assert!(result_str.contains("10"));
    }

    // ========================================================================
    // convert_arm_body_to_string tests
    // ========================================================================

    #[test]
    fn test_convert_string_literal_arm() {
        let transpiler = make_transpiler();
        let body = string_expr("hello");
        let result = transpiler.convert_arm_body_to_string(&body).unwrap();
        let result_str = result.to_string();
        assert!(result_str.contains("hello"));
        assert!(result_str.contains("to_string"));
    }

    #[test]
    fn test_convert_non_string_arm() {
        let transpiler = make_transpiler();
        let body = int_expr(42);
        let result = transpiler.convert_arm_body_to_string(&body).unwrap();
        let result_str = result.to_string();
        assert!(result_str.contains("42"));
        assert!(!result_str.contains("to_string"));
    }

    // ========================================================================
    // convert_value_for_string_context tests
    // ========================================================================

    #[test]
    fn test_convert_string_literal_with_string_type() {
        let transpiler = make_transpiler();
        let value = string_expr("hello");
        let type_ann = Some(make_type("String"));
        let result = transpiler
            .convert_value_for_string_context("x", &value, type_ann.as_ref(), false)
            .unwrap();
        let result_str = result.to_string();
        assert!(result_str.contains("hello"));
        assert!(result_str.contains("to_string"));
    }

    #[test]
    fn test_convert_mutable_string_literal() {
        let transpiler = make_transpiler();
        let value = string_expr("hello");
        let result = transpiler
            .convert_value_for_string_context("x", &value, None, true)
            .unwrap();
        let result_str = result.to_string();
        assert!(result_str.contains("String :: from"));
    }

    #[test]
    fn test_convert_integer_value() {
        let transpiler = make_transpiler();
        let value = int_expr(42);
        let result = transpiler
            .convert_value_for_string_context("x", &value, None, false)
            .unwrap();
        assert!(result.to_string().contains("42"));
    }

    // ========================================================================
    // check_mutability tests
    // ========================================================================

    #[test]
    fn test_check_mutability_explicit() {
        let transpiler = make_transpiler();
        let body = int_expr(0);
        assert!(transpiler.check_mutability("x", true, &body));
    }

    #[test]
    fn test_check_mutability_not_mutable() {
        let transpiler = make_transpiler();
        let body = int_expr(0);
        assert!(!transpiler.check_mutability("x", false, &body));
    }

    // ========================================================================
    // convert_let_body_to_string tests
    // ========================================================================

    #[test]
    fn test_convert_let_body_simple_immutable() {
        let transpiler = make_transpiler();
        let value = int_expr(42);
        let body = ident_expr("x");
        let result = transpiler
            .convert_let_body_to_string("x", None, &value, &body, false)
            .unwrap();
        let result_str = result.to_string();
        assert!(result_str.contains("let"));
        assert!(result_str.contains("x"));
        assert!(result_str.contains("42"));
        assert!(result_str.contains("to_string"));
    }

    #[test]
    fn test_convert_let_body_mutable() {
        let transpiler = make_transpiler();
        let value = int_expr(10);
        let body = ident_expr("y");
        let result = transpiler
            .convert_let_body_to_string("y", None, &value, &body, true)
            .unwrap();
        let result_str = result.to_string();
        assert!(result_str.contains("mut"));
        assert!(result_str.contains("y"));
        assert!(result_str.contains("to_string"));
    }

    #[test]
    fn test_convert_let_body_with_type_annotation() {
        let transpiler = make_transpiler();
        let value = int_expr(99);
        let body = ident_expr("z");
        let type_ann = make_type("i32");
        let result = transpiler
            .convert_let_body_to_string("z", Some(&type_ann), &value, &body, false)
            .unwrap();
        let result_str = result.to_string();
        assert!(result_str.contains("z"));
        assert!(result_str.contains("i32"));
        assert!(result_str.contains("to_string"));
    }

    #[test]
    fn test_convert_let_body_with_string_value() {
        let transpiler = make_transpiler();
        let value = string_expr("hello");
        let body = ident_expr("s");
        let result = transpiler
            .convert_let_body_to_string("s", None, &value, &body, false)
            .unwrap();
        let result_str = result.to_string();
        assert!(result_str.contains("hello"));
        assert!(result_str.contains("to_string"));
    }

    #[test]
    fn test_convert_let_body_with_string_type() {
        let transpiler = make_transpiler();
        let value = string_expr("world");
        let body = ident_expr("s");
        let type_ann = make_type("String");
        let result = transpiler
            .convert_let_body_to_string("s", Some(&type_ann), &value, &body, false)
            .unwrap();
        let result_str = result.to_string();
        assert!(result_str.contains("String"));
        assert!(result_str.contains("to_string"));
    }

    #[test]
    fn test_convert_let_body_mutable_with_type() {
        let transpiler = make_transpiler();
        let value = int_expr(0);
        let body = ident_expr("count");
        let type_ann = make_type("usize");
        let result = transpiler
            .convert_let_body_to_string("count", Some(&type_ann), &value, &body, true)
            .unwrap();
        let result_str = result.to_string();
        assert!(result_str.contains("mut"));
        assert!(result_str.contains("count"));
        assert!(result_str.contains("usize"));
    }

    #[test]
    fn test_convert_let_body_complex_body_expression() {
        let transpiler = make_transpiler();
        let value = int_expr(5);
        let body = make_expr(ExprKind::Binary {
            left: Box::new(ident_expr("n")),
            op: crate::frontend::ast::BinaryOp::Multiply,
            right: Box::new(int_expr(2)),
        });
        let result = transpiler
            .convert_let_body_to_string("n", None, &value, &body, false)
            .unwrap();
        let result_str = result.to_string();
        assert!(result_str.contains("n"));
        assert!(result_str.contains("to_string"));
    }

    #[test]
    fn test_convert_let_body_identifier_value() {
        let transpiler = make_transpiler();
        let value = ident_expr("other_var");
        let body = ident_expr("x");
        let result = transpiler
            .convert_let_body_to_string("x", None, &value, &body, false)
            .unwrap();
        let result_str = result.to_string();
        assert!(result_str.contains("other_var"));
        assert!(result_str.contains("to_string"));
    }
}