oak-python 0.0.11

Hand-written Python frontend
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
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
#![doc = include_str!("readme.md")]
use core::range::Range;

/// Root node of a Python source file.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, PartialEq)]
pub struct PythonRoot {
    /// The program structure
    pub program: Program,
    /// Source code span
    #[cfg_attr(feature = "serde", serde(with = "oak_core::serde_range"))]
    pub span: Range<usize>,
}

/// A Python program consisting of a list of statements.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, PartialEq)]
pub struct Program {
    /// List of statements in the program
    pub statements: Vec<Statement>,
}

/// Represents a Python statement.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, PartialEq)]
pub enum Statement {
    /// Function definition
    FunctionDef {
        /// Decorators applied to the function
        decorators: Vec<Expression>,
        /// Function name
        name: String,
        /// List of parameters
        parameters: Vec<Parameter>,
        /// Optional return type annotation
        return_type: Option<Type>,
        /// Function body
        body: Vec<Statement>,
    },
    /// Async function definition
    AsyncFunctionDef {
        /// Decorators applied to the function
        decorators: Vec<Expression>,
        /// Function name
        name: String,
        /// List of parameters
        parameters: Vec<Parameter>,
        /// Optional return type annotation
        return_type: Option<Type>,
        /// Function body
        body: Vec<Statement>,
    },
    /// Class definition
    ClassDef {
        /// Decorators applied to the class
        decorators: Vec<Expression>,
        /// Class name
        name: String,
        /// Base classes
        bases: Vec<Expression>,
        /// Class body
        body: Vec<Statement>,
    },
    /// Variable assignment
    Assignment {
        /// Target expression
        target: Expression,
        /// Value expression
        value: Expression,
    },
    /// Augmented assignment (e.g., `+=`, `-=`)
    AugmentedAssignment {
        /// Target expression
        target: Expression,
        /// Augmented operator
        operator: AugmentedOperator,
        /// Value expression
        value: Expression,
    },
    /// Expression statement
    Expression(Expression),
    /// Return statement
    Return(Option<Expression>),
    /// If statement
    If {
        /// Test expression
        test: Expression,
        /// Body of the if block
        body: Vec<Statement>,
        /// Else block (or empty)
        orelse: Vec<Statement>,
    },
    /// For loop
    For {
        /// Loop target
        target: Expression,
        /// Iterable expression
        iter: Expression,
        /// Loop body
        body: Vec<Statement>,
        /// Else block (or empty)
        orelse: Vec<Statement>,
    },
    /// Async for loop
    AsyncFor {
        /// Loop target
        target: Expression,
        /// Iterable expression
        iter: Expression,
        /// Loop body
        body: Vec<Statement>,
        /// Else block (or empty)
        orelse: Vec<Statement>,
    },
    /// While loop
    While {
        /// Test expression
        test: Expression,
        /// Loop body
        body: Vec<Statement>,
        /// Else block (or empty)
        orelse: Vec<Statement>,
    },
    /// Break statement
    Break,
    /// Continue statement
    Continue,
    /// Pass statement
    Pass,
    /// Import statement
    Import {
        /// List of names being imported
        names: Vec<ImportName>,
    },
    /// From-import statement
    ImportFrom {
        /// Optional module name
        module: Option<String>,
        /// List of names being imported
        names: Vec<ImportName>,
    },
    /// Global statement
    Global {
        /// List of global names
        names: Vec<String>,
    },
    /// Nonlocal statement
    Nonlocal {
        /// List of nonlocal names
        names: Vec<String>,
    },
    /// Try statement
    Try {
        /// Try body
        body: Vec<Statement>,
        /// Exception handlers
        handlers: Vec<ExceptHandler>,
        /// Else block
        orelse: Vec<Statement>,
        /// Finally block
        finalbody: Vec<Statement>,
    },
    /// Raise statement
    Raise {
        /// Optional exception
        exc: Option<Expression>,
        /// Optional cause
        cause: Option<Expression>,
    },
    /// With statement
    With {
        /// With items
        items: Vec<WithItem>,
        /// With body
        body: Vec<Statement>,
    },
    /// Async with statement
    AsyncWith {
        /// With items
        items: Vec<WithItem>,
        /// With body
        body: Vec<Statement>,
    },
    /// Assert statement
    Assert {
        /// Test expression
        test: Expression,
        /// Optional error message
        msg: Option<Expression>,
    },
    /// Match statement
    Match {
        /// Subject expression
        subject: Expression,
        /// Match cases
        cases: Vec<MatchCase>,
    },
    /// Delete statement
    Delete {
        /// Targets to delete
        targets: Vec<Expression>,
    },
}

