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
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
// Type Parser - Windjammer Type Parsing Functions
//
// This module contains functions for parsing type annotations in Windjammer.

use crate::lexer::Token;
use crate::parser::ast::*;
use crate::parser_impl::Parser;

/// When parsing `lhs::rhs` and the lookahead delimiter is `>`, `,`, `)`, etc., distinguish:
/// - **Module path** (`ffi::GpuVertex`, `std::fs::File`) → extend into a single [`Type::Custom`] path
///   so Rust codegen can run `qualify_parent_child_external_path` (e.g. `ffi::api::GpuVertex`).
/// - **Associated type** (`Self::Item`, `T::Output`, `MyTrait::Assoc`) → [`Type::Associated`].
fn type_path_lhs_is_module_prefix(lhs: &str) -> bool {
    matches!(lhs, "crate" | "super" | "self")
        || lhs.chars().next().is_some_and(|c| c.is_ascii_lowercase())
}

impl Parser {
    /// Convert a Type to a string representation (for error messages and debugging)
    #[allow(clippy::only_used_in_recursion)]
    pub fn type_to_string(&self, ty: &Type) -> String {
        match ty {
            Type::Int => "int".to_string(),
            Type::Int32 => "i32".to_string(),
            Type::Uint => "uint".to_string(),
            Type::Float => "float".to_string(),
            Type::Bool => "bool".to_string(),
            Type::String => "string".to_string(),
            Type::Custom(name) => name.clone(),
            Type::Generic(name) => name.clone(),
            Type::Reference(inner) => format!("&{}", self.type_to_string(inner)),
            Type::MutableReference(inner) => format!("&mut {}", self.type_to_string(inner)),
            Type::RawPointer { mutable, pointee } => {
                if *mutable {
                    format!("*mut {}", self.type_to_string(pointee))
                } else {
                    format!("*const {}", self.type_to_string(pointee))
                }
            }
            Type::Option(inner) => format!("Option<{}>", self.type_to_string(inner)),
            Type::Result(ok, err) => format!(
                "Result<{}, {}>",
                self.type_to_string(ok),
                self.type_to_string(err)
            ),
            Type::Vec(inner) => format!("Vec<{}>", self.type_to_string(inner)),
            Type::Array(inner, size) => format!("[{}; {}]", self.type_to_string(inner), size),
            Type::Tuple(types) => {
                let type_strs: Vec<String> = types.iter().map(|t| self.type_to_string(t)).collect();
                format!("({})", type_strs.join(", "))
            }
            Type::Parameterized(base, args) => {
                let arg_strs: Vec<String> = args.iter().map(|t| self.type_to_string(t)).collect();
                format!("{}<{}>", base, arg_strs.join(", "))
            }
            Type::Associated(base, name) => format!("{}::{}", base, name),
            Type::TraitObject(trait_name) => format!("dyn {}", trait_name),
            Type::ImplTrait(trait_name) => format!("trait {}", trait_name),
            Type::Infer => "_".to_string(),
            Type::FunctionPointer {
                params,
                return_type,
            } => {
                let param_strs: Vec<String> =
                    params.iter().map(|t| self.type_to_string(t)).collect();
                if let Some(ret) = return_type {
                    format!(
                        "fn({}) -> {}",
                        param_strs.join(", "),
                        self.type_to_string(ret)
                    )
                } else {
                    format!("fn({})", param_strs.join(", "))
                }
            }
        }
    }

    /// Parse generic type parameters: <T, U: Display, V: Clone + Send>
    pub fn parse_type_params(&mut self) -> Result<Vec<TypeParam>, String> {
        let mut type_params = Vec::new();
        if self.current_token() == &Token::Lt {
            self.advance(); // Consume <
            while self.current_token() != &Token::Gt {
                let name = if let Token::Ident(n) = self.current_token() {
                    let name = n.clone();
                    self.advance();
                    name
                } else {
                    return Err("Expected type parameter name".to_string());
                };

                let mut bounds = Vec::new();
                if self.current_token() == &Token::Colon {
                    self.advance(); // Consume :
                    while self.current_token() != &Token::Comma
                        && self.current_token() != &Token::Gt
                    {
                        if let Token::Ident(bound) = self.current_token() {
                            bounds.push(bound.clone());
                            self.advance();
                        } else {
                            return Err("Expected trait bound name".to_string());
                        }

                        if self.current_token() == &Token::Plus {
                            self.advance(); // Consume + for multiple bounds
                        } else {
                            break;
                        }
                    }
                }

                type_params.push(TypeParam { name, bounds });

                if self.current_token() == &Token::Comma {
                    self.advance(); // Consume ,
                } else {
                    break;
                }
            }
            self.expect_gt_or_split_shr()?; // Consume > (handles >> for nested generics)
        }
        Ok(type_params)
    }

