use crate::adapter::julia::julia_type_name;
use crate::default_common::{discriminator_default_value, resolve_alias, selected_case};
use crate::emit::CodecTarget;
use crate::emit::julia::Julia;
use crate::encode::EncodeError;
use crate::fixed_literal::{fixed_text, zero_decimal};
use zerodds_ast::{
Ast, ConstExpr, Literal as AstLiteral, MemberNode, PrimitiveKind, TypeKind, TypeNode,
};
use zerodds_ast_core::Id;
use zerodds_lang_cst::common::{Doc, Ident, Literal};
use zerodds_lang_cst::julia::{self as jl, escape_field, escape_name};
const MAX_ALIAS_DEPTH: usize = 64;
#[must_use]
pub fn defaulter_name(ast: &Ast, id: Id<TypeNode>) -> String {
match ast.type_(id).map(|node| node.kind.clone()) {
Ok(TypeKind::Primitive(kind)) => {
format!("zd_def_p_{}", kind.as_str().replace(' ', "_"))
}
_ => format!("zd_def_{}", Julia::type_name(ast, id)),
}
}
#[must_use]
pub fn defaulter_from_decoder(decoder: &str) -> String {
match decoder.strip_prefix("zd_dec_") {
Some(rest) => format!("zd_def_{rest}"),
None => format!("zd_def_{decoder}"),
}
}
#[must_use]
pub fn default_into(ast: &Ast, id: Id<TypeNode>, place: jl::Expr) -> jl::Statement {
jl::Statement::Assign {
place,
value: jl::Expr::free_call(&defaulter_name(ast, id), Vec::new()),
}
}
pub fn member_default(
ast: &Ast,
node: &MemberNode,
type_: Id<TypeNode>,
place: jl::Expr,
) -> Result<Vec<jl::Statement>, EncodeError> {
Ok(vec![jl::Statement::Assign {
place,
value: member_value(ast, node, type_)?,
}])
}
pub fn julia_defaulters_called_by(
ast: &Ast,
decls: &[jl::Decl],
) -> Result<Vec<jl::Decl>, EncodeError> {
let index: Vec<(String, Id<TypeNode>)> = ast
.types()
.map(|(id, _)| (defaulter_name(ast, id), id))
.collect();
let mut called: Vec<String> = Vec::new();
for decl in decls {
calls_in_decl(decl, &mut called);
}
let mut wanted: Vec<Id<TypeNode>> = Vec::new();
let mut have: Vec<String> = Vec::new();
for _ in 0..=index.len() {
let mut grew = false;
for name in &called {
if have.contains(name) {
continue;
}
have.push(name.clone());
if let Some(id) = index.iter().find(|(n, _)| n == name).map(|(_, id)| *id) {
wanted.push(id);
grew = true;
}
}
let produced = julia_defaulters_over(ast, &wanted)?;
if !grew {
return Ok(produced);
}
for decl in &produced {
calls_in_decl(decl, &mut called);
}
}
julia_defaulters_over(ast, &wanted)
}
pub fn julia_defaulters_over(
ast: &Ast,
types: &[Id<TypeNode>],
) -> Result<Vec<jl::Decl>, EncodeError> {
let mut out = Vec::new();
let mut emitted: Vec<String> = Vec::new();
for id in types.iter().copied() {
let name = defaulter_name(ast, id);
if emitted.contains(&name) {
continue;
}
let Some(value) = value_of(ast, id, &name)? else {
continue;
};
emitted.push(name.clone());
out.push(jl::Decl::FunctionDef(jl::FunctionDef {
doc: Doc::line(
"Table 9 of DDS-XTypes 1.3: what this type is where the stream did not \
carry it. An aggregate answers the mutable scratch zd_freeze builds \
the immutable value from.",
),
name: Ident::new(&name),
params: Vec::new(),
returns: None,
body: vec![jl::Statement::Return(Some(value))],
}));
}
Ok(out)
}
#[allow(clippy::too_many_lines)]
fn value_of(ast: &Ast, id: Id<TypeNode>, own_name: &str) -> Result<Option<jl::Expr>, EncodeError> {
let id = resolve_alias(ast, id);
let refuse = |kind: &'static str| EncodeError::NoWriter {
member: own_name.to_string(),
kind,
};
let Ok(node) = ast.type_(id) else {
return Err(refuse("a type the model does not hold"));
};
let value = match &node.kind {
TypeKind::Primitive(kind) => primitive_default(*kind),
TypeKind::String { .. } => text(""),
TypeKind::Fixed { scale, .. } => text(&zero_decimal(*scale)),
TypeKind::Alias { .. } => {
return Err(refuse("typedef with an unresolved target"));
}
TypeKind::Enumeration { .. } => {
let Some(enumerator) = crate::emit::default_enumerator_name(ast, id) else {
return Err(refuse(
"enumeration with no enumerator to take as its default",
));
};
Julia::enumerator_constant(ast, id, &enumerator)
}
TypeKind::Bitmask { .. } => {
jl::Expr::convert(jl::Type::named(&julia_type_name(ast, id)), jl::Expr::int(0))
}
TypeKind::Bitset { .. } => {
let mut pairs = Vec::new();
for field in &ast.all_bitfields_of(id) {
let Ok(field_node) = ast.bitfield(*field) else {
continue;
};
if let Some(field_name) = field_node.name.as_ref() {
pairs.push((
escape_field(field_name),
jl::Expr::convert(
Julia::unsigned_holder(field_node.bits),
jl::Expr::int(0),
),
));
}
}
scratch_of(pairs)
}
TypeKind::Sequence { .. } | TypeKind::Map { .. } => jl::Expr::AnyVector(Vec::new()),
TypeKind::Array { element, dims } => {
let Some(element) = element.resolved() else {
return Err(refuse("array with an unresolved element"));
};
let mut lengths = Vec::new();
for dim in dims {
let length = ast
.eval_integral(*dim)
.map_err(|_| refuse("array whose length does not evaluate"))?;
lengths.push(
usize::try_from(length)
.map_err(|_| refuse("array of a length this column cannot spell"))?,
);
}
let mut out = jl::Expr::free_call(&defaulter_name(ast, element), Vec::new());
for length in lengths.into_iter().rev() {
out = jl::Expr::AnyVector(vec![out; length]);
}
out
}
TypeKind::Structure { .. } | TypeKind::Valuetype { .. } => {
let mut pairs = Vec::new();
if let Some(base) = crate::adapter::c::struct_base(ast, id) {
pairs.push((
escape_field("parent"),
jl::Expr::free_call(&defaulter_name(ast, base), Vec::new()),
));
}
for member_id in ast.members_of(id) {
let Ok(member_node) = ast.member(*member_id) else {
continue;
};
if member_node.facets.is_optional() {
continue;
}
let Some(member_type) = member_node.type_.resolved() else {
return Err(EncodeError::NoWriter {
member: member_node.name.clone(),
kind: "member with an unresolved type",
});
};
pairs.push((
escape_field(&member_node.name),
member_value(ast, member_node, member_type)?,
));
}
scratch_of(pairs)
}
TypeKind::Union { discriminator, .. } => {
let Some(discriminator) = discriminator.resolved() else {
return Err(refuse("union with an unresolved discriminator"));
};
let selector = discriminator_default_value(ast, discriminator);
let mut pairs = vec![(
"_d".to_string(),
discriminant_literal(ast, discriminator, selector.unwrap_or(0)),
)];
if let Some((member_type, field)) = selected_by_default(ast, id, selector)? {
pairs.push((
field,
jl::Expr::free_call(&defaulter_name(ast, member_type), Vec::new()),
));
}
scratch_of(pairs)
}
TypeKind::Native | TypeKind::ObjectRef { .. } | TypeKind::AnnotationType { .. } => {
return Ok(None);
}
TypeKind::ValueBox { .. } => {
return Err(refuse(
"boxed value, whose presence flag has no settled wire form",
));
}
TypeKind::Any => {
return Err(refuse(
"`any`, which DDS-XTypes has no encoding for; only CORBA CDR writes one, \
as a TypeCode ahead of the value",
));
}
TypeKind::ValueBase => {
return Err(refuse(
"`ValueBase`, which DDS-XTypes has no encoding for; only CORBA CDR writes \
one, as a chunked value with its repository id",
));
}
};
Ok(Some(value))
}
fn member_value(
ast: &Ast,
node: &MemberNode,
type_: Id<TypeNode>,
) -> Result<jl::Expr, EncodeError> {
match node.facets.xtypes.as_ref().and_then(|x| x.default_value) {
Some(expr) => explicit(ast, expr, type_, &node.name),
None => Ok(jl::Expr::free_call(&defaulter_name(ast, type_), Vec::new())),
}
}
fn primitive_default(kind: PrimitiveKind) -> jl::Expr {
let converted = |primitive: jl::Primitive| {
jl::Expr::convert(jl::Type::Primitive(primitive), jl::Expr::int(0))
};
match kind {
PrimitiveKind::Boolean => jl::Expr::Literal(Literal::Bool(false)),
PrimitiveKind::Char | PrimitiveKind::Octet | PrimitiveKind::UInt8 => {
converted(jl::Primitive::UInt8)
}
PrimitiveKind::WChar | PrimitiveKind::UInt16 => converted(jl::Primitive::UInt16),
PrimitiveKind::Int8 => converted(jl::Primitive::Int8),
PrimitiveKind::Int16 => converted(jl::Primitive::Int16),
PrimitiveKind::Int32 => converted(jl::Primitive::Int32),
PrimitiveKind::UInt32 => converted(jl::Primitive::UInt32),
PrimitiveKind::Int64 => converted(jl::Primitive::Int64),
PrimitiveKind::UInt64 => converted(jl::Primitive::UInt64),
PrimitiveKind::Float32 => jl::Expr::convert(
jl::Type::Primitive(jl::Primitive::Float32),
jl::Expr::Literal(Literal::Float("0.0".to_string())),
),
PrimitiveKind::Float64 => jl::Expr::Literal(Literal::Float("0.0".to_string())),
PrimitiveKind::Float128 => text("0"),
}
}
fn scratch_of(pairs: Vec<(String, jl::Expr)>) -> jl::Expr {
let mut args = Vec::new();
for (name, value) in pairs {
args.push(text(&name));
args.push(value);
}
jl::Expr::free_call("zd_scratch_of", args)
}
fn selected_by_default(
ast: &Ast,
id: Id<TypeNode>,
selector: Option<i128>,
) -> Result<Option<(Id<TypeNode>, String)>, EncodeError> {
let Some(selector) = selector else {
return Ok(None);
};
Ok(selected_case(ast, id, selector)?
.map(|(member, member_type)| (member_type, escape_field(&member.name))))
}
fn discriminant_literal(ast: &Ast, discriminator: Id<TypeNode>, value: i128) -> jl::Expr {
let resolved = resolve_alias(ast, discriminator);
if matches!(
ast.type_(resolved).map(|node| node.kind.clone()),
Ok(TypeKind::Enumeration { .. })
) {
if let Some(enumerator) = crate::emit::default_enumerator_name(ast, resolved) {
return Julia::enumerator_constant(ast, resolved, &enumerator);
}
}
match resolved_primitive(ast, resolved) {
Some(PrimitiveKind::Boolean) => jl::Expr::Literal(Literal::Bool(value != 0)),
Some(PrimitiveKind::Char) => jl::Expr::convert(
jl::Type::Primitive(jl::Primitive::UInt8),
jl::Expr::int(value),
),
Some(PrimitiveKind::WChar) => jl::Expr::convert(
jl::Type::Primitive(jl::Primitive::UInt16),
jl::Expr::int(value),
),
_ => jl::Expr::int(value),
}
}
fn resolved_primitive(ast: &Ast, id: Id<TypeNode>) -> Option<PrimitiveKind> {
let mut current = id;
for _ in 0..MAX_ALIAS_DEPTH {
match ast.type_(current).map(|node| node.kind.clone()) {
Ok(TypeKind::Primitive(kind)) => return Some(kind),
Ok(TypeKind::Alias { aliased }) => current = aliased.resolved()?,
_ => return None,
}
}
None
}
#[allow(clippy::too_many_lines)]
fn explicit(
ast: &Ast,
expr: Id<zerodds_ast::ConstExprNode>,
type_: Id<TypeNode>,
member_name: &str,
) -> Result<jl::Expr, EncodeError> {
let refuse = |kind: &'static str| EncodeError::NoWriter {
member: member_name.to_string(),
kind,
};
let node = ast
.expr(expr)
.map_err(|_| refuse("a `@default` this frontend cannot follow"))?;
let resolved = resolve_alias(ast, type_);
let kind = ast.type_(resolved).map(|node| node.kind.clone());
let is_float128 = matches!(kind, Ok(TypeKind::Primitive(PrimitiveKind::Float128)));
let code_unit = |code: u32, wide: bool| {
jl::Expr::convert(
jl::Type::Primitive(if wide {
jl::Primitive::UInt16
} else {
jl::Primitive::UInt8
}),
jl::Expr::int(i128::from(code)),
)
};
match &node.expr {
ConstExpr::Literal(AstLiteral::Boolean(flag)) => {
Ok(jl::Expr::Literal(Literal::Bool(*flag)))
}
ConstExpr::Literal(AstLiteral::Char(ch)) => {
let code = u32::from(*ch);
if code > 0xFF {
return Err(refuse("a `@default` character above one octet"));
}
Ok(code_unit(code, false))
}
ConstExpr::Literal(AstLiteral::WChar(code)) => Ok(code_unit(*code, true)),
ConstExpr::Literal(AstLiteral::String(value)) => Ok(text(value)),
ConstExpr::Literal(AstLiteral::WString(codes)) => {
let mut out = String::new();
for code in codes {
let Some(ch) = char::from_u32(*code) else {
return Err(refuse("a `@default` wide string that is not code points"));
};
out.push(ch);
}
Ok(text(&out))
}
ConstExpr::Literal(AstLiteral::Float { mantissa, exponent }) => {
let exponent = exponent
.as_ref()
.map_or(String::new(), |text| format!("e{text}"));
let written = format!("{mantissa}{exponent}");
if is_float128 {
return Ok(text(&written));
}
Ok(jl::Expr::Literal(Literal::Float(written)))
}
ConstExpr::Literal(AstLiteral::Fixed { digits, scale }) => {
Ok(text(&fixed_text(digits, *scale)))
}
ConstExpr::Literal(AstLiteral::Enumerator(reference)) => {
let target = reference
.resolved()
.ok_or_else(|| refuse("a `@default` enumerator that is unresolved"))?;
let enumerator = ast
.enumerator(target)
.map_err(|_| refuse("a `@default` enumerator this frontend cannot follow"))?;
Ok(Julia::enumerator_constant(ast, resolved, &enumerator.name))
}
_ => {
let value = ast
.eval_integral(expr)
.map_err(|_| refuse("a `@default` this frontend cannot evaluate"))?;
Ok(match kind {
Ok(TypeKind::Primitive(PrimitiveKind::Boolean)) => {
jl::Expr::Literal(Literal::Bool(value != 0))
}
Ok(TypeKind::Primitive(PrimitiveKind::Char)) => {
let code = u32::try_from(value)
.ok()
.filter(|code| *code <= 0xFF)
.ok_or_else(|| refuse("a `@default` character above one octet"))?;
code_unit(code, false)
}
Ok(TypeKind::Primitive(PrimitiveKind::WChar)) => {
let code = u32::try_from(value)
.ok()
.filter(|code| *code <= u32::from(u16::MAX))
.ok_or_else(|| {
refuse("a `@default` character outside the range of a UTF-16 code unit")
})?;
code_unit(code, true)
}
Ok(TypeKind::Primitive(PrimitiveKind::Float128)) => text(&format!("{value}")),
_ => jl::Expr::int(value),
})
}
}
}
fn calls_in_decl(decl: &jl::Decl, out: &mut Vec<String>) {
match decl {
jl::Decl::FunctionDef(function) => calls_in_body(&function.body, out),
jl::Decl::Const(constant) => calls_in_expr(&constant.value, out),
jl::Decl::Enum(declaration) => {
for member in &declaration.members {
calls_in_expr(&member.value, out);
}
}
jl::Decl::Abstract(_)
| jl::Decl::Struct(_)
| jl::Decl::Function(_)
| jl::Decl::Comment(_)
| jl::Decl::Verbatim(_) => {}
}
}
fn calls_in_body(body: &[jl::Statement], out: &mut Vec<String>) {
for statement in body {
calls_in_statement(statement, out);
}
}
fn calls_in_statement(statement: &jl::Statement, out: &mut Vec<String>) {
match statement {
jl::Statement::Local { value, .. } => {
if let Some(value) = value {
calls_in_expr(value, out);
}
}
jl::Statement::Assign { place, value } => {
calls_in_expr(place, out);
calls_in_expr(value, out);
}
jl::Statement::Expr(value) => calls_in_expr(value, out),
jl::Statement::If {
condition,
then,
otherwise,
} => {
calls_in_expr(condition, out);
calls_in_body(then, out);
if let Some(otherwise) = otherwise {
calls_in_body(otherwise, out);
}
}
jl::Statement::For { iter, body, .. } => {
calls_in_expr(iter, out);
calls_in_body(body, out);
}
jl::Statement::While { condition, body } => {
calls_in_expr(condition, out);
calls_in_body(body, out);
}
jl::Statement::Return(value) => {
if let Some(value) = value {
calls_in_expr(value, out);
}
}
jl::Statement::Break | jl::Statement::Comment(_) => {}
}
}
fn calls_in_expr(expr: &jl::Expr, out: &mut Vec<String>) {
match expr {
jl::Expr::FreeCall { func, args } => {
let name = func.as_str();
if name.starts_with("zd_def_") && !out.iter().any(|seen| seen == name) {
out.push(name.to_string());
}
for arg in args {
calls_in_expr(arg, out);
}
}
jl::Expr::Call { args, .. } => {
for arg in args {
calls_in_expr(arg, out);
}
}
jl::Expr::AnyVector(items) => {
for item in items {
calls_in_expr(item, out);
}
}
jl::Expr::Field { value, .. } | jl::Expr::Unary { value, .. } | jl::Expr::Paren(value) => {
calls_in_expr(value, out);
}
jl::Expr::Index { value, index } => {
calls_in_expr(value, out);
calls_in_expr(index, out);
}
jl::Expr::Range { start, stop } => {
calls_in_expr(start, out);
calls_in_expr(stop, out);
}
jl::Expr::Binary { lhs, rhs, .. } => {
calls_in_expr(lhs, out);
calls_in_expr(rhs, out);
}
jl::Expr::Literal(_) | jl::Expr::Name(_) | jl::Expr::Type(_) => {}
}
}
fn text(value: &str) -> jl::Expr {
jl::Expr::Literal(Literal::Str(value.to_string()))
}
const _: () = {
let _ = escape_name;
};