/// Represents a case in a match statement.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, PartialEq)]
pub struct MatchCase {
    /// Pattern to match
    pub pattern: Pattern,
    /// Optional guard expression
    pub guard: Option<Expression>,
    /// Case body
    pub body: Vec<Statement>,
}

/// Represents a pattern in a match case.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, PartialEq)]
pub enum Pattern {
    /// Value pattern
    Value(Expression),
    /// Wildcard pattern
    Wildcard,
    /// As pattern
    As {
        /// Optional sub-pattern
        pattern: Option<Box<Pattern>>,
        /// Target name
        name: String,
    },
    /// Sequence pattern
    Sequence(Vec<Pattern>),
    /// Mapping pattern
    Mapping {
        /// Keys to match
        keys: Vec<Expression>,
        /// Corresponding patterns
        patterns: Vec<Pattern>,
    },
    /// Class pattern
    Class {
        /// Class expression
        cls: Expression,
        /// Positional patterns
        patterns: Vec<Pattern>,
        /// Keyword names
        keywords: Vec<String>,
        /// Keyword patterns
        keyword_patterns: Vec<Pattern>,
    },
    /// Or pattern
    Or(Vec<Pattern>),
}

/// Represents a Python expression.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, PartialEq)]
pub enum Expression {
    /// Literal value
    Literal(Literal),
    /// Identifier name
    Name(String),
    /// Binary operation
    BinaryOp {
        /// Left operand
        left: Box<Expression>,
        /// Binary operator
        operator: BinaryOperator,
        /// Right operand
        right: Box<Expression>,
    },
    /// Unary operation
    UnaryOp {
        /// Unary operator
        operator: UnaryOperator,
        /// Operand
        operand: Box<Expression>,
    },
    /// Boolean operation (and, or)
    BoolOp {
        /// Boolean operator
        operator: BoolOperator,
        /// List of values
        values: Vec<Expression>,
    },
    /// Comparison operation
    Compare {
        /// Leftmost operand
        left: Box<Expression>,
        /// Comparison operators
        ops: Vec<CompareOperator>,
        /// Subsequent operands
        comparators: Vec<Expression>,
    },
    /// Function call
    Call {
        /// Function being called
        func: Box<Expression>,
        /// Positional arguments
        args: Vec<Expression>,
        /// Keyword arguments
        keywords: Vec<Keyword>,
    },
    /// Attribute access
    Attribute {
        /// Base expression
        value: Box<Expression>,
        /// Attribute name
        attr: String,
    },
    /// Subscript access
    Subscript {
        /// Base expression
        value: Box<Expression>,
        /// Slice or index expression
        slice: Box<Expression>,
    },
    /// List literal
    List {
        /// List elements
        elts: Vec<Expression>,
    },
    /// Tuple literal
    Tuple {
        /// Tuple elements
        elts: Vec<Expression>,
    },
    /// Slice expression
    Slice {
        /// Optional lower bound
        lower: Option<Box<Expression>>,
        /// Optional upper bound
        upper: Option<Box<Expression>>,
        /// Optional step
        step: Option<Box<Expression>>,
    },
    /// Dictionary literal
    Dict {
        /// Optional keys
        keys: Vec<Option<Expression>>,
        /// Values
        values: Vec<Expression>,
    },
    /// Set literal
    Set {
        /// Set elements
        elts: Vec<Expression>,
    },
    /// List comprehension
    ListComp {
        /// Result expression
        elt: Box<Expression>,
        /// Generators
        generators: Vec<Comprehension>,
    },
    /// Dictionary comprehension
    DictComp {
        /// Key expression
        key: Box<Expression>,
        /// Value expression
        value: Box<Expression>,
        /// Generators
        generators: Vec<Comprehension>,
    },
    /// Set comprehension
    SetComp {
        /// Result expression
        elt: Box<Expression>,
        /// Generators
        generators: Vec<Comprehension>,
    },
    /// Generator expression
    GeneratorExp {
        /// Result expression
        elt: Box<Expression>,
        /// Generators
        generators: Vec<Comprehension>,
    },
    /// Lambda expression
    Lambda {
        /// Lambda arguments
        args: Vec<Parameter>,
        /// Lambda body
        body: Box<Expression>,
    },
    /// Conditional expression (ternary operator)
    IfExp {
        /// Test expression
        test: Box<Expression>,
        /// Body expression
        body: Box<Expression>,
        /// Else expression
        orelse: Box<Expression>,
    },
    /// f-string
    JoinedStr {
        /// f-string parts
        values: Vec<Expression>,
    },
    /// Formatted value within an f-string
    FormattedValue {
        /// Value to format
        value: Box<Expression>,
        /// Conversion type
        conversion: usize,
        /// Optional format specification
        format_spec: Option<Box<Expression>>,
    },
    /// Yield expression
    Yield(Option<Box<Expression>>),
    /// Yield from expression
    YieldFrom(Box<Expression>),
    /// Await expression
    Await(Box<Expression>),
    /// Starred expression (*args, **kwargs)
    Starred {
        /// Value being starred
        value: Box<Expression>,
        /// Whether it's a double star (**kwargs)
        is_double: bool,
    },
}

