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
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
//! JavaScript code generator (ES2020+)
//!
//! Generates clean, idiomatic JavaScript from Windjammer AST

use crate::parser::*;
use std::collections::HashMap;

use super::type_conversion::{escape_js_keyword, type_to_jsdoc};

pub struct JavaScriptGenerator {
    pub(crate) indent_level: usize,
    pub(crate) async_functions: HashMap<String, bool>,
    /// Impl methods collected per type name, to inject into class bodies
    pub(crate) impl_methods: HashMap<String, Vec<(String, Vec<String>)>>,
    /// Track variable declarations per scope for shadowing → renaming.
    /// Maps original name → current JS name (e.g., "x" → "x$2")
    pub(crate) var_scopes: Vec<HashMap<String, String>>,
    /// Counter for generating unique shadowed variable names
    pub(crate) shadow_counter: HashMap<String, usize>,
}

impl JavaScriptGenerator {
    pub fn new() -> Self {
        Self {
            indent_level: 0,
            async_functions: HashMap::new(),
            impl_methods: HashMap::new(),
            var_scopes: vec![HashMap::new()],
            shadow_counter: HashMap::new(),
        }
    }

    /// Push a new variable scope (function body, block, etc.)
    pub(crate) fn push_var_scope(&mut self) {
        self.var_scopes.push(HashMap::new());
    }

    /// Pop the current variable scope
    pub(crate) fn pop_var_scope(&mut self) {
        self.var_scopes.pop();
    }

    /// Declare a variable, generating a renamed version if it shadows an existing one.
    /// Returns the JS name to use.
    pub(crate) fn declare_var(&mut self, name: &str) -> String {
        // Check if this name is already declared in any scope
        let already_exists = self.var_scopes.iter().any(|s| s.contains_key(name));
        let js_name = if already_exists {
            let counter = self.shadow_counter.entry(name.to_string()).or_insert(0);
            *counter += 1;
            format!("{}${}", name, counter)
        } else {
            name.to_string()
        };
        // Register in current scope
        if let Some(scope) = self.var_scopes.last_mut() {
            scope.insert(name.to_string(), js_name.clone());
        }
        js_name
    }

    /// Resolve a variable reference to its current JS name
    pub(crate) fn resolve_var(&self, name: &str) -> String {
        // Search scopes from innermost to outermost
        for scope in self.var_scopes.iter().rev() {
            if let Some(js_name) = scope.get(name) {
                return js_name.clone();
            }
        }
        name.to_string()
    }

    pub fn generate(&mut self, program: &Program) -> String {
        let mut output = String::new();

        // Add file header
        output.push_str("// Generated by Windjammer JavaScript transpiler (v0.32.0)\n");
        output.push_str("// https://windjammer.dev\n\n");

        // First pass: Detect async functions
        self.detect_async_functions(program);

        // Second pass: Collect impl methods per type
        self.collect_impl_methods(program);

        // Generate each item
        for item in &program.items {
            let code = self.generate_item(item);
            if !code.is_empty() {
                output.push_str(&code);
                output.push_str("\n\n");
            }
        }

        // Add auto-run main if it exists
        if self.has_main_function(program) {
            output.push_str(&self.generate_auto_run_main());
        }

        output
    }

    fn detect_async_functions(&mut self, program: &Program) {
        for item in &program.items {
            if let Item::Function { decl: func, .. } = item {
                let is_async = func.is_async || self.contains_await_in_body(&func.body);
                self.async_functions.insert(func.name.clone(), is_async);
            }
        }
    }

