Skip to main content

gobject_ast/model/expression/
sizeof.rs

1use serde::Serialize;
2
3use crate::{
4    TypeInfo,
5    model::{SourceLocation, expression::Expression},
6};
7
8#[derive(Debug, Clone, Serialize)]
9pub struct SizeofExpression {
10    #[serde(skip_serializing_if = "Option::is_none")]
11    pub operand: Option<SizeofOperand>,
12    pub text: String, // Full text like "sizeof(int)" or "sizeof x"
13    pub location: SourceLocation,
14}
15
16#[derive(Debug, Clone, Serialize)]
17#[serde(rename_all = "snake_case")]
18pub enum SizeofOperand {
19    Type(TypeInfo),              // sizeof(MyType) or sizeof(struct MyType *)
20    Expression(Box<Expression>), // sizeof(expr)
21}
22
23impl SizeofExpression {
24    /// Get the type if this is sizeof(Type)
25    /// Returns Some for both explicit types and simple identifiers (which are
26    /// likely types)
27    pub fn type_name(&self) -> Option<&str> {
28        match &self.operand {
29            Some(SizeofOperand::Type(t)) => Some(&t.base_type),
30            Some(SizeofOperand::Expression(expr)) => {
31                if let Expression::Identifier(id) = expr.as_ref() {
32                    Some(&id.name)
33                } else {
34                    None
35                }
36            }
37            None => None,
38        }
39    }
40
41    /// Check if this is sizeof of a simple type (not a complex expression)
42    pub fn is_sizeof_type(&self) -> bool {
43        match &self.operand {
44            Some(SizeofOperand::Type(_)) => true,
45            // Simple identifier is likely a type
46            Some(SizeofOperand::Expression(expr)) => {
47                matches!(expr.as_ref(), Expression::Identifier(_))
48            }
49            None => false,
50        }
51    }
52}