golem-rib 1.3.1

Parser for Golem's Rib language
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
// Copyright 2024-2025 Golem Cloud
//
// Licensed under the Golem Source License v1.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://license.golem.cloud/LICENSE
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use golem_wasm_ast::analysis::AnalysedType;
use golem_wasm_rpc::{IntoValueAndType, Value, ValueAndType};
use std::cmp::Ordering;
use std::fmt::Display;

pub trait GetLiteralValue {
    fn get_literal(&self) -> Option<LiteralValue>;
}

impl GetLiteralValue for ValueAndType {
    fn get_literal(&self) -> Option<LiteralValue> {
        match self {
            ValueAndType {
                value: Value::String(value),
                ..
            } => Some(LiteralValue::String(value.clone())),
            ValueAndType {
                value: Value::Char(code_point),
                ..
            } => char::from_u32(*code_point as u32)
                .map(|c| c.to_string())
                .map(LiteralValue::String),
            ValueAndType {
                value: Value::Bool(value),
                ..
            } => Some(LiteralValue::Bool(*value)),
            ValueAndType {
                value: Value::Enum(idx),
                typ: AnalysedType::Enum(typ),
            } => {
                // An enum can be turned into a simple literal and can be part of string concatenations
                Some(LiteralValue::String(typ.cases[*idx as usize].clone()))
            }
            ValueAndType {
                value:
                    Value::Variant {
                        case_idx,
                        case_value,
                    },
                typ: AnalysedType::Variant(typ),
            } => {
                // A no arg variant can be turned into a simple literal and can be part of string concatenations
                if case_value.is_none() {
                    Some(LiteralValue::String(
                        typ.cases[*case_idx as usize].name.clone(),
                    ))
                } else {
                    None
                }
            }
            other => internal::get_numeric_value(other).map(LiteralValue::Num),
        }
    }
}

#[derive(Clone, Debug, PartialEq, PartialOrd)]
pub enum LiteralValue {
    Num(CoercedNumericValue),
    String(String),
    Bool(bool),
}

impl LiteralValue {
    pub fn get_bool(&self) -> Option<bool> {
        match self {
            LiteralValue::Bool(value) => Some(*value),
            _ => None,
        }
    }

    pub fn get_number(&self) -> Option<CoercedNumericValue> {
        match self {
            LiteralValue::Num(num) => Some(num.clone()),
            _ => None,
        }
    }

    pub fn as_string(&self) -> String {
        match self {
            LiteralValue::Num(number) => number.to_string(),
            LiteralValue::String(value) => value.clone(),
            LiteralValue::Bool(value) => value.to_string(),
        }
    }
}

impl From<String> for LiteralValue {
    fn from(value: String) -> Self {
        if let Ok(u64) = value.parse::<u64>() {
            LiteralValue::Num(CoercedNumericValue::PosInt(u64))
        } else if let Ok(i64_value) = value.parse::<i64>() {
            LiteralValue::Num(CoercedNumericValue::NegInt(i64_value))
        } else if let Ok(f64_value) = value.parse::<f64>() {
            LiteralValue::Num(CoercedNumericValue::Float(f64_value))
        } else if let Ok(bool) = value.parse::<bool>() {
            LiteralValue::Bool(bool)
        } else {
            LiteralValue::String(value.to_string())
        }
    }
}

// A coerced representation of numeric wasm types, simplifying finer-grained TypeAnnotatedValue types into u64, i64, and f64.
#[derive(Clone, Debug)]
pub enum CoercedNumericValue {
    PosInt(u64),
    NegInt(i64),
    Float(f64),
}

impl CoercedNumericValue {
    pub fn is_zero(&self) -> bool {
        match self {
            CoercedNumericValue::PosInt(val) => *val == 0,
            CoercedNumericValue::NegInt(val) => *val == 0,
            CoercedNumericValue::Float(val) => *val == 0.0,
        }
    }

