Skip to main content

gobject_ast/model/types/
gtype.rs

1use serde::Serialize;
2
3use crate::model::{expression::Expression, types::BasicType};
4
5/// A GLib GType reference — either a macro/define or a `_get_type()` call.
6#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
7#[serde(rename_all = "snake_case")]
8pub enum GType {
9    /// `G_TYPE_NONE` — void / no return value.
10    None,
11    /// A macro or `#define` like `G_TYPE_BOOLEAN` or `GTK_TYPE_WIDGET`.
12    Identifier(String),
13    /// A `_get_type()` function call; stores the function name (e.g.
14    /// `"gtk_widget_get_type"`).
15    Call(String),
16}
17
18impl GType {
19    pub fn is_none(&self) -> bool {
20        matches!(self, Self::None)
21    }
22
23    pub fn from_expression(expr: &Expression) -> Option<Self> {
24        match expr {
25            Expression::Identifier(id) if id.name == "G_TYPE_NONE" => Some(Self::None),
26            Expression::Identifier(id) => Some(Self::Identifier(id.name.clone())),
27            Expression::Call(call) => Some(Self::Call(call.function_name().to_owned())),
28            _ => None,
29        }
30    }
31
32    /// Returns the `BasicType` if this GType maps to a GLib primitive, `None`
33    /// for object/boxed/interface types and `_get_type()` calls.
34    pub fn as_basic(&self) -> Option<BasicType> {
35        let Self::Identifier(id) = self else {
36            return None;
37        };
38        match id.as_str() {
39            "G_TYPE_BOOLEAN" => Some(BasicType::Boolean),
40            "G_TYPE_CHAR" => Some(BasicType::Char),
41            "G_TYPE_UCHAR" => Some(BasicType::UChar),
42            "G_TYPE_INT" => Some(BasicType::Int),
43            "G_TYPE_UINT" => Some(BasicType::UInt),
44            "G_TYPE_LONG" => Some(BasicType::Long),
45            "G_TYPE_ULONG" => Some(BasicType::ULong),
46            "G_TYPE_INT64" => Some(BasicType::Int64),
47            "G_TYPE_UINT64" => Some(BasicType::UInt64),
48            "G_TYPE_FLOAT" => Some(BasicType::Float),
49            "G_TYPE_DOUBLE" => Some(BasicType::Double),
50            "G_TYPE_STRING" => Some(BasicType::String),
51            "G_TYPE_POINTER" => Some(BasicType::Pointer),
52            _ => None,
53        }
54    }
55}