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    Restrict,
138    Volatile,
139}
140
141/// Function specifier
142#[derive(Debug, Clone, PartialEq)]
143#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
144pub enum FunctionSpecifier {
145    Inline,
146    Noreturn,
147}
148
149/// Struct or union specifier
150#[derive(Debug, Clone, PartialEq)]
151#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
152pub struct StructOrUnionSpecifier {
153    pub struct_or_union: StructOrUnion,
154    pub identifier: Option<String>,
155    pub struct_declarations: Option<Vec<StructDeclaration>>,
156    #[cfg_attr(feature = "serde", serde(with = "oak_core::serde_range"))]
157    pub span: SourceSpan,
158}
159
160/// Struct or union
161#[derive(Debug, Clone, PartialEq)]
162#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
163pub enum StructOrUnion {
164    Struct,
165    Union,
166}
167
168/// Struct declaration
169#[derive(Debug, Clone, PartialEq)]
170#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
171pub struct StructDeclaration {
172    pub specifier_qualifiers: Vec<SpecifierQualifier>,
173    pub struct_declarators: Vec<StructDeclarator>,
174    #[cfg_attr(feature = "serde", serde(with = "oak_core::serde_range"))]
175    pub span: SourceSpan,
176}
177
178/// Specifier qualifier
179#[derive(Debug, Clone, PartialEq)]
180#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
181pub enum SpecifierQualifier {
182    TypeSpecifier(TypeSpecifier),
183    TypeQualifier(TypeQualifier),
184}
185
186/// Struct declarator
187#[derive(Debug, Clone, PartialEq)]
188#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
189pub struct StructDeclarator {
190    pub declarator: Option<Declarator>,
191    pub constant_expression: Option<Expression>,
192    #[cfg_attr(feature = "serde", serde(with = "oak_core::serde_range"))]
193    pub span: SourceSpan,
194}
195
196/// Enum specifier
197#[derive(Debug, Clone, PartialEq)]
198#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
199pub struct EnumSpecifier {
200    pub identifier: Option<String>,
201    pub enumerators: Option<Vec<Enumerator>>,
202    #[cfg_attr(feature = "serde", serde(with = "oak_core::serde_range"))]
203    pub span: SourceSpan,
204}
205
206/// Enumerator
207#[derive(Debug, Clone, PartialEq)]
208#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
209pub struct Enumerator {
210    /// Enumerator identifier.
211    pub identifier: String,
212    /// Constant expression.
213    pub constant_expression: Option<Expression>,
214    /// Source span.
215    #[cfg_attr(feature = "serde", serde(with = "oak_core::serde_range"))]
216    pub span: SourceSpan,
217}
218
219/// Init declarator
220#[derive(Debug, Clone, PartialEq)]
221#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
222pub struct InitDeclarator {
223    /// Declarator.
224    pub declarator: Declarator,
225    /// Initializer.
226    pub initializer: Option<Initializer>,
227    /// Source span.
228    #[cfg_attr(feature = "serde", serde(with = "oak_core::serde_range"))]
229    pub span: SourceSpan,
230}
231
232/// Declarator
233#[derive(Debug, Clone, PartialEq)]
234#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
235pub struct Declarator {
236    /// Pointer.
237    pub pointer: Option<Pointer>,
238    /// Direct declarator.
239    pub direct_declarator: DirectDeclarator,
240    /// Source span.
241    #[cfg_attr(feature = "serde", serde(with = "oak_core::serde_range"))]
242    pub span: SourceSpan,
243}
244
245/// Pointer
246#[derive(Debug, Clone, PartialEq)]
247#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
248pub struct Pointer {
249    /// Type qualifiers.
250    pub type_qualifiers: Vec<TypeQualifier>,
251    /// Pointer.
252    pub pointer: Option<Box<Pointer>>,
253    /// Source span.
254    #[cfg_attr(feature = "serde", serde(with = "oak_core::serde_range"))]
255    pub span: SourceSpan,
256}
257
258/// Direct declarator
259#[derive(Debug, Clone, PartialEq)]
260#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
261pub enum DirectDeclarator {
262    /// Identifier.
263    Identifier(String),
264    /// Declarator.
265    Declarator(Box<Declarator>),
266    /// Array.
267    Array {
268        /// Declarator.
269        declarator: Box<DirectDeclarator>,
270        /// Assignment expression.
271        assignment_expression: Option<Expression>,
272    },
273    /// Function.
274    Function {
275        /// Declarator.
276        declarator: Box<DirectDeclarator>,
277        /// Parameter type list.
278        parameter_type_list: Option<ParameterTypeList>,
279        /// Identifier list.
280        identifier_list: Option<Vec<String>>,
281    },
282}
283
284/// Parameter type list
285#[derive(Debug, Clone, PartialEq)]
286#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
287pub struct ParameterTypeList {
288    /// Parameter list.
289    pub parameter_list: Vec<ParameterDeclaration>,
290    /// Whether it is variadic.
291    pub variadic: bool,
292    /// Source span.
293    #[cfg_attr(feature = "serde", serde(with = "oak_core::serde_range"))]
294    pub span: SourceSpan,
295}
296
297/// Parameter declaration
298#[derive(Debug, Clone, PartialEq)]
299#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
300pub struct ParameterDeclaration {
301    /// Declaration specifiers.
302    pub declaration_specifiers: Vec<DeclarationSpecifier>,
303    /// Declarator.
304    pub declarator: Option<Declarator>,
305    /// Abstract declarator.
306    pub abstract_declarator: Option<AbstractDeclarator>,
307    /// Source span.
308    #[cfg_attr(feature = "serde", serde(with = "oak_core::serde_range"))]
309    pub span: SourceSpan,
310}
311
312/// Abstract declarator
313#[derive(Debug, Clone, PartialEq)]
314#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
315pub struct AbstractDeclarator {
316    /// Pointer.
317    pub pointer: Option<Pointer>,
318    /// Direct abstract declarator.
319    pub direct_abstract_declarator: Option<Box<DirectAbstractDeclarator>>,
320    /// Source span.
321    #[cfg_attr(feature = "serde", serde(with = "oak_core::serde_range"))]
322    pub span: Range<usize>,
323}
324
325/// Direct abstract declarator
326#[derive(Debug, Clone, PartialEq)]
327#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
328pub enum DirectAbstractDeclarator {
329    /// Abstract declarator.
330    AbstractDeclarator(Box<AbstractDeclarator>),
331    /// Array.
332    Array {
333        /// Declarator.
334        declarator: Option<Box<DirectAbstractDeclarator>>,
335        /// Assignment expression.
336        assignment_expression: Option<Box<Expression>>,
337    },
338    /// Function.
339    Function {
340        /// Declarator.
341        declarator: Option<Box<DirectAbstractDeclarator>>,
342        /// Parameter type list.
343        parameter_type_list: Option<ParameterTypeList>,
344    },
345}
346
347/// Initializer
348#[derive(Debug, Clone, PartialEq)]
349#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
350pub enum Initializer {
351    /// Assignment expression.
352    AssignmentExpression(Expression),
353    /// Initializer list.
354    InitializerList(Vec<Initializer>),
355}
356
357/// Statement
358#[derive(Debug, Clone, PartialEq)]
359#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
360pub enum Statement {
361    /// Labeled statement
362    Labeled(LabeledStatement),
363    /// Compound statement
364    Compound(CompoundStatement),
365    /// Expression statement
366    Expression(ExpressionStatement),
367    /// Selection statement
368    Selection(SelectionStatement),
369    /// Iteration statement
370    Iteration(IterationStatement),
371    /// Jump statement
372    Jump(JumpStatement),
373}
374
375/// Labeled statement
376#[derive(Debug, Clone, PartialEq)]
377#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
378pub enum LabeledStatement {
379    /// Label.
380    Label {
381        /// Identifier.
382        identifier: String,
383        /// Statement.
384        statement: Box<Statement>,
385    },
386    /// Case.
387    Case {
388        /// Constant expression.
389        constant_expression: Expression,
390        /// Statement.
391        statement: Box<Statement>,
392    },
393    /// Default.
394    Default {
395        /// Statement.
396        statement: Box<Statement>,
397    },
398}
399
400/// Compound statement
401#[derive(Debug, Clone, PartialEq)]
402#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
403pub struct CompoundStatement {
404    /// Block items.
405    pub block_items: Vec<BlockItem>,
406    /// Source span.
407    #[cfg_attr(feature = "serde", serde(with = "oak_core::serde_range"))]
408    pub span: SourceSpan,
409}
410
411/// Block item
412#[derive(Debug, Clone, PartialEq)]
413#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
414pub enum BlockItem {
415    /// Declaration.
416    Declaration(Declaration),
417    /// Statement.
418    Statement(Statement),
419}
420
421/// Expression statement
422#[derive(Debug, Clone, PartialEq)]
423#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
424pub struct ExpressionStatement {
425    /// Expression.
426    pub expression: Option<Expression>,
427    /// Source span.
428    #[cfg_attr(feature = "serde", serde(with = "oak_core::serde_range"))]
429    pub span: SourceSpan,
430}
431
432/// Selection statement
433#[derive(Debug, Clone, PartialEq)]
434#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
435pub enum SelectionStatement {
436    /// If statement.
437    If {
438        /// Condition.
439        condition: Expression,
440        /// Then branch.
441        then_branch: Box<Statement>,
442        /// Else branch.
443        else_branch: Option<Box<Statement>>,
444    },
445    /// Switch statement.
446    Switch {
447        /// Condition.
448        condition: Expression,
449        /// Statement.
450        statement: Box<Statement>,
451    },
452}
453
454/// Iteration statement
455#[derive(Debug, Clone, PartialEq)]
456#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
457pub enum IterationStatement {
458    /// While loop.
459    While {
460        /// Condition.
461        condition: Expression,
462        /// Statement.
463        statement: Box<Statement>,
464    },
465    /// Do-while loop.
466    DoWhile {
467        /// Statement.
468        statement: Box<Statement>,
469        /// Condition.
470        condition: Expression,
471    },
472    /// For loop.
473    For {
474        /// Initializer.
475        initializer: Option<Box<ForInitializer>>,
476        /// Condition.
477        condition: Option<Expression>,
478        /// Increment.
479        increment: Option<Expression>,
480        /// Statement.
481        statement: Box<Statement>,
482    },
483}
484
485/// For initializer
486#[derive(Debug, Clone, PartialEq)]
487#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
488pub enum ForInitializer {
489    /// Expression.
490    Expression(Expression),
491    /// Declaration.
492    Declaration(Declaration),
493}
494
495/// Jump statement
496#[derive(Debug, Clone, PartialEq)]
497#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
498pub enum JumpStatement {
499    /// Goto.
500    Goto(String),
501    /// Continue.
502    Continue,
503    /// Break.
504    Break,
505    /// Return.
506    Return(Option<Expression>),
507}
508
509/// Expression
510#[derive(Debug, Clone, PartialEq)]
511#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
512pub struct Expression {
513    /// Expression kind.
514    pub kind: ExpressionKind,
515    /// Source span.
516    #[cfg_attr(feature = "serde", serde(with = "oak_core::serde_range"))]
517    pub span: SourceSpan,
518}
519
520/// Expression kind
521#[derive(Debug, Clone, PartialEq)]
522#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
523pub enum ExpressionKind {
524    /// Identifier
525    Identifier(String),
526    /// Constant
527    Constant(String),
528    /// String literal
529    StringLiteral(String),
530    /// Parenthesized expression
531    Parenthesized(Box<Expression>),
532    /// Array access
533    ArrayAccess {
534        /// Array.
535        array: Box<Expression>,
536        /// Index.
537        index: Box<Expression>,
538    },
539    /// Function call
540    FunctionCall {
541        /// Function.
542        function: Box<Expression>,
543        /// Arguments.
544        arguments: Vec<Expression>,
545    },
546    /// Member access
547    MemberAccess {
548        /// Object.
549        object: Box<Expression>,
550        /// Member.
551        member: String,
552        /// Whether it's a pointer.
553        is_pointer: bool,
554    },
555    /// Unary operation
556    Unary {
557        /// Operator.
558        operator: UnaryOperator,
559        /// Operand.
560        operand: Box<Expression>,
561    },
562    /// Binary operation
563    Binary {
564        /// Left.
565        left: Box<Expression>,
566        /// Operator.
567        operator: BinaryOperator,
568        /// Right.
569        right: Box<Expression>,
570    },
571    /// Conditional expression
572    Conditional {
573        /// Condition.
574        condition: Box<Expression>,
575        /// Then branch.
576        then_branch: Box<Expression>,
577        /// Else branch.
578        else_branch: Box<Expression>,
579    },
580    /// Assignment
581    Assignment {
582        /// Left.
583        left: Box<Expression>,
584        /// Operator.
585        operator: AssignmentOperator,
586        /// Right.
587        right: Box<Expression>,
588    },
589    /// Comma expression
590    Comma(Vec<Expression>),
591}
592
593/// Unary operator
594#[derive(Debug, Clone, Copy, PartialEq)]
595#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
596pub enum UnaryOperator {
597    /// Post-increment (x++)
598    PostIncrement,
599    /// Post-decrement (x--)
600    PostDecrement,
601    /// Pre-increment (++x)
602    PreIncrement,
603    /// Pre-decrement (--x)
604    PreDecrement,
605    /// Address of (&x)
606    AddressOf,
607    /// Indirection (*x)
608    Deref,
609    /// Unary plus (+x)
610    Plus,
611    /// Unary minus (-x)
612    Minus,
613    /// Bitwise NOT (~x)
614    BitNot,
615    /// Logical NOT (!x)
616    LogicalNot,
617    /// Size of (sizeof)
618    Sizeof,
619    /// Align of (alignof)
620    AlignOf,
621}
622
623/// Binary operator
624#[derive(Debug, Clone, Copy, PartialEq)]
625#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
626pub enum BinaryOperator {
627    /// Addition (+)
628    Add,
629    /// Subtraction (-)
630    Subtract,
631    /// Multiplication (*)
632    Multiply,
633    /// Division (/)
634    Divide,
635    /// Modulo (%)
636    Remainder,
637    /// Bitwise shift left (<<)
638    ShiftLeft,
639    /// Bitwise shift right (>>)
640    ShiftRight,
641    /// Less than (<)
642    Less,
643    /// Greater than (>)
644    Greater,
645    /// Less than or equal (<=)
646    LessEqual,
647    /// Greater than or equal (>=)
648    GreaterEqual,
649    /// Equal (==)
650    Equal,
651    /// Not equal (!=)
652    NotEqual,
653    /// Bitwise AND (&)
654    BitAnd,
655    /// Bitwise XOR (^)
656    BitXor,
657    /// Bitwise OR (|)
658    BitOr,
659    /// Logical AND (&&)
660    LogicalAnd,
661    /// Logical OR (||)
662    LogicalOr,
663}
664
665/// Assignment operator
666#[derive(Debug, Clone, Copy, PartialEq)]
667#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
668pub enum AssignmentOperator {
669    /// Assignment (=)
670    Assign,
671    /// Addition assignment (+=)
672    AddAssign,
673    /// Subtraction assignment (-=)
674    SubAssign,
675    /// Multiplication assignment (*=)
676    MulAssign,
677    /// Division assignment (/=)
678    DivAssign,
679    /// Modulo assignment (%=)
680    RemAssign,
681    /// Bitwise shift left assignment (<<=)
682    ShlAssign,
683    /// Bitwise shift right assignment (>>=)
684    ShrAssign,
685    /// Bitwise AND assignment (&=)
686    AndAssign,
687    /// Bitwise XOR assignment (^=)
688    XorAssign,
689    /// Bitwise OR assignment (|=)
690    OrAssign,
691}
692
693/// Type name
694#[derive(Debug, Clone, PartialEq)]
695#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
696pub struct TypeName {
697    pub specifier_qualifiers: Vec<SpecifierQualifier>,
698    pub abstract_declarator: Option<Box<AbstractDeclarator>>,
699    #[cfg_attr(feature = "serde", serde(with = "oak_core::serde_range"))]
700    pub span: Range<usize>,
701}
702
703impl TypeName {
704    /// Create a new type name
705    pub fn new(specifier_qualifiers: Vec<SpecifierQualifier>, abstract_declarator: Option<Box<AbstractDeclarator>>, span: Range<usize>) -> Self {
706        Self { specifier_qualifiers, abstract_declarator, span }
707    }
708}
709
710impl CppRoot {
711    /// Create a new AST
712    pub fn new(translation_unit: TranslationUnit) -> Self {
713        Self { translation_unit }
714    }
715}
716
717impl TranslationUnit {
718    /// Create a new translation unit
719    pub fn new(external_declarations: Vec<ExternalDeclaration>, span: Range<usize>) -> Self {
720        Self { external_declarations, span }
721    }
722}