    fn contains_await_in_body<'ast>(&self, statements: &[&'ast Statement<'ast>]) -> bool {
        statements.iter().any(|s| Self::contains_await_stmt(s))
    }

    fn contains_await_stmt(stmt: &Statement) -> bool {
        match stmt {
            Statement::Expression { expr, .. } => Self::contains_await_expr(expr),
            Statement::Let { value, .. } => Self::contains_await_expr(value),
            Statement::Return {
                value: Some(expr), ..
            } => Self::contains_await_expr(expr),
            Statement::If {
                condition,
                then_block,
                else_block,
                ..
            } => {
                Self::contains_await_expr(condition)
                    || then_block.iter().any(|s| Self::contains_await_stmt(s))
                    || else_block
                        .as_ref()
                        .is_some_and(|block| block.iter().any(|s| Self::contains_await_stmt(s)))
            }
            _ => false,
        }
    }

    fn contains_await_expr(expr: &Expression) -> bool {
        match expr {
            Expression::Await { .. } => true,
            Expression::Binary { left, right, .. } => {
                Self::contains_await_expr(left) || Self::contains_await_expr(right)
            }
            Expression::Call {
                function,
                arguments,
                ..
            } => {
                Self::contains_await_expr(function)
                    || arguments
                        .iter()
                        .any(|(_, arg)| Self::contains_await_expr(arg))
            }
            Expression::MethodCall {
                object, arguments, ..
            } => {
                Self::contains_await_expr(object)
                    || arguments
                        .iter()
                        .any(|(_, arg)| Self::contains_await_expr(arg))
            }
            _ => false,
        }
    }

    fn has_main_function(&self, program: &Program) -> bool {
        program
            .items
            .iter()
            .any(|item| matches!(item, Item::Function { decl: func, .. } if func.name == "main"))
    }

    fn generate_auto_run_main(&self) -> String {
        let is_async = self.async_functions.get("main").copied().unwrap_or(false);

        if is_async {
            r#"// Auto-run main if executed directly (Node.js)
if (import.meta.url === `file://${process.argv[1]}`) {
    main().catch(console.error);
}
"#
            .to_string()
        } else {
            r#"// Auto-run main if executed directly (Node.js)
if (import.meta.url === `file://${process.argv[1]}`) {
    main();
}
"#
            .to_string()
        }
    }

    /// Collect impl methods per type name for injection into classes
    fn collect_impl_methods(&mut self, program: &Program) {
        for item in &program.items {
            if let Item::Impl { block, .. } = item {
                let type_name = block.type_name.clone();
                let methods: Vec<(String, Vec<String>)> = block
                    .functions
                    .iter()
                    .map(|func| {
                        let method_code = self.generate_class_method(func);
                        (func.name.clone(), vec![method_code])
                    })
                    .collect();
                self.impl_methods
                    .entry(type_name)
                    .or_default()
                    .extend(methods);
            }
        }
    }

    /// Generate a method for inclusion in a class body
    fn generate_class_method(&mut self, func: &FunctionDecl) -> String {
        let mut output = String::new();
        let indent = self.indent();

        let is_async = self
            .async_functions
            .get(&func.name)
            .copied()
            .unwrap_or(false);

        // Check if this is a static method (no self parameter)
        let is_static = !func.parameters.iter().any(|p| p.name == "self");

        output.push_str(&indent);
        if is_static {
            output.push_str("static ");
        }
        if is_async {
            output.push_str("async ");
        }

        // Method name — use 'create' instead of 'new' since 'new' is reserved in JS
        let method_name = if func.name == "new" {
            "create"
        } else {
            &func.name
        };
        output.push_str(method_name);
        output.push('(');
        let params: Vec<String> = func
            .parameters
            .iter()
            .filter(|p| p.name != "self")
            .map(|p| p.name.clone())
            .collect();
        output.push_str(&params.join(", "));
        output.push_str(") {\n");

        self.indent_level += 1;
        let body_len = func.body.len();
        let has_return_type = func.return_type.is_some();
        for (i, stmt) in func.body.iter().enumerate() {
            let is_last = i == body_len - 1;
            if is_last && has_return_type {
                if let Statement::Expression { expr, .. } = stmt {
                    let indent_inner = self.indent();
                    let expr_str = self.generate_expression(expr);
                    // Replace self. with this.
                    let expr_str = expr_str.replace("self.", "this.");
                    output.push_str(&format!("{}return {};\n", indent_inner, expr_str));
                    continue;
                }
            }
            let stmt_code = self.generate_statement(stmt);
            // Replace self. with this.
            let stmt_code = stmt_code.replace("self.", "this.");
            output.push_str(&stmt_code);
        }
        self.indent_level -= 1;

        output.push_str(&self.indent());
        output.push_str("}\n");

        output
    }

    fn generate_item(&mut self, item: &Item) -> String {
        match item {
            Item::Function { decl: func, .. } => self.generate_function(func),
            Item::Struct {
                decl: struct_decl, ..
            } => self.generate_struct(struct_decl),
            Item::Enum {
                decl: enum_decl, ..
            } => self.generate_enum(enum_decl),
            Item::Trait { .. } => String::from("// Trait (use duck typing in JavaScript)"),
            Item::Impl { .. } => String::new(), // Impl blocks are merged into classes
            Item::Use { .. } => String::new(),  // Imports handled separately
            Item::Const { name, value, .. } => {
                format!(
                    "export const {} = {};\n",
                    name,
                    self.generate_expression(value)
                )
            }
            Item::Static { name, value, .. } => {
                format!(
                    "export let {} = {};\n",
                    name,
                    self.generate_expression(value)
                )
            }
            _ => "// TODO: Unsupported item type".to_string(),
        }
    }

    fn generate_function(&mut self, func: &FunctionDecl) -> String {
        let mut output = String::new();

        // Generate JSDoc (TDD FIX: Escape keywords in param names)
        if !func.parameters.is_empty() || func.return_type.is_some() {
            output.push_str("/**\n");
            for param in &func.parameters {
                let param_name = escape_js_keyword(&param.name);
                output.push_str(&format!(
                    " * @param {{{}}} {}\n",
                    type_to_jsdoc(&param.type_),
                    param_name
                ));
            }
            if let Some(ref ret_type) = func.return_type {
                output.push_str(&format!(" * @returns {{{}}}\n", type_to_jsdoc(ret_type)));
            }
            output.push_str(" */\n");
        }

        // Function declaration
        output.push_str("export ");

        let is_async = self
            .async_functions
            .get(&func.name)
            .copied()
            .unwrap_or(false);
        if is_async {
            output.push_str("async ");
        }

        output.push_str("function ");
        output.push_str(&func.name);
        output.push('(');

        // Parameters (TDD FIX: Escape JavaScript keywords)
        let params: Vec<String> = func
            .parameters
            .iter()
            .map(|p| escape_js_keyword(&p.name))
            .collect();
        output.push_str(&params.join(", "));
        output.push_str(") {\n");

        // Body
        self.push_var_scope();
        // Declare parameters in scope (TDD FIX: Use escaped names)
        for p in &func.parameters {
            let escaped = escape_js_keyword(&p.name);
            self.var_scopes
                .last_mut()
                .unwrap()
                .insert(p.name.clone(), escaped);
        }
        self.indent_level += 1;
        let body_len = func.body.len();
        let has_return_type = func.return_type.is_some();
        for (i, stmt) in func.body.iter().enumerate() {
            let is_last = i == body_len - 1;
            // TDD FIX: Auto-insert return for tail expressions
            if is_last && has_return_type {
                match stmt {
                    Statement::Expression { expr, .. } => {
                        let indent = self.indent();
                        let expr_str = self.generate_expression(expr);
                        output.push_str(&format!("{}return {};\n", indent, expr_str));
                        continue;
                    }
                    Statement::Match { .. } => {
                        // Match in tail position: need returns in each arm
                        output.push_str(&self.generate_statement_match_with_return(stmt));
                        continue;
                    }
                    _ => {}
                }
            }
            output.push_str(&self.generate_statement(stmt));
        }
        self.indent_level -= 1;
        self.pop_var_scope();

        output.push('}');
        output
    }

    fn generate_struct(&mut self, struct_decl: &StructDecl) -> String {
        let mut output = String::new();

        output.push_str(&format!("export class {} {{\n", struct_decl.name));
        self.indent_level += 1;

        // Constructor
        output.push_str(&self.indent());
        output.push_str("constructor(");
        let params: Vec<String> = struct_decl.fields.iter().map(|f| f.name.clone()).collect();
        output.push_str(&params.join(", "));
        output.push_str(") {\n");

        self.indent_level += 1;
        for field in &struct_decl.fields {
            output.push_str(&self.indent());
            output.push_str(&format!("this.{} = {};\n", field.name, field.name));
        }
        self.indent_level -= 1;

        output.push_str(&self.indent());
        output.push_str("}\n");

        // Inject impl methods if any exist for this type
        if let Some(methods) = self.impl_methods.get(&struct_decl.name).cloned() {
            for (_method_name, code_parts) in &methods {
                output.push('\n');
                for code in code_parts {
                    output.push_str(code);
                }
            }
        }

        self.indent_level -= 1;
        output.push('}');
        output
    }

    fn generate_enum(&mut self, enum_decl: &EnumDecl) -> String {
        let mut output = String::new();

        // Generate enum as a frozen object.
        // - Unit variants → unique string tags (comparable with ===)
        // - Tuple/struct variants → factory functions returning tagged objects
        output.push_str(&format!(
            "export const {} = Object.freeze({{\n",
            enum_decl.name
        ));

        self.indent_level += 1;
        for (i, variant) in enum_decl.variants.iter().enumerate() {
            output.push_str(&self.indent());
            let tag = format!("{}.{}", enum_decl.name, variant.name);
            match &variant.data {
                EnumVariantData::Unit => {
                    // Unit variant: Color.Red === 'Color.Red'
                    output.push_str(&format!("{}: '{}'", variant.name, tag));
                }
                EnumVariantData::Tuple(types) => {
                    // Tuple variant: Shape.Circle(5) → { type: 'Shape.Circle', value: [5] }
                    let params: Vec<String> = (0..types.len()).map(|i| format!("v{}", i)).collect();
                    output.push_str(&format!(
                        "{}: ({}) => ({{ type: '{}', value: [{}] }})",
                        variant.name,
                        params.join(", "),
                        tag,
                        params.join(", ")
                    ));
                }
                EnumVariantData::Struct(fields) => {
                    // Struct variant: Event.Click { x, y } → { type: 'Event.Click', value: { x, y } }
                    let params: Vec<String> = fields.iter().map(|(n, _)| n.clone()).collect();
                    output.push_str(&format!(
                        "{}: ({}) => ({{ type: '{}', value: {{ {} }} }})",
                        variant.name,
                        params.join(", "),
                        tag,
                        params.join(", ")
                    ));
                }
            }
            if i < enum_decl.variants.len() - 1 {
                output.push(',');
            }
            output.push('\n');
        }
        self.indent_level -= 1;

        output.push_str("});");
        output
    }

    pub(crate) fn indent(&self) -> String {
        "    ".repeat(self.indent_level)
    }
}

