geam-core 0.2.0

Typed Gleam planning, host, and execution core for Geam
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
use crate::host::{
    HostCall, HostExternalEquality, HostExternalHashing, HostExternalInspection, HostListType,
    HostProfile, HostProvider, HostStoredDynamic, HostStoredType, HostStoredValue, HostType,
    HostTypeIndex0, HostTypeIndexNext,
};
use crate::provider::{
    List, ProviderConstructions, ProviderExternalDeclaration, ProviderInputValue,
    ProviderListContext, ProviderListInputCodec, ProviderListInputValue, ProviderNoConstructions,
    ProviderOutputValue, ProviderStoredOwner, ProviderValue, ProviderValueContext, Value,
};
use ecow::EcoString;
use std::marker::PhantomData;

/// Source-equality access for retained values in one immutable payload.
pub type Equality<'value> = HostExternalEquality<'value>;

/// Source-hash access for retained values in one immutable payload.
pub type Hashing<'value> = HostExternalHashing<'value>;

/// Source-inspection access for retained values in one immutable payload.
pub type Inspection<'value> = HostExternalInspection<'value>;

/// One retained source value owned by an advanced external payload.
///
/// The payload type is the owner brand. The argument index identifies the
/// corresponding source type parameter. Values are created only by
/// [`super::Call::store`] followed by the generated external boundary.
pub struct Retained<Owner, Index> {
    value: HostStoredValue<HostStoredType<Index>>,
    owner: PhantomData<fn() -> Owner>,
}

/// One existential source value owned by an advanced external payload.
///
/// The exact specialized source type stays sealed inside Geam. Providers can
/// inspect its broad family, confirm a generated external declaration, or
/// request an exact typed restore through an active [`crate::provider::Call`].
pub struct StoredDynamic<Owner> {
    value: HostStoredDynamic,
    owner: PhantomData<fn() -> Owner>,
}

/// An existing external source value with its original runtime identity.
///
/// This advanced input is useful when a provider must pass an external value
/// to a callback or return it unchanged. Dereferencing it borrows the ordinary
/// Rust payload; consuming it preserves the original source handle.
pub type External<Payload> = crate::provider::ProviderExternalItem<Payload>;

/// Static pass-through into existential retention without materialization.
#[doc(hidden)]
pub trait ProviderDynamicValue<'call, Profile, Provider, Return>
where
    Profile: HostProfile,
    Provider: HostProvider<Profile>,
    Return: HostType,
{
    type Host: HostType;

    fn into_host(
        self,
        call: &mut HostCall<'call, Profile, Provider, Return>,
    ) -> <Self::Host as HostType>::Value<'call>;
}

impl<'call, Profile, Provider, Return, Type, Host>
    ProviderDynamicValue<'call, Profile, Provider, Return>
    for Value<Type, ProviderValueContext<'call, Host>>
where
    Profile: HostProfile,
    Provider: HostProvider<Profile>,
    Return: HostType,
    Host: HostType,
{
    type Host = Host;

    fn into_host(
        self,
        _call: &mut HostCall<'call, Profile, Provider, Return>,
    ) -> <Self::Host as HostType>::Value<'call> {
        self.into_host()
    }
}

impl<'call, Profile, Provider, Return, Type> ProviderDynamicValue<'call, Profile, Provider, Return>
    for Type
where
    Profile: HostProfile,
    Provider: HostProvider<Profile>,
    Return: HostType,
    Type: ProviderValue<OutputRequirements = ProviderNoConstructions>
        + ProviderOutputValue<Profile, Provider, Return>,
{
    type Host = Type::Host;

    fn into_host(
        self,
        call: &mut HostCall<'call, Profile, Provider, Return>,
    ) -> <Self::Host as HostType>::Value<'call> {
        self.into_host(call, &ProviderConstructions::none())
    }
}

impl<'call, Profile, Provider, Return, Item, HostItem, Decoder>
    ProviderDynamicValue<'call, Profile, Provider, Return>
    for List<Item, ProviderListContext<'call, HostItem, Decoder>>
where
    Profile: HostProfile,
    Provider: HostProvider<Profile>,
    Return: HostType,
    HostItem: HostType,
    Decoder: crate::provider::ProviderListItemDecoder<Item>,
{
    type Host = HostListType<HostItem>;

    fn into_host(
        self,
        _call: &mut HostCall<'call, Profile, Provider, Return>,
    ) -> <Self::Host as HostType>::Value<'call> {
        self.__geam_into_context().into_host()
    }
}

/// Broad runtime family of one existentially retained source value.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum DynamicKind {
    Int,
    Float,
    String,
    BitArray,
    UtfCodepoint,
    Bool,
    Nil,
    List,
    Tuple,
    Custom,
    External,
    Function,
}