    pub fn cast_to(&self, analysed_type: &AnalysedType) -> Option<ValueAndType> {
        match self {
            CoercedNumericValue::PosInt(number) => {
                let num = *number;

                match analysed_type {
                    AnalysedType::U8(_) if num <= u8::MAX as u64 => {
                        Some((num as u8).into_value_and_type())
                    }
                    AnalysedType::U16(_) if num <= u16::MAX as u64 => {
                        Some((num as u16).into_value_and_type())
                    }
                    AnalysedType::U32(_) if num <= u32::MAX as u64 => {
                        Some((num as u32).into_value_and_type())
                    }
                    AnalysedType::U64(_) => Some(num.into_value_and_type()),

                    AnalysedType::S8(_) if num <= i8::MAX as u64 => {
                        Some((num as i8).into_value_and_type())
                    }
                    AnalysedType::S16(_) if num <= i16::MAX as u64 => {
                        Some((num as i16).into_value_and_type())
                    }
                    AnalysedType::S32(_) if num <= i32::MAX as u64 => {
                        Some((num as i32).into_value_and_type())
                    }
                    AnalysedType::S64(_) if num <= i64::MAX as u64 => {
                        Some((num as i64).into_value_and_type())
                    }

                    AnalysedType::F32(_) if num <= f32::MAX as u64 => {
                        Some((num as f32).into_value_and_type())
                    }
                    AnalysedType::F64(_) if num <= f64::MAX as u64 => {
                        Some((num as f64).into_value_and_type())
                    }

                    _ => None,
                }
            }

            CoercedNumericValue::NegInt(number) => {
                let num = *number;

                match analysed_type {
                    AnalysedType::S8(_) if num >= i8::MIN as i64 && num <= i8::MAX as i64 => {
                        Some((num as i8).into_value_and_type())
                    }
                    AnalysedType::S16(_) if num >= i16::MIN as i64 && num <= i16::MAX as i64 => {
                        Some((num as i16).into_value_and_type())
                    }
                    AnalysedType::S32(_) if num >= i32::MIN as i64 && num <= i32::MAX as i64 => {
                        Some((num as i32).into_value_and_type())
                    }
                    AnalysedType::S64(_) => Some(num.into_value_and_type()),

                    // Allow unsigned conversion only if non-negative
                    AnalysedType::U8(_) if num >= 0 && num <= u8::MAX as i64 => {
                        Some((num as u8).into_value_and_type())
                    }
                    AnalysedType::U16(_) if num >= 0 && num <= u16::MAX as i64 => {
                        Some((num as u16).into_value_and_type())
                    }
                    AnalysedType::U32(_) if num >= 0 && num <= u32::MAX as i64 => {
                        Some((num as u32).into_value_and_type())
                    }
                    AnalysedType::U64(_) if num >= 0 => Some((num as u64).into_value_and_type()),

                    AnalysedType::F32(_) if num >= f32::MIN as i64 && num <= f32::MAX as i64 => {
                        Some((num as f32).into_value_and_type())
                    }
                    AnalysedType::F64(_) if num >= f64::MIN as i64 && num <= f64::MAX as i64 => {
                        Some((num as f64).into_value_and_type())
                    }

                    _ => None,
                }
            }

            CoercedNumericValue::Float(number) => {
                let num = *number;

                match analysed_type {
                    AnalysedType::F64(_) => Some(num.into_value_and_type()),

                    AnalysedType::F32(_)
                        if num.is_finite() && num >= f32::MIN as f64 && num <= f32::MAX as f64 =>
                    {
                        Some((num as f32).into_value_and_type())
                    }

                    AnalysedType::U64(_)
                        if num.is_finite()
                            && num >= 0.0
                            && num <= u64::MAX as f64
                            && num.fract() == 0.0 =>
                    {
                        Some((num as u64).into_value_and_type())
                    }

                    AnalysedType::S64(_)
                        if num.is_finite()
                            && num >= i64::MIN as f64
                            && num <= i64::MAX as f64
                            && num.fract() == 0.0 =>
                    {
                        Some((num as i64).into_value_and_type())
                    }

                    _ => None,
                }
            }
        }
    }
}

macro_rules! impl_ops {
    ($trait:ident, $method:ident, $checked_method:ident) => {
        impl std::ops::$trait for CoercedNumericValue {
            type Output = Result<Self, String>;

            fn $method(self, rhs: Self) -> Self::Output {
                use CoercedNumericValue::*;
                Ok(match (self, rhs) {
                    (Float(a), Float(b)) => Float(a.$method(b)),
                    (Float(a), PosInt(b)) => Float(a.$method(b as f64)),
                    (Float(a), NegInt(b)) => Float(a.$method(b as f64)),
                    (PosInt(a), Float(b)) => Float((a as f64).$method(b)),
                    (NegInt(a), Float(b)) => Float((a as f64).$method(b)),
                    (PosInt(a), PosInt(b)) => a.$checked_method(b).map(PosInt).ok_or(format!(
                        "overflow in unsigned operation between {} and {}",
                        a, b
                    ))?,
                    (NegInt(a), NegInt(b)) => a.$checked_method(b).map(NegInt).ok_or(format!(
                        "overflow in signed operation between {} and {}",
                        a, b
                    ))?,
                    (PosInt(a), NegInt(b)) => (a as i64).$checked_method(b).map(NegInt).ok_or(
                        format!("overflow in signed operation between {} and {}", a, b),
                    )?,
                    (NegInt(a), PosInt(b)) => a.$checked_method(b as i64).map(NegInt).ok_or(
                        format!("overflow in signed operation between {} and {}", a, b),
                    )?,
                })
            }
        }
    };
}

