decy_parser/ast_types.rs
1//! AST type definitions for parsed C code.
2//!
3//! This module contains all the data types used to represent a parsed C program:
4//! statements, expressions, types, operators, functions, structs, enums,
5//! typedefs, variables, and macros.
6
7/// Represents a single case in a switch statement.
8#[derive(Debug, Clone, PartialEq)]
9pub struct SwitchCase {
10 /// Case value expression (None for default case)
11 pub value: Option<Expression>,
12 /// Statements to execute for this case
13 pub body: Vec<Statement>,
14}
15
16/// Represents a C statement.
17#[derive(Debug, Clone, PartialEq)]
18pub enum Statement {
19 /// Variable declaration: `int* ptr = malloc(4);`
20 VariableDeclaration {
21 /// Variable name
22 name: String,
23 /// Variable type
24 var_type: Type,
25 /// Optional initializer expression
26 initializer: Option<Expression>,
27 },
28 /// Return statement: `return expr;`
29 Return(Option<Expression>),
30 /// Assignment statement: `x = 42;`
31 Assignment {
32 /// Target variable name
33 target: String,
34 /// Value expression to assign
35 value: Expression,
36 },
37 /// If statement: `if (cond) { ... } else { ... }`
38 If {
39 /// Condition expression
40 condition: Expression,
41 /// Then block
42 then_block: Vec<Statement>,
43 /// Optional else block
44 else_block: Option<Vec<Statement>>,
45 },
46 /// For loop: `for (init; cond; inc) { ... }`
47 For {
48 /// Init statements (can be multiple with comma: int i = 0, j = 10)
49 init: Vec<Statement>,
50 /// Optional condition expression
51 condition: Option<Expression>,
52 /// Optional increment statements (can be multiple with comma: i++, j--)
53 increment: Vec<Statement>,
54 /// Loop body
55 body: Vec<Statement>,
56 },
57 /// While loop: `while (cond) { ... }`
58 While {
59 /// Condition expression
60 condition: Expression,
61 /// Loop body
62 body: Vec<Statement>,
63 },
64 /// Pointer dereference assignment: `*ptr = value;`
65 DerefAssignment {
66 /// Target expression to dereference
67 target: Expression,
68 /// Value expression to assign
69 value: Expression,
70 },
71 /// Array index assignment: `arr[i] = value;`
72 ArrayIndexAssignment {
73 /// Array expression
74 array: Box<Expression>,
75 /// Index expression
76 index: Box<Expression>,
77 /// Value expression to assign
78 value: Expression,
79 },
80 /// Field assignment: `ptr->field = value;` or `obj.field = value;`
81 FieldAssignment {
82 /// Object/pointer expression
83 object: Expression,
84 /// Field name
85 field: String,
86 /// Value expression to assign
87 value: Expression,
88 },
89 /// Break statement: `break;`
90 Break,
91 /// Continue statement: `continue;`
92 Continue,
93 /// Switch statement: `switch (expr) { case 1: ...; default: ...; }`
94 Switch {
95 /// Condition expression to switch on
96 condition: Expression,
97 /// List of case statements
98 cases: Vec<SwitchCase>,
99 /// Optional default case body
100 default_case: Option<Vec<Statement>>,
101 },
102 /// Post-increment statement: `ptr++;`
103 PostIncrement {
104 /// Target variable name
105 target: String,
106 },
107 /// Pre-increment statement: `++ptr;`
108 PreIncrement {
109 /// Target variable name
110 target: String,
111 },
112 /// Post-decrement statement: `ptr--;`
113 PostDecrement {
114 /// Target variable name
115 target: String,
116 },
117 /// Pre-decrement statement: `--ptr;`
118 PreDecrement {
119 /// Target variable name
120 target: String,
121 },
122 /// Compound assignment: `ptr += offset;`, `x *= 2;`, etc.
123 CompoundAssignment {
124 /// Target variable name
125 target: String,
126 /// Binary operator to apply
127 op: BinaryOperator,
128 /// Value expression
129 value: Expression,
130 },
131 /// DECY-185: Compound assignment to expression target: `*ptr *= 2;`, `sb->capacity *= 2;`
132 /// Used when target is not a simple variable (Dereference, PointerFieldAccess, etc.)
133 DerefCompoundAssignment {
134 /// Target expression (e.g., the dereferenced pointer or field access)
135 target: Expression,
136 /// Binary operator to apply
137 op: BinaryOperator,
138 /// Value expression
139 value: Expression,
140 },
141 /// Function call statement: `strlen(s);`, `strcpy(dst, src);`
142 FunctionCall {
143 /// Function name
144 function: String,
145 /// Arguments
146 arguments: Vec<Expression>,
147 },
148}
149
150impl Statement {
151 /// Check if this statement is a string function call.
152 pub fn is_string_function_call(&self) -> bool {
153 match self {
154 Statement::FunctionCall { function, .. } => {
155 matches!(function.as_str(), "strlen" | "strcmp" | "strcpy" | "strdup")
156 }
157 _ => false,
158 }
159 }
160
161 /// Check if this statement is a function call.
162 pub fn is_function_call(&self) -> bool {
163 matches!(self, Statement::FunctionCall { .. })
164 }
165
166 /// Convert this statement to a function call expression if it is one.
167 ///
168 /// # Implementation Status
169 ///
170 /// Stub implementation - always returns `None`.
171 /// The `Statement::FunctionCall` variant doesn't store the call as an `Expression`,
172 /// so conversion would require reconstructing an `Expression::FunctionCall` from
173 /// the statement's fields.
174 pub fn as_function_call(&self) -> Option<&Expression> {
175 None
176 }
177}
178
179/// Unary operators for C expressions.
180#[derive(Debug, Clone, Copy, PartialEq, Eq)]
181pub enum UnaryOperator {
182 /// Unary minus (-x)
183 Minus,
184 /// Logical NOT (!x)
185 LogicalNot,
186 /// Bitwise NOT (~x)
187 BitwiseNot,
188 /// Address-of (&x)
189 AddressOf,
190}
191
192/// Binary operators for C expressions.
193#[derive(Debug, Clone, Copy, PartialEq, Eq)]
194pub enum BinaryOperator {
195 /// Addition (+)
196 Add,
197 /// Subtraction (-)
198 Subtract,
199 /// Multiplication (*)
200 Multiply,
201 /// Division (/)
202 Divide,
203 /// Modulo (%)
204 Modulo,
205 /// Equality (==)
206 Equal,
207 /// Inequality (!=)
208 NotEqual,
209 /// Less than (<)
210 LessThan,
211 /// Greater than (>)
212 GreaterThan,
213 /// Less than or equal (<=)
214 LessEqual,
215 /// Greater than or equal (>=)
216 GreaterEqual,
217 /// Logical AND (&&)
218 LogicalAnd,
219 /// Logical OR (||)
220 LogicalOr,
221 /// Left shift (<<)
222 LeftShift,
223 /// Right shift (>>)
224 RightShift,
225 /// Bitwise AND (&)
226 BitwiseAnd,
227 /// Bitwise OR (|)
228 BitwiseOr,
229 /// Bitwise XOR (^)
230 BitwiseXor,
231 /// Assignment (=) - used for embedded assignments like (c=getchar())
232 Assign,
233 /// Comma operator (,) - DECY-224: for multi-expression statements
234 Comma,
235}
236
237/// Represents a C expression.
238#[derive(Debug, Clone, PartialEq)]
239pub enum Expression {
240 /// Integer literal: `42`
241 IntLiteral(i32),
242 /// Float literal: `3.14` (stored as string to preserve precision)
243 FloatLiteral(String),
244 /// String literal: `"hello"`
245 StringLiteral(String),
246 /// Character literal: `'a'`, `'\0'`, `'\n'`
247 CharLiteral(i8),
248 /// Variable reference: `x`
249 Variable(String),
250 /// Binary operation: `a + b`
251 BinaryOp {
252 /// Operator
253 op: BinaryOperator,
254 /// Left operand
255 left: Box<Expression>,
256 /// Right operand
257 right: Box<Expression>,
258 },
259 /// Function call: `malloc(4)`
260 FunctionCall {
261 /// Function name
262 function: String,
263 /// Arguments
264 arguments: Vec<Expression>,
265 },
266 /// Pointer dereference: `*ptr`
267 Dereference(Box<Expression>),
268 /// Unary operation: `-x`, `!x`
269 UnaryOp {
270 /// Operator
271 op: UnaryOperator,
272 /// Operand
273 operand: Box<Expression>,
274 },
275 /// Array indexing: `arr[i]`
276 ArrayIndex {
277 /// Array expression
278 array: Box<Expression>,
279 /// Index expression
280 index: Box<Expression>,
281 },
282 /// Struct field access: `obj.field`
283 FieldAccess {
284 /// Object expression
285 object: Box<Expression>,
286 /// Field name
287 field: String,
288 },
289 /// Pointer field access: `ptr->field`
290 PointerFieldAccess {
291 /// Pointer expression
292 pointer: Box<Expression>,
293 /// Field name
294 field: String,
295 },
296 /// Post-increment expression: `ptr++`
297 PostIncrement {
298 /// Operand expression
299 operand: Box<Expression>,
300 },
301 /// Pre-increment expression: `++ptr`
302 PreIncrement {
303 /// Operand expression
304 operand: Box<Expression>,
305 },
306 /// Post-decrement expression: `ptr--`
307 PostDecrement {
308 /// Operand expression
309 operand: Box<Expression>,
310 },
311 /// Pre-decrement expression: `--ptr`
312 PreDecrement {
313 /// Operand expression
314 operand: Box<Expression>,
315 },
316 /// Sizeof expression: `sizeof(int)` or `sizeof(struct Data)`
317 Sizeof {
318 /// Type name as a string (e.g., "int", "struct Data")
319 type_name: String,
320 },
321 /// Cast expression: `(int)x` or `(void*)ptr`
322 ///
323 /// C-style cast that converts an expression to a target type.
324 /// Maps to Rust `as` operator for safe casts, or `transmute` for unsafe casts.
325 ///
326 /// # Examples
327 ///
328 /// ```c
329 /// int x = (int)3.14; // float to int
330 /// void* ptr = (void*)buffer; // pointer cast
331 /// long l = (long)small_int; // widening cast
332 /// ```
333 Cast {
334 /// Target type to cast to
335 target_type: Type,
336 /// Expression being cast
337 expr: Box<Expression>,
338 },
339 /// Compound literal: `(struct Point){10, 20}` or `(int[]){1, 2, 3}`
340 ///
341 /// C99 compound literals create anonymous objects of a specified type.
342 /// Useful for passing struct values to functions or creating temporary objects.
343 ///
344 /// # Examples
345 ///
346 /// ```c
347 /// struct Point p = (struct Point){10, 20}; // struct compound literal
348 /// int* arr = (int[]){1, 2, 3, 4, 5}; // array compound literal
349 /// draw((struct Rect){.x=0, .y=0, .w=100, .h=50}); // with designated initializers
350 /// ```
351 CompoundLiteral {
352 /// Type of the compound literal (struct Point, int[], etc.)
353 literal_type: Type,
354 /// Initializer expressions (values for struct fields or array elements)
355 initializers: Vec<Expression>,
356 },
357 /// Ternary/Conditional expression: `cond ? then_val : else_val`
358 ///
359 /// The C ternary operator evaluates the condition and returns either
360 /// the then_val or else_val based on whether condition is truthy.
361 ///
362 /// # DECY-192
363 ///
364 /// Added to support K&R Chapter 2.11 Conditional Expressions.
365 ///
366 /// # Examples
367 ///
368 /// ```c
369 /// int max = (a > b) ? a : b;
370 /// char* msg = (x == 0) ? "zero" : "nonzero";
371 /// ```
372 Ternary {
373 /// Condition expression (evaluated as boolean)
374 condition: Box<Expression>,
375 /// Value if condition is true
376 then_expr: Box<Expression>,
377 /// Value if condition is false
378 else_expr: Box<Expression>,
379 },
380 /// C++ new expression: `new T(args)` (DECY-207)
381 CxxNew {
382 /// Type name being allocated
383 type_name: String,
384 /// Constructor arguments
385 arguments: Vec<Expression>,
386 },
387 /// C++ delete expression: `delete ptr` (DECY-207)
388 CxxDelete {
389 /// Expression being deleted
390 operand: Box<Expression>,
391 },
392 /// C++ nullptr literal (DECY-226)
393 NullLiteral,
394 /// C++ bool literal true/false (DECY-226)
395 BoolLiteral(bool),
396}
397
398impl Expression {
399 /// Check if this expression is a string function call (strlen, strcmp, strcpy, strdup).
400 pub fn is_string_function_call(&self) -> bool {
401 match self {
402 Expression::FunctionCall { function, .. } => {
403 matches!(function.as_str(), "strlen" | "strcmp" | "strcpy" | "strdup")
404 }
405 _ => false,
406 }
407 }
408
409 /// Get the string function name if this is a string function call.
410 pub fn string_function_name(&self) -> Option<&str> {
411 match self {
412 Expression::FunctionCall { function, .. } if self.is_string_function_call() => {
413 Some(function.as_str())
414 }
415 _ => None,
416 }
417 }
418
419 /// Check if this expression has a string literal argument.
420 pub fn has_string_literal_argument(&self) -> bool {
421 match self {
422 Expression::FunctionCall { arguments, .. } => {
423 arguments.iter().any(|arg| matches!(arg, Expression::StringLiteral(_)))
424 }
425 _ => false,
426 }
427 }
428}
429
430/// Represents a C typedef declaration.
431#[derive(Debug, Clone, PartialEq)]
432pub struct Typedef {
433 /// Typedef name (the alias)
434 pub name: String,
435 /// Underlying type being aliased
436 pub underlying_type: Type,
437}
438
439impl Typedef {
440 /// Create a new typedef.
441 pub fn new(name: String, underlying_type: Type) -> Self {
442 Self { name, underlying_type }
443 }
444
445 /// Get the typedef name.
446 pub fn name(&self) -> &str {
447 &self.name
448 }
449
450 /// Get the underlying type as a string representation.
451 pub fn underlying_type(&self) -> &str {
452 // Return a string representation of the type
453 match &self.underlying_type {
454 Type::Void => "void",
455 Type::Bool => "_Bool",
456 Type::Int => "int",
457 Type::UnsignedInt => "unsigned int", // DECY-158
458 Type::Float => "float",
459 Type::Double => "double",
460 Type::Char => "char",
461 Type::SignedChar => "signed char", // DECY-250
462 Type::Pointer(inner) => match **inner {
463 Type::Char => "char*",
464 Type::SignedChar => "signed char*", // DECY-250
465 Type::Int => "int*",
466 Type::UnsignedInt => "unsigned int*", // DECY-158
467 Type::Float => "float*",
468 Type::Double => "double*",
469 Type::Void => "void*",
470 _ => "pointer",
471 },
472 Type::Struct(name) => name,
473 Type::FunctionPointer { .. } => "function pointer",
474 Type::Array { .. } => "array",
475 // DECY-172: TypeAlias returns the alias name
476 Type::TypeAlias(name) => name,
477 }
478 }
479
480 /// Check if this typedef is a pointer type.
481 pub fn is_pointer(&self) -> bool {
482 matches!(self.underlying_type, Type::Pointer(_))
483 }
484
485 /// Check if this typedef is a struct type.
486 pub fn is_struct(&self) -> bool {
487 matches!(self.underlying_type, Type::Struct(_))
488 }
489
490 /// Check if this typedef is a function pointer type.
491 pub fn is_function_pointer(&self) -> bool {
492 matches!(self.underlying_type, Type::FunctionPointer { .. })
493 }
494
495 /// Check if this typedef is an array type.
496 pub fn is_array(&self) -> bool {
497 // Arrays are not yet in the Type enum, so return false for now
498 false
499 }
500}
501
502/// Represents a struct field.
503#[derive(Debug, Clone, PartialEq)]
504pub struct StructField {
505 /// Field name
506 pub name: String,
507 /// Field type
508 pub field_type: Type,
509}
510
511impl StructField {
512 /// Create a new struct field.
513 pub fn new(name: String, field_type: Type) -> Self {
514 Self { name, field_type }
515 }
516
517 /// Get the field name.
518 pub fn name(&self) -> &str {
519 &self.name
520 }
521
522 /// Check if this field is a function pointer.
523 pub fn is_function_pointer(&self) -> bool {
524 matches!(self.field_type, Type::FunctionPointer { .. })
525 }
526}
527
528/// Represents a struct definition.
529#[derive(Debug, Clone, PartialEq)]
530pub struct Struct {
531 /// Struct name
532 pub name: String,
533 /// Struct fields
534 pub fields: Vec<StructField>,
535}
536
537impl Struct {
538 /// Create a new struct.
539 pub fn new(name: String, fields: Vec<StructField>) -> Self {
540 Self { name, fields }
541 }
542
543 /// Get the struct name.
544 pub fn name(&self) -> &str {
545 &self.name
546 }
547
548 /// Get the struct fields.
549 pub fn fields(&self) -> &[StructField] {
550 &self.fields
551 }
552}
553
554/// C++ access specifier (DECY-200).
555#[derive(Debug, Clone, Copy, PartialEq, Eq)]
556pub enum AccessSpecifier {
557 /// public:
558 Public,
559 /// protected:
560 Protected,
561 /// private: (default for class)
562 Private,
563}
564
565/// C++ overloaded operator kind (DECY-208).
566///
567/// Maps to Rust `std::ops` traits in codegen.
568#[derive(Debug, Clone, Copy, PartialEq, Eq)]
569pub enum CxxOperatorKind {
570 /// operator+ -> std::ops::Add
571 Add,
572 /// operator- -> std::ops::Sub
573 Sub,
574 /// operator* -> std::ops::Mul
575 Mul,
576 /// operator/ -> std::ops::Div
577 Div,
578 /// operator% -> std::ops::Rem
579 Rem,
580 /// operator== -> PartialEq::eq
581 Equal,
582 /// operator!= -> PartialEq::ne (derived from eq)
583 NotEqual,
584 /// operator< -> PartialOrd::lt
585 Less,
586 /// operator<= -> PartialOrd::le
587 LessEqual,
588 /// operator> -> PartialOrd::gt
589 Greater,
590 /// operator>= -> PartialOrd::ge
591 GreaterEqual,
592 /// operator[] -> std::ops::Index
593 Index,
594 /// operator<< -> std::ops::Shl (or Display for ostream)
595 Shl,
596 /// operator>> -> std::ops::Shr
597 Shr,
598 /// operator+= -> std::ops::AddAssign
599 AddAssign,
600 /// operator-= -> std::ops::SubAssign
601 SubAssign,
602}
603
604/// A C++ class method with its access level (DECY-200).
605#[derive(Debug, Clone, PartialEq)]
606pub struct Method {
607 /// The function definition
608 pub function: Function,
609 /// Access specifier (public/protected/private)
610 pub access: AccessSpecifier,
611 /// Whether this is a const method
612 pub is_const: bool,
613 /// Whether this is a static method
614 pub is_static: bool,
615 /// Whether this is virtual
616 pub is_virtual: bool,
617 /// Overloaded operator kind, if this is an operator method (DECY-208)
618 pub operator_kind: Option<CxxOperatorKind>,
619}
620
621/// Represents a C++ class (DECY-200).
622///
623/// Maps to Rust `struct` + `impl` block. Constructors become `new()`,
624/// destructors become `impl Drop`.
625#[derive(Debug, Clone, PartialEq)]
626pub struct Class {
627 /// Class name
628 pub name: String,
629 /// Data fields (inherited from struct model)
630 pub fields: Vec<StructField>,
631 /// Methods (including constructors/destructors)
632 pub methods: Vec<Method>,
633 /// Constructor parameters (from the first constructor found)
634 pub constructor_params: Vec<Parameter>,
635 /// Whether a destructor was defined
636 pub has_destructor: bool,
637 /// Base class name for single inheritance (DECY-209), None if no base
638 pub base_class: Option<String>,
639}
640
641impl Class {
642 /// Create a new empty class.
643 pub fn new(name: String) -> Self {
644 Self {
645 name,
646 fields: Vec::new(),
647 methods: Vec::new(),
648 constructor_params: Vec::new(),
649 has_destructor: false,
650 base_class: None,
651 }
652 }
653}
654
655/// Represents a C++ namespace (DECY-201).
656///
657/// Maps to Rust `mod` block. Nested namespaces become nested modules.
658#[derive(Debug, Clone, PartialEq)]
659pub struct Namespace {
660 /// Namespace name (empty for anonymous namespaces)
661 pub name: String,
662 /// Functions declared in this namespace
663 pub functions: Vec<Function>,
664 /// Structs declared in this namespace
665 pub structs: Vec<Struct>,
666 /// Classes declared in this namespace
667 pub classes: Vec<Class>,
668 /// Nested namespaces
669 pub namespaces: Vec<Namespace>,
670}
671
672impl Namespace {
673 /// Create a new empty namespace.
674 pub fn new(name: String) -> Self {
675 Self {
676 name,
677 functions: Vec::new(),
678 structs: Vec::new(),
679 classes: Vec::new(),
680 namespaces: Vec::new(),
681 }
682 }
683}
684
685/// Represents a variable declaration.
686#[derive(Debug, Clone, PartialEq)]
687pub struct Variable {
688 /// Variable name
689 name: String,
690 /// Variable type
691 var_type: Type,
692 /// Optional initializer expression
693 initializer: Option<Expression>,
694 /// Static storage class (file-local)
695 is_static: bool,
696 /// Extern storage class (external linkage)
697 is_extern: bool,
698 /// Const qualifier (immutable)
699 is_const: bool,
700}
701
702impl Variable {
703 /// Create a new variable.
704 pub fn new(name: String, var_type: Type) -> Self {
705 Self {
706 name,
707 var_type,
708 initializer: None,
709 is_static: false,
710 is_extern: false,
711 is_const: false,
712 }
713 }
714
715 /// Create a new variable with an initializer.
716 pub fn new_with_initializer(name: String, var_type: Type, initializer: Expression) -> Self {
717 Self {
718 name,
719 var_type,
720 initializer: Some(initializer),
721 is_static: false,
722 is_extern: false,
723 is_const: false,
724 }
725 }
726
727 /// Create a new variable with storage class specifiers.
728 pub fn new_with_storage_class(
729 name: String,
730 var_type: Type,
731 initializer: Option<Expression>,
732 is_static: bool,
733 is_extern: bool,
734 is_const: bool,
735 ) -> Self {
736 Self { name, var_type, initializer, is_static, is_extern, is_const }
737 }
738
739 /// Get the variable name.
740 pub fn name(&self) -> &str {
741 &self.name
742 }
743
744 /// Get the variable type.
745 pub fn var_type(&self) -> &Type {
746 &self.var_type
747 }
748
749 /// Check if this variable is a function pointer.
750 pub fn is_function_pointer(&self) -> bool {
751 matches!(self.var_type, Type::FunctionPointer { .. })
752 }
753
754 /// Get the number of parameters if this is a function pointer.
755 pub fn function_pointer_param_count(&self) -> usize {
756 match &self.var_type {
757 Type::FunctionPointer { param_types, .. } => param_types.len(),
758 _ => 0,
759 }
760 }
761
762 /// Check if this function pointer has a void return type.
763 pub fn function_pointer_has_void_return(&self) -> bool {
764 match &self.var_type {
765 Type::FunctionPointer { return_type, .. } => matches!(**return_type, Type::Void),
766 _ => false,
767 }
768 }
769
770 /// Check if this variable is a string literal (char* with literal initializer).
771 ///
772 /// Detects patterns like: `const char* msg = "Hello";`
773 ///
774 /// # Implementation
775 ///
776 /// Checks if:
777 /// - Type is a pointer to char (`char*`)
778 /// - Has an initializer that is a `StringLiteral` expression
779 ///
780 /// Note: Const qualifier detection not yet implemented - checks all char* pointers.
781 pub fn is_string_literal(&self) -> bool {
782 // Check if type is char*
783 let is_char_ptr =
784 matches!(self.var_type, Type::Pointer(ref inner) if **inner == Type::Char);
785
786 // Check if initializer is a string literal
787 if let Some(initializer) = &self.initializer {
788 is_char_ptr && matches!(initializer, Expression::StringLiteral(_))
789 } else {
790 false
791 }
792 }
793
794 /// Check if this variable is a string buffer (char* allocated with malloc).
795 ///
796 /// Detects patterns like: `char* buffer = malloc(100);`
797 ///
798 /// # Implementation
799 ///
800 /// Checks if:
801 /// - Type is a pointer to char (`char*`)
802 /// - Has an initializer that is a malloc/calloc function call
803 pub fn is_string_buffer(&self) -> bool {
804 // Check if type is char*
805 let is_char_ptr =
806 matches!(self.var_type, Type::Pointer(ref inner) if **inner == Type::Char);
807
808 // Check if initializer is malloc/calloc call
809 if let Some(Expression::FunctionCall { function, .. }) = &self.initializer {
810 is_char_ptr && (function == "malloc" || function == "calloc")
811 } else {
812 false
813 }
814 }
815
816 /// Get the initializer expression for this variable.
817 ///
818 /// Returns `Some(&Expression)` if the variable has an initializer, `None` otherwise.
819 pub fn initializer(&self) -> Option<&Expression> {
820 self.initializer.as_ref()
821 }
822
823 /// Check if this variable has static storage class (file-local).
824 pub fn is_static(&self) -> bool {
825 self.is_static
826 }
827
828 /// Check if this variable is extern (external linkage).
829 pub fn is_extern(&self) -> bool {
830 self.is_extern
831 }
832
833 /// Check if this variable is const (immutable).
834 pub fn is_const(&self) -> bool {
835 self.is_const
836 }
837}
838
839/// Represents an enum variant (constant) in C.
840#[derive(Debug, Clone, PartialEq)]
841pub struct EnumVariant {
842 /// Variant name
843 pub name: String,
844 /// Explicit value if specified
845 pub value: Option<i64>,
846}
847
848impl EnumVariant {
849 /// Create a new enum variant.
850 pub fn new(name: String, value: Option<i64>) -> Self {
851 Self { name, value }
852 }
853}
854
855/// Represents a C enum definition.
856#[derive(Debug, Clone, PartialEq)]
857pub struct Enum {
858 /// Enum name (empty string for anonymous enums)
859 pub name: String,
860 /// Enum variants
861 pub variants: Vec<EnumVariant>,
862}
863
864impl Enum {
865 /// Create a new enum.
866 pub fn new(name: String, variants: Vec<EnumVariant>) -> Self {
867 Self { name, variants }
868 }
869}
870
871/// Abstract Syntax Tree representing parsed C code.
872#[derive(Debug, Clone, PartialEq)]
873pub struct Ast {
874 functions: Vec<Function>,
875 typedefs: Vec<Typedef>,
876 structs: Vec<Struct>,
877 macros: Vec<MacroDefinition>,
878 variables: Vec<Variable>,
879 enums: Vec<Enum>,
880 /// C++ classes (DECY-200)
881 classes: Vec<Class>,
882 /// C++ namespaces (DECY-201)
883 namespaces: Vec<Namespace>,
884}
885
886/// Represents a C macro definition (#define).
887///
888/// C macros come in two forms:
889/// - **Object-like**: Simple text replacement (e.g., `#define MAX 100`)
890/// - **Function-like**: Parameterized text replacement (e.g., `#define SQR(x) ((x) * (x))`)
891///
892/// # Examples
893///
894/// ```no_run
895/// use decy_parser::parser::{CParser, MacroDefinition};
896///
897/// // Parse a simple object-like macro
898/// let parser = CParser::new()?;
899/// let ast = parser.parse("#define MAX 100\nint main() { return 0; }")?;
900/// assert_eq!(ast.macros().len(), 1);
901/// assert_eq!(ast.macros()[0].name(), "MAX");
902/// assert!(ast.macros()[0].is_object_like());
903///
904/// // Parse a function-like macro
905/// let ast2 = parser.parse("#define SQR(x) ((x) * (x))\nint main() { return 0; }")?;
906/// assert_eq!(ast2.macros()[0].name(), "SQR");
907/// assert!(ast2.macros()[0].is_function_like());
908/// assert_eq!(ast2.macros()[0].parameters(), &["x"]);
909/// # Ok::<(), anyhow::Error>(())
910/// ```
911///
912/// # Reference
913///
914/// K&R §4.11, ISO C99 §6.10.3
915#[derive(Debug, Clone, PartialEq)]
916pub struct MacroDefinition {
917 /// Macro name
918 pub name: String,
919 /// Parameters (empty for object-like macros)
920 pub parameters: Vec<String>,
921 /// Macro body (unparsed, tokenized without spaces)
922 pub body: String,
923}
924
925impl MacroDefinition {
926 /// Create a new object-like macro.
927 pub fn new_object_like(name: String, body: String) -> Self {
928 Self { name, parameters: vec![], body }
929 }
930
931 /// Create a new function-like macro.
932 pub fn new_function_like(name: String, parameters: Vec<String>, body: String) -> Self {
933 Self { name, parameters, body }
934 }
935
936 /// Get the macro name.
937 pub fn name(&self) -> &str {
938 &self.name
939 }
940
941 /// Get the macro parameters.
942 pub fn parameters(&self) -> &[String] {
943 &self.parameters
944 }
945
946 /// Get the macro body.
947 pub fn body(&self) -> &str {
948 &self.body
949 }
950
951 /// Check if this is a function-like macro.
952 pub fn is_function_like(&self) -> bool {
953 !self.parameters.is_empty()
954 }
955
956 /// Check if this is an object-like macro.
957 pub fn is_object_like(&self) -> bool {
958 self.parameters.is_empty()
959 }
960}
961
962impl Ast {
963 /// Create a new empty AST.
964 pub fn new() -> Self {
965 Self {
966 functions: Vec::new(),
967 typedefs: Vec::new(),
968 structs: Vec::new(),
969 macros: Vec::new(),
970 variables: Vec::new(),
971 enums: Vec::new(),
972 classes: Vec::new(),
973 namespaces: Vec::new(),
974 }
975 }
976
977 /// Get the functions in the AST.
978 pub fn functions(&self) -> &[Function] {
979 &self.functions
980 }
981
982 /// Get mutable access to functions (DECY-221: for CUDA qualifier post-processing).
983 pub fn functions_mut(&mut self) -> &mut [Function] {
984 &mut self.functions
985 }
986
987 /// Add a function to the AST.
988 pub fn add_function(&mut self, function: Function) {
989 self.functions.push(function);
990 }
991
992 /// Get the typedefs in the AST.
993 pub fn typedefs(&self) -> &[Typedef] {
994 &self.typedefs
995 }
996
997 /// Add a typedef to the AST.
998 pub fn add_typedef(&mut self, typedef: Typedef) {
999 self.typedefs.push(typedef);
1000 }
1001
1002 /// Get the structs in the AST.
1003 pub fn structs(&self) -> &[Struct] {
1004 &self.structs
1005 }
1006
1007 /// Add a struct to the AST.
1008 /// Deduplicates by name to avoid duplicate definitions from system includes.
1009 pub fn add_struct(&mut self, struct_def: Struct) {
1010 // Deduplicate: don't add if a struct with the same name already exists
1011 if !self.structs.iter().any(|s| s.name() == struct_def.name()) {
1012 self.structs.push(struct_def);
1013 }
1014 }
1015
1016 /// Get the macro definitions in the AST.
1017 pub fn macros(&self) -> &[MacroDefinition] {
1018 &self.macros
1019 }
1020
1021 /// Add a macro definition to the AST.
1022 pub fn add_macro(&mut self, macro_def: MacroDefinition) {
1023 self.macros.push(macro_def);
1024 }
1025
1026 /// Get the variables in the AST.
1027 pub fn variables(&self) -> &[Variable] {
1028 &self.variables
1029 }
1030
1031 /// Add a variable to the AST.
1032 pub fn add_variable(&mut self, variable: Variable) {
1033 self.variables.push(variable);
1034 }
1035
1036 /// Get the enums in the AST.
1037 pub fn enums(&self) -> &[Enum] {
1038 &self.enums
1039 }
1040
1041 /// Add an enum to the AST.
1042 pub fn add_enum(&mut self, enum_def: Enum) {
1043 self.enums.push(enum_def);
1044 }
1045
1046 /// Get the C++ classes in the AST (DECY-200).
1047 pub fn classes(&self) -> &[Class] {
1048 &self.classes
1049 }
1050
1051 /// Add a C++ class to the AST (DECY-200).
1052 pub fn add_class(&mut self, class: Class) {
1053 if !self.classes.iter().any(|c| c.name == class.name) {
1054 self.classes.push(class);
1055 }
1056 }
1057
1058 /// Get the C++ namespaces in the AST (DECY-201).
1059 pub fn namespaces(&self) -> &[Namespace] {
1060 &self.namespaces
1061 }
1062
1063 /// Add a C++ namespace to the AST (DECY-201).
1064 pub fn add_namespace(&mut self, ns: Namespace) {
1065 self.namespaces.push(ns);
1066 }
1067}
1068
1069impl Default for Ast {
1070 fn default() -> Self {
1071 Self::new()
1072 }
1073}
1074
1075/// CUDA function qualifier (DECY-199).
1076///
1077/// Represents `__global__`, `__device__`, `__host__`, or combined qualifiers
1078/// extracted from CUDA source files via clang-sys cursor attributes.
1079#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1080pub enum CudaQualifier {
1081 /// `__global__` - kernel entry point, callable from host, runs on device
1082 Global,
1083 /// `__device__` - callable from device only, runs on device
1084 Device,
1085 /// `__host__` - callable from host only, runs on host (default)
1086 Host,
1087 /// `__host__ __device__` - callable from both host and device
1088 HostDevice,
1089}
1090
1091/// Represents a C function.
1092#[derive(Debug, Clone, PartialEq)]
1093pub struct Function {
1094 /// Function name
1095 pub name: String,
1096 /// Return type
1097 pub return_type: Type,
1098 /// Parameters
1099 pub parameters: Vec<Parameter>,
1100 /// Function body (statements)
1101 pub body: Vec<Statement>,
1102 /// CUDA qualifier (DECY-199), None for plain C/C++ functions
1103 pub cuda_qualifier: Option<CudaQualifier>,
1104}
1105
1106impl Function {
1107 /// Create a new function.
1108 pub fn new(name: String, return_type: Type, parameters: Vec<Parameter>) -> Self {
1109 Self { name, return_type, parameters, body: Vec::new(), cuda_qualifier: None }
1110 }
1111
1112 /// Create a new function with body.
1113 pub fn new_with_body(
1114 name: String,
1115 return_type: Type,
1116 parameters: Vec<Parameter>,
1117 body: Vec<Statement>,
1118 ) -> Self {
1119 Self { name, return_type, parameters, body, cuda_qualifier: None }
1120 }
1121}
1122
1123/// Represents a C type.
1124#[derive(Debug, Clone, PartialEq)]
1125#[allow(clippy::enum_variant_names)] // TypeAlias is a meaningful variant name
1126pub enum Type {
1127 /// void
1128 Void,
1129 /// C99 _Bool type (maps to bool in Rust)
1130 Bool,
1131 /// int
1132 Int,
1133 /// unsigned int (DECY-158)
1134 UnsignedInt,
1135 /// float
1136 Float,
1137 /// double
1138 Double,
1139 /// char (unsigned char or plain char → u8)
1140 Char,
1141 /// signed char → i8 (DECY-250)
1142 SignedChar,
1143 /// Pointer to a type
1144 Pointer(Box<Type>),
1145 /// Struct type (e.g., struct Point)
1146 Struct(String),
1147 /// Function pointer type (e.g., int (*callback)(int))
1148 FunctionPointer {
1149 /// Parameter types
1150 param_types: Vec<Type>,
1151 /// Return type
1152 return_type: Box<Type>,
1153 },
1154 /// Array type (e.g., `int arr[10]`)
1155 /// For typedef assertions like: `typedef char check[sizeof(int) == 4 ? 1 : -1]`
1156 Array {
1157 /// Element type
1158 element_type: Box<Type>,
1159 /// Array size (None for unknown/expression-based size)
1160 size: Option<i64>,
1161 },
1162 /// Type alias (typedef) - preserves the alias name
1163 /// DECY-172: Used for size_t, ssize_t, ptrdiff_t, etc.
1164 TypeAlias(String),
1165}
1166
1167/// Represents a function parameter.
1168#[derive(Debug, Clone, PartialEq)]
1169pub struct Parameter {
1170 /// Parameter name
1171 pub name: String,
1172 /// Parameter type
1173 pub param_type: Type,
1174 /// Whether the pointee type is const (for pointer params like `const char*`)
1175 /// DECY-135: Track const qualifier to enable const char* → &str transformation
1176 pub is_pointee_const: bool,
1177}
1178
1179impl Parameter {
1180 /// Create a new parameter.
1181 pub fn new(name: String, param_type: Type) -> Self {
1182 Self { name, param_type, is_pointee_const: false }
1183 }
1184
1185 /// Create a new parameter with const pointee information.
1186 /// DECY-135: Used for const char* parameters
1187 pub fn new_with_const(name: String, param_type: Type, is_pointee_const: bool) -> Self {
1188 Self { name, param_type, is_pointee_const }
1189 }
1190
1191 /// Check if this parameter is a function pointer.
1192 pub fn is_function_pointer(&self) -> bool {
1193 matches!(self.param_type, Type::FunctionPointer { .. })
1194 }
1195
1196 /// Check if this parameter is a const char pointer (const char*).
1197 ///
1198 /// DECY-135: Now properly checks if pointee is const-qualified.
1199 /// Returns `true` only for `const char*` parameters, not `char*`.
1200 pub fn is_const_char_pointer(&self) -> bool {
1201 self.is_pointee_const
1202 && matches!(self.param_type, Type::Pointer(ref inner) if matches!(**inner, Type::Char))
1203 }
1204
1205 /// Check if this parameter is any char pointer (char* or const char*).
1206 pub fn is_char_pointer(&self) -> bool {
1207 matches!(self.param_type, Type::Pointer(ref inner) if matches!(**inner, Type::Char))
1208 }
1209}