impl DynamicKind {
    fn from_family(family: crate::provider_support::HostStoredValueFamily) -> Self {
        match family {
            crate::provider_support::HostStoredValueFamily::Int => Self::Int,
            crate::provider_support::HostStoredValueFamily::Float => Self::Float,
            crate::provider_support::HostStoredValueFamily::String => Self::String,
            crate::provider_support::HostStoredValueFamily::BitArray => Self::BitArray,
            crate::provider_support::HostStoredValueFamily::UtfCodepoint => Self::UtfCodepoint,
            crate::provider_support::HostStoredValueFamily::Bool => Self::Bool,
            crate::provider_support::HostStoredValueFamily::Nil => Self::Nil,
            crate::provider_support::HostStoredValueFamily::List => Self::List,
            crate::provider_support::HostStoredValueFamily::Tuple => Self::Tuple,
            crate::provider_support::HostStoredValueFamily::Custom => Self::Custom,
            crate::provider_support::HostStoredValueFamily::External => Self::External,
            crate::provider_support::HostStoredValueFamily::Function => Self::Function,
        }
    }
}

/// Static input conversion used by exact existential restores.
#[doc(hidden)]
pub trait ProviderDynamicInput<Profile, Provider, Return>
where
    Profile: HostProfile,
    Provider: HostProvider<Profile>,
    Return: HostType,
{
    type Host: HostType;
    type View<'call>;

    fn from_host<'call>(
        call: &mut HostCall<'call, Profile, Provider, Return>,
        value: <Self::Host as HostType>::Value<'call>,
    ) -> Self::View<'call>;
}

impl<Profile, Provider, Return, Type> ProviderDynamicInput<Profile, Provider, Return> for Type
where
    Profile: HostProfile,
    Provider: HostProvider<Profile>,
    Return: HostType,
    Type: ProviderValue,
    Type::Input: ProviderInputValue<Profile, Provider, Return> + ProviderValue<Host = Type::Host>,
{
    type Host = Type::Host;
    type View<'call> = Type::Input;

    fn from_host<'call>(
        call: &mut HostCall<'call, Profile, Provider, Return>,
        value: <Self::Host as HostType>::Value<'call>,
    ) -> Self::View<'call> {
        Type::Input::from_host(call, value)
    }
}

impl<Profile, Provider, Return, Item> ProviderDynamicInput<Profile, Provider, Return> for List<Item>
where
    Profile: HostProfile,
    Provider: HostProvider<Profile>,
    Return: HostType,
    Item: ProviderValue<ListInput = Item>,
    Item::ListInput: ProviderListInputCodec<Profile>,
{
    type Host = HostListType<Item::Host>;
    type View<'call> = List<
        Item,
        ProviderListContext<
            'call,
            Item::Host,
            <Item::ListInput as ProviderListInputValue>::Decoder,
        >,
    >;

    fn from_host<'call>(
        call: &mut HostCall<'call, Profile, Provider, Return>,
        value: <Self::Host as HostType>::Value<'call>,
    ) -> Self::View<'call> {
        let decoder = <Item::ListInput as ProviderListInputCodec<Profile>>::decoder(call);
        call.provider_list(value, decoder)
    }
}

/// The first source type-argument position of an advanced external payload.
pub type Index0 = HostTypeIndex0;

/// The source type-argument position after `Index`.
pub type Next<Index> = HostTypeIndexNext<Index>;