impl_ops!(Add, add, checked_add);
impl_ops!(Sub, sub, checked_sub);
impl_ops!(Mul, mul, checked_mul);
impl_ops!(Div, div, checked_div);

// Auto-derived PartialOrd fails if types don't match
// and therefore custom impl.
impl PartialOrd for CoercedNumericValue {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        use CoercedNumericValue::*;
        match (self, other) {
            (PosInt(a), PosInt(b)) => a.partial_cmp(b),
            (NegInt(a), NegInt(b)) => a.partial_cmp(b),
            (Float(a), Float(b)) => a.partial_cmp(b),

            (PosInt(a), NegInt(b)) => {
                if let Ok(b_as_u64) = u64::try_from(*b) {
                    a.partial_cmp(&b_as_u64)
                } else {
                    Some(Ordering::Greater) // Positive numbers are greater than negative numbers
                }
            }

            (NegInt(a), PosInt(b)) => {
                if let Ok(a_as_u64) = u64::try_from(*a) {
                    a_as_u64.partial_cmp(b)
                } else {
                    Some(Ordering::Less) // Negative numbers are less than positive numbers
                }
            }

            (PosInt(a), Float(b)) => (*a as f64).partial_cmp(b),

            (Float(a), PosInt(b)) => a.partial_cmp(&(*b as f64)),

            (NegInt(a), Float(b)) => (*a as f64).partial_cmp(b),

            (Float(a), NegInt(b)) => a.partial_cmp(&(*b as f64)),
        }
    }
}

// Similarly, auto-derived PartialEq fails if types don't match
// and therefore custom impl
// There is a high chance two variables can be inferred S32(1) and U32(1)
impl PartialEq for CoercedNumericValue {
    fn eq(&self, other: &Self) -> bool {
        use CoercedNumericValue::*;
        match (self, other) {
            (PosInt(a), PosInt(b)) => a == b,
            (NegInt(a), NegInt(b)) => a == b,
            (Float(a), Float(b)) => a == b,

            // Comparing PosInt with NegInt
            (PosInt(a), NegInt(b)) => {
                if let Ok(b_as_u64) = u64::try_from(*b) {
                    a == &b_as_u64
                } else {
                    false
                }
            }

            // Comparing NegInt with PosInt
            (NegInt(a), PosInt(b)) => {
                if let Ok(a_as_u64) = u64::try_from(*a) {
                    &a_as_u64 == b
                } else {
                    false
                }
            }

            // Comparing PosInt with Float
            (PosInt(a), Float(b)) => (*a as f64) == *b,

            // Comparing Float with PosInt
            (Float(a), PosInt(b)) => *a == (*b as f64),

            // Comparing NegInt with Float
            (NegInt(a), Float(b)) => (*a as f64) == *b,

            // Comparing Float with NegInt
            (Float(a), NegInt(b)) => *a == (*b as f64),
        }
    }
}

impl Display for CoercedNumericValue {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            CoercedNumericValue::PosInt(value) => write!(f, "{value}"),
            CoercedNumericValue::NegInt(value) => write!(f, "{value}"),
            CoercedNumericValue::Float(value) => write!(f, "{value}"),
        }
    }
}

impl Display for LiteralValue {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            LiteralValue::Num(number) => write!(f, "{number}"),
            LiteralValue::String(value) => write!(f, "{value}"),
            LiteralValue::Bool(value) => write!(f, "{value}"),
        }
    }
}

mod internal {
    use crate::interpreter::literal::CoercedNumericValue;
    use golem_wasm_rpc::{Value, ValueAndType};

    pub(crate) fn get_numeric_value(value_and_type: &ValueAndType) -> Option<CoercedNumericValue> {
        match &value_and_type.value {
            Value::S8(value) => Some(CoercedNumericValue::NegInt(*value as i64)),
            Value::S16(value) => Some(CoercedNumericValue::NegInt(*value as i64)),
            Value::S32(value) => Some(CoercedNumericValue::NegInt(*value as i64)),
            Value::S64(value) => Some(CoercedNumericValue::NegInt(*value)),
            Value::U8(value) => Some(CoercedNumericValue::PosInt(*value as u64)),
            Value::U16(value) => Some(CoercedNumericValue::PosInt(*value as u64)),
            Value::U32(value) => Some(CoercedNumericValue::PosInt(*value as u64)),
            Value::U64(value) => Some(CoercedNumericValue::PosInt(*value)),
            Value::F32(value) => Some(CoercedNumericValue::Float(*value as f64)),
            Value::F64(value) => Some(CoercedNumericValue::Float(*value)),
            _ => None,
        }
    }
}