Skip to main content

oak_cpp/ast/
mod.rs

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