Skip to main content

oak_cpp/ast/
mod.rs

1#![doc = include_str!("readme.md")]
2use core::range::Range;
3#[cfg(feature = "serde")]
4use serde::{Deserialize, Serialize};
5
6/// Type alias for source span.
7type SourceSpan = Range<usize>;
8
9/// C++ language abstract syntax tree root.
10#[derive(Debug, Clone, PartialEq)]
11#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
12pub struct CppRoot {
13    /// Translation unit.
14    pub translation_unit: TranslationUnit,
15}
16
17/// Translation unit (top-level structure of a C++ program).
18#[derive(Debug, Clone, PartialEq)]
19#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
20pub struct TranslationUnit {
21    /// List of external declarations.
22    pub external_declarations: Vec<ExternalDeclaration>,
23    /// Source span.
24    #[cfg_attr(feature = "serde", serde(with = "oak_core::serde_range"))]
25    pub span: Range<usize>,
26}
27
28/// External declaration.
29#[derive(Debug, Clone, PartialEq)]
30#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
31pub enum ExternalDeclaration {
32    /// Function definition.
33    FunctionDefinition(FunctionDefinition),
34    /// Declaration.
35    Declaration(Declaration),
36}
37
38/// Function definition.
39#[derive(Debug, Clone, PartialEq)]
40#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
41pub struct FunctionDefinition {
42    /// Declaration specifiers.
43    pub declaration_specifiers: Vec<DeclarationSpecifier>,
44    /// Declarator.
45    pub declarator: Declarator,
46    /// Compound statement.
47    pub compound_statement: CompoundStatement,
48    /// Source span.
49    #[cfg_attr(feature = "serde", serde(with = "oak_core::serde_range"))]
50    pub span: SourceSpan,
51}
52
53/// Declaration.
54#[derive(Debug, Clone, PartialEq)]
55#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
56pub struct Declaration {
57    /// Declaration specifiers.
58    pub declaration_specifiers: Vec<DeclarationSpecifier>,
59    /// List of initialization declarators.
60    pub init_declarators: Vec<InitDeclarator>,
61    /// Source span.
62    #[cfg_attr(feature = "serde", serde(with = "oak_core::serde_range"))]
63    pub span: SourceSpan,
64}
65
66/// Declaration specifier.
67#[derive(Debug, Clone, PartialEq)]
68#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
69pub enum DeclarationSpecifier {
70    /// Storage class specifier.
71    StorageClassSpecifier(StorageClassSpecifier),
72    /// Type specifier.
73    TypeSpecifier(TypeSpecifier),
74    /// Type qualifier.
75    TypeQualifier(TypeQualifier),
76    /// Function specifier.
77    FunctionSpecifier(FunctionSpecifier),
78}
79
80/// Storage class specifier.
81#[derive(Debug, Clone, PartialEq)]
82#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
83pub enum StorageClassSpecifier {
84    /// typedef
85    Typedef,
86    /// extern
87    Extern,
88    /// static
89    Static,
90    /// auto
91    Auto,
92    /// register
93    Register,
94}
95
96/// Type specifier.
97#[derive(Debug, Clone, PartialEq)]
98#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
99pub enum TypeSpecifier {
100    /// void
101    Void,
102    /// char
103    Char,
104    /// short
105    Short,
106    /// int
107    Int,
108    /// long
109    Long,
110    /// float
111    Float,
112    /// double
113    Double,
114    /// signed
115    Signed,
116    /// unsigned
117    Unsigned,
118    /// bool
119    Bool,
120    /// _Complex
121    Complex,
122    /// _Imaginary
123    Imaginary,
124    /// Struct or union specifier.
125    StructOrUnion(StructOrUnionSpecifier),
126    /// Enum specifier.
127    Enum(EnumSpecifier),
128    /// typedef name.
129    TypedefName(String),
130}
131
132/// Type qualifier
133#[derive(Debug, Clone, PartialEq)]
134#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
135pub enum TypeQualifier {
136    /// const
137    Const,
138    /// restrict
139    Restrict,
140    /// volatile
141    Volatile,
142}
143
144/// Function specifier
145#[derive(Debug, Clone, PartialEq)]
146#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
147pub enum FunctionSpecifier {
148    /// inline
149    Inline,
150    /// _Noreturn
151    Noreturn,
152}
153
154/// Struct or union specifier
155#[derive(Debug, Clone, PartialEq)]
156#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
157pub struct StructOrUnionSpecifier {
158    /// Struct or union.
159    pub struct_or_union: StructOrUnion,
160    /// Identifier.
161    pub identifier: Option<String>,
162    /// List of struct declarations.
163    pub struct_declarations: Option<Vec<StructDeclaration>>,
164    /// Source span.
165    #[cfg_attr(feature = "serde", serde(with = "oak_core::serde_range"))]
166    pub span: SourceSpan,
167}
168
169/// Struct or union
170#[derive(Debug, Clone, PartialEq)]
171#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
172pub enum StructOrUnion {
173    /// struct
174    Struct,
175    /// union
176    Union,
177}
178
179/// Struct declaration
180#[derive(Debug, Clone, PartialEq)]
181#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
182pub struct StructDeclaration {
183    /// List of specifier qualifiers.
184    pub specifier_qualifiers: Vec<SpecifierQualifier>,
185    /// List of struct declarators.
186    pub struct_declarators: Vec<StructDeclarator>,
187    /// Source span.
188    #[cfg_attr(feature = "serde", serde(with = "oak_core::serde_range"))]
189    pub span: SourceSpan,
190}
191
192/// Specifier qualifier
193#[derive(Debug, Clone, PartialEq)]
194#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
195pub enum SpecifierQualifier {
196    /// Type specifier.
197    TypeSpecifier(TypeSpecifier),
198    /// Type qualifier.
199    TypeQualifier(TypeQualifier),
200}
201
202/// Struct declarator
203#[derive(Debug, Clone, PartialEq)]
204#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
205pub struct StructDeclarator {
206    /// Declarator.
207    pub declarator: Option<Declarator>,
208    /// Constant expression.
209    pub constant_expression: Option<Expression>,
210    /// Source span.
211    #[cfg_attr(feature = "serde", serde(with = "oak_core::serde_range"))]
212    pub span: SourceSpan,
213}
214
215/// Enum specifier
216#[derive(Debug, Clone, PartialEq)]
217#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
218pub struct EnumSpecifier {
219    /// Identifier.
220    pub identifier: Option<String>,
221    /// List of enumerators.
222    pub enumerators: Option<Vec<Enumerator>>,
223    /// Source span.
224    #[cfg_attr(feature = "serde", serde(with = "oak_core::serde_range"))]
225    pub span: SourceSpan,
226}
227
228/// Enumerator
229#[derive(Debug, Clone, PartialEq)]
230#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
231pub struct Enumerator {
232    /// Enumerator identifier.
233    pub identifier: String,
234    /// Constant expression.
235    pub constant_expression: Option<Expression>,
236    /// Source span.
237    #[cfg_attr(feature = "serde", serde(with = "oak_core::serde_range"))]
238    pub span: SourceSpan,
239}
240
241/// Init declarator
242#[derive(Debug, Clone, PartialEq)]
243#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
244pub struct InitDeclarator {
245    /// Declarator.
246    pub declarator: Declarator,
247    /// Initializer.
248    pub initializer: Option<Initializer>,
249    /// Source span.
250    #[cfg_attr(feature = "serde", serde(with = "oak_core::serde_range"))]
251    pub span: SourceSpan,
252}
253
254/// Declarator
255#[derive(Debug, Clone, PartialEq)]
256#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
257pub struct Declarator {
258    /// Pointer.
259    pub pointer: Option<Pointer>,
260    /// Direct declarator.
261    pub direct_declarator: DirectDeclarator,
262    /// Source span.
263    #[cfg_attr(feature = "serde", serde(with = "oak_core::serde_range"))]
264    pub span: SourceSpan,
265}
266
267/// Pointer
268#[derive(Debug, Clone, PartialEq)]
269#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
270pub struct Pointer {
271    /// Type qualifiers.
272    pub type_qualifiers: Vec<TypeQualifier>,
273    /// Pointer.
274    pub pointer: Option<Box<Pointer>>,
275    /// Source span.
276    #[cfg_attr(feature = "serde", serde(with = "oak_core::serde_range"))]
277    pub span: SourceSpan,
278}
279
280/// Direct declarator
281#[derive(Debug, Clone, PartialEq)]
282#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
283pub enum DirectDeclarator {
284    /// Identifier.
285    Identifier(String),
286    /// Declarator.
287    Declarator(Box<Declarator>),
288    /// Array.
289    Array {
290        /// Declarator.
291        declarator: Box<DirectDeclarator>,
292        /// Assignment expression.
293        assignment_expression: Option<Expression>,
294    },
295    /// Function.
296    Function {
297        /// Declarator.
298        declarator: Box<DirectDeclarator>,
299        /// Parameter type list.
300        parameter_type_list: Option<ParameterTypeList>,
301        /// Identifier list.
302        identifier_list: Option<Vec<String>>,
303    },
304}
305
306/// Parameter type list
307#[derive(Debug, Clone, PartialEq)]
308#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
309pub struct ParameterTypeList {
310    /// Parameter list.
311    pub parameter_list: Vec<ParameterDeclaration>,
312    /// Whether it is variadic.
313    pub variadic: bool,
314    /// Source span.
315    #[cfg_attr(feature = "serde", serde(with = "oak_core::serde_range"))]
316    pub span: SourceSpan,
317}
318
319/// Parameter declaration
320#[derive(Debug, Clone, PartialEq)]
321#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
322pub struct ParameterDeclaration {
323    /// Declaration specifiers.
324    pub declaration_specifiers: Vec<DeclarationSpecifier>,
325    /// Declarator.
326    pub declarator: Option<Declarator>,
327    /// Abstract declarator.
328    pub abstract_declarator: Option<AbstractDeclarator>,
329    /// Source span.
330    #[cfg_attr(feature = "serde", serde(with = "oak_core::serde_range"))]
331    pub span: SourceSpan,
332}
333
334/// Abstract declarator
335#[derive(Debug, Clone, PartialEq)]
336#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
337pub struct AbstractDeclarator {
338    /// Pointer.
339    pub pointer: Option<Pointer>,
340    /// Direct abstract declarator.
341    pub direct_abstract_declarator: Option<Box<DirectAbstractDeclarator>>,
342    /// Source span.
343    #[cfg_attr(feature = "serde", serde(with = "oak_core::serde_range"))]
344    pub span: Range<usize>,
345}
346
347/// Direct abstract declarator
348#[derive(Debug, Clone, PartialEq)]
349#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
350pub enum DirectAbstractDeclarator {
351    /// Abstract declarator.
352    AbstractDeclarator(Box<AbstractDeclarator>),
353    /// Array.
354    Array {
355        /// Declarator.
356        declarator: Option<Box<DirectAbstractDeclarator>>,
357        /// Assignment expression.
358        assignment_expression: Option<Box<Expression>>,
359    },
360    /// Function.
361    Function {
362        /// Declarator.
363        declarator: Option<Box<DirectAbstractDeclarator>>,
364        /// Parameter type list.
365        parameter_type_list: Option<ParameterTypeList>,
366    },
367}
368
369/// Initializer
370#[derive(Debug, Clone, PartialEq)]
371#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
372pub enum Initializer {
373    /// Assignment expression.
374    AssignmentExpression(Expression),
375    /// Initializer list.
376    InitializerList(Vec<Initializer>),
377}
378
379/// Statement
380#[derive(Debug, Clone, PartialEq)]
381#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
382pub enum Statement {
383    /// Labeled statement
384    Labeled(LabeledStatement),
385    /// Compound statement
386    Compound(CompoundStatement),
387    /// Expression statement
388    Expression(ExpressionStatement),
389    /// Selection statement
390    Selection(SelectionStatement),
391    /// Iteration statement
392    Iteration(IterationStatement),
393    /// Jump statement
394    Jump(JumpStatement),
395}
396
397/// Labeled statement
398#[derive(Debug, Clone, PartialEq)]
399#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
400pub enum LabeledStatement {
401    /// Label.
402    Label {
403        /// Identifier.
404        identifier: String,
405        /// Statement.
406        statement: Box<Statement>,
407    },
408    /// Case.
409    Case {
410        /// Constant expression.
411        constant_expression: Expression,
412        /// Statement.
413        statement: Box<Statement>,
414    },
415    /// Default.
416    Default {
417        /// Statement.
418        statement: Box<Statement>,
419    },
420}
421
422/// Compound statement
423#[derive(Debug, Clone, PartialEq)]
424#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
425pub struct CompoundStatement {
426    /// Block items.
427    pub block_items: Vec<BlockItem>,
428    /// Source span.
429    #[cfg_attr(feature = "serde", serde(with = "oak_core::serde_range"))]
430    pub span: SourceSpan,
431}
432
433/// Block item
434#[derive(Debug, Clone, PartialEq)]
435#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
436pub enum BlockItem {
437    /// Declaration.
438    Declaration(Declaration),
439    /// Statement.
440    Statement(Statement),
441}
442
443/// Expression statement
444#[derive(Debug, Clone, PartialEq)]
445#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
446pub struct ExpressionStatement {
447    /// Expression.
448    pub expression: Option<Expression>,
449    /// Source span.
450    #[cfg_attr(feature = "serde", serde(with = "oak_core::serde_range"))]
451    pub span: SourceSpan,
452}
453
454/// Selection statement
455#[derive(Debug, Clone, PartialEq)]
456#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
457pub enum SelectionStatement {
458    /// If statement.
459    If {
460        /// Condition.
461        condition: Expression,
462        /// Then branch.
463        then_branch: Box<Statement>,
464        /// Else branch.
465        else_branch: Option<Box<Statement>>,
466    },
467    /// Switch statement.
468    Switch {
469        /// Condition.
470        condition: Expression,
471        /// Statement.
472        statement: Box<Statement>,
473    },
474}
475
476/// Iteration statement
477#[derive(Debug, Clone, PartialEq)]
478#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
479pub enum IterationStatement {
480    /// While loop.
481    While {
482        /// Condition.
483        condition: Expression,
484        /// Statement.
485        statement: Box<Statement>,
486    },
487    /// Do-while loop.
488    DoWhile {
489        /// Statement.
490        statement: Box<Statement>,
491        /// Condition.
492        condition: Expression,
493    },
494    /// For loop.
495    For {
496        /// Initializer.
497        initializer: Option<Box<ForInitializer>>,
498        /// Condition.
499        condition: Option<Expression>,
500        /// Increment.
501        increment: Option<Expression>,
502        /// Statement.
503        statement: Box<Statement>,
504    },
505}
506
507/// For initializer
508#[derive(Debug, Clone, PartialEq)]
509#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
510pub enum ForInitializer {
511    /// Expression.
512    Expression(Expression),
513    /// Declaration.
514    Declaration(Declaration),
515}
516
517/// Jump statement
518#[derive(Debug, Clone, PartialEq)]
519#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
520pub enum JumpStatement {
521    /// Goto.
522    Goto(String),
523    /// Continue.
524    Continue,
525    /// Break.
526    Break,
527    /// Return.
528    Return(Option<Expression>),
529}
530
531/// Expression
532#[derive(Debug, Clone, PartialEq)]
533#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
534pub struct Expression {
535    /// Expression kind.
536    pub kind: ExpressionKind,
537    /// Source span.
538    #[cfg_attr(feature = "serde", serde(with = "oak_core::serde_range"))]
539    pub span: SourceSpan,
540}
541
542/// Expression kind
543#[derive(Debug, Clone, PartialEq)]
544#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
545pub enum ExpressionKind {
546    /// Identifier
547    Identifier(String),
548    /// Constant
549    Constant(String),
550    /// String literal
551    StringLiteral(String),
552    /// Parenthesized expression
553    Parenthesized(Box<Expression>),
554    /// Array access
555    ArrayAccess {
556        /// Array.
557        array: Box<Expression>,
558        /// Index.
559        index: Box<Expression>,
560    },
561    /// Function call
562    FunctionCall {
563        /// Function.
564        function: Box<Expression>,
565        /// Arguments.
566        arguments: Vec<Expression>,
567    },
568    /// Member access
569    MemberAccess {
570        /// Object.
571        object: Box<Expression>,
572        /// Member.
573        member: String,
574        /// Whether it's a pointer.
575        is_pointer: bool,
576    },
577    /// Unary operation
578    Unary {
579        /// Operator.
580        operator: UnaryOperator,
581        /// Operand.
582        operand: Box<Expression>,
583    },
584    /// Binary operation
585    Binary {
586        /// Left.
587        left: Box<Expression>,
588        /// Operator.
589        operator: BinaryOperator,
590        /// Right.
591        right: Box<Expression>,
592    },
593    /// Conditional expression
594    Conditional {
595        /// Condition.
596        condition: Box<Expression>,
597        /// Then branch.
598        then_branch: Box<Expression>,
599        /// Else branch.
600        else_branch: Box<Expression>,
601    },
602    /// Assignment
603    Assignment {
604        /// Left.
605        left: Box<Expression>,
606        /// Operator.
607        operator: AssignmentOperator,
608        /// Right.
609        right: Box<Expression>,
610    },
611    /// Comma expression
612    Comma(Vec<Expression>),
613}
614
615/// Unary operator
616#[derive(Debug, Clone, Copy, PartialEq)]
617#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
618pub enum UnaryOperator {
619    /// Post-increment (x++)
620    PostIncrement,
621    /// Post-decrement (x--)
622    PostDecrement,
623    /// Pre-increment (++x)
624    PreIncrement,
625    /// Pre-decrement (--x)
626    PreDecrement,
627    /// Address of (&x)
628    AddressOf,
629    /// Indirection (*x)
630    Deref,
631    /// Unary plus (+x)
632    Plus,
633    /// Unary minus (-x)
634    Minus,
635    /// Bitwise NOT (~x)
636    BitNot,
637    /// Logical NOT (!x)
638    LogicalNot,
639    /// Size of (sizeof)
640    Sizeof,
641    /// Align of (alignof)
642    AlignOf,
643}
644
645/// Binary operator
646#[derive(Debug, Clone, Copy, PartialEq)]
647#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
648pub enum BinaryOperator {
649    /// Addition (+)
650    Add,
651    /// Subtraction (-)
652    Subtract,
653    /// Multiplication (*)
654    Multiply,
655    /// Division (/)
656    Divide,
657    /// Modulo (%)
658    Remainder,
659    /// Bitwise shift left (<<)
660    ShiftLeft,
661    /// Bitwise shift right (>>)
662    ShiftRight,
663    /// Less than (<)
664    Less,
665    /// Greater than (>)
666    Greater,
667    /// Less than or equal (<=)
668    LessEqual,
669    /// Greater than or equal (>=)
670    GreaterEqual,
671    /// Equal (==)
672    Equal,
673    /// Not equal (!=)
674    NotEqual,
675    /// Bitwise AND (&)
676    BitAnd,
677    /// Bitwise XOR (^)
678    BitXor,
679    /// Bitwise OR (|)
680    BitOr,
681    /// Logical AND (&&)
682    LogicalAnd,
683    /// Logical OR (||)
684    LogicalOr,
685}
686
687/// Assignment operator
688#[derive(Debug, Clone, Copy, PartialEq)]
689#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
690pub enum AssignmentOperator {
691    /// Assignment (=)
692    Assign,
693    /// Addition assignment (+=)
694    AddAssign,
695    /// Subtraction assignment (-=)
696    SubAssign,
697    /// Multiplication assignment (*=)
698    MulAssign,
699    /// Division assignment (/=)
700    DivAssign,
701    /// Modulo assignment (%=)
702    RemAssign,
703    /// Bitwise shift left assignment (<<=)
704    ShlAssign,
705    /// Bitwise shift right assignment (>>=)
706    ShrAssign,
707    /// Bitwise AND assignment (&=)
708    AndAssign,
709    /// Bitwise XOR assignment (^=)
710    XorAssign,
711    /// Bitwise OR assignment (|=)
712    OrAssign,
713}
714
715/// Type name
716#[derive(Debug, Clone, PartialEq)]
717#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
718pub struct TypeName {
719    /// List of specifier qualifiers.
720    pub specifier_qualifiers: Vec<SpecifierQualifier>,
721    /// Abstract declarator.
722    pub abstract_declarator: Option<Box<AbstractDeclarator>>,
723    /// Source span.
724    #[cfg_attr(feature = "serde", serde(with = "oak_core::serde_range"))]
725    pub span: Range<usize>,
726}
727
728impl TypeName {
729    /// Create a new type name
730    pub fn new(specifier_qualifiers: Vec<SpecifierQualifier>, abstract_declarator: Option<Box<AbstractDeclarator>>, span: Range<usize>) -> Self {
731        Self { specifier_qualifiers, abstract_declarator, span }
732    }
733}
734
735impl CppRoot {
736    /// Create a new AST
737    pub fn new(translation_unit: TranslationUnit) -> Self {
738        Self { translation_unit }
739    }
740}
741
742impl TranslationUnit {
743    /// Create a new translation unit
744    pub fn new(external_declarations: Vec<ExternalDeclaration>, span: Range<usize>) -> Self {
745        Self { external_declarations, span }
746    }
747}