use super::{CodecTarget, Constant, Handle, Handoff, Routine, Scalar};
use crate::adapter::go::{
field_name, go_map_entry_name, go_type_name, go_value_type, module_prefix,
};
use crate::encode::EncodeError;
use zerodds_ast::{Ast, CharWidth, MemberNode, TypeKind, TypeNode};
use zerodds_ast_core::Id;
use zerodds_lang_cst::common::{Doc, Ident, Literal};
use zerodds_lang_cst::go;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Go;
const MAX_TYPE_DEPTH: usize = 64;
const RUNTIME: &str = "zdwire";
const SIGNED_CHAR: &str = "signed char";
#[derive(Debug, Clone)]
pub enum GoExpr {
Plain(go::Expr),
OptionalSlot(go::Expr),
}
fn inner(expr: GoExpr) -> go::Expr {
match expr {
GoExpr::Plain(e) | GoExpr::OptionalSlot(e) => e,
}
}
fn plain(e: go::Expr) -> GoExpr {
GoExpr::Plain(e)
}
impl Go {
fn runtime_name(name: &str) -> go::Expr {
go::Expr::selector(go::Expr::name(RUNTIME), name)
}
fn pascal(method: &str) -> String {
let mut out = String::new();
for segment in method.split('_') {
let mut chars = segment.chars();
if let Some(first) = chars.next() {
out.extend(first.to_uppercase());
out.push_str(chars.as_str());
}
}
out
}
fn text(value: &str) -> GoExpr {
plain(go::Expr::Literal(Literal::Str(value.to_string())))
}
fn runtime_constant(name: &str) -> GoExpr {
plain(Self::runtime_name(name))
}
}
impl CodecTarget for Go {
type Expr = GoExpr;
type Stmt = go::Stmt;
type Block = Vec<go::Stmt>;
type Type = go::Type;
type Decl = go::Decl;
fn scalar(kind: Scalar) -> Self::Type {
match kind {
Scalar::Bool => go::Type::Primitive(go::Primitive::Bool),
Scalar::Char => go::Type::Primitive(go::Primitive::UInt8),
Scalar::Int8 => go::Type::Primitive(go::Primitive::Int8),
Scalar::Int16 => go::Type::Primitive(go::Primitive::Int16),
Scalar::Int32 => go::Type::Primitive(go::Primitive::Int32),
Scalar::Int64 => go::Type::Primitive(go::Primitive::Int64),
Scalar::UInt8 => go::Type::Primitive(go::Primitive::UInt8),
Scalar::UInt16 => go::Type::Primitive(go::Primitive::UInt16),
Scalar::UInt32 | Scalar::Index => go::Type::Primitive(go::Primitive::UInt32),
Scalar::UInt64 => go::Type::Primitive(go::Primitive::UInt64),
Scalar::Float => go::Type::Primitive(go::Primitive::Float32),
Scalar::Double => go::Type::Primitive(go::Primitive::Float64),
Scalar::LongDouble => go::Type::Primitive(go::Primitive::String),
Scalar::Size => go::Type::named("int"),
}
}
fn named(name: &str) -> Self::Type {
go::Type::named(name)
}
fn nothing() -> Self::Type {
go::Type::named("")
}
fn handle(kind: Handle) -> Self::Type {
go::Type::named(match kind {
Handle::DHeader => "zdwire.DHeader",
Handle::EmHeader => "zdwire.EmHeader",
Handle::Pid => "zdwire.Pid",
Handle::TryConstruct => "zdwire.TryConstruct",
Handle::ReaderMark => "zdwire.ReaderMark",
Handle::PidRead => "zdwire.PidRead",
Handle::EmHeaderRead => "zdwire.EmHeaderRead",
})
}
fn code_point(value: Self::Expr, _narrow: bool) -> Self::Expr {
value
}
fn constant(which: Constant) -> Self::Expr {
match which {
Constant::WcharWidth2 => plain(go::Expr::int(2)),
Constant::WcharWidth4 => plain(go::Expr::int(4)),
Constant::WcharFixed => Self::text("fixed"),
Constant::WcharGiopLengthPrefixed => Self::text("giop-length-prefixed"),
Constant::WstringUnitsStream => Self::text("stream"),
Constant::WstringUnitsBigEndianAlways => Self::text("big-endian-always"),
Constant::WstringUnitsByteOrderMark => Self::text("byte-order-mark"),
Constant::WstringUnitsHostUnswapped => Self::text("host-unswapped"),
Constant::WstringSpecification => Self::text("specification"),
Constant::WstringCharacterCount => Self::text("character-count"),
Constant::WstringCharacterCountTerminated => Self::text("character-count-terminated"),
Constant::WstringSpecificationWideUnits => Self::text("specification-wide-units"),
Constant::WstringRosTypeSupport => Self::text("ros-type-support"),
Constant::WstringOctetsTerminated2 => Self::text("octets/terminated/2"),
Constant::WstringOctetsTerminated4 => Self::text("octets/terminated/4"),
Constant::WstringCharactersTerminated2 => Self::text("characters/terminated/2"),
Constant::FixedDeclared => Self::text("declared"),
Constant::FixedValuePrecision => Self::text("value-precision"),
Constant::FixedValueStringDigits => Self::text("value-string-digits"),
Constant::ParameterMember => Self::runtime_constant("ParameterMember"),
Constant::ParameterOptional => Self::runtime_constant("ParameterOptional"),
Constant::TryConstructDiscard => Self::runtime_constant("TryConstructDiscard"),
Constant::TryConstructTrim => Self::runtime_constant("TryConstructTrim"),
Constant::TryConstructUseDefault => Self::runtime_constant("TryConstructUseDefault"),
Constant::StatusOk => Self::runtime_constant("StatusOk"),
Constant::StatusDiscarded => Self::runtime_constant("StatusDiscarded"),
Constant::StatusImpossibleLength => Self::runtime_constant("StatusImpossibleLength"),
Constant::StatusOutOfRange => Self::runtime_constant("StatusOutOfRange"),
Constant::StatusTruncated => Self::runtime_constant("StatusTruncated"),
}
}
fn unsigned_holder(bits: u16) -> Self::Type {
go::Type::Primitive(crate::adapter::go::go_holder(bits))
}
fn value_type(ast: &Ast, id: Id<TypeNode>) -> Self::Type {
#[allow(clippy::manual_unwrap_or_default, clippy::manual_unwrap_or)]
match go_value_type(ast, id) {
Ok(type_) => type_,
Err(_) => go::Type::Primitive(go::Primitive::Any),
}
}
fn type_name(ast: &Ast, id: Id<TypeNode>) -> String {
type_tag(ast, id, 0)
}
fn map_entry_name(ast: &Ast, id: Id<TypeNode>) -> String {
go_map_entry_name(ast, id).unwrap_or_else(|_| format!("ZdUnresolvedEntry{}", id.slot()))
}
fn module_prefix(ast: &Ast, id: Id<TypeNode>) -> String {
module_prefix(ast, id)
}
fn escape(name: &str) -> String {
field_name(name)
}
fn inherited_path(depth: usize) -> Option<String> {
Some(format!("{}.", field_name("parent")).repeat(depth))
}
fn name(text: &str) -> Self::Expr {
plain(go::Expr::name(text))
}
fn int(value: i128) -> Self::Expr {
plain(go::Expr::int(value))
}
fn literal(value: Literal) -> Self::Expr {
let Literal::Int(text) = &value else {
return plain(go::Expr::Literal(value));
};
match text.as_str() {
"true" => plain(go::Expr::Literal(Literal::Bool(true))),
"false" => plain(go::Expr::Literal(Literal::Bool(false))),
_ => plain(go::Expr::Literal(value)),
}
}
fn wide_int(value: i128) -> Self::Expr {
plain(go::Expr::int(value))
}
fn unsigned_int(value: i128) -> Self::Expr {
plain(go::Expr::int(value))
}
fn wide_unsigned(value: u64) -> Self::Expr {
plain(go::Expr::Convert {
type_: Box::new(go::Type::Primitive(go::Primitive::UInt64)),
value: Box::new(go::Expr::int(i128::from(value))),
})
}
fn wide_signed(value: i128) -> Self::Expr {
plain(go::Expr::Convert {
type_: Box::new(go::Type::Primitive(go::Primitive::Int64)),
value: Box::new(go::Expr::int(value)),
})
}
fn member(base: &str, field: &str) -> Self::Expr {
let spelled = if field == "_d" { "D" } else { field };
plain(go::Expr::selector(go::Expr::name(base), spelled))
}
fn whole(base: &str) -> Self::Expr {
plain(go::Expr::name(base))
}
fn field_of(value: Self::Expr, field: &str) -> Self::Expr {
plain(go::Expr::selector(inner(value), field))
}
fn header_field(value: Self::Expr, field: &str) -> Self::Expr {
plain(go::Expr::selector(inner(value), &Self::pascal(field)))
}
fn index(value: Self::Expr, at: Self::Expr) -> Self::Expr {
plain(go::Expr::Index {
value: Box::new(inner(value)),
index: Box::new(inner(at)),
})
}
fn count_of(base: &str, fixed: Option<u64>) -> Self::Expr {
match fixed {
Some(bound) => plain(go::Expr::int(i128::from(bound))),
None => plain(go::Expr::Convert {
type_: Box::new(go::Type::Primitive(go::Primitive::UInt32)),
value: Box::new(go::Expr::call(
go::Expr::name("len"),
vec![go::Expr::name(base)],
)),
}),
}
}
fn elements(base: &str) -> Self::Expr {
plain(go::Expr::name(base))
}
fn case_member(base: &str, field: &str) -> Self::Expr {
Self::member(base, field)
}
fn entry_half(entry: Self::Expr, key: bool) -> Self::Expr {
plain(go::Expr::selector(
inner(entry),
if key { "Key" } else { "Value" },
))
}
fn absent() -> Self::Expr {
plain(go::Expr::Literal(Literal::Null))
}
fn materialised(_value: Self::Expr) -> Option<Self::Expr> {
None
}
fn optional_value(_ast: &Ast, _id: Id<TypeNode>, base: &str, field: &str) -> Self::Expr {
plain(go::Expr::Unary {
op: "*",
value: Box::new(inner(Self::member(base, field))),
})
}
fn present(base: &str, field: &str) -> Self::Expr {
plain(go::Expr::Binary {
op: "!=",
lhs: Box::new(inner(Self::member(base, field))),
rhs: Box::new(go::Expr::Literal(Literal::Null)),
})
}
fn set_present(base: &str, field: &str, present: bool) -> Vec<Self::Stmt> {
if present {
return Vec::new();
}
vec![go::Stmt::Assign {
place: inner(Self::member(base, field)),
value: go::Expr::Literal(Literal::Null),
}]
}
fn optional_destination(base: &str, field: &str) -> (Vec<Self::Stmt>, Self::Expr) {
(
Vec::new(),
GoExpr::OptionalSlot(inner(Self::member(base, field))),
)
}
fn binary(op: &'static str, lhs: Self::Expr, rhs: Self::Expr) -> Self::Expr {
plain(go::Expr::Binary {
op,
lhs: Box::new(inner(lhs)),
rhs: Box::new(inner(rhs)),
})
}
fn unary(op: &'static str, value: Self::Expr) -> Self::Expr {
plain(go::Expr::Unary {
op: match op {
"~" => "^",
other => other,
},
value: Box::new(inner(value)),
})
}
fn paren(value: Self::Expr) -> Self::Expr {
plain(go::Expr::Paren(Box::new(inner(value))))
}
fn bool_less(left: Self::Expr, right: Self::Expr) -> Self::Expr {
Self::binary("&&", Self::unary("!", Self::paren(left)), right)
}
fn cast(type_: Self::Type, value: Self::Expr) -> Self::Expr {
if type_ == go::Type::named(SIGNED_CHAR) {
return plain(go::Expr::Convert {
type_: Box::new(go::Type::Primitive(go::Primitive::Int8)),
value: Box::new(inner(value)),
});
}
if type_ == go::Type::Primitive(go::Primitive::Bool) {
if let GoExpr::Plain(go::Expr::Literal(Literal::Int(text))) = &value {
return plain(go::Expr::Literal(Literal::Bool(text != "0")));
}
}
plain(go::Expr::Convert {
type_: Box::new(type_),
value: Box::new(inner(value)),
})
}
fn handoff(value: Self::Expr, _form: Handoff) -> Self::Expr {
value
}
fn call(callee: &str, args: Vec<Self::Expr>) -> Self::Expr {
let arguments: Vec<go::Expr> = args.into_iter().map(inner).collect();
if callee == "strcmp" {
return plain(go::Expr::call(Self::runtime_name("Strcmp"), arguments));
}
plain(go::Expr::call(go::Expr::name(callee), arguments))
}
fn runtime(receiver: &str, method: &str, args: Vec<Self::Expr>) -> Self::Expr {
if method == "read_pid" && args.is_empty() {
return Self::runtime(
receiver,
"read_pid_as",
vec![Self::constant(Constant::ParameterMember)],
);
}
plain(go::Expr::call(
go::Expr::selector(go::Expr::name(receiver), &Self::pascal(method)),
args.into_iter().map(inner).collect(),
))
}
fn carries_hdds_axes() -> bool {
true
}
fn runtime_static(method: &str, args: Vec<Self::Expr>) -> Self::Expr {
if method == "pid_is_user_member" {
let mut arguments = args.into_iter().map(inner);
if let Some(header) = arguments.next() {
return plain(go::Expr::call(
go::Expr::selector(header, "IsUserMember"),
Vec::new(),
));
}
return plain(go::Expr::call(
Self::runtime_name("IsUserMember"),
Vec::new(),
));
}
plain(go::Expr::call(
Self::runtime_name(&Self::pascal(method)),
args.into_iter().map(inner).collect(),
))
}
fn declare(type_: Self::Type, name: &str, value: Option<Self::Expr>) -> Self::Stmt {
go::Stmt::Var {
name: Ident::new(name),
type_: Some(type_),
value: value.map(inner),
}
}
fn perform(value: Self::Expr) -> Self::Stmt {
if let GoExpr::Plain(go::Expr::Binary { op: "=", lhs, rhs }) = value {
return go::Stmt::Assign {
place: *lhs,
value: *rhs,
};
}
go::Stmt::Expr(inner(value))
}
fn give_back(value: Option<Self::Expr>) -> Self::Stmt {
go::Stmt::Return(Some(match value {
Some(value) => inner(value),
None => go::Expr::name("v"),
}))
}
fn when(
condition: Self::Expr,
then: Self::Block,
otherwise: Option<Self::Block>,
) -> Self::Stmt {
go::Stmt::If {
condition: inner(condition),
then,
otherwise: otherwise.filter(|body| !body.is_empty()),
}
}
fn count_up(counter: &str, bound: Self::Expr, body: Self::Block) -> Self::Stmt {
go::Stmt::For {
counter: Ident::new(counter),
init: Box::new(go::Expr::Convert {
type_: Box::new(go::Type::Primitive(go::Primitive::UInt32)),
value: Box::new(go::Expr::int(0)),
}),
bound: Box::new(inner(bound)),
body,
}
}
fn until(condition: Self::Expr, body: Self::Block) -> Self::Stmt {
go::Stmt::While {
condition: inner(condition),
body,
}
}
fn leave() -> Self::Stmt {
go::Stmt::Break
}
fn note(doc: Doc) -> Self::Stmt {
go::Stmt::Comment(doc)
}
fn drop_value(value: Self::Expr) -> Self::Stmt {
go::Stmt::Assign {
place: go::Expr::name("_"),
value: inner(value),
}
}
fn mark_used(name: &str) -> Vec<Self::Stmt> {
vec![go::Stmt::Assign {
place: go::Expr::name("_"),
value: go::Expr::name(name),
}]
}
fn read_call(
callee: &str,
place: Self::Expr,
_form: Handoff,
behaviour: Self::Expr,
) -> Self::Stmt {
let decoded = go::Expr::call(
go::Expr::name(callee),
vec![go::Expr::name("r"), inner(behaviour)],
);
match place {
GoExpr::OptionalSlot(field) => go::Stmt::Assign {
place: field,
value: go::Expr::call(Self::runtime_name("Ptr"), vec![decoded]),
},
GoExpr::Plain(place) => go::Stmt::Assign {
place,
value: decoded,
},
}
}
fn read_forward(callee: &str) -> Self::Stmt {
Self::read_call(
callee,
Self::whole("v"),
Handoff::Value,
Self::name("zd_tc"),
)
}
fn block(statements: Vec<Self::Stmt>) -> Self::Block {
statements
}
fn into_statements(block: Self::Block) -> Vec<Self::Stmt> {
block
}
fn make_room(
base: &str,
element: Self::Type,
count: Self::Expr,
_assigned_whole: bool,
fill: Vec<Self::Stmt>,
) -> Vec<Self::Stmt> {
let mut out = vec![go::Stmt::Assign {
place: go::Expr::name(base),
value: go::Expr::Make {
type_: Box::new(go::Type::slice(element)),
length: Box::new(inner(count)),
},
}];
out.extend(fill);
out
}
fn keep_first(base: &str, count: Self::Expr) -> Vec<Self::Stmt> {
vec![go::Stmt::Assign {
place: go::Expr::name(base),
value: go::Expr::SliceTo {
value: Box::new(go::Expr::name(base)),
high: Box::new(inner(count)),
},
}]
}
fn sequence_element(
base: &str,
index: Self::Expr,
_element: Self::Type,
) -> (Vec<Self::Stmt>, Self::Expr, Vec<Self::Stmt>) {
(
Vec::new(),
Self::index(Self::elements(base), index),
Vec::new(),
)
}
fn published_name(name: String) -> String {
exported_name(&name)
}
fn routine(spec: Routine<Self>) -> Option<Self::Decl> {
let body = spec.body?;
let mut params = vec![go::Param {
name: Some(Ident::new(if spec.writing { "w" } else { "r" })),
type_: go::Type::pointer(go::Type::named(if spec.writing {
"zdwire.Writer"
} else {
"zdwire.Reader"
})),
}];
if spec.writing {
params.push(go::Param {
name: Some(Ident::new("v")),
type_: spec.sample.clone(),
});
}
for (type_, name) in spec.extra {
params.push(go::Param {
name: Some(Ident::new(&name)),
type_,
});
}
let (results, body) = if spec.writing {
(Vec::new(), body)
} else {
let defaulter = crate::default_go::defaulter_from_decoder(&spec.name);
let mut statements = vec![go::Stmt::Var {
name: Ident::new("v"),
type_: None,
value: Some(go::Expr::call(go::Expr::name(&defaulter), Vec::new())),
}];
statements.extend(body);
statements.push(go::Stmt::Return(Some(go::Expr::name("v"))));
(vec![spec.sample], statements)
};
Some(go::Decl::Func(go::FuncDecl {
doc: spec.doc,
name: Ident::new(&spec.name),
params,
results,
body,
}))
}
fn default_into(
ast: &Ast,
id: Id<TypeNode>,
place: Self::Expr,
) -> Result<Self::Stmt, EncodeError> {
Ok(go::Stmt::Assign {
place: inner(place),
value: go::Expr::call(
go::Expr::name(&crate::default_go::defaulter_name(ast, id)),
Vec::new(),
),
})
}
fn member_default(
ast: &Ast,
node: &MemberNode,
type_: Id<TypeNode>,
place: Self::Expr,
) -> Result<Vec<Self::Stmt>, EncodeError> {
crate::default_go::member_default(ast, node, type_, inner(place))
}
}
fn bound_tag(ast: &Ast, bound: &zerodds_ast::Bound) -> String {
match bound.expr() {
None => String::new(),
Some(expr) => match ast.eval_integral(expr) {
Ok(limit) => format!("_b{limit}"),
Err(_) => "_bx".to_string(),
},
}
}
#[must_use]
pub fn type_tag(ast: &Ast, id: Id<TypeNode>, depth: usize) -> String {
if depth > MAX_TYPE_DEPTH {
return "unresolved".to_string();
}
let node = match ast.type_(id) {
Ok(node) => node,
Err(_) => return "unresolved".to_string(),
};
match &node.kind {
TypeKind::Primitive(kind) => kind.as_str().replace(' ', "_"),
TypeKind::String {
width: CharWidth::Char,
bound,
} => format!("string{}", bound_tag(ast, bound)),
TypeKind::String {
width: CharWidth::WChar,
bound,
} => format!("wstring{}", bound_tag(ast, bound)),
TypeKind::Fixed { digits, scale } => format!("fixed_{digits}_{scale}"),
TypeKind::Sequence { element, bound } => match element.resolved() {
Some(element) => format!(
"seq{}_{}",
bound_tag(ast, bound),
type_tag(ast, element, depth + 1)
),
None => format!("seq_unresolved{}", bound_tag(ast, bound)),
},
TypeKind::Array { element, dims } => {
let mut name = match element.resolved() {
Some(element) => format!("arr_{}", type_tag(ast, element, depth + 1)),
None => "arr_unresolved".to_string(),
};
for dim in dims {
match ast.eval_integral(*dim) {
Ok(length) => name.push_str(&format!("_{length}")),
Err(_) => name.push_str("_x"),
}
}
name
}
TypeKind::Map { key, value, bound } => {
let half = |half: Option<Id<TypeNode>>| match half {
Some(target) => type_tag(ast, target, depth + 1),
None => "unresolved".to_string(),
};
format!(
"map{}_{}_{}",
bound_tag(ast, bound),
half(key.resolved()),
half(value.resolved())
)
}
TypeKind::Alias { aliased } => match aliased.resolved() {
Some(target) => type_tag(ast, target, depth + 1),
None => "unresolved".to_string(),
},
TypeKind::ValueBox { boxed } => match boxed.resolved() {
Some(target) => format!("box_{}", type_tag(ast, target, depth + 1)),
None => "box_unresolved".to_string(),
},
TypeKind::Structure { .. }
| TypeKind::Union { .. }
| TypeKind::Enumeration { .. }
| TypeKind::Bitmask { .. }
| TypeKind::Bitset { .. }
| TypeKind::Valuetype { .. }
| TypeKind::Native => go_type_name(ast, id),
TypeKind::Any => "any".to_string(),
TypeKind::ValueBase => "valuebase".to_string(),
TypeKind::ObjectRef { .. } => "objectref".to_string(),
TypeKind::AnnotationType { .. } => "annotation".to_string(),
}
}
pub fn exported_name(name: &str) -> String {
if !name.starts_with("zd_") {
return name.to_string();
}
let mut chars = name.chars();
match chars.next() {
None => String::new(),
Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
}
}