Skip to main content

gobject_ast/model/expression/
sizeof.rs

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