use super::Definition;
use crate::types::{self, CompoundKind, Type, TypeKind};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum GoHint {
AnonStruct,
BitFlagSet,
ClosedDomain,
CollapsedTypeParams,
CommaOk,
ComparableIf,
Constraint,
HiddenEmbed,
HiddenFields,
Incomparable,
ReadOnly,
SentinelMinusOne,
Skipped,
SupersededBy,
TypeTerms,
Unexported,
ValueMethodSet,
ZeroSafe,
ZeroUnsafe,
}
impl GoHint {
pub fn parse(name: &str) -> Option<Self> {
Some(match name {
"anon_struct" => Self::AnonStruct,
"bit_flag_set" => Self::BitFlagSet,
"closed_domain" => Self::ClosedDomain,
"collapsed_type_params" => Self::CollapsedTypeParams,
"comma_ok" => Self::CommaOk,
"comparable_if" => Self::ComparableIf,
"constraint" => Self::Constraint,
"hidden_embed" => Self::HiddenEmbed,
"hidden_fields" => Self::HiddenFields,
"incomparable" => Self::Incomparable,
"read_only" => Self::ReadOnly,
"sentinel_minus_one" => Self::SentinelMinusOne,
"skipped" => Self::Skipped,
"superseded_by" => Self::SupersededBy,
"type_terms" => Self::TypeTerms,
"unexported" => Self::Unexported,
"value_method_set" => Self::ValueMethodSet,
"zero_safe" => Self::ZeroSafe,
"zero_unsafe" => Self::ZeroUnsafe,
_ => return None,
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GoReturnContract {
Value,
Error,
Result,
Partial,
CommaOk,
Nullable,
Sentinel(i64),
Tuple(usize),
}
pub fn go_return_contract<'a>(
ty: &Type,
hints: &[GoHint],
lookup: impl Fn(&str) -> Option<&'a Definition>,
) -> GoReturnContract {
let ty = &ty.without_spelling();
if ty.is_partial() {
return GoReturnContract::Partial;
}
if ty.is_result() {
return if ty.ok_type().is_unit() {
GoReturnContract::Error
} else {
GoReturnContract::Result
};
}
if ty.is_option() {
if hints.contains(&GoHint::SentinelMinusOne) {
return GoReturnContract::Sentinel(-1);
}
return if hints.contains(&GoHint::CommaOk)
|| !types::is_nilable_go_type(&ty.ok_type(), lookup)
{
GoReturnContract::CommaOk
} else {
GoReturnContract::Nullable
};
}
match ty.tuple_arity() {
Some(arity) if arity >= 2 => GoReturnContract::Tuple(arity),
_ => GoReturnContract::Value,
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GoReturnForm {
Void,
Value,
NullableOption,
CommaOkOption,
Result,
BareError,
Partial,
Tuple(usize),
}
pub fn go_return_form<'a>(
return_ty: &Type,
lookup: impl Fn(&str) -> Option<&'a Definition>,
) -> GoReturnForm {
let peeled = return_ty.without_spelling();
let err_is_nilable = || {
let err = peeled.err_type();
err.is_prelude_error() || types::is_nilable_go_type(&err, &lookup)
};
match go_return_contract(&peeled, &[], &lookup) {
GoReturnContract::Error if err_is_nilable() => GoReturnForm::BareError,
GoReturnContract::Result if err_is_nilable() => GoReturnForm::Result,
GoReturnContract::Partial if err_is_nilable() => GoReturnForm::Partial,
GoReturnContract::Nullable => GoReturnForm::NullableOption,
GoReturnContract::CommaOk => GoReturnForm::CommaOkOption,
GoReturnContract::Tuple(arity) => GoReturnForm::Tuple(arity),
_ if peeled.is_unit() || peeled.is_never() => GoReturnForm::Void,
_ => GoReturnForm::Value,
}
}
#[derive(Debug, Clone)]
pub struct GoInteropContract {
pub declared: Type,
pub instantiated: Type,
pub hints: Vec<GoHint>,
}
impl GoInteropContract {
pub fn new(declared: &Type, instantiated: &Type, hints: &[GoHint]) -> Self {
Self {
declared: declared.clone(),
instantiated: instantiated.clone(),
hints: hints.to_vec(),
}
}
pub fn return_contract<'a>(
&self,
lookup: impl Fn(&str) -> Option<&'a Definition>,
) -> GoReturnContract {
self.declared
.get_function_ret()
.map_or(GoReturnContract::Value, |ty| {
go_return_contract(ty, &self.hints, lookup)
})
}
pub fn permits_nullable_lift<'a>(
&self,
implementation_return: &Type,
lookup: impl Fn(&str) -> Option<&'a Definition>,
) -> bool {
let Some(required) = self.instantiated.get_function_ret() else {
return false;
};
required.is_option()
&& required.ok_type() == *implementation_return
&& self.return_contract(lookup) == GoReturnContract::Nullable
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SlotOrigin {
Lisette,
GoParameter,
GoReturn,
GoField,
GoAny,
}
impl SlotOrigin {
pub fn of_go_declaration(origin: Self, declared: &Type) -> Self {
let slot = match declared.as_compound() {
Some((CompoundKind::VarArgs, [element])) => element,
_ => declared,
};
if slot.is_unknown() {
Self::GoAny
} else {
origin
}
}
pub fn nested(self) -> Self {
if matches!(self, Self::GoAny) {
Self::Lisette
} else {
self
}
}
pub fn declared_by_go(self) -> bool {
matches!(self, Self::GoParameter | Self::GoReturn | Self::GoField)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GoOptionRepresentation {
Tagged,
Nullable,
Pointer,
}
pub fn go_option_representation<'a>(
ty: &Type,
origin: SlotOrigin,
lookup: impl Fn(&str) -> Option<&'a Definition>,
) -> GoOptionRepresentation {
if !origin.declared_by_go() || !ty.is_option() {
return GoOptionRepresentation::Tagged;
}
let inner = ty.ok_type();
if types::is_nilable_go_type(&inner, &lookup) {
GoOptionRepresentation::Nullable
} else if types::contains_unknown(&inner) || inner.has_name("any") {
GoOptionRepresentation::Tagged
} else {
GoOptionRepresentation::Pointer
}
}
pub fn go_boundary_converts_container<'a>(
ty: &Type,
origin: SlotOrigin,
lookup: impl Fn(&str) -> Option<&'a Definition>,
) -> bool {
fn converts<'a>(
ty: &Type,
origin: SlotOrigin,
lookup: &impl Fn(&str) -> Option<&'a Definition>,
) -> bool {
let ty = ty.without_spelling();
if ty.is_option() {
return go_option_representation(&ty, origin, lookup) != GoOptionRepresentation::Tagged;
}
match ty.kind() {
TypeKind::Compound {
kind: CompoundKind::Slice | CompoundKind::EnumeratedSlice | CompoundKind::Map,
args: arguments,
..
} => arguments.iter().any(|ty| converts(ty, origin, lookup)),
TypeKind::Array { element, .. } => converts(element, origin, lookup),
_ => false,
}
}
converts(ty, origin, &lookup)
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum GoTypeRecipe {
Parameter(String),
Slice(Box<GoTypeRecipe>),
Map(Box<GoTypeRecipe>, Box<GoTypeRecipe>),
Array(Box<GoTypeRecipe>, u64),
}
impl GoTypeRecipe {
pub fn parse_list(input: &str) -> Option<Vec<Self>> {
let mut depth = 0u32;
let mut start = 0;
let mut entries = Vec::new();
for (index, character) in input.char_indices() {
match character {
'<' => depth += 1,
'>' => depth = depth.checked_sub(1)?,
',' if depth == 0 => {
entries.push(Self::parse(&input[start..index])?);
start = index + 1;
}
_ => {}
}
}
if depth != 0 {
return None;
}
entries.push(Self::parse(&input[start..])?);
Some(entries)
}
fn parse(input: &str) -> Option<Self> {
let input = input.trim();
if let Some((name, arguments)) = input.split_once('<') {
let arguments = arguments.strip_suffix('>')?;
return match name.trim() {
"Slice" => {
let mut arguments = Self::parse_list(arguments)?;
(arguments.len() == 1).then(|| Self::Slice(Box::new(arguments.remove(0))))
}
"Map" => {
let mut arguments = Self::parse_list(arguments)?;
(arguments.len() == 2).then(|| {
Self::Map(Box::new(arguments.remove(0)), Box::new(arguments.remove(0)))
})
}
"Array" => {
let (element, length) = arguments.rsplit_once(',')?;
Some(Self::Array(
Box::new(Self::parse(element)?),
length.trim().parse().ok()?,
))
}
_ => None,
};
}
let mut chars = input.chars();
if !chars
.next()
.is_some_and(|character| character == '_' || character.is_alphabetic())
|| !chars.all(|character| character == '_' || character.is_alphanumeric())
{
return None;
}
Some(Self::Parameter(input.to_string()))
}
}
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct GoTypeTerm {
pub tilde: bool,
pub ty: Type,
}
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct GoTypeTerms {
pub parameter: ecow::EcoString,
pub terms: Vec<GoTypeTerm>,
}
impl GoTypeTerms {
pub fn parse_list(input: &str) -> Option<Vec<Self>> {
input.split(';').map(Self::parse).collect()
}
fn parse(input: &str) -> Option<Self> {
let (parameter, terms) = input.split_once(':')?;
let terms = terms
.split('|')
.map(|term| {
let term = term.trim();
let (tilde, ty) = term
.strip_prefix('~')
.map_or((false, term), |rest| (true, rest));
Some(GoTypeTerm {
tilde,
ty: parse_term_type(ty)?,
})
})
.collect::<Option<Vec<_>>>()?;
Some(Self {
parameter: parameter.trim().into(),
terms,
})
}
pub fn display_terms(&self) -> String {
self.terms
.iter()
.map(|term| format!("{}{}", if term.tilde { "~" } else { "" }, term.ty))
.collect::<Vec<_>>()
.join(" | ")
}
}
fn parse_term_type(input: &str) -> Option<Type> {
let input = input.trim();
let Some((name, arguments)) = input.split_once('<') else {
return types::SimpleKind::from_name(input)
.filter(|kind| *kind != types::SimpleKind::Unit)
.map(Type::simple);
};
let arguments = split_top_level(arguments.strip_suffix('>')?)?;
let compound = |kind, arguments: &[&str]| {
Some(
TypeKind::Compound {
kind,
args: arguments
.iter()
.map(|argument| parse_term_type(argument))
.collect::<Option<_>>()?,
writable: false,
}
.into(),
)
};
match (name.trim(), arguments.as_slice()) {
("Slice", [_]) => compound(CompoundKind::Slice, &arguments),
("Ref", [_]) => compound(CompoundKind::Ref, &arguments),
("Map", [_, _]) => compound(CompoundKind::Map, &arguments),
("Array", [element, length]) => Some(
TypeKind::Array {
length: length.trim().parse().ok()?,
element: Box::new(parse_term_type(element)?),
}
.into(),
),
_ => None,
}
}
fn split_top_level(input: &str) -> Option<Vec<&str>> {
let mut depth = 0u32;
let mut start = 0;
let mut parts = Vec::new();
for (index, character) in input.char_indices() {
match character {
'<' => depth += 1,
'>' => depth = depth.checked_sub(1)?,
',' if depth == 0 => {
parts.push(&input[start..index]);
start = index + 1;
}
_ => {}
}
}
parts.push(&input[start..]);
(depth == 0).then_some(parts)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::types::TypeList;
#[test]
fn option_conversion_respects_slot_origin_and_payload_representation() {
use crate::types::CompoundKind;
let reference: Type = TypeKind::Compound {
kind: CompoundKind::Ref,
args: vec![Type::int()].into(),
writable: false,
}
.into();
for origin in [
SlotOrigin::GoParameter,
SlotOrigin::GoReturn,
SlotOrigin::GoField,
] {
assert_eq!(
go_option_representation(&Type::option_of(reference.clone()), origin, |_| None),
GoOptionRepresentation::Nullable
);
assert_eq!(
go_option_representation(&Type::option_of(Type::int()), origin, |_| None),
GoOptionRepresentation::Pointer
);
assert_eq!(
go_option_representation(
&Type::option_of(
TypeKind::Nominal {
id: types::Symbol::from_raw("prelude.Unknown"),
params: TypeList::new(),
writable: false
}
.into()
),
origin,
|_| None
),
GoOptionRepresentation::Tagged
);
}
for origin in [SlotOrigin::Lisette, SlotOrigin::GoAny] {
assert_eq!(
go_option_representation(&Type::option_of(reference.clone()), origin, |_| None),
GoOptionRepresentation::Tagged
);
}
let container: Type = TypeKind::Compound {
kind: CompoundKind::Slice,
args: vec![Type::option_of(reference)].into(),
writable: true,
}
.into();
assert!(go_boundary_converts_container(
&container,
SlotOrigin::GoField,
|_| None
));
assert!(!go_boundary_converts_container(
&container,
SlotOrigin::Lisette,
|_| None
));
}
#[test]
fn nested_recipes_are_checked_at_registration_boundary() {
let recipe = GoTypeRecipe::parse_list("Map<K, Slice<Array<V, 2>>>, K, V").unwrap();
assert_eq!(recipe.len(), 3);
assert!(
matches!(&recipe[0], GoTypeRecipe::Map(_, value) if matches!(value.as_ref(), GoTypeRecipe::Slice(_)))
);
for invalid in [
"",
"Map<K>",
"Slice<T>>",
"Array<T, -1>",
"Unknown<T>",
"T,",
"Slice<>",
] {
assert!(GoTypeRecipe::parse_list(invalid).is_none(), "{invalid}");
}
}
}