/// Context-aware source semantics for an advanced retained payload declared
/// with `#[geam::external(name = "...", retained)]`.
pub trait RetainedExternalPayload: 'static {
    fn source_equal(&self, context: &Equality<'_>, other: &Self) -> bool;

    fn source_hash(&self, context: &Hashing<'_>) -> u64;

    fn inspect(&self, context: &Inspection<'_>) -> EcoString;
}

impl<Owner, Index> Retained<Owner, Index>
where
    Owner: ProviderStoredOwner,
{
    pub(crate) fn new(value: HostStoredValue<HostStoredType<Index>>) -> Self {
        Self {
            value,
            owner: PhantomData,
        }
    }

    pub(crate) fn host(&self) -> &HostStoredValue<HostStoredType<Index>> {
        &self.value
    }

    /// Compares two retained values with Gleam source equality.
    pub fn source_equal(&self, context: &Equality<'_>, other: &Self) -> bool {
        context.stored_values_equal(&self.value, &other.value)
    }

    /// Hashes this retained value consistently with Gleam source equality.
    pub fn source_hash(&self, context: &Hashing<'_>) -> u64 {
        context.stored_value_hash(&self.value)
    }

    /// Inspects this retained value with Gleam source formatting.
    pub fn inspect(&self, context: &Inspection<'_>) -> EcoString {
        context.inspect_stored_value(&self.value)
    }
}

impl<Owner> StoredDynamic<Owner>
where
    Owner: ProviderStoredOwner,
{
    pub(crate) fn new(value: HostStoredDynamic) -> Self {
        Self {
            value,
            owner: PhantomData,
        }
    }

    pub(crate) fn host(&self) -> &HostStoredDynamic {
        &self.value
    }

    /// Returns the broad source family without exposing its runtime type.
    pub fn kind(&self) -> DynamicKind {
        DynamicKind::from_family(self.value.value_family())
    }

    /// Confirms one generated external declaration without exposing names.
    pub fn is_external<Declaration>(&self) -> bool
    where
        Declaration: ProviderExternalDeclaration,
    {
        self.value.has_external_schema::<Declaration::Schema>()
    }

    /// Consumes a retained tuple and retains each element under the same owner.
    ///
    /// Non-tuples are returned unchanged.
    #[expect(
        clippy::result_large_err,
        reason = "non-tuples retain the original value without another heap allocation"
    )]
    pub fn into_tuple_items(self) -> Result<Box<[Self]>, Self> {
        self.value.map_tuple_items(Self::new).map_err(Self::new)
    }

    /// Compares two existential values with Gleam source equality.
    pub fn source_equal(&self, context: &Equality<'_>, other: &Self) -> bool {
        context.dynamic_values_equal(&self.value, &other.value)
    }

    /// Hashes this existential value consistently with Gleam source equality.
    pub fn source_hash(&self, context: &Hashing<'_>) -> u64 {
        context.dynamic_value_hash(&self.value)
    }

    /// Inspects this existential value with Gleam source formatting.
    pub fn inspect(&self, context: &Inspection<'_>) -> EcoString {
        context.inspect_dynamic_value(&self.value)
    }
}

#[cfg(test)]
mod tests {
    use super::{DynamicKind, Index0, Retained};
    use crate::host::{
        HostExternalEquality, HostExternalHashing, HostExternalInspection, HostStoredType,
        HostStoredValue,
    };
    use crate::runtime::StoredRuntimeValue;

    struct Payload;

    impl crate::provider::ProviderStoredOwner for Payload {}

    fn retained(value: i64) -> Retained<Payload, Index0> {
        Retained::new(HostStoredValue::<HostStoredType<Index0>>::new(
            StoredRuntimeValue::test_int(value.into()),
        ))
    }

    #[test]
    fn dynamic_kind_covers_every_retained_runtime_family() {
        use crate::provider_support::HostStoredValueFamily;

        assert_eq!(
            DynamicKind::from_family(HostStoredValueFamily::Int),
            DynamicKind::Int
        );
        assert_eq!(
            DynamicKind::from_family(HostStoredValueFamily::Float),
            DynamicKind::Float
        );
        assert_eq!(
            DynamicKind::from_family(HostStoredValueFamily::String),
            DynamicKind::String
        );
        assert_eq!(
            DynamicKind::from_family(HostStoredValueFamily::BitArray),
            DynamicKind::BitArray,
        );
        assert_eq!(
            DynamicKind::from_family(HostStoredValueFamily::UtfCodepoint),
            DynamicKind::UtfCodepoint,
        );
        assert_eq!(
            DynamicKind::from_family(HostStoredValueFamily::Bool),
            DynamicKind::Bool
        );
        assert_eq!(
            DynamicKind::from_family(HostStoredValueFamily::Nil),
            DynamicKind::Nil
        );
        assert_eq!(
            DynamicKind::from_family(HostStoredValueFamily::List),
            DynamicKind::List
        );
        assert_eq!(
            DynamicKind::from_family(HostStoredValueFamily::Tuple),
            DynamicKind::Tuple
        );
        assert_eq!(
            DynamicKind::from_family(HostStoredValueFamily::Custom),
            DynamicKind::Custom
        );
        assert_eq!(
            DynamicKind::from_family(HostStoredValueFamily::External),
            DynamicKind::External,
        );
        assert_eq!(
            DynamicKind::from_family(HostStoredValueFamily::Function),
            DynamicKind::Function,
        );
    }

    #[test]
    fn retained_values_delegate_each_source_operation_to_its_narrow_context() {
        let first = retained(7);
        let different = retained(8);
        let stored_equal =
            |left: &StoredRuntimeValue, right: &StoredRuntimeValue| std::ptr::eq(left, right);
        let stored_hash = |_: &StoredRuntimeValue| 17;
        let stored_inspect = |_: &StoredRuntimeValue| "Int(7)".into();
        let equality = HostExternalEquality::new(&stored_equal);
        let hashing = HostExternalHashing::new(&stored_hash);
        let inspection = HostExternalInspection::new(&stored_inspect);

        assert!(first.source_equal(&equality, &first));
        assert!(!first.source_equal(&equality, &different));
        assert_eq!(first.source_hash(&hashing), 17);
        assert_eq!(first.inspect(&inspection), "Int(7)");
    }
}