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
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
use cstree::{
interning::{Resolver, TokenKey},
text::TextRange,
};
mod _ast;
mod span;
pub use span::Span;
/// Converts a concrete syntax tree (CST) node to its corresponding abstract syntax tree (AST) representation.
pub trait ToAst {
/// The target AST type that this CST node converts to.
type Output;
/// Attempts to convert this CST node to its corresponding AST representation.
///
/// Returns `Some(ast_node)` if the conversion is successful, or `None` if the
/// CST node cannot be represented in the AST (e.g., due to syntax errors or
/// unsupported constructs).
fn to_ast<I>(self, resolver: &I) -> Option<Self::Output>
where
I: Resolver<TokenKey> + ?Sized;
}
/// Core AST expression enum - simplified and semantic.
#[derive(Debug, Clone, PartialEq)]
pub enum Expr {
// Literals and identifiers
/// Literal value (numbers, strings, booleans)
Literal(Literal),
/// Variable or function identifier
Ident(Ident),
// Operators
/// Binary operation between two expressions (e.g., `a + b`, `x == y`)
Binary(BinaryExpr),
/// Unary operation on a single expression (e.g., `-x`, `!condition`)
Unary(UnaryExpr),
// Method chaining
/// Method call or property access (e.g., `obj.method()`, `obj.field`)
Chain(ChainExpr),
// Grouping
/// Parenthesized expression for precedence (e.g., `(a + b)`)
Paren(ParenExpr),
/// Block of statements/expressions (e.g., `{ stmt1; stmt2; expr }`)
Block(BlockExpr),
// Control flow
/// Break statement, optionally with a value (e.g., `break;`, `break value;`)
Break(Break),
/// Continue statement (e.g., `continue;`)
Continue(Continue),
/// Return statement, optionally with a value (e.g., `return;`, `return value;`)
Return(Return),
/// Throw statement with an exception value (e.g., `throw error;`)
Throw(Throw),
// Loops
/// While loop with condition and body (e.g., `while (condition) { body }`)
While(While),
/// For loop with iterator and body (e.g., `for (iterator) { body }`)
For(ForLoop),
// Conditionals
/// If/else conditional expression (e.g., `if (cond) { then } else { else }`)
If(IfElse),
/// MatchPat matching expression (e.g., `match expr { MatchPat => body }`)
Match(Match),
// Exception handling
/// Try-catch expression for exception handling (e.g., `try { code } catch (e) { handler }`)
TryCatch(TryCatch),
// Declarations (when used as expressions)
/// Variable declaration/definition (e.g., `let x: int = value;`)
Variable(VariableStmt),
/// Function declaration/definition (e.g., `fn add(a: int, b: int) -> int { a + b }`)
Function(Function),
/// Class declaration/definition (e.g., `class MyClass { fields, methods }`)
Class(Class),
/// Trait declaration/definition (e.g., `trait Drawable { fn draw(&self); }`)
Trait(Trait),
/// Trait implementation block (e.g., `impl Drawable for MyClass { ... }`)
TraitImpl(TraitImpl),
/// Enum declaration/definition (e.g., `enum Option<T> { Some(T), None }`)
Enum(Enum),
/// Type alias declaration (e.g., `type UserId = u64;`)
TypeAlias(TypeAlias),
/// Import statement (e.g., `import { items } from "module";`)
Import(ImportStmt),
}
/// Simplified literal representation in the abstract syntax tree.
///
/// Represents the basic literal values that can appear in expressions,
#[derive(Debug, Clone, PartialEq)]
pub struct Literal {
///
span: TextRange,
///
pub value: Value,
}
///
#[derive(Debug, Clone, PartialEq)]
pub enum Value {
/// Boolean literal (`true` or `false`)
Bool(bool),
/// Signed integer literal
Int(i64),
/// Double-precision floating point literal
Double(f64),
/// String literal
Str(String),
}
/// An identifier in the abstract syntax tree.
///
/// Represents a named identifier such as variable names, function names,
/// or other symbolic references in the source code.
#[derive(Debug, Clone, PartialEq)]
pub struct Ident {
///
span: TextRange,
/// The name of the identifier
pub name: String,
}
/// Binary operation expression in the abstract syntax tree.
///
/// Represents an expression with two operands and a binary operator,
/// such as `a + b`, `x == y`, or `foo && bar`.
#[derive(Debug, Clone, PartialEq)]
pub struct BinaryExpr {
/// The left and right operands, boxed to reduce memory usage
operand: Box<(Expr, Expr)>,
/// The binary operator applied to the operands
pub op: BinaryOp,
}
impl BinaryExpr {
/// Returns a reference to the left operand of the binary expression.
pub const fn left(&self) -> &Expr {
&self.operand.0
}
/// Returns a reference to the right operand of the binary expression.
pub const fn right(&self) -> &Expr {
&self.operand.1 // Note: This should be .1, not .0
}
/// Returns a mutable reference to the left operand of the binary expression.
pub const fn left_mut(&mut self) -> &mut Expr {
&mut self.operand.0
}
/// Returns a mutable reference to the right operand of the binary expression.
pub const fn right_mut(&mut self) -> &mut Expr {
&mut self.operand.1
}
}
/// Binary operators available in expressions.
///
/// Represents the various binary operations that can be performed between two operands,
/// organized by category for clarity.
#[derive(Debug, Clone, PartialEq)]
pub enum BinaryOp {
// Arithmetic operators
/// Addition operator (`+`)
Add,
/// Subtraction operator (`-`)
Sub,
/// Multiplication operator (`*`)
Mul,
/// Division operator (`/`)
Div,
/// Modulo operator (`%`)
Mod,
// Comparison operators
/// Equality operator (`==`)
Eq,
/// Inequality operator (`!=`)
NotEq,
/// Less than operator (`<`)
Lt,
/// Greater than operator (`>`)
Gt,
/// Less than or equal operator (`<=`)
LtEq,
/// Greater than or equal operator (`>=`)
GtEq,
// Logical operators
/// Logical AND operator (`&&`)
And,
/// Logical OR operator (`||`)
Or,
}
/// Unary operation expression in the abstract syntax tree.
///
/// Represents an expression with a single operand and a unary operator,
/// such as `-x` (negation) or `!condition` (logical not).
#[derive(Debug, Clone, PartialEq)]
pub struct UnaryExpr {
/// The unary operator to apply
pub op: UnaryOp,
/// The operand expression, boxed to reduce memory usage
pub expr: Box<Expr>,
}
/// Unary operators available in expressions.
///
/// Represents the unary operations that can be performed on a single operand.
#[derive(Debug, Clone, PartialEq)]
pub enum UnaryOp {
/// Arithmetic negation operator (`-`)
Minus,
/// Logical NOT operator (`!`)
Not,
}
/// Method chaining expression in the abstract syntax tree.
///
/// Represents method invocation or property access on an object,
/// such as `obj.method()` or `obj.property`.
#[derive(Debug, Clone, PartialEq)]
pub struct ChainExpr {
/// The object and method/property pair, boxed to reduce memory usage
data: Box<(Expr, Expr)>,
}
impl ChainExpr {
/// Returns a reference to the object being accessed.
pub const fn object(&self) -> &Expr {
&self.data.0
}
/// Returns a reference to the method or property being accessed.
pub const fn method(&self) -> &Expr {
&self.data.1 // Note: This should be .1, not .0
}
/// Returns a mutable reference to the object being accessed.
pub const fn object_mut(&mut self) -> &mut Expr {
&mut self.data.0
}
/// Returns a mutable reference to the method or property being accessed.
pub const fn method_mut(&mut self) -> &mut Expr {
&mut self.data.1 // Note: This should be .1, not .0
}
}
/// Parenthesized expression in the abstract syntax tree.
///
/// Represents an expression wrapped in parentheses, such as `(x + y)`.
/// While parentheses don't change the semantic meaning, they can affect
/// operator precedence and are sometimes preserved for clarity.
#[derive(Debug, Clone, PartialEq)]
pub struct ParenExpr {
///
span: TextRange,
/// The expression contained within the parentheses
pub expr: Box<Expr>,
}
/// Block expression in the abstract syntax tree.
///
/// Represents a sequence of statements or expressions enclosed in braces,
/// such as `{ stmt1; stmt2; expr }`. The last expression in the block
/// is typically the block's value.
#[derive(Debug, Clone, PartialEq)]
pub struct BlockExpr {
///
pub span: TextRange,
/// The statements and expressions within the block
pub statements: Box<[Expr]>,
}
/// Break statement in the abstract syntax tree.
///
/// Represents a break statement that exits from a loop, optionally
/// with a value, such as `break;` or `break value;`.
#[derive(Debug, Clone, PartialEq)]
pub struct Break {
///
span: TextRange,
/// Optional value to break with
pub value: Option<Box<Expr>>,
}
/// Continue statement in the abstract syntax tree.
///
/// Represents a continue statement that skips to the next iteration
/// of a loop, such as `continue;`.
#[derive(Debug, Clone, PartialEq)]
pub struct Continue {
///
span: TextRange,
}
/// Return statement in the abstract syntax tree.
///
/// Represents a return statement that exits from a function, optionally
/// with a value, such as `return;` or `return value;`.
#[derive(Debug, Clone, PartialEq)]
pub struct Return {
///
span: TextRange,
/// Optional value to return
pub value: Option<Box<Expr>>,
}
/// Throw statement in the abstract syntax tree.
///
/// Represents a throw statement that raises an exception with the given value,
/// such as `throw error;`.
#[derive(Debug, Clone, PartialEq)]
pub struct Throw {
///
span: TextRange,
/// The value/exception to throw
pub value: Box<Expr>,
}
/// While loop expression in the abstract syntax tree.
///
/// Represents a while loop with a condition and body, such as
/// `while (condition) { body }`.
#[derive(Debug, Clone, PartialEq)]
pub struct While {
///
span: TextRange,
/// The loop condition wrapped in parentheses
pub condition: ParenExpr,
/// The loop body
pub body: BlockExpr,
}
/// For loop expression in the abstract syntax tree.
///
/// Represents a for loop with an iterator expression and body, such as
/// `for (iterator) { body }`.
#[derive(Debug, Clone, PartialEq)]
pub struct ForLoop {
///
span: TextRange,
/// The iterator expression wrapped in parentheses
pub iterator: ParenExpr,
/// The loop body
pub body: BlockExpr,
}
/// If expression in the abstract syntax tree.
///
/// Represents conditional branching with if/else if/else chains, such as
/// `if (condition) { then_branch } else if (condition2) { branch2 } else { final_branch }`.
#[derive(Debug, Clone, PartialEq)]
pub struct IfElse {
///
span: TextRange,
/// The primary condition wrapped in parentheses
pub condition: ParenExpr,
/// The block to execute when the condition is true
pub then_branch: BlockExpr,
/// Optional chain of else-if and else branches
pub else_branches: Option<Box<[ElseBranch]>>,
}
/// A single else or else-if branch in an if expression.
///
/// Represents either an `else if (condition) { block }` branch (when condition is Some)
/// or a final `else { block }` branch (when condition is None).
#[derive(Debug, Clone, PartialEq)]
pub struct ElseBranch {
///
span: TextRange,
/// The condition for else-if branches, None for final else branch
pub condition: Option<ParenExpr>,
/// The block to execute for this branch
pub then_branch: BlockExpr,
}
/// Match expression in the abstract syntax tree.
///
/// Represents MatchPat matching against an expression with multiple arms,
/// such as `match expr { MatchPat1 => body1, MatchPat2 => body2 }`.
#[derive(Debug, Clone, PartialEq)]
pub struct Match {
///
span: TextRange,
/// The expression being matched against
pub expr: ParenExpr,
/// The match arms containing MatchPats and their corresponding bodies
pub arms: Box<[MatchArm]>,
}
/// A single arm in a match expression.
///
/// Represents one MatchPat-body pair in a match expression,
/// such as `MatchPat => body`.
#[derive(Debug, Clone, PartialEq)]
pub struct MatchArm {
/// The MatchPat to match against
pub pat: Option<MatchPat>,
/// The expression to evaluate when the MatchPat matches
pub body: BlockExpr,
}
/// MatchPat for matching in match expressions and other MatchPat contexts.
///
/// Represents the various MatchPats that can be used to match against values
/// in MatchPat matching constructs like match expressions.
#[derive(Debug, Clone, PartialEq)]
pub enum MatchPat {
/// Literal MatchPat that matches a specific literal value
Literal(Literal),
///
Ident(Ident),
}
/// Try-catch expression in the abstract syntax tree.
///
/// Represents exception handling with a try block and optional catch arms,
/// such as `try { risky_code } catch (ErrorType e) { handle_error }`.
#[derive(Debug, Clone, PartialEq)]
pub struct TryCatch {
///
span: TextRange,
/// The block of code that might throw an exception
pub try_block: BlockExpr,
/// Optional catch arms for handling different exception types
pub catch_arms: Option<Box<[CatchArm]>>,
}
/// A single catch arm in a try-catch expression.
///
/// Represents one exception handler that catches a specific type of exception
/// and executes a corresponding block of code.
#[derive(Debug, Clone, PartialEq)]
pub struct CatchArm {
///
span: TextRange,
/// The type of exception this arm catches
pub catch_ty: Option<CatchType>,
/// The block of code to execute when this exception is caught
pub body: BlockExpr,
}
/// Exception type specification for catch arms.
///
/// Specifies both the type of exception to catch and the variable name
/// to bind the caught exception to within the catch block.
#[derive(Debug, Clone, PartialEq)]
pub struct CatchType {
///
span: TextRange,
/// The type of exception to catch
pub ty: Type,
/// The variable name to bind the caught exception to
pub name: Ident,
}
/// Type representation in the abstract syntax tree.
///
/// Represents the various types that can appear in type annotations,
/// function signatures, and other type contexts.
#[derive(Debug, Clone, PartialEq)]
pub enum Type {
/// A simple identifier type (e.g., `String`, `MyClass`)
Ident(Ident),
/// A function type with its signature (e.g., `(int, string) -> bool`)
Function(FunctionSignature),
}
/// Variable declaration/expression in the abstract syntax tree.
///
/// Represents variable declarations with optional type annotations and initializers,
/// such as `let mut x: int = { compute_value() }`.
#[derive(Debug, Clone, PartialEq)]
pub struct VariableStmt {
///
span: TextRange,
/// Whether the variable is mutable
pub is_mutable: bool,
/// Access modifiers (public, private, etc.)
pub modifiers: Modifiers,
/// The variable name
pub name: Ident,
/// Optional type annotation
pub ty_annotation: Option<Type>,
/// The initialization expression
pub initializer: BlockExpr,
}
/// Function declaration/expression in the abstract syntax tree.
///
/// Represents function definitions with their signature, modifiers, and body,
/// such as `pub fn add(a: int, b: int) -> int { a + b }`.
#[derive(Debug, Clone, PartialEq)]
pub struct Function {
///
span: TextRange,
/// Access modifiers (public, private, static, etc.)
pub modifiers: Modifiers,
/// The function name
pub name: Ident,
/// The function signature (parameters and return type)
pub signature: FunctionSignature,
/// The function body
pub body: BlockExpr,
}
/// Function signature specification.
///
/// Defines the parameters and return type of a function without the body.
#[derive(Debug, Clone, PartialEq)]
pub struct FunctionSignature {
///
span: TextRange,
/// The function parameters
pub parameters: Box<[Parameter]>,
/// Optional return type (None for void functions)
pub return_type: Option<Box<Type>>,
}
/// Function parameter specification.
///
/// Represents a single parameter in a function signature with its name and type.
#[derive(Debug, Clone, PartialEq)]
pub struct Parameter {
/// The parameter name
pub name: Ident,
/// The parameter type
pub ty: Type,
}
/// Class declaration/expression in the abstract syntax tree.
///
/// Represents class definitions with their members and nested implementations,
/// such as `pub class MyClass { fields, methods, etc. }`.
#[derive(Debug, Clone, PartialEq)]
pub struct Class {
///
span: TextRange,
/// Access modifiers (public, abstract, etc.)
pub modifiers: Modifiers,
/// The class name
pub name: Ident,
/// The class members (fields, methods, etc.)
pub members: MemberConstructions,
/// Nested trait implementations within the class
pub nested_impls: Box<[TraitImpl]>,
}
/// Collection of member constructions for classes, traits, and enums.
///
/// Groups together all the different types of members that can appear
/// within a class, trait, or enum definition.
#[derive(Debug, Clone, PartialEq)]
pub struct MemberConstructions<T = Function> {
/// Implicit initialization expressions
pub implicit_inits: Box<[Expr]>,
/// Method definitions
pub methods: Box<[T]>,
/// Field declarations
pub fields: Box<[VariableStmt]>,
/// Type aliases defined within this scope
pub aliasz: Box<[TypeAlias]>,
}
/// Trait declaration/expression in the abstract syntax tree.
///
/// Represents trait definitions that specify a contract of methods and types,
/// such as `pub trait Drawable { fn draw(&self); }`.
#[derive(Debug, Clone, PartialEq)]
pub struct Trait {
///
span: TextRange,
/// Access modifiers (public, etc.)
pub modifiers: Modifiers,
/// The trait name
pub name: Ident,
/// The trait members (method signatures, associated types, etc.)
pub members: MemberConstructions<FunctionItem>,
}
/// Function declaration/expression in the abstract syntax tree.
#[derive(Debug, Clone, PartialEq)]
pub struct FunctionItem {
///
span: TextRange,
/// Access modifiers (public, private, static, etc.)
pub modifiers: Modifiers,
/// The function name
pub name: Ident,
/// The function signature (parameters and return type)
pub signature: FunctionSignature,
/// The function body
pub body: Option<BlockExpr>,
}
/// Trait implementation block.
///
/// Represents the implementation of trait methods and associated items,
/// providing concrete implementations for trait requirements.
#[derive(Debug, Clone, PartialEq)]
pub struct TraitImpl {
///
span: TextRange,
/// The implemented members (method bodies, type definitions, etc.)
pub members: MemberConstructions,
}
/// Enum declaration/expression in the abstract syntax tree.
///
/// Represents enumeration types with variants and associated members,
/// such as `pub enum Option<T> { Some(T), None }`.
#[derive(Debug, Clone, PartialEq)]
pub struct Enum {
///
span: TextRange,
/// Access modifiers (public, etc.)
pub modifiers: Modifiers,
/// The enum name
pub name: Ident,
/// The enum variants
pub variants: Box<[EnumVariant]>,
/// Associated members (methods, constants, etc.)
pub members: MemberConstructions,
/// Nested trait implementations for the enum
pub nested_impls: Box<[TraitImpl]>,
}
/// A single variant in an enum definition.
///
/// Represents one possible value of an enumeration, optionally with associated data,
/// such as `Some(T)` or `Error { code: int, message: string }`.
#[derive(Debug, Clone, PartialEq)]
pub struct EnumVariant {
/// The variant name
pub name: Ident,
/// Optional fields associated with this variant
pub fields: Option<Box<[EnumVariantField]>>,
}
/// A named field within an enum variant.
#[derive(Debug, Clone, PartialEq)]
pub struct EnumVariantField {
/// The name of the field
pub name: Ident,
/// The type of the field
pub ty: Type,
}
/// Type alias declaration/expression in the abstract syntax tree.
///
/// Represents type aliases that create alternative names for existing types,
/// such as `pub type UserId = u64;`.
#[derive(Debug, Clone, PartialEq)]
pub struct TypeAlias {
///
span: TextRange,
/// Access modifiers (public, etc.)
pub modifiers: Modifiers,
/// The alias name
pub name: Ident,
/// The type being aliased
pub aliased_type: Type,
}
/// Import statement in the abstract syntax tree.
///
/// Represents module imports that bring external items into scope,
/// such as `import { foo, bar } from "module";`.
#[derive(Debug, Clone, PartialEq)]
pub struct ImportStmt {
///
span: TextRange,
/// The source module or file path
pub source: String,
/// The specific items to import from the source
pub items: Box<[Ident]>,
}
bitflags::bitflags! {
/// Represents various modifiers that can be applied to functions, classes, variables,
/// and other declarations to control their visibility, accessibility, and behavior.
#[derive(Debug, Clone, PartialEq)]
pub struct Modifiers : u8 {
/// Public visibility modifier.
///
/// Makes the declaration accessible from outside its defining module
const Public = 0b00000001;
/// Instance access modifier.
///
/// Indicates that the declaration requires instance access (non-static).
const InstanceAccess = 0b00000010;
}
}