/// Represents a literal value.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, PartialEq)]
pub enum Literal {
    /// Integer literal
    Integer(i64),
    /// Float literal
    Float(f64),
    /// String literal
    String(String),
    /// Bytes literal
    Bytes(Vec<u8>),
    /// Boolean literal
    Boolean(bool),
    /// None literal
    None,
}

/// Represents an augmented assignment operator.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, PartialEq)]
pub enum AugmentedOperator {
    /// `+=`
    Add,
    /// `-=`
    Sub,
    /// `*=`
    Mult,
    /// `/=`
    Div,
    /// `//= `
    FloorDiv,
    /// `%=`
    Mod,
    /// `**=`
    Pow,
    /// `<<=`
    LShift,
    /// `>>=`
    RShift,
    /// `|=`
    BitOr,
    /// `^=`
    BitXor,
    /// `&=`
    BitAnd,
}

/// Represents a binary operator.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, PartialEq)]
pub enum BinaryOperator {
    /// `+`
    Add,
    /// `-`
    Sub,
    /// `*`
    Mult,
    /// `/`
    Div,
    /// `//`
    FloorDiv,
    /// `%`
    Mod,
    /// `**`
    Pow,
    /// `<<`
    LShift,
    /// `>>`
    RShift,
    /// `|`
    BitOr,
    /// `^`
    BitXor,
    /// `&`
    BitAnd,
}

/// Represents a unary operator.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, PartialEq)]
pub enum UnaryOperator {
    /// `~`
    Invert,
    /// `not`
    Not,
    /// `+`
    UAdd,
    /// `-`
    USub,
}

/// Represents a boolean operator.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, PartialEq)]
pub enum BoolOperator {
    /// `and`
    And,
    /// `or`
    Or,
}

/// Represents a comparison operator.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, PartialEq)]
pub enum CompareOperator {
    /// `==`
    Eq,
    /// `!=`
    NotEq,
    /// `<`
    Lt,
    /// `<=`
    LtE,
    /// `>`
    Gt,
    /// `>=`
    GtE,
    /// `is`
    Is,
    /// `is not`
    IsNot,
    /// `in`
    In,
    /// `not in`
    NotIn,
}

/// Represents a function parameter.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, PartialEq)]
pub struct Parameter {
    /// Parameter name
    pub name: String,
    /// Optional type annotation
    pub annotation: Option<Type>,
    /// Optional default value
    pub default: Option<Expression>,
    /// Whether it's a variable positional argument (*args)
    pub is_vararg: bool,
    /// Whether it's a variable keyword argument (**kwargs)
    pub is_kwarg: bool,
}

/// Represents a type annotation.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, PartialEq)]
pub enum Type {
    /// Basic type name
    Name(String),
    /// Generic type
    Generic {
        /// Type name
        name: String,
        /// Type arguments
        args: Vec<Type>,
    },
    /// Union type
    Union(Vec<Type>),
    /// Optional type
    Optional(Box<Type>),
}

/// Represents a keyword argument.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, PartialEq)]
pub struct Keyword {
    /// Optional argument name
    pub arg: Option<String>,
    /// Argument value
    pub value: Expression,
}

/// Represents a comprehension in a list/dict/set/generator.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, PartialEq)]
pub struct Comprehension {
    /// Target expression
    pub target: Expression,
    /// Iterable expression
    pub iter: Expression,
    /// Optional conditions
    pub ifs: Vec<Expression>,
    /// Whether it's an async comprehension
    pub is_async: bool,
}

/// Represents a name in an import statement.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, PartialEq)]
pub struct ImportName {
    /// Name being imported
    pub name: String,
    /// Optional alias (asname)
    pub asname: Option<String>,
}

/// Represents an exception handler in a try statement.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, PartialEq)]
pub struct ExceptHandler {
    /// Optional exception type
    pub type_: Option<Expression>,
    /// Optional name for the exception instance
    pub name: Option<String>,
    /// Handler body
    pub body: Vec<Statement>,
}

/// Represents an item in a with statement.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, PartialEq)]
pub struct WithItem {
    /// Context manager expression
    pub context_expr: Expression,
    /// Optional variables to bind to
    pub optional_vars: Option<Expression>,
}

impl Program {
    /// Creates a new empty program.
    pub fn new() -> Self {
        Self { statements: Vec::new() }
    }

    /// Adds a statement to the program.
    pub fn add_statement(&mut self, statement: Statement) {
        self.statements.push(statement)
    }
}

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

impl Expression {
    /// Creates a name expression.
    pub fn name(name: impl Into<String>) -> Self {
        Self::Name(name.into())
    }

    /// Creates a string literal expression.
    pub fn string(value: impl Into<String>) -> Self {
        Self::Literal(Literal::String(value.into()))
    }

    /// Creates an integer literal expression.
    pub fn integer(value: i64) -> Self {
        Self::Literal(Literal::Integer(value))
    }

    /// Creates a float literal expression.
    pub fn float(value: f64) -> Self {
        Self::Literal(Literal::Float(value))
    }

    /// Creates a boolean literal expression.
    pub fn boolean(value: bool) -> Self {
        Self::Literal(Literal::Boolean(value))
    }

    /// Creates a None literal expression.
    pub fn none() -> Self {
        Self::Literal(Literal::None)
    }
}

impl Statement {
    /// Creates a function definition statement.
    pub fn function_def(name: impl Into<String>, parameters: Vec<Parameter>, return_type: Option<Type>, body: Vec<Statement>) -> Self {
        Self::FunctionDef { decorators: Vec::new(), name: name.into(), parameters, return_type, body }
    }

    /// Creates an assignment statement.
    pub fn assignment(target: Expression, value: Expression) -> Self {
        Self::Assignment { target, value }
    }

    /// Creates an expression statement.
    pub fn expression(expr: Expression) -> Self {
        Self::Expression(expr)
    }

    /// Creates a return statement.
    pub fn return_stmt(value: Option<Expression>) -> Self {
        Self::Return(value)
    }
}