Skip to main content

lisette_syntax/program/
go_interop.rs

1use super::Definition;
2use crate::types::{self, CompoundKind, Type, TypeKind};
3
4#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
6pub enum GoHint {
7    AnonStruct,
8    BitFlagSet,
9    ClosedDomain,
10    CollapsedTypeParams,
11    CommaOk,
12    ComparableIf,
13    Constraint,
14    HiddenEmbed,
15    HiddenFields,
16    Incomparable,
17    ReadOnly,
18    SentinelMinusOne,
19    Skipped,
20    SupersededBy,
21    TypeTerms,
22    Unexported,
23    ValueMethodSet,
24    ZeroSafe,
25    ZeroUnsafe,
26}
27impl GoHint {
28    pub fn parse(name: &str) -> Option<Self> {
29        Some(match name {
30            "anon_struct" => Self::AnonStruct,
31            "bit_flag_set" => Self::BitFlagSet,
32            "closed_domain" => Self::ClosedDomain,
33            "collapsed_type_params" => Self::CollapsedTypeParams,
34            "comma_ok" => Self::CommaOk,
35            "comparable_if" => Self::ComparableIf,
36            "constraint" => Self::Constraint,
37            "hidden_embed" => Self::HiddenEmbed,
38            "hidden_fields" => Self::HiddenFields,
39            "incomparable" => Self::Incomparable,
40            "read_only" => Self::ReadOnly,
41            "sentinel_minus_one" => Self::SentinelMinusOne,
42            "skipped" => Self::Skipped,
43            "superseded_by" => Self::SupersededBy,
44            "type_terms" => Self::TypeTerms,
45            "unexported" => Self::Unexported,
46            "value_method_set" => Self::ValueMethodSet,
47            "zero_safe" => Self::ZeroSafe,
48            "zero_unsafe" => Self::ZeroUnsafe,
49            _ => return None,
50        })
51    }
52}
53
54#[derive(Debug, Clone, Copy, PartialEq, Eq)]
55pub enum GoReturnContract {
56    Value,
57    Error,
58    Result,
59    Partial,
60    CommaOk,
61    Nullable,
62    Sentinel(i64),
63    Tuple(usize),
64}
65
66pub fn go_return_contract<'a>(
67    ty: &Type,
68    hints: &[GoHint],
69    lookup: impl Fn(&str) -> Option<&'a Definition>,
70) -> GoReturnContract {
71    let ty = &ty.without_spelling();
72    if ty.is_partial() {
73        return GoReturnContract::Partial;
74    }
75    if ty.is_result() {
76        return if ty.ok_type().is_unit() {
77            GoReturnContract::Error
78        } else {
79            GoReturnContract::Result
80        };
81    }
82    if ty.is_option() {
83        if hints.contains(&GoHint::SentinelMinusOne) {
84            return GoReturnContract::Sentinel(-1);
85        }
86        return if hints.contains(&GoHint::CommaOk)
87            || !types::is_nilable_go_type(&ty.ok_type(), lookup)
88        {
89            GoReturnContract::CommaOk
90        } else {
91            GoReturnContract::Nullable
92        };
93    }
94    match ty.tuple_arity() {
95        Some(arity) if arity >= 2 => GoReturnContract::Tuple(arity),
96        _ => GoReturnContract::Value,
97    }
98}
99
100#[derive(Debug, Clone, Copy, PartialEq, Eq)]
101pub enum GoReturnForm {
102    Void,
103    Value,
104    NullableOption,
105    CommaOkOption,
106    Result,
107    BareError,
108    Partial,
109    Tuple(usize),
110}
111
112pub fn go_return_form<'a>(
113    return_ty: &Type,
114    lookup: impl Fn(&str) -> Option<&'a Definition>,
115) -> GoReturnForm {
116    let peeled = return_ty.without_spelling();
117    let err_is_nilable = || {
118        let err = peeled.err_type();
119        err.is_prelude_error() || types::is_nilable_go_type(&err, &lookup)
120    };
121    match go_return_contract(&peeled, &[], &lookup) {
122        GoReturnContract::Error if err_is_nilable() => GoReturnForm::BareError,
123        GoReturnContract::Result if err_is_nilable() => GoReturnForm::Result,
124        GoReturnContract::Partial if err_is_nilable() => GoReturnForm::Partial,
125        GoReturnContract::Nullable => GoReturnForm::NullableOption,
126        GoReturnContract::CommaOk => GoReturnForm::CommaOkOption,
127        GoReturnContract::Tuple(arity) => GoReturnForm::Tuple(arity),
128        _ if peeled.is_unit() || peeled.is_never() => GoReturnForm::Void,
129        _ => GoReturnForm::Value,
130    }
131}
132
133#[derive(Debug, Clone)]
134pub struct GoInteropContract {
135    pub declared: Type,
136    pub instantiated: Type,
137    pub hints: Vec<GoHint>,
138}
139impl GoInteropContract {
140    pub fn new(declared: &Type, instantiated: &Type, hints: &[GoHint]) -> Self {
141        Self {
142            declared: declared.clone(),
143            instantiated: instantiated.clone(),
144            hints: hints.to_vec(),
145        }
146    }
147    pub fn return_contract<'a>(
148        &self,
149        lookup: impl Fn(&str) -> Option<&'a Definition>,
150    ) -> GoReturnContract {
151        self.declared
152            .get_function_ret()
153            .map_or(GoReturnContract::Value, |ty| {
154                go_return_contract(ty, &self.hints, lookup)
155            })
156    }
157    pub fn permits_nullable_lift<'a>(
158        &self,
159        implementation_return: &Type,
160        lookup: impl Fn(&str) -> Option<&'a Definition>,
161    ) -> bool {
162        let Some(required) = self.instantiated.get_function_ret() else {
163            return false;
164        };
165        required.is_option()
166            && required.ok_type() == *implementation_return
167            && self.return_contract(lookup) == GoReturnContract::Nullable
168    }
169}
170
171#[derive(Debug, Clone, Copy, PartialEq, Eq)]
172pub enum SlotOrigin {
173    Lisette,
174    GoParameter,
175    GoReturn,
176    GoField,
177    GoAny,
178}
179
180impl SlotOrigin {
181    pub fn of_go_declaration(origin: Self, declared: &Type) -> Self {
182        let slot = match declared.as_compound() {
183            Some((CompoundKind::VarArgs, [element])) => element,
184            _ => declared,
185        };
186        if slot.is_unknown() {
187            Self::GoAny
188        } else {
189            origin
190        }
191    }
192
193    pub fn nested(self) -> Self {
194        if matches!(self, Self::GoAny) {
195            Self::Lisette
196        } else {
197            self
198        }
199    }
200
201    pub fn declared_by_go(self) -> bool {
202        matches!(self, Self::GoParameter | Self::GoReturn | Self::GoField)
203    }
204}
205
206#[derive(Debug, Clone, Copy, PartialEq, Eq)]
207pub enum GoOptionRepresentation {
208    Tagged,
209    Nullable,
210    Pointer,
211}
212
213pub fn go_option_representation<'a>(
214    ty: &Type,
215    origin: SlotOrigin,
216    lookup: impl Fn(&str) -> Option<&'a Definition>,
217) -> GoOptionRepresentation {
218    if !origin.declared_by_go() || !ty.is_option() {
219        return GoOptionRepresentation::Tagged;
220    }
221    let inner = ty.ok_type();
222    if types::is_nilable_go_type(&inner, &lookup) {
223        GoOptionRepresentation::Nullable
224    } else if types::contains_unknown(&inner) || inner.has_name("any") {
225        GoOptionRepresentation::Tagged
226    } else {
227        GoOptionRepresentation::Pointer
228    }
229}
230
231pub fn go_boundary_converts_container<'a>(
232    ty: &Type,
233    origin: SlotOrigin,
234    lookup: impl Fn(&str) -> Option<&'a Definition>,
235) -> bool {
236    fn converts<'a>(
237        ty: &Type,
238        origin: SlotOrigin,
239        lookup: &impl Fn(&str) -> Option<&'a Definition>,
240    ) -> bool {
241        let ty = ty.without_spelling();
242        if ty.is_option() {
243            return go_option_representation(&ty, origin, lookup) != GoOptionRepresentation::Tagged;
244        }
245        match ty.kind() {
246            TypeKind::Compound {
247                kind: CompoundKind::Slice | CompoundKind::EnumeratedSlice | CompoundKind::Map,
248                args: arguments,
249                ..
250            } => arguments.iter().any(|ty| converts(ty, origin, lookup)),
251            TypeKind::Array { element, .. } => converts(element, origin, lookup),
252            _ => false,
253        }
254    }
255    converts(ty, origin, &lookup)
256}
257
258#[derive(Debug, Clone, PartialEq, Eq)]
259#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
260pub enum GoTypeRecipe {
261    Parameter(String),
262    Slice(Box<GoTypeRecipe>),
263    Map(Box<GoTypeRecipe>, Box<GoTypeRecipe>),
264    Array(Box<GoTypeRecipe>, u64),
265}
266impl GoTypeRecipe {
267    pub fn parse_list(input: &str) -> Option<Vec<Self>> {
268        let mut depth = 0u32;
269        let mut start = 0;
270        let mut entries = Vec::new();
271        for (index, character) in input.char_indices() {
272            match character {
273                '<' => depth += 1,
274                '>' => depth = depth.checked_sub(1)?,
275                ',' if depth == 0 => {
276                    entries.push(Self::parse(&input[start..index])?);
277                    start = index + 1;
278                }
279                _ => {}
280            }
281        }
282        if depth != 0 {
283            return None;
284        }
285        entries.push(Self::parse(&input[start..])?);
286        Some(entries)
287    }
288    fn parse(input: &str) -> Option<Self> {
289        let input = input.trim();
290        if let Some((name, arguments)) = input.split_once('<') {
291            let arguments = arguments.strip_suffix('>')?;
292            return match name.trim() {
293                "Slice" => {
294                    let mut arguments = Self::parse_list(arguments)?;
295                    (arguments.len() == 1).then(|| Self::Slice(Box::new(arguments.remove(0))))
296                }
297                "Map" => {
298                    let mut arguments = Self::parse_list(arguments)?;
299                    (arguments.len() == 2).then(|| {
300                        Self::Map(Box::new(arguments.remove(0)), Box::new(arguments.remove(0)))
301                    })
302                }
303                "Array" => {
304                    let (element, length) = arguments.rsplit_once(',')?;
305                    Some(Self::Array(
306                        Box::new(Self::parse(element)?),
307                        length.trim().parse().ok()?,
308                    ))
309                }
310                _ => None,
311            };
312        }
313        let mut chars = input.chars();
314        if !chars
315            .next()
316            .is_some_and(|character| character == '_' || character.is_alphabetic())
317            || !chars.all(|character| character == '_' || character.is_alphanumeric())
318        {
319            return None;
320        }
321        Some(Self::Parameter(input.to_string()))
322    }
323}
324
325#[derive(Debug, Clone, PartialEq)]
326#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
327pub struct GoTypeTerm {
328    pub tilde: bool,
329    pub ty: Type,
330}
331
332#[derive(Debug, Clone, PartialEq)]
333#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
334pub struct GoTypeTerms {
335    pub parameter: ecow::EcoString,
336    pub terms: Vec<GoTypeTerm>,
337}
338
339impl GoTypeTerms {
340    pub fn parse_list(input: &str) -> Option<Vec<Self>> {
341        input.split(';').map(Self::parse).collect()
342    }
343
344    fn parse(input: &str) -> Option<Self> {
345        let (parameter, terms) = input.split_once(':')?;
346        let terms = terms
347            .split('|')
348            .map(|term| {
349                let term = term.trim();
350                let (tilde, ty) = term
351                    .strip_prefix('~')
352                    .map_or((false, term), |rest| (true, rest));
353                Some(GoTypeTerm {
354                    tilde,
355                    ty: parse_term_type(ty)?,
356                })
357            })
358            .collect::<Option<Vec<_>>>()?;
359        Some(Self {
360            parameter: parameter.trim().into(),
361            terms,
362        })
363    }
364
365    pub fn display_terms(&self) -> String {
366        self.terms
367            .iter()
368            .map(|term| format!("{}{}", if term.tilde { "~" } else { "" }, term.ty))
369            .collect::<Vec<_>>()
370            .join(" | ")
371    }
372}
373
374fn parse_term_type(input: &str) -> Option<Type> {
375    let input = input.trim();
376    let Some((name, arguments)) = input.split_once('<') else {
377        return types::SimpleKind::from_name(input)
378            .filter(|kind| *kind != types::SimpleKind::Unit)
379            .map(Type::simple);
380    };
381    let arguments = split_top_level(arguments.strip_suffix('>')?)?;
382    let compound = |kind, arguments: &[&str]| {
383        Some(
384            TypeKind::Compound {
385                kind,
386                args: arguments
387                    .iter()
388                    .map(|argument| parse_term_type(argument))
389                    .collect::<Option<_>>()?,
390                writable: false,
391            }
392            .into(),
393        )
394    };
395    match (name.trim(), arguments.as_slice()) {
396        ("Slice", [_]) => compound(CompoundKind::Slice, &arguments),
397        ("Ref", [_]) => compound(CompoundKind::Ref, &arguments),
398        ("Map", [_, _]) => compound(CompoundKind::Map, &arguments),
399        ("Array", [element, length]) => Some(
400            TypeKind::Array {
401                length: length.trim().parse().ok()?,
402                element: Box::new(parse_term_type(element)?),
403            }
404            .into(),
405        ),
406        _ => None,
407    }
408}
409
410fn split_top_level(input: &str) -> Option<Vec<&str>> {
411    let mut depth = 0u32;
412    let mut start = 0;
413    let mut parts = Vec::new();
414    for (index, character) in input.char_indices() {
415        match character {
416            '<' => depth += 1,
417            '>' => depth = depth.checked_sub(1)?,
418            ',' if depth == 0 => {
419                parts.push(&input[start..index]);
420                start = index + 1;
421            }
422            _ => {}
423        }
424    }
425    parts.push(&input[start..]);
426    (depth == 0).then_some(parts)
427}
428
429#[cfg(test)]
430mod tests {
431    use super::*;
432    use crate::types::TypeList;
433    #[test]
434    fn option_conversion_respects_slot_origin_and_payload_representation() {
435        use crate::types::CompoundKind;
436        let reference: Type = TypeKind::Compound {
437            kind: CompoundKind::Ref,
438            args: vec![Type::int()].into(),
439            writable: false,
440        }
441        .into();
442        for origin in [
443            SlotOrigin::GoParameter,
444            SlotOrigin::GoReturn,
445            SlotOrigin::GoField,
446        ] {
447            assert_eq!(
448                go_option_representation(&Type::option_of(reference.clone()), origin, |_| None),
449                GoOptionRepresentation::Nullable
450            );
451            assert_eq!(
452                go_option_representation(&Type::option_of(Type::int()), origin, |_| None),
453                GoOptionRepresentation::Pointer
454            );
455            assert_eq!(
456                go_option_representation(
457                    &Type::option_of(
458                        TypeKind::Nominal {
459                            id: types::Symbol::from_raw("prelude.Unknown"),
460                            params: TypeList::new(),
461                            writable: false
462                        }
463                        .into()
464                    ),
465                    origin,
466                    |_| None
467                ),
468                GoOptionRepresentation::Tagged
469            );
470        }
471        for origin in [SlotOrigin::Lisette, SlotOrigin::GoAny] {
472            assert_eq!(
473                go_option_representation(&Type::option_of(reference.clone()), origin, |_| None),
474                GoOptionRepresentation::Tagged
475            );
476        }
477        let container: Type = TypeKind::Compound {
478            kind: CompoundKind::Slice,
479            args: vec![Type::option_of(reference)].into(),
480            writable: true,
481        }
482        .into();
483        assert!(go_boundary_converts_container(
484            &container,
485            SlotOrigin::GoField,
486            |_| None
487        ));
488        assert!(!go_boundary_converts_container(
489            &container,
490            SlotOrigin::Lisette,
491            |_| None
492        ));
493    }
494
495    #[test]
496    fn nested_recipes_are_checked_at_registration_boundary() {
497        let recipe = GoTypeRecipe::parse_list("Map<K, Slice<Array<V, 2>>>, K, V").unwrap();
498        assert_eq!(recipe.len(), 3);
499        assert!(
500            matches!(&recipe[0], GoTypeRecipe::Map(_, value) if matches!(value.as_ref(), GoTypeRecipe::Slice(_)))
501        );
502        for invalid in [
503            "",
504            "Map<K>",
505            "Slice<T>>",
506            "Array<T, -1>",
507            "Unknown<T>",
508            "T,",
509            "Slice<>",
510        ] {
511            assert!(GoTypeRecipe::parse_list(invalid).is_none(), "{invalid}");
512        }
513    }
514}