impl Default for JavaScriptGenerator {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::codegen::javascript::type_conversion::binary_op_to_js;

    #[test]
    fn test_generate_empty_program() {
        let mut gen = JavaScriptGenerator::new();
        let program = Program { items: vec![] };
        let code = gen.generate(&program);
        assert!(code.contains("Windjammer JavaScript transpiler"));
    }

    #[test]
    fn test_generate_simple_function() {
        let mut gen = JavaScriptGenerator::new();
        let program = Program {
            items: vec![Item::Function {
                decl: FunctionDecl {
                    name: "greet".to_string(),
                    is_pub: false,
                    is_extern: false,
                    parameters: vec![],
                    return_type: None,
                    return_decorators: Vec::new(),
                    body: vec![],
                    decorators: vec![],
                    is_async: false,
                    type_params: vec![],
                    where_clause: vec![],
                    parent_type: None,
                    impl_trait: None,
                    doc_comment: None,
                },
                location: None,
            }],
        };

        let code = gen.generate(&program);
        assert!(code.contains("export function greet"));
    }

    #[test]
    fn test_generate_literal() {
        let gen = JavaScriptGenerator::new();
        assert_eq!(gen.generate_literal(&Literal::Int(42)), "42");
        assert_eq!(
            gen.generate_literal(&Literal::String("hello".to_string())),
            "'hello'"
        );
        assert_eq!(gen.generate_literal(&Literal::Bool(true)), "true");
    }

    #[test]
    fn test_binary_op_conversion() {
        assert_eq!(binary_op_to_js(&BinaryOp::Eq), "===");
        assert_eq!(binary_op_to_js(&BinaryOp::Ne), "!==");
        assert_eq!(binary_op_to_js(&BinaryOp::And), "&&");
        assert_eq!(binary_op_to_js(&BinaryOp::Add), "+");
    }
}