    /// Parse where clause: where T: Display, U: Clone + Send, P::Output: Debug
    pub fn parse_where_clause(&mut self) -> Result<Vec<(String, Vec<String>)>, String> {
        let mut where_clause = Vec::new();
        if self.current_token() == &Token::Where {
            self.advance(); // Consume where
            while self.current_token() != &Token::LBrace
                && self.current_token() != &Token::Semicolon
            {
                // Parse type parameter name (can be T or P::Output for associated types)
                let type_param = if let Token::Ident(n) = self.current_token() {
                    let mut name = n.clone();
                    self.advance();

                    // Check for associated type syntax: P::Output
                    while self.current_token() == &Token::ColonColon {
                        self.advance(); // Consume ::
                        if let Token::Ident(assoc_name) = self.current_token() {
                            name.push_str("::");
                            name.push_str(assoc_name);
                            self.advance();
                        } else {
                            return Err("Expected associated type name after '::'".to_string());
                        }
                    }
                    name
                } else {
                    return Err("Expected type parameter name in where clause".to_string());
                };

                // Expect :
                if self.current_token() != &Token::Colon {
                    return Err("Expected ':' after type parameter in where clause".to_string());
                }
                self.advance();

                // Parse trait bounds
                let mut bounds = Vec::new();
                loop {
                    if let Token::Ident(bound) = self.current_token() {
                        bounds.push(bound.clone());
                        self.advance();
                    } else {
                        return Err("Expected trait bound in where clause".to_string());
                    }

                    if self.current_token() == &Token::Plus {
                        self.advance(); // Consume + for multiple bounds
                    } else {
                        break;
                    }
                }

                where_clause.push((type_param, bounds));

                if self.current_token() == &Token::Comma {
                    self.advance(); // Consume ,
                } else {
                    break;
                }
            }
        }
        Ok(where_clause)
    }

    /// Parse a type annotation
    pub fn parse_type(&mut self) -> Result<Type, String> {
        // Handle raw pointer types: *const T, *mut T
        if self.current_token() == &Token::Star {
            self.advance();

            // Check for const or mut
            let mutable = if self.current_token() == &Token::Const {
                self.advance();
                false
            } else if self.current_token() == &Token::Mut {
                self.advance();
                true
            } else {
                return Err("Expected 'const' or 'mut' after '*' in pointer type".to_string());
            };

            let pointee = Box::new(self.parse_type()?);
            return Ok(Type::RawPointer { mutable, pointee });
        }

        // Handle reference types
        if self.current_token() == &Token::Ampersand {
            self.advance();
            if self.current_token() == &Token::Mut {
                self.advance();
                let inner = Box::new(self.parse_type()?);
                return Ok(Type::MutableReference(inner));
            } else {
                let inner = Box::new(self.parse_type()?);
                return Ok(Type::Reference(inner));
            }
        }

        let base_type = match self.current_token() {
            Token::Dyn => {
                // Parse: dyn TraitName
                self.advance();
                if let Token::Ident(trait_name) = self.current_token() {
                    let name = trait_name.clone();
                    self.advance();
                    Type::TraitObject(name)
                } else {
                    return Err("Expected trait name after 'dyn'".to_string());
                }
            }
            Token::Trait => {
                // Parse: trait TraitName (Windjammer syntax - compiler infers dispatch)
                self.advance();
                if let Token::Ident(trait_name) = self.current_token() {
                    let name = trait_name.clone();
                    self.advance();
                    Type::ImplTrait(name)
                } else {
                    return Err("Expected trait name after 'trait'".to_string());
                }
            }
            Token::Int => {
                self.advance();
                Type::Int
            }
            Token::Int32 => {
                self.advance();
                Type::Int32
            }
            Token::Uint => {
                self.advance();
                Type::Uint
            }
            Token::Float => {
                self.advance();
                Type::Float
            }
            Token::Bool => {
                self.advance();
                Type::Bool
            }
            Token::String => {
                self.advance();
                Type::String
            }
            Token::LBracket => {
                // Array/Slice type: [T] or fixed-size array: [T; N]
                self.advance();
                let inner = Box::new(self.parse_type()?);

                // Check for fixed-size array syntax: [T; N]
                if self.current_token() == &Token::Semicolon {
                    self.advance();

                    // Parse the size - must be a literal integer
                    let size = match self.current_token() {
                        Token::IntLiteral(n) | Token::IntLiteralSuffixed(n, _) => {
                            let size = *n as usize;
                            self.advance();
                            size
                        }
                        _ => {
                            return Err(format!(
                                "Expected integer literal for array size, got {:?}",
                                self.current_token()
                            ));
                        }
                    };

                    self.expect(Token::RBracket)?;
                    Type::Array(inner, size)
                } else {
                    self.expect(Token::RBracket)?;
                    // [T] without size is a dynamic array (Vec)
                    Type::Vec(inner)
                }
            }
            Token::Fn => {
                // Function pointer type: fn(int, string) -> bool
                self.advance(); // consume 'fn'
                self.expect(Token::LParen)?;

                let mut params = Vec::new();
                while self.current_token() != &Token::RParen {
                    params.push(self.parse_type()?);

                    if self.current_token() == &Token::Comma {
                        self.advance();
                    } else {
                        break;
                    }
                }

                self.expect(Token::RParen)?;

                let return_type = if self.current_token() == &Token::Arrow {
                    self.advance();
                    Some(Box::new(self.parse_type()?))
                } else {
                    None
                };

                Type::FunctionPointer {
                    params,
                    return_type,
                }
            }
            Token::LParen => {
                // Tuple type: (T1, T2, T3) or unit type: ()
                self.advance();

                // Check for unit type ()
                if self.current_token() == &Token::RParen {
                    self.advance();
                    return Ok(Type::Tuple(vec![])); // Unit type is an empty tuple
                }

                let mut types = Vec::new();

                while self.current_token() != &Token::RParen {
                    types.push(self.parse_type()?);

                    if self.current_token() == &Token::Comma {
                        self.advance();
                    } else {
                        break;
                    }
                }

                self.expect(Token::RParen)?;
                Type::Tuple(types)
            }
            Token::Ident(name) => {
                let mut type_name = name.clone();
                self.advance();

                // Handle qualified type names with both . and :: (module.Type or module::Type)
                loop {
                    if self.current_token() == &Token::Dot {
                        self.advance();
                        if let Token::Ident(segment) = self.current_token() {
                            type_name.push('.');
                            type_name.push_str(segment);
                            self.advance();
                        } else {
                            return Err("Expected identifier after '.' in type name".to_string());
                        }
                    } else if self.current_token() == &Token::ColonColon {
                        // Look ahead to check if this is an associated type or path segment
                        if self.position + 1 < self.tokens.len() {
                            // Allow keywords as identifiers in type paths (e.g., std::thread::JoinHandle)
                            let next_segment_opt = match &self.tokens[self.position + 1].token {
                                Token::Ident(n) => Some(n.clone()),
                                Token::Thread => Some("thread".to_string()),
                                Token::Async => Some("async".to_string()),
                                _ => None,
                            };

                            if let Some(next_segment_str) = next_segment_opt {
                                // Could be either:
                                // 1. Path segment: std::fs::File
                                // 2. Associated type: Self::Item

                                // For now, check if the next token after the identifier is a generic or end
                                // to determine if this is the final segment (associated type)
                                if self.position + 2 < self.tokens.len() {
                                    let after_next = &self.tokens[self.position + 2];
                                    match &after_next.token {
                                        Token::Lt => {
                                            // This is a parameterized type (e.g., HashMap<K, V>)
                                            // Add to path and break to let generic parsing handle it
                                            type_name.push_str("::");
                                            type_name.push_str(&next_segment_str);
                                            self.advance(); // consume ::
                                            self.advance(); // consume identifier
                                            break; // Exit loop to handle generics
                                        }
                                        Token::Comma
                                        | Token::Gt
                                        | Token::RParen
                                        | Token::RBrace
                                        | Token::Semicolon
                                        | Token::FatArrow
                                        | Token::LBrace
                                        | Token::Where => {
                                            if type_path_lhs_is_module_prefix(&type_name) {
                                                type_name.push_str("::");
                                                type_name.push_str(&next_segment_str);
                                                self.advance(); // consume ::
                                                self.advance(); // consume identifier
                                                break;
                                            }
                                            // Associated type (final segment): Self::Item, T::Output, …
                                            self.advance(); // consume ::
                                            self.advance(); // consume identifier
                                            return Ok(Type::Associated(
                                                type_name,
                                                next_segment_str,
                                            ));
                                        }
                                        Token::ColonColon => {
                                            // More path segments to come
                                            type_name.push_str("::");
                                            type_name.push_str(&next_segment_str);
                                            self.advance(); // consume ::
                                            self.advance(); // consume identifier
                                            continue;
                                        }
                                        _ => {
                                            if type_path_lhs_is_module_prefix(&type_name) {
                                                type_name.push_str("::");
                                                type_name.push_str(&next_segment_str);
                                                self.advance(); // consume ::
                                                self.advance(); // consume identifier
                                                break;
                                            }
                                            self.advance(); // consume ::
                                            self.advance(); // consume identifier
                                            return Ok(Type::Associated(
                                                type_name,
                                                next_segment_str,
                                            ));
                                        }
                                    }
                                } else {
                                    self.advance(); // consume ::
                                    self.advance(); // consume identifier
                                    if type_path_lhs_is_module_prefix(&type_name) {
                                        type_name.push_str("::");
                                        type_name.push_str(&next_segment_str);
                                        return Ok(Type::Custom(type_name));
                                    }
                                    return Ok(Type::Associated(type_name, next_segment_str));
                                }
                            } else {
                                return Err(
                                    "Expected identifier after '::' in type name".to_string()
                                );
                            }
                        } else {
                            return Err("Expected identifier after '::' in type name".to_string());
                        }
                    } else {
                        break;
                    }
                }

                // Check for generic parameters
                // BUT: Primitive types like usize, i32, u32, etc. can't have generics
                // If we see `<` after a primitive type, it's a comparison operator, not generics!
                let is_primitive_type = matches!(
                    type_name.as_str(),
                    "usize"
                        | "isize"
                        | "u8"
                        | "u16"
                        | "u32"
                        | "u64"
                        | "u128"
                        | "i8"
                        | "i16"
                        | "i32"
                        | "i64"
                        | "i128"
                        | "f32"
                        | "f64"
                        | "char"
                        | "str"
                        | "bool"
                        | "unit"
                        | "()"
                );

                // Normalize Rust string types to canonical Type::String
                if (type_name == "str" || type_name == "String") && !self.in_extern_fn {
                    let loc = self.current_location();
                    let (line, col) = loc.as_ref().map(|l| (l.line, l.column)).unwrap_or((1, 1));
                    self.emit_error_diagnostic(
                        format!(
                            "W0010: use `string` instead of `{}` -- Windjammer has one string type",
                            type_name
                        ),
                        Some(self.filename.clone()),
                        Some(line),
                        Some(col),
                    );
                    Type::String
                } else if !is_primitive_type && self.current_token() == &Token::Lt {
                    self.advance();

                    // Handle Vec<T>, Option<T>, Result<T, E>
                    if type_name == "Vec" {
                        let inner = Box::new(self.parse_type()?);
                        self.expect_gt_or_split_shr()?;
                        Type::Vec(inner)
                    } else if type_name == "Option" {
                        let inner = Box::new(self.parse_type()?);
                        self.expect_gt_or_split_shr()?;
                        Type::Option(inner)
                    } else if type_name == "Result" {
                        let ok_type = Box::new(self.parse_type()?);
                        self.expect(Token::Comma)?;
                        let err_type = Box::new(self.parse_type()?);
                        self.expect_gt_or_split_shr()?;
                        Type::Result(ok_type, err_type)
                    } else {
                        // Generic custom type: Box<T>, HashMap<K, V>, etc.
                        let mut type_args = Vec::new();

                        loop {
                            type_args.push(self.parse_type()?);

                            if self.current_token() == &Token::Comma {
                                self.advance();
                            } else if self.current_token() == &Token::Gt
                                || self.current_token() == &Token::Shr
                            {
                                // Handle both > and >> (for nested generics like HashMap<K, Vec<V>>)
                                self.expect_gt_or_split_shr()?;
                                break;
                            } else {
                                eprintln!("DEBUG: Parsing type arguments for: {}", type_name);
                                eprintln!("DEBUG: After parsing type arg, current token: {:?} at position: {}", self.current_token(), self.position);
                                return Err(format!(
                                    "Expected ',' or '>' in type arguments for '{}', got {:?} at position {}",
                                    type_name, self.current_token(), self.position
                                ));
                            }
                        }

                        Type::Parameterized(type_name, type_args)
                    }
                } else {
                    Type::Custom(type_name)
                }
            }
            Token::Underscore => {
                // Type inference placeholder: _
                self.advance();
                Type::Infer
            }
            Token::Self_ => {
                // Self type (e.g. in &self, &mut self parameter types)
                self.advance();
                Type::Custom("Self".to_string())
            }
            _ => return Err(format!("Expected type, got {:?}", self.current_token())),
        };

        Ok(base_type)
    }

    /// Public wrapper for parse_type (for external use)
    pub fn parse_type_public(&mut self) -> Result<Type, String> {
        self.parse_type()
    }
}