java-lang 0.3.2

A Java AST parser in Rust, syn-style API for Java 25 (JLS SE 25)
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
//! Expression types.

use crate::{ident::Ident, span::Span};

use super::{
    attribute::Annotation,
    lit::Lit,
    op::{AssignOpToken, BinOpToken, UnaryOp},
    pat::Pattern,
    path::{Path, TypeArguments},
    stmt::Block,
    ty::Type,
};

/// A Java expression.
///
/// Expressions are represented in a mostly-desugared form, following the JLS
/// grammar hierarchy.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Expr {
    /// A literal value.
    Literal(Lit),
    /// An identifier expression.
    Ident(Ident),
    /// `this`
    This(Span),
    /// `Super`
    Super(Span),
    /// Parenthesized expression: `(expr)`
    Paren {
        paren_span: (Span, Span),
        expr: Box<Expr>,
    },
    /// Class literal: `String.class`, `int[].class`
    ClassLit {
        type_expr: Box<Type>,
        dot_span: Span,
        class_span: Span,
    },
    /// Field access: `expr.field`
    FieldAccess(FieldAccessExpr),
    /// Method invocation: `method(args)`, `obj.method(args)`
    MethodCall(MethodCallExpr),
    /// Array access: `array[index]`
    ArrayAccess(ArrayAccessExpr),
    /// Method reference: `String::valueOf`, `System.out::println`
    MethodRef(MethodRefExpr),
    /// Array creation: `new int[]{1, 2, 3}`, `new String[10]`
    ArrayNew(ArrayNewExpr),
    /// Type cast: `(int) expr`
    Cast(CastExpr),
    /// Binary operation: `a + b`
    Binary(BinaryExpr),
    /// Unary operation: `-x`, `!flag`
    Unary(UnaryExpr),
    /// instanceof: `obj instanceof String`, `obj instanceof String s`
    Instanceof(InstanceofExpr),
    /// Assignment: `x = 5`, `x += 1`
    Assign(AssignExpr),
    /// Ternary conditional: `cond ? a : b`
    Conditional(ConditionalExpr),
    /// Lambda expression: `x -> x + 1`, `(x, y) -> x + y`
    Lambda(LambdaExpr),
    /// Switch expression (Java 14+): `switch (x) { case 1 -> "one"; ... }`
    Switch(SwitchExpr),
    /// Class instance creation (anonymous class): `new Foo() { ... }`
    NewClass(NewClassExpr),
    /// Array initializer: `{1, 2, 3}`
    ArrayInit(ArrayInitExpr),
}

impl Expr {
    pub fn span(&self) -> Span {
        match self {
            Self::Literal(lit) => lit.span(),
            Self::Ident(ident) => ident.span(),
            Self::This(s) => *s,
            Self::Super(s) => *s,
            Self::Paren { paren_span, .. } => paren_span.0.join(paren_span.1),
            Self::ClassLit {
                type_expr,
                class_span,
                ..
            } => type_expr.span().join(*class_span),
            Self::FieldAccess(e) => e.span(),
            Self::MethodCall(e) => e.span(),
            Self::ArrayAccess(e) => e.span(),
            Self::MethodRef(e) => e.span(),
            Self::ArrayNew(e) => e.span(),
            Self::Cast(e) => e.span(),
            Self::Binary(e) => e.span(),
            Self::Unary(e) => e.span(),
            Self::Instanceof(e) => e.span(),
            Self::Assign(e) => e.span(),
            Self::Conditional(e) => e.span(),
            Self::Lambda(e) => e.span,
            Self::Switch(e) => e.span(),
            Self::NewClass(e) => e.span(),
            Self::ArrayInit(e) => e.brace_span.0.join(e.brace_span.1),
        }
    }
}

/// Field access expression: `expr.field`.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct FieldAccessExpr {
    pub target: Box<Expr>,
    pub dot_span: Span,
    pub field: Ident,
}

impl FieldAccessExpr {
    pub fn span(&self) -> Span {
        self.target.span().join(self.field.span())
    }
}

/// Method invocation expression.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct MethodCallExpr {
    /// The method receiver (None for unqualified calls like `method()`).
    pub receiver: Option<Box<Expr>>,
    /// Type arguments for the method call.
    pub type_args: Option<TypeArguments>,
    /// The method name.
    pub method: Ident,
    /// Parenthesized arguments.
    pub paren_span: (Span, Span),
    /// The arguments passed to the method.
    pub args: Vec<Expr>,
}

impl MethodCallExpr {
    pub fn span(&self) -> Span {
        let start = match &self.receiver {
            Some(r) => r.span(),
            None => self.method.span(),
        };
        start.join(self.paren_span.1)
    }
}

/// Array access expression: `array[index]`.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ArrayAccessExpr {
    pub array: Box<Expr>,
    pub index: Box<Expr>,
    pub bracket_span: (Span, Span),
}

impl ArrayAccessExpr {
    pub fn span(&self) -> Span {
        self.array.span().join(self.bracket_span.1)
    }
}

/// Method reference expression: `String::valueOf`.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct MethodRefExpr {
    pub target: MethodRefTarget,
    pub colon_colon_span: Span,
    pub type_args: Option<TypeArguments>,
    pub method_name: Ident,
}

impl MethodRefExpr {
    pub fn span(&self) -> Span {
        let start = self.target.span();
        start.join(self.method_name.span())
    }
}

/// The target of a method reference.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum MethodRefTarget {
    /// `TypeName::method`
    Type(Path),
    /// `expr::method`
    Expr(Box<Expr>),
    /// `super::method`
    Super(Span),
    /// `TypeName.super::method`
    SuperFromType {
        type_name: Path,
        dot_span: Span,
        super_span: Span,
    },
}

impl MethodRefTarget {
    pub fn span(&self) -> Span {
        match self {
            Self::Type(p) => p.span,
            Self::Expr(e) => e.span(),
            Self::Super(s) => *s,
            Self::SuperFromType {
                type_name,
                super_span,
                ..
            } => type_name.span.join(*super_span),
        }
    }
}

/// Class instance creation expression with optional body (anonymous class).
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct NewClassExpr {
    pub new_span: Span,
    pub type_args: Option<TypeArguments>,
    pub class_type: Path,
    pub paren_span: (Span, Span),
    pub args: Vec<Expr>,
    pub body: Option<super::item::ClassBodyDeclList>,
}

impl NewClassExpr {
    pub fn span(&self) -> Span {
        let end = match &self.body {
            Some(b) => b.brace_span.1,
            None => self.paren_span.1,
        };
        self.new_span.join(end)
    }
}

/// Array creation expression: `new int[10]` or `new int[]{1, 2, 3}`.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ArrayNewExpr {
    pub new_span: Span,
    pub elem_type: Type,
    pub dim_exprs: Vec<ArrayDimExpr>,
    pub dims: Vec<super::ty::ArrayDim>,
    pub initializer: Option<ArrayInitExpr>,
}

impl ArrayNewExpr {
    pub fn span(&self) -> Span {
        let end = match &self.initializer {
            Some(init) => init.brace_span.1,
            None => {
                if let Some(dim) = self.dims.last() {
                    dim.bracket_span.1
                } else if let Some(dim_expr) = self.dim_exprs.last() {
                    dim_expr.bracket_span.1
                } else {
                    self.elem_type.span()
                }
            }
        };
        self.new_span.join(end)
    }
}

/// A dimension expression in array creation: `[expr]`.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ArrayDimExpr {
    pub annotations: Vec<Annotation>,
    pub bracket_span: (Span, Span),
    pub expr: Box<Expr>,
}

/// Array initializer: `{1, 2, 3}`.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ArrayInitExpr {
    pub brace_span: (Span, Span),
    pub elements: Vec<Expr>,
    pub trailing_comma: bool,
}

/// Type cast expression: `(int) expr`.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CastExpr {
    pub paren_span: (Span, Span),
    pub target_type: Type,
    pub expr: Box<Expr>,
}

impl CastExpr {
    pub fn span(&self) -> Span {
        self.paren_span.0.join(self.expr.span())
    }
}

/// Binary expression: `a + b`.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct BinaryExpr {
    pub left: Box<Expr>,
    pub op: BinOpToken,
    pub right: Box<Expr>,
}

impl BinaryExpr {
    pub fn span(&self) -> Span {
        self.left.span().join(self.right.span())
    }
}

/// Unary expression: `-x`, `!flag`, `++x`.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct UnaryExpr {
    pub op: UnaryOp,
    pub op_span: Span,
    pub expr: Box<Expr>,
    /// True if operator is postfix (e.g., `x++`).
    pub is_postfix: bool,
}

impl UnaryExpr {
    pub fn span(&self) -> Span {
        if self.is_postfix {
            self.expr.span().join(self.op_span)
        } else {
            self.op_span.join(self.expr.span())
        }
    }
}

/// instanceof expression: `obj instanceof String` or `obj instanceof String s`.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct InstanceofExpr {
    pub expr: Box<Expr>,
    pub instanceof_span: Span,
    pub pattern: InstanceofPattern,
}

impl InstanceofExpr {
    pub fn span(&self) -> Span {
        match &self.pattern {
            InstanceofPattern::Type(t) => self.expr.span().join(t.span()),
            InstanceofPattern::Pattern(p) => self.expr.span().join(p.span()),
        }
    }
}

/// The right-hand side of an instanceof expression.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum InstanceofPattern {
    /// Simple type check: `obj instanceof String`
    Type(Type),
    /// Pattern matching: `obj instanceof String s`
    Pattern(Pattern),
}

/// Assignment expression: `x = 5`, `x += 1`.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct AssignExpr {
    pub target: AssignTarget,
    pub op: AssignOpToken,
    pub value: Box<Expr>,
}

impl AssignExpr {
    pub fn span(&self) -> Span {
        self.target.span().join(self.value.span())
    }
}

/// The target of an assignment expression.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum AssignTarget {
    /// Simple variable name: `x`
    Ident(Ident),
    /// Field access: `obj.field`
    FieldAccess(FieldAccessExpr),
    /// Array access: `arr[i]`
    ArrayAccess(ArrayAccessExpr),
}

impl AssignTarget {
    pub fn span(&self) -> Span {
        match self {
            Self::Ident(i) => i.span(),
            Self::FieldAccess(f) => f.span(),
            Self::ArrayAccess(a) => a.span(),
        }
    }
}

/// Ternary conditional expression: `cond ? a : b`.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ConditionalExpr {
    pub cond: Box<Expr>,
    pub question_span: Span,
    pub then_expr: Box<Expr>,
    pub colon_span: Span,
    pub else_expr: Box<Expr>,
}

impl ConditionalExpr {
    pub fn span(&self) -> Span {
        self.cond.span().join(self.else_expr.span())
    }
}

/// Lambda expression: `x -> x + 1`, `(x, y) -> { return x + y; }`.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct LambdaExpr {
    pub params: LambdaParams,
    pub arrow_span: Span,
    pub body: LambdaBody,
    pub span: Span,
}

/// Lambda parameters.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum LambdaParams {
    /// `(Type name, Type name, ...)`
    List {
        paren_span: (Span, Span),
        params: Vec<LambdaParam>,
    },
    /// `(name, name, ...)` (inferred types)
    IdentList {
        paren_span: (Span, Span),
        idents: Vec<Ident>,
    },
    /// `name` (single inferred parameter)
    Single(Ident),
}

/// A lambda parameter with explicit type.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct LambdaParam {
    pub modifiers: Vec<super::item::Modifier>,
    pub ty: Type,
    pub name: Ident,
}

/// Lambda body: either an expression or a block.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum LambdaBody {
    Expr(Box<Expr>),
    Block(Block),
}

impl LambdaBody {
    pub fn span(&self) -> Span {
        match self {
            Self::Expr(e) => e.span(),
            Self::Block(b) => b.span(),
        }
    }
}

/// Switch expression (Java 14+): `switch (x) { case 1 -> "one"; ... }`.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct SwitchExpr {
    pub switch_span: Span,
    pub paren_span: (Span, Span),
    pub selector: Box<Expr>,
    pub brace_span: (Span, Span),
    pub cases: Vec<SwitchArm>,
}

impl SwitchExpr {
    pub fn span(&self) -> Span {
        self.switch_span.join(self.brace_span.1)
    }
}

/// A single arm of a switch expression.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum SwitchArm {
    /// `case pattern -> expr;`
    Expr(SwitchCase, Span, Expr),
    /// `case pattern -> { ... }`
    Block(SwitchCase, Span, Block),
    /// `case pattern -> throw ...;`
    Throw(SwitchCase, Span, Expr),
    /// `case pattern: statements` (colon-style, from switch statements)
    Colon(SwitchCase, Vec<super::stmt::Stmt>),
}

impl SwitchArm {
    pub fn span(&self) -> Span {
        match self {
            Self::Expr(case, _arrow, expr) => case.span().join(expr.span()),
            Self::Block(case, _arrow, block) => case.span().join(block.brace_span.1),
            Self::Throw(case, _arrow, expr) => case.span().join(expr.span()),
            Self::Colon(case, stmts) => {
                let end = stmts.last().map(|s| s.span()).unwrap_or(case.span());
                case.span().join(end)
            }
        }
    }
}

/// A case label in a switch.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum SwitchCase {
    /// `case 1`, `case 1, 2, 3`
    CaseValues { case_span: Span, values: Vec<Expr> },
    /// `case null`
    CaseNull { case_span: Span, null_span: Span },
    /// `case null, default`
    CaseNullDefault {
        case_span: Span,
        null_span: Span,
        default_span: Span,
    },
    /// `case String s`, `case String s when s.length() > 0`
    CasePattern {
        case_span: Span,
        pattern: Pattern,
        guard: Box<Option<super::pat::Guard>>,
    },
    /// `default`
    Default { default_span: Span },
}

impl SwitchCase {
    pub fn span(&self) -> Span {
        match self {
            Self::CaseValues { case_span, values } => {
                let end = values.last().map(|v| v.span()).unwrap_or(*case_span);
                case_span.join(end)
            }
            Self::CaseNull {
                case_span,
                null_span,
            } => case_span.join(*null_span),
            Self::CaseNullDefault {
                case_span,
                default_span,
                ..
            } => case_span.join(*default_span),
            Self::CasePattern {
                case_span,
                pattern,
                guard,
            } => {
                let end = match guard.as_ref() {
                    Some(g) => g.expr.span(),
                    None => pattern.span(),
                };
                case_span.join(end)
            }
            Self::Default { default_span } => *default_span,
        }
    }
}