use crate::adapter::constant;
use crate::adapter::cst::{MaterialiseError, no_spelling_collision};
use crate::adapter::interface;
use crate::apply::Applied;
use crate::verbatim;
use seesaw_tgg::ident::GhostId;
use zerodds_ast::{Ast, CharWidth, PrimitiveKind, TypeKind, TypeNode};
use zerodds_ast_core::{Id, NodeId};
use zerodds_lang_cst::common::{Doc, Ident, Literal, Path};
use zerodds_lang_cst::d;
const LANGUAGE: &str = "D";
pub const MODULE: &str = "zdtypes";
const INVENTED_PREFIX: &str = "ZdMapEntry_";
pub const DISCRIMINATOR: &str = "_d";
pub fn d_items(ast: &Ast, applied: &Applied) -> Result<Vec<d::Decl>, MaterialiseError> {
let mut out = Vec::new();
let mut emitted: Vec<(String, String)> = Vec::new();
for (id, node) in ast.types() {
let start = out.len();
declare(ast, applied, id, &mut out, &mut emitted)?;
verbatim::weave(
verbatim::declaration_slots(ast, id, verbatim::aliases::D),
&declared_name(ast, &node.name, node.module),
start,
&mut out,
);
}
for (_, node) in ast.constants() {
if ghost_created_for(applied, node.node_id, "DConst").is_none() {
continue;
}
let value = ast
.eval_const(node.expr)
.map_err(|_| MaterialiseError::Unevaluated {
construct: "constant's value".to_string(),
at: node.name.clone(),
})?;
let declared = node.type_.resolved();
let type_ = match declared {
Some(target) => d_value_type(ast, target)?,
None => d::Type::Primitive(d::Primitive::Int),
};
let name = declared_name(ast, &node.name, node.module);
remember(&mut emitted, &name, &node.name)?;
out.push(d::Decl::Const(d::ConstDecl {
doc: idl_note(&name, &node.name),
name: Ident::new(&name),
type_: Some(type_.clone()),
value: d_constant(&value, &type_, &node.name)?,
}));
}
for (_, node) in ast.exceptions() {
if ghost_created_for(applied, node.node_id, "DError").is_none() {
continue;
}
let name = declared_name(ast, &node.name, node.module);
remember(&mut emitted, &name, &node.name)?;
let mut pairs = Vec::new();
for member in &node.members {
if let Ok(member_node) = ast.member(*member) {
pairs.push((field_name(&member_node.name), member_node.name.clone()));
}
}
no_spelling_collision(as_pairs(&pairs), LANGUAGE, &name)?;
let mut members = Vec::new();
for member in &node.members {
let Ok(member_node) = ast.member(*member) else {
continue;
};
let Some(target) = member_node.type_.resolved() else {
return Err(MaterialiseError::Unevaluated {
construct: "exception member type".to_string(),
at: member_node.name.clone(),
});
};
members.push(d::Member::Field(member_field(ast, member_node, target)?));
}
out.push(d::Decl::Struct(d::StructDecl {
doc: with_idl_note(
Doc::lines(&[
"An exception, as the structure its members make. A struct and not a",
"class deriving Throwable: what goes on the wire is the member list,",
"and the throwing is the RPC arc's business.",
]),
&name,
&node.name,
),
name: Ident::new(&name),
members,
}));
}
for (id, node) in ast.interfaces() {
if ghost_created_for(applied, node.node_id, "DInterface").is_none() {
continue;
}
let name = declared_name(ast, &node.name, node.module);
remember(&mut emitted, &name, &node.name)?;
let mut methods = Vec::new();
let mut signatures = Vec::new();
let operations = interface::all_operations_flattened(ast, id)
.map_err(|error| interface::interface_error_to_materialise(error, &node.name))?;
for op in &operations {
let field_ident = match op.origin {
interface::Origin::AttributeGetter => field_name(op.attribute_name()),
interface::Origin::AttributeSetter => {
let attr = op.attribute_name();
format!("set{}", capitalised(&field_name(attr)))
}
interface::Origin::Declared => field_name(&op.name),
};
signatures.push((field_ident.clone(), op.name.clone()));
let mut params = Vec::new();
for param in &op.params {
params.push(d::Param {
name: Ident::new(&d::escape_name(¶m.name)),
type_: d_member_type(ast, param.type_, ¶m.name)?,
});
}
let returns = match op.returns {
Some(target) => Some(d_member_type(ast, target, &op.name)?),
None => None,
};
let doc = op
.raises_line()
.map_or_else(Doc::none, |line| Doc::line(&line));
methods.push(d::Method {
doc,
name: Ident::new(&field_ident),
returns,
params,
});
}
no_spelling_collision(as_pairs(&signatures), LANGUAGE, &name)?;
out.push(d::Decl::Interface(d::InterfaceDecl {
doc: with_idl_note(
Doc::lines(&[
"An interface, as the method set its operations and attributes make",
"— an attribute a `name`/`setName` pair, `readonly` only the first.",
"A D interface declares signatures and nothing else, which is what",
"an IDL interface declares; the transport is the RPC arc's",
"business. `raises`/`getraises`/`setraises` are documented on the",
"method they belong to.",
"",
"A derived interface carries its bases' operations and attributes",
"too: this declaration has no base list, so IDL 4.2 7.4.3's",
"inherited members are written into it rather than reached through",
"one.",
]),
&name,
&node.name,
),
name: Ident::new(&name),
methods,
}));
}
Ok(verbatim::weave_file(ast, verbatim::aliases::D, out))
}
impl verbatim::Carrier for d::Decl {
fn verbatim(text: String) -> Self {
Self::Verbatim(text)
}
fn take_into_body(
&mut self,
name: &str,
begin: &mut Vec<String>,
end: &mut Vec<String>,
) -> bool {
let Self::Struct(node) = self else {
return false;
};
if node.name.as_str() != name {
return false;
}
let mut members: Vec<d::Member> = begin.drain(..).map(d::Member::Verbatim).collect();
members.append(&mut node.members);
members.extend(end.drain(..).map(d::Member::Verbatim));
node.members = members;
true
}
}
pub fn d_file(ast: &Ast, applied: &Applied) -> Result<d::File, MaterialiseError> {
let decls = d_items(ast, applied)?;
let mut imports = Vec::new();
if decls.iter().any(decl_uses_nullable) {
imports.push(d::Import::selective(&["std", "typecons"], "Nullable"));
}
Ok(d::File {
doc: Doc::lines(&[
"Generated by ZeroDDS from an IDL source. Do not edit.",
"",
"The IDL spelling of every renamed declaration is in the comment",
"above it; the IDL spelling of every member is in its @(\"idl:...\")",
"attribute, because a member's ID under @autoid(HASH) is the MD5 of",
"the IDL name (DDS-XTypes 1.3 7.3.1.2.1.1) and the D spelling does",
"not invert.",
"",
"An IDL `long` is 32 bits and is written `int` here; a D `long` is",
"64 bits and is what an IDL `long long` becomes.",
]),
module: Path::new(&[MODULE]),
imports,
decls,
})
}
fn decl_uses_nullable(decl: &d::Decl) -> bool {
match decl {
d::Decl::Struct(node) => node.members.iter().any(|member| match member {
d::Member::Field(field) => type_uses_nullable(&field.type_),
d::Member::Union(fields) => fields.iter().any(|f| type_uses_nullable(&f.type_)),
d::Member::Verbatim(_) => false,
}),
d::Decl::Alias(node) => type_uses_nullable(&node.type_),
d::Decl::Const(node) => node.type_.as_ref().is_some_and(type_uses_nullable),
d::Decl::Interface(node) => node.methods.iter().any(|method| {
method.returns.as_ref().is_some_and(type_uses_nullable)
|| method.params.iter().any(|p| type_uses_nullable(&p.type_))
}),
d::Decl::Func(_) | d::Decl::Enum(_) | d::Decl::Comment(_) | d::Decl::Verbatim(_) => false,
}
}
fn type_uses_nullable(type_: &d::Type) -> bool {
match type_ {
d::Type::Nullable(_) => true,
d::Type::Slice(inner) | d::Type::Pointer(inner) => type_uses_nullable(inner),
d::Type::Array { element, .. } => type_uses_nullable(element),
d::Type::Primitive(_) | d::Type::Named(_) => false,
}
}
#[allow(clippy::too_many_lines)]
fn declare(
ast: &Ast,
applied: &Applied,
id: Id<TypeNode>,
out: &mut Vec<d::Decl>,
emitted: &mut Vec<(String, String)>,
) -> Result<(), MaterialiseError> {
let Ok(node) = ast.type_(id) else {
return Ok(());
};
match &node.kind {
TypeKind::Primitive(_)
| TypeKind::String { .. }
| TypeKind::Fixed { .. }
| TypeKind::Sequence { .. }
| TypeKind::Array { .. } => {}
TypeKind::Map { key, value, .. } => {
let (Some(key), Some(value)) = (key.resolved(), value.resolved()) else {
return Err(MaterialiseError::Unevaluated {
construct: "map key or value".to_string(),
at: d_type_name(ast, id),
});
};
let name = map_entry_name_at(ast, id, 0)?;
if emitted.iter().any(|(spelled, _)| *spelled == name) {
return Ok(());
}
emitted.push((name.clone(), name.clone()));
out.push(d::Decl::Struct(d::StructDecl {
doc: Doc::lines(&[
"One entry of a map. DDS-XTypes 1.3 7.4.1.1.4 defines a map as a",
"sequence of these, and the rules write the two halves with no",
"framing between them.",
]),
name: Ident::new(&name),
members: vec![
d::Member::Field(d::Field {
doc: Doc::none(),
udas: Vec::new(),
name: Ident::new("key"),
type_: d_member_type(ast, key, &name)?,
}),
d::Member::Field(d::Field {
doc: Doc::none(),
udas: Vec::new(),
name: Ident::new("value"),
type_: d_member_type(ast, value, &name)?,
}),
],
}));
}
TypeKind::Alias { aliased } => {
if node.name.is_empty() {
return Ok(());
}
if ghost_created_for(applied, node.node_id, "DAlias").is_none() {
return Ok(());
}
let Some(target) = aliased.resolved() else {
return Err(MaterialiseError::Unevaluated {
construct: "typedef target".to_string(),
at: node.name.clone(),
});
};
let name = d_type_name(ast, id);
remember(emitted, &name, &node.name)?;
out.push(d::Decl::Alias(d::AliasDecl {
doc: idl_note(&name, &node.name),
name: Ident::new(&name),
type_: d_member_type(ast, target, &node.name)?,
}));
}
TypeKind::Enumeration { enumerators } => {
if ghost_created_for(applied, node.node_id, "DEnum").is_none() {
return Ok(());
}
let name = d_type_name(ast, id);
remember(emitted, &name, &node.name)?;
let mut pairs = Vec::new();
let mut members = Vec::new();
for enumerator in enumerators {
let Ok(enum_node) = ast.enumerator(*enumerator) else {
continue;
};
if ghost_created_for(applied, enum_node.node_id, "DEnumMember").is_none() {
continue;
}
let value = ast.effective_enumerator_value(*enumerator).ok_or_else(|| {
MaterialiseError::Unevaluated {
construct: "enumerator value".to_string(),
at: enum_node.name.clone(),
}
})?;
pairs.push((field_name(&enum_node.name), enum_node.name.clone()));
members.push(d::EnumMember {
doc: idl_note(&field_name(&enum_node.name), &enum_node.name),
name: Ident::new(&field_name(&enum_node.name)),
value: d::Expr::int(value),
});
}
no_spelling_collision(as_pairs(&pairs), LANGUAGE, &name)?;
let doc = with_idl_note(
Doc::lines(&[
"An enumeration. The base type is signed because DDS-XTypes 1.3",
"7.4.3.5.3 makes it so; the width on the wire is the @bit_bound's",
"and is applied by the runtime.",
]),
&name,
&node.name,
);
if members.is_empty() {
out.push(d::Decl::Alias(d::AliasDecl {
doc,
name: Ident::new(&name),
type_: d::Type::Primitive(d::Primitive::Int),
}));
} else {
out.push(d::Decl::Enum(d::EnumDecl {
doc,
name: Ident::new(&name),
base: Some(d::Type::Primitive(d::Primitive::Int)),
members,
}));
}
}
TypeKind::Bitmask { bits } => {
if ghost_created_for(applied, node.node_id, "DBitmask").is_none() {
return Ok(());
}
let name = d_type_name(ast, id);
remember(emitted, &name, &node.name)?;
let bound = ast.effective_bit_bound(id);
out.push(d::Decl::Alias(d::AliasDecl {
doc: with_idl_note(
Doc::lines(&[
"A bitmask, as the unsigned integer Table 33 of DDS-XTypes 1.3",
"7.4.1.1.3.2 gives for its bound. An alias and not an enum: a",
"bitmask value is any combination of its bits, and a D enum is a",
"closed set of named values.",
]),
&name,
&node.name,
),
name: Ident::new(&name),
type_: d::Type::Primitive(d_holder(bound)),
}));
let prefix = module_prefix(ast, id);
for bit in bits {
let Ok(bit_node) = ast.bit_value(*bit) else {
continue;
};
if ghost_created_for(applied, bit_node.node_id, "DBitConst").is_none() {
continue;
}
let position = ast.effective_bit_position(*bit).ok_or_else(|| {
MaterialiseError::Unevaluated {
construct: "bit position".to_string(),
at: bit_node.name.clone(),
}
})?;
let constant = format!("{prefix}{}", field_name(&bit_node.name));
remember(emitted, &constant, &bit_node.name)?;
out.push(d::Decl::Const(d::ConstDecl {
doc: idl_note(&constant, &bit_node.name),
name: Ident::new(&constant),
type_: Some(d::Type::named(&name)),
value: d::Expr::Binary {
op: "<<",
lhs: Box::new(shift_base(position)),
rhs: Box::new(d::Expr::int(i128::from(position))),
},
}));
}
}
TypeKind::Bitset { .. } => {
if ghost_created_for(applied, node.node_id, "DBitset").is_none() {
return Ok(());
}
let name = d_type_name(ast, id);
remember(emitted, &name, &node.name)?;
let mut pairs = Vec::new();
for field in &ast.all_bitfields_of(id) {
let Ok(field_node) = ast.bitfield(*field) else {
continue;
};
let Some(field_ident) = field_node.name.as_ref() else {
continue;
};
pairs.push((field_name(field_ident), field_ident.clone()));
}
no_spelling_collision(as_pairs(&pairs), LANGUAGE, &name)?;
let mut members = Vec::new();
let mut index = 0;
for field in &ast.all_bitfields_of(id) {
let Ok(field_node) = ast.bitfield(*field) else {
continue;
};
let Some(field_ident) = field_node.name.as_ref() else {
continue;
};
members.push(d::Member::Field(d::Field {
doc: Doc::none(),
udas: vec![d::Uda::keyed("idl", field_ident)],
name: Ident::new(&pairs[index].0),
type_: d::Type::Primitive(d_holder(field_node.bits)),
}));
index += 1;
}
out.push(d::Decl::Struct(d::StructDecl {
doc: with_idl_note(
Doc::lines(&[
"A bitset. The fields are separate integers here rather than D",
"bitfields: the order on the wire is the declaration's, and D's",
"own bit-field packing is the target ABI's.",
]),
&name,
&node.name,
),
name: Ident::new(&name),
members,
}));
}
TypeKind::Structure { .. } | TypeKind::Valuetype { .. } => {
let created = if matches!(node.kind, TypeKind::Valuetype { .. }) {
"DValue"
} else {
"DStruct"
};
if ghost_created_for(applied, node.node_id, created).is_none() {
return Ok(());
}
let name = d_type_name(ast, id);
remember(emitted, &name, &node.name)?;
let members = ast.members_of(id).to_vec();
let base = super::c::struct_base(ast, id);
let mut pairs = Vec::new();
if base.is_some() {
pairs.push((field_name("parent"), "parent".to_string()));
}
for member in &members {
if let Ok(member_node) = ast.member(*member) {
pairs.push((field_name(&member_node.name), member_node.name.clone()));
}
}
no_spelling_collision(as_pairs(&pairs), LANGUAGE, &name)?;
let mut fields = Vec::new();
if let Some(base) = base {
fields.push(d::Member::Field(parent_field(ast, base)?));
}
for member in &members {
let Ok(member_node) = ast.member(*member) else {
continue;
};
let Some(target) = member_node.type_.resolved() else {
return Err(MaterialiseError::Unevaluated {
construct: "member type".to_string(),
at: member_node.name.clone(),
});
};
fields.push(d::Member::Field(member_field(ast, member_node, target)?));
}
out.push(d::Decl::Struct(d::StructDecl {
doc: idl_note(&name, &node.name),
name: Ident::new(&name),
members: fields,
}));
}
TypeKind::Union { discriminator, .. } => {
if ghost_created_for(applied, node.node_id, "DUnion").is_none() {
return Ok(());
}
let name = d_type_name(ast, id);
remember(emitted, &name, &node.name)?;
let Some(disc) = discriminator.resolved() else {
return Err(MaterialiseError::Unevaluated {
construct: "union discriminator".to_string(),
at: name,
});
};
let cases = ast.cases_of(id);
let mut pairs = vec![(DISCRIMINATOR.to_string(), "<discriminator>".to_string())];
for case in cases {
if let Ok(case_node) = ast.case(*case) {
if let Ok(member) = ast.member(case_node.member) {
pairs.push((field_name(&member.name), member.name.clone()));
}
}
}
no_spelling_collision(as_pairs(&pairs), LANGUAGE, &name)?;
let mut branches = Vec::new();
for case in cases {
let Ok(case_node) = ast.case(*case) else {
continue;
};
if ghost_created_for(applied, case_node.node_id, "DCase").is_none() {
continue;
}
let Ok(member) = ast.member(case_node.member) else {
continue;
};
let Some(target) = member.type_.resolved() else {
return Err(MaterialiseError::Unevaluated {
construct: "union case type".to_string(),
at: member.name.clone(),
});
};
branches.push(member_field(ast, member, target)?);
}
let members = vec![
d::Member::Field(d::Field {
doc: Doc::line("Which branch carries the value."),
udas: Vec::new(),
name: Ident::new(DISCRIMINATOR),
type_: d_member_type(ast, disc, &name)?,
}),
d::Member::Union(branches),
];
out.push(d::Decl::Struct(d::StructDecl {
doc: with_idl_note(
Doc::lines(&[
"A union: the branches overlay, which is the shape the wire form",
"has — only the branch `_d` selects is written (DDS-XTypes 1.3",
"7.4.1.1.5.2). Reading a branch other than the one `_d` names is",
"undefined; where a branch holds a slice or a string the union",
"overlaps a reference, which D permits only from @system or",
"@trusted code.",
]),
&name,
&node.name,
),
name: Ident::new(&name),
members,
}));
}
TypeKind::Native => {
if ghost_created_for(applied, node.node_id, "DNative").is_none() {
return Ok(());
}
let name = d_type_name(ast, id);
remember(emitted, &name, &node.name)?;
let mapping = ast
.any_of_type(id)
.ok()
.and_then(|any| ast.facets(any))
.and_then(|facets| facets.corba.as_ref())
.and_then(|corba| corba.native_mapping.clone());
out.push(d::Decl::Alias(d::AliasDecl {
doc: with_idl_note(
Doc::line("A native type. Opaque unless a facet named its mapping."),
&name,
&node.name,
),
name: Ident::new(&name),
type_: match mapping {
Some(spelling) => d::Type::named(&spelling),
None => d::Type::pointer(d::Type::Primitive(d::Primitive::Void)),
},
}));
}
TypeKind::ValueBox { boxed } => {
let Some(target) = boxed.resolved() else {
return Ok(());
};
let name = d_type_name(ast, id);
if emitted.iter().any(|(spelled, _)| *spelled == name) {
return Ok(());
}
remember(emitted, &name, &node.name)?;
out.push(d::Decl::Alias(d::AliasDecl {
doc: with_idl_note(
Doc::line("A boxed value: present or not, and `isNull` when it is not."),
&name,
&node.name,
),
name: Ident::new(&name),
type_: d::Type::nullable(d_member_type(ast, target, &name)?),
}));
}
TypeKind::ObjectRef { .. }
| TypeKind::AnnotationType { .. }
| TypeKind::Any
| TypeKind::ValueBase => {}
}
Ok(())
}
fn shift_base(position: u16) -> d::Expr {
if position >= 31 {
d::Expr::suffixed_int(1, "UL")
} else {
d::Expr::int(1)
}
}
fn reaches_enclosing_by_value(ast: &Ast, mut type_: Id<TypeNode>, enclosing: Id<TypeNode>) -> bool {
for _ in 0..64 {
if type_ == enclosing {
return true;
}
let Ok(node) = ast.type_(type_) else {
return false;
};
let next = match &node.kind {
TypeKind::Alias { aliased } => aliased.resolved(),
TypeKind::Array { element, .. } => element.resolved(),
_ => return false,
};
match next {
Some(next) => type_ = next,
None => return false,
}
}
false
}
fn member_field(
ast: &Ast,
member: &zerodds_ast::MemberNode,
target: Id<TypeNode>,
) -> Result<d::Field, MaterialiseError> {
let mut type_ = d_member_type(ast, target, &member.name)?;
let mut doc = Doc::none();
let external = super::held_externally(ast, member);
let optional = member.facets.is_optional();
if !super::annotated_external(member)
&& !optional
&& let zerodds_ast::AnyId::Type(enclosing, _) = member.parent
&& reaches_enclosing_by_value(ast, target, enclosing)
{
return Err(MaterialiseError::NoLanguageForm {
construct: format!(
"a member whose type reaches `{}` back with no indirection — a D \
struct cannot contain itself by value, and IDL 4.2 §7.4.1.4.4.4.4 \
admits no cycle that nothing on it can terminate",
d_type_name(ast, enclosing)
),
language: LANGUAGE,
at: member.name.clone(),
});
}
if external {
type_ = d::Type::pointer(type_);
doc.push("Stored by reference — @external, DDS-XTypes 1.3 Table 21. The");
doc.push("annotation changes no octet on the wire; it says where the binding");
doc.push("keeps the value, and in D a pointer is the whole of it.");
}
if optional {
if external {
doc.push("Optional. `null` when the member is absent — DDS-XTypes 1.3");
doc.push("7.2.2.4.4.4.7. The pointer above carries that state already, so no");
doc.push("Nullable is wrapped around it.");
} else {
type_ = d::Type::nullable(type_);
doc.push("Optional. `isNull` when the member is absent — DDS-XTypes 1.3");
doc.push("7.2.2.4.4.4.7. In a @mutable type an absent member is not written");
doc.push("at all; outside one its absence is written.");
}
}
Ok(d::Field {
doc,
udas: vec![d::Uda::keyed("idl", &member.name)],
name: Ident::new(&field_name(&member.name)),
type_,
})
}
fn parent_field(ast: &Ast, base: Id<TypeNode>) -> Result<d::Field, MaterialiseError> {
let mut doc = Doc::none();
doc.push("The base structure, the first member (XTypes 1.3 7.5.1.4.1.3).");
Ok(d::Field {
doc,
udas: vec![d::Uda::keyed("idl", "parent")],
name: Ident::new(&field_name("parent")),
type_: d_member_type(ast, base, "parent")?,
})
}
pub fn d_member_type(
ast: &Ast,
target: Id<TypeNode>,
at: &str,
) -> Result<d::Type, MaterialiseError> {
let construct = match ast.type_(target).map(|node| &node.kind) {
Ok(TypeKind::Any) => Some("any"),
Ok(TypeKind::ValueBase) => Some("ValueBase"),
Ok(TypeKind::ObjectRef { .. }) => Some("Object"),
_ => None,
};
if let Some(construct) = construct {
return Err(MaterialiseError::NoLanguageForm {
construct: construct.to_string(),
language: LANGUAGE,
at: at.to_string(),
});
}
d_value_type(ast, target)
}
pub fn d_value_type(ast: &Ast, id: Id<TypeNode>) -> Result<d::Type, MaterialiseError> {
value_type_at(ast, id, 0)
}
fn value_type_at(ast: &Ast, id: Id<TypeNode>, depth: usize) -> Result<d::Type, MaterialiseError> {
if depth > MAX_TYPE_DEPTH {
return Err(MaterialiseError::Unevaluated {
construct: format!("type, whose D spelling nests past {MAX_TYPE_DEPTH}"),
at: d_type_name(ast, id),
});
}
let Ok(node) = ast.type_(id) else {
return Ok(d::Type::pointer(d::Type::Primitive(d::Primitive::Void)));
};
Ok(match &node.kind {
TypeKind::Primitive(kind) => d_primitive_type(*kind),
TypeKind::String { .. } | TypeKind::Fixed { .. } => {
d::Type::Primitive(d::Primitive::String)
}
TypeKind::Sequence { element, .. } => {
let Some(element) = element.resolved() else {
return Err(MaterialiseError::Unevaluated {
construct: "sequence element".to_string(),
at: node.name.clone(),
});
};
d::Type::slice(value_type_at(ast, element, depth + 1)?)
}
TypeKind::Array { element, dims } => {
let Some(element) = element.resolved() else {
return Err(MaterialiseError::Unevaluated {
construct: "array element".to_string(),
at: node.name.clone(),
});
};
let mut type_ = value_type_at(ast, element, depth + 1)?;
for dim in dims.iter().rev() {
let length =
ast.eval_integral(*dim)
.map_err(|_| MaterialiseError::Unevaluated {
construct: "array length".to_string(),
at: node.name.clone(),
})?;
type_ = d::Type::array(length, type_);
}
type_
}
TypeKind::Map { .. } => {
d::Type::slice(d::Type::named(&map_entry_name_at(ast, id, depth + 1)?))
}
TypeKind::Alias { aliased } if node.name.is_empty() => match aliased.resolved() {
Some(target) => value_type_at(ast, target, depth + 1)?,
None => d::Type::pointer(d::Type::Primitive(d::Primitive::Void)),
},
_ => d::Type::named(&d_type_name(ast, id)),
})
}
#[must_use]
pub fn d_primitive_type(kind: PrimitiveKind) -> d::Type {
let primitive = match kind {
PrimitiveKind::Boolean => d::Primitive::Bool,
PrimitiveKind::Octet | PrimitiveKind::UInt8 | PrimitiveKind::Char => d::Primitive::UByte,
PrimitiveKind::Int8 => d::Primitive::Byte,
PrimitiveKind::WChar | PrimitiveKind::UInt16 => d::Primitive::UShort,
PrimitiveKind::Int16 => d::Primitive::Short,
PrimitiveKind::Int32 => d::Primitive::Int,
PrimitiveKind::UInt32 => d::Primitive::UInt,
PrimitiveKind::Int64 => d::Primitive::Long,
PrimitiveKind::UInt64 => d::Primitive::ULong,
PrimitiveKind::Float32 => d::Primitive::Float,
PrimitiveKind::Float64 => d::Primitive::Double,
PrimitiveKind::Float128 => d::Primitive::String,
};
d::Type::Primitive(primitive)
}
#[must_use]
pub const fn d_holder(bits: u16) -> d::Primitive {
match bits {
0..=8 => d::Primitive::UByte,
9..=16 => d::Primitive::UShort,
17..=32 => d::Primitive::UInt,
_ => d::Primitive::ULong,
}
}
#[must_use]
pub fn d_type_name(ast: &Ast, id: Id<TypeNode>) -> String {
let Ok(any) = ast.any_of_type(id) else {
return "ZdUnnamed".to_string();
};
match ast.scoped_name_of(any) {
Some(scoped) => flatten(scoped.segments()),
None => "ZdUnnamed".to_string(),
}
}
pub fn d_map_entry_name(ast: &Ast, id: Id<TypeNode>) -> Result<String, MaterialiseError> {
map_entry_name_at(ast, id, 0)
}
fn map_entry_name_at(
ast: &Ast,
id: Id<TypeNode>,
depth: usize,
) -> Result<String, MaterialiseError> {
if depth > MAX_TYPE_DEPTH {
return Err(MaterialiseError::Unevaluated {
construct: format!("map entry name, which nests past {MAX_TYPE_DEPTH}"),
at: d_type_name(ast, id),
});
}
let Ok(node) = ast.type_(id) else {
return Ok(format!("{INVENTED_PREFIX}Unknown"));
};
let TypeKind::Map { key, value, .. } = &node.kind else {
return Ok(format!("{INVENTED_PREFIX}Unknown"));
};
let key = match key.resolved() {
Some(k) => type_tag(ast, k, depth + 1)?,
None => "Unknown".to_string(),
};
let value = match value.resolved() {
Some(v) => type_tag(ast, v, depth + 1)?,
None => "Unknown".to_string(),
};
Ok(format!("{INVENTED_PREFIX}{key}_{value}"))
}
fn type_tag(ast: &Ast, id: Id<TypeNode>, depth: usize) -> Result<String, MaterialiseError> {
if depth > MAX_TYPE_DEPTH {
return Err(MaterialiseError::Unevaluated {
construct: format!("type tag, which nests past {MAX_TYPE_DEPTH}"),
at: d_type_name(ast, id),
});
}
Ok(match ast.type_(id).map(|node| node.kind.clone()) {
Ok(TypeKind::Primitive(kind)) => capitalised(&kind.as_str().replace(' ', "_")),
Ok(TypeKind::String {
width: CharWidth::Char,
..
}) => "String".to_string(),
Ok(TypeKind::String {
width: CharWidth::WChar,
..
}) => "WString".to_string(),
Ok(TypeKind::Sequence { element, .. }) => match element.resolved() {
Some(element) => format!("SeqOf{}", type_tag(ast, element, depth + 1)?),
None => "SeqOfUnknown".to_string(),
},
Ok(TypeKind::Array { element, dims }) => match element.resolved() {
Some(element) => {
let mut name = format!("ArrOf{}", type_tag(ast, element, depth + 1)?);
for dim in &dims {
match ast.eval_integral(*dim) {
Ok(length) => name.push_str(&format!("_{length}")),
Err(_) => name.push_str("_x"),
}
}
name
}
None => "ArrOfUnknown".to_string(),
},
Ok(TypeKind::Map { .. }) => map_entry_name_at(ast, id, depth + 1)?,
_ => d_type_name(ast, id),
})
}
fn capitalised(text: &str) -> String {
let mut chars = text.chars();
let Some(first) = chars.next() else {
return String::new();
};
let mut out = String::new();
for upper in first.to_uppercase() {
out.push(upper);
}
out.push_str(chars.as_str());
out
}
fn module_prefix(ast: &Ast, id: Id<TypeNode>) -> String {
let Ok(any) = ast.any_of_type(id) else {
return String::new();
};
let Some(scoped) = ast.scoped_name_of(any) else {
return String::new();
};
let segments = scoped.segments();
if segments.len() <= 1 {
return String::new();
}
let mut prefix = flatten(&segments[..segments.len() - 1]);
prefix.push('_');
prefix
}
fn declared_name(ast: &Ast, name: &str, module: Id<zerodds_ast::ModuleNode>) -> String {
let mut segments: Vec<String> = Vec::new();
let mut current = Some(module);
let mut depth = 0;
while let Some(id) = current {
if depth > MAX_MODULE_DEPTH {
break;
}
depth += 1;
let Ok(node) = ast.module(id) else { break };
if node.name.is_empty() {
break;
}
segments.push(node.name.clone());
current = node.parent;
}
segments.reverse();
segments.push(name.to_string());
let borrowed: Vec<&str> = segments.iter().map(String::as_str).collect();
flatten_str(&borrowed)
}
const MAX_MODULE_DEPTH: usize = 64;
const MAX_TYPE_DEPTH: usize = 64;
fn flatten(segments: &[String]) -> String {
let borrowed: Vec<&str> = segments.iter().map(String::as_str).collect();
flatten_str(&borrowed)
}
fn flatten_str(segments: &[&str]) -> String {
segments
.iter()
.map(|segment| d::escape_name(segment))
.collect::<Vec<String>>()
.join("_")
}
#[must_use]
pub fn field_name(name: &str) -> String {
d::escape_name(name)
}
fn idl_note(spelled: &str, declared: &str) -> Doc {
if spelled == declared {
return Doc::none();
}
Doc::line(&format!("IDL: `{declared}`."))
}
fn with_idl_note(mut doc: Doc, spelled: &str, declared: &str) -> Doc {
if spelled != declared {
doc.push(&format!("IDL: `{declared}`."));
}
doc
}
fn remember(
emitted: &mut Vec<(String, String)>,
spelled: &str,
declared: &str,
) -> Result<(), MaterialiseError> {
if let Some((_, first)) = emitted.iter().find(|(other, _)| other == spelled) {
return Err(MaterialiseError::SpellingCollision {
first: first.clone(),
second: declared.to_string(),
spelled: spelled.to_string(),
language: LANGUAGE,
at: "the generated module".to_string(),
});
}
emitted.push((spelled.to_string(), declared.to_string()));
Ok(())
}
fn as_pairs(pairs: &[(String, String)]) -> Vec<(&str, &str)> {
pairs
.iter()
.map(|(spelled, declared)| (spelled.as_str(), declared.as_str()))
.collect()
}
fn ghost_created_for(applied: &Applied, node: NodeId, type_name: &str) -> Option<GhostId> {
let anchor = applied
.origin
.iter()
.find(|(_, model)| **model == node)
.map(|(ghost, _)| *ghost)?;
let typ = applied.graph.types.lookup(type_name)?;
applied
.graph
.nodes_of_type(typ)
.map(|created| created.id)
.find(|created| {
applied.graph.connected(&anchor, created)
|| applied
.graph
.parts(&anchor)
.any(|part| applied.graph.connected(&part.other, created))
})
}
fn d_constant(
value: &zerodds_ast::ConstValue,
type_: &d::Type,
at: &str,
) -> Result<d::Expr, MaterialiseError> {
use zerodds_ast::ConstValue;
let refuse = |construct: &str| MaterialiseError::NoLanguageForm {
construct: construct.to_string(),
language: LANGUAGE,
at: at.to_string(),
};
let is_string = matches!(type_, d::Type::Primitive(d::Primitive::String));
Ok(match value {
ConstValue::Boolean(flag) => d::Expr::Literal(Literal::Bool(*flag)),
ConstValue::Integer(number) => d::Expr::Literal(Literal::int(*number)),
ConstValue::Char(character) => {
d::Expr::Literal(Literal::int(i128::from(u32::from(*character))))
}
ConstValue::WChar(point) => d::Expr::Literal(Literal::int(i128::from(*point))),
ConstValue::Float { mantissa, exponent } => {
if is_string {
return Err(refuse("a `long double` constant, which has no D literal"));
}
d::Expr::Literal(Literal::Float(constant::float_text(
mantissa,
exponent.as_deref(),
)))
}
ConstValue::Fixed { digits, scale } => {
d::Expr::Literal(Literal::Str(constant::fixed_decimal(digits, *scale)))
}
ConstValue::String(text) => d::Expr::Literal(Literal::Str(text.clone())),
ConstValue::WString(points) => d::Expr::Literal(Literal::Str(
constant::wstring_utf8(points)
.ok_or_else(|| refuse("a `wstring` constant holding a lone surrogate"))?,
)),
_ => return Err(refuse("a constant form this binding has no literal for")),
})
}