use crate::adapter::cst::MaterialiseError;
use crate::adapter::typescript::{declared_path, factory_path, unsigned_holder};
use crate::default_common::{discriminator_default_value, resolve_alias, selected_case};
use crate::emit::CodecTarget;
use crate::emit::typescript::TypeScript;
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, Path};
use zerodds_lang_cst::typescript as ts;
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_{}", TypeScript::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: ts::Expr) -> ts::Statement {
assign(place, call(&defaulter_name(ast, id), Vec::new()))
}
pub fn member_default(
ast: &Ast,
node: &MemberNode,
type_: Id<TypeNode>,
place: ts::Expr,
) -> Result<Vec<ts::Statement>, EncodeError> {
let Some(expr) = node.facets.xtypes.as_ref().and_then(|x| x.default_value) else {
return Ok(vec![default_into(ast, type_, place)]);
};
let value = explicit(ast, expr, type_, &node.name)?;
Ok(vec![assign(place, value)])
}
pub fn typescript_defaulters_called_by(
ast: &Ast,
decls: &[ts::Decl],
) -> Result<Vec<ts::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 = typescript_defaulters_over(ast, &wanted)?;
if !grew {
return Ok(produced);
}
for decl in &produced {
calls_in_decl(decl, &mut called);
}
}
typescript_defaulters_over(ast, &wanted)
}
pub fn typescript_defaulters_over(
ast: &Ast,
types: &[Id<TypeNode>],
) -> Result<Vec<ts::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(body) = body_of(ast, id, &name)? else {
continue;
};
emitted.push(name.clone());
out.push(ts::Decl::Function(ts::Function {
doc: Doc::line(
"Table 9 of DDS-XTypes 1.3: what this type is where the stream did not \
carry it.",
),
exported: false,
name: Ident::new(&name),
generics: Vec::new(),
params: Vec::new(),
returns: Some(TypeScript::value_type(ast, id)),
body: Some(ts::Block { statements: body }),
}));
}
Ok(out)
}
#[allow(clippy::too_many_lines)]
fn body_of(
ast: &Ast,
id: Id<TypeNode>,
own_name: &str,
) -> Result<Option<Vec<ts::Statement>>, EncodeError> {
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 statements = match &node.kind {
TypeKind::Primitive(kind) => vec![give_back(primitive_default(*kind))],
TypeKind::String { .. } => vec![give_back(text(""))],
TypeKind::Fixed { scale, .. } => vec![give_back(text(&zero_decimal(*scale)))],
TypeKind::Alias { aliased } => {
let Some(target) = aliased.resolved() else {
return Err(refuse("typedef with an unresolved target"));
};
vec![give_back(call(&defaulter_name(ast, target), Vec::new()))]
}
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",
));
};
vec![give_back(enumerator_constant(ast, id, &enumerator))]
}
TypeKind::Bitmask { .. } => {
let holder = unsigned_holder(ast.effective_bit_bound(id));
vec![give_back(zero_of(&holder))]
}
TypeKind::Bitset { .. } => {
let mut statements = vec![new_local(ast, id, own_name)?];
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() {
statements.push(assign(
member("v", &ts::escape_member(field_name)),
zero_of(&unsigned_holder(field_node.bits)),
));
}
}
statements.push(give_back(name("v")));
statements
}
TypeKind::Sequence { .. } => {
vec![give_back(ts::Expr::Array(Vec::new()))]
}
TypeKind::Map { .. } => {
vec![give_back(ts::Expr::New {
callee: Path::new(&["Map"]),
args: 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 {
lengths.push(
ast.eval_integral(*dim)
.map_err(|_| refuse("array whose length does not evaluate"))?,
);
}
let mut out = call(&defaulter_name(ast, element), Vec::new());
for length in lengths.into_iter().rev() {
out = filled_array(length, out);
}
vec![give_back(out)]
}
TypeKind::Structure { .. } | TypeKind::Valuetype { .. } => {
let mut statements = vec![new_local(ast, id, own_name)?];
if let Some(base) = crate::adapter::c::struct_base(ast, id) {
statements.push(assign(
member("v", "parent"),
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;
};
let field = ts::escape_member(&member_node.name);
if member_node.facets.is_optional() {
statements.push(ts::Statement::Expr(ts::Expr::Unary {
op: "delete ",
value: Box::new(member("v", &field)),
}));
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",
});
};
statements.extend(member_default(
ast,
member_node,
member_type,
member("v", &field),
)?);
}
statements.push(give_back(name("v")));
statements
}
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 entries = vec![(
ts::PropertyName::ident(crate::adapter::typescript::DISCRIMINANT_PROPERTY),
discriminant_literal(ast, discriminator, selector.unwrap_or(0), refuse)?,
)];
if let Some((member_type, field)) = selected_by_default(ast, id, selector)? {
entries.push((
ts::PropertyName::ident(&field),
call(&defaulter_name(ast, member_type), Vec::new()),
));
}
vec![give_back(ts::Expr::Object(entries))]
}
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(statements))
}
fn primitive_default(kind: PrimitiveKind) -> ts::Expr {
match kind {
PrimitiveKind::Boolean => ts::Expr::Literal(Literal::Bool(false)),
PrimitiveKind::Char | PrimitiveKind::WChar => ts::Expr::Literal(Literal::Char('\0')),
PrimitiveKind::Float128 => ts::Expr::Object(vec![(
ts::PropertyName::ident("octets"),
ts::Expr::New {
callee: Path::new(&["Uint8Array"]),
args: vec![ts::Expr::Literal(Literal::int(16))],
},
)]),
PrimitiveKind::Int64 | PrimitiveKind::UInt64 => {
ts::Expr::Literal(Literal::Int("0n".to_string()))
}
PrimitiveKind::Float32
| PrimitiveKind::Float64
| PrimitiveKind::Int8
| PrimitiveKind::Octet
| PrimitiveKind::UInt8
| PrimitiveKind::Int16
| PrimitiveKind::UInt16
| PrimitiveKind::Int32
| PrimitiveKind::UInt32 => ts::Expr::Literal(Literal::int(0)),
}
}
fn zero_of(holder: &ts::Type) -> ts::Expr {
if *holder == ts::Type::bigint() {
return ts::Expr::Literal(Literal::Int("0n".to_string()));
}
ts::Expr::Literal(Literal::int(0))
}
fn filled_array(length: i128, element: ts::Expr) -> ts::Expr {
let element = match element {
ts::Expr::Object(_) => ts::Expr::Parenthesised(Box::new(element)),
other => other,
};
ts::Expr::Call {
callee: Box::new(ts::Expr::Member {
object: Box::new(ts::Expr::Path(Path::new(&["Array"]))),
name: Ident::new("from"),
}),
args: vec![
ts::Expr::Object(vec![(
ts::PropertyName::ident("length"),
ts::Expr::Literal(Literal::int(length)),
)]),
ts::Expr::Arrow {
params: Vec::new(),
body: Box::new(element),
},
],
}
}
#[must_use]
pub fn enumerator_constant(ast: &Ast, id: Id<TypeNode>, enumerator: &str) -> ts::Expr {
let mut segments: Vec<String> = match declared_path(ast, id) {
Ok(path) => path
.segments()
.iter()
.map(|segment| segment.as_str().to_string())
.collect(),
Err(_) => vec![format!("UnresolvedEnum{}", id.slot())],
};
segments.push(ts::escape_member(enumerator));
ts::Expr::Path(Path::new(
&segments.iter().map(String::as_str).collect::<Vec<&str>>(),
))
}
fn new_local(ast: &Ast, id: Id<TypeNode>, own_name: &str) -> Result<ts::Statement, EncodeError> {
let path = factory_path(ast, id).map_err(|_| EncodeError::NoWriter {
member: own_name.to_string(),
kind: "aggregate whose declared name the module chain will not answer for",
})?;
Ok(ts::Statement::Declare {
kind: ts::VarKind::Const,
name: Ident::new("v"),
type_: Some(TypeScript::value_type(ast, id)),
value: Some(ts::Expr::Call {
callee: Box::new(ts::Expr::Path(path)),
args: Vec::new(),
}),
})
}
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, ts::escape_member(&member.name))))
}
fn discriminant_literal(
ast: &Ast,
discriminator: Id<TypeNode>,
value: i128,
refuse: impl Fn(&'static str) -> EncodeError,
) -> Result<ts::Expr, EncodeError> {
Ok(match resolved_primitive(ast, discriminator) {
Some(PrimitiveKind::Boolean) => ts::Expr::Literal(Literal::Bool(value != 0)),
Some(PrimitiveKind::Char | PrimitiveKind::WChar) => {
char_literal(code_unit_of(value, refuse)?)
}
Some(PrimitiveKind::Int64 | PrimitiveKind::UInt64) => wide(value),
_ => {
match resolve_enumeration(ast, discriminator) {
Some(enumeration) => {
let Some(name) = enumerator_named_by(ast, enumeration, value) else {
return Err(refuse(
"a union discriminator value that names no enumerator",
));
};
enumerator_constant(ast, enumeration, &name)
}
None => ts::Expr::Literal(Literal::int(value)),
}
}
})
}
#[must_use]
pub fn case_label(ast: &Ast, discriminator: Id<TypeNode>, value: i128) -> Option<ts::Expr> {
let enumeration = resolve_enumeration(ast, discriminator)?;
let name = enumerator_named_by(ast, enumeration, value)?;
Some(enumerator_constant(ast, enumeration, &name))
}
fn resolve_enumeration(ast: &Ast, id: Id<TypeNode>) -> Option<Id<TypeNode>> {
let mut current = id;
for _ in 0..MAX_ALIAS_DEPTH {
match ast.type_(current).map(|node| node.kind.clone()) {
Ok(TypeKind::Enumeration { .. }) => return Some(current),
Ok(TypeKind::Alias { aliased }) => current = aliased.resolved()?,
_ => return None,
}
}
None
}
fn enumerator_named_by(ast: &Ast, id: Id<TypeNode>, value: i128) -> Option<String> {
for enumerator in ast.enumerators_of(id) {
if ast.effective_enumerator_value(*enumerator) == Some(value) {
return ast
.enumerator(*enumerator)
.ok()
.map(|node| node.name.clone());
}
}
None
}
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
}
pub fn explicit_default(
ast: &Ast,
expr: Id<zerodds_ast::ConstExprNode>,
type_: Id<TypeNode>,
member_name: &str,
) -> Result<ts::Expr, EncodeError> {
explicit(ast, expr, type_, member_name)
}
#[allow(clippy::too_many_lines)]
fn explicit(
ast: &Ast,
expr: Id<zerodds_ast::ConstExprNode>,
type_: Id<TypeNode>,
member_name: &str,
) -> Result<ts::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());
match &node.expr {
ConstExpr::Literal(AstLiteral::Boolean(flag)) => {
Ok(ts::Expr::Literal(Literal::Bool(*flag)))
}
ConstExpr::Literal(AstLiteral::Char(ch)) => Ok(char_literal(u32::from(*ch))),
ConstExpr::Literal(AstLiteral::WChar(code)) => {
Ok(char_literal(code_unit_of(i128::from(*code), refuse)?))
}
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}"));
Ok(ts::Expr::Literal(Literal::Float(format!(
"{mantissa}{exponent}"
))))
}
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(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)) => {
ts::Expr::Literal(Literal::Bool(value != 0))
}
Ok(TypeKind::Primitive(PrimitiveKind::Char | PrimitiveKind::WChar)) => {
char_literal(code_unit_of(value, refuse)?)
}
Ok(TypeKind::Primitive(PrimitiveKind::Int64 | PrimitiveKind::UInt64)) => {
wide(value)
}
_ => ts::Expr::Literal(Literal::int(value)),
})
}
}
}
fn wide(value: i128) -> ts::Expr {
ts::Expr::Literal(Literal::Int(format!("{value}n")))
}
fn char_literal(code: u32) -> ts::Expr {
ts::Expr::Call {
callee: Box::new(ts::Expr::Member {
object: Box::new(ts::Expr::Path(Path::new(&["String"]))),
name: Ident::new("fromCharCode"),
}),
args: vec![ts::Expr::Literal(Literal::int(i128::from(code)))],
}
}
fn code_unit_of(
value: i128,
refuse: impl Fn(&'static str) -> EncodeError,
) -> Result<u32, EncodeError> {
let code = u32::try_from(value)
.map_err(|_| refuse("a `@default` character outside the range of a code unit"))?;
if code > u32::from(u16::MAX) {
return Err(refuse(
"a `@default` character above the Basic Multilingual Plane, \
which no single UTF-16 code unit holds",
));
}
Ok(code)
}
fn calls_in_decl(decl: &ts::Decl, out: &mut Vec<String>) {
match decl {
ts::Decl::Function(function) => {
if let Some(body) = &function.body {
calls_in_block(body, out);
}
}
ts::Decl::Variable(variable) => {
if let Some(value) = &variable.value {
calls_in_expr(value, out);
}
}
ts::Decl::Class(class) => {
for member in &class.members {
match member {
ts::ClassMember::Field(field) => {
if let Some(value) = &field.value {
calls_in_expr(value, out);
}
}
ts::ClassMember::Method(method) => {
if let Some(body) = &method.body {
calls_in_block(body, out);
}
}
ts::ClassMember::Constructor(constructor) => {
calls_in_block(&constructor.body, out);
}
ts::ClassMember::Comment(_) | ts::ClassMember::Verbatim(_) => {}
}
}
}
ts::Decl::Namespace(namespace) => {
for nested in &namespace.decls {
calls_in_decl(nested, out);
}
}
ts::Decl::Statement(statement) => calls_in_statement(statement, out),
ts::Decl::Interface(_)
| ts::Decl::TypeAlias(_)
| ts::Decl::Enum(_)
| ts::Decl::Comment(_)
| ts::Decl::Verbatim(_) => {}
}
}
fn calls_in_block(block: &ts::Block, out: &mut Vec<String>) {
for statement in &block.statements {
calls_in_statement(statement, out);
}
}
fn calls_in_statement(statement: &ts::Statement, out: &mut Vec<String>) {
match statement {
ts::Statement::Declare { value, .. } => {
if let Some(value) = value {
calls_in_expr(value, out);
}
}
ts::Statement::Expr(expr) | ts::Statement::Throw(expr) => calls_in_expr(expr, out),
ts::Statement::Return(value) => {
if let Some(value) = value {
calls_in_expr(value, out);
}
}
ts::Statement::If {
condition,
then,
otherwise,
} => {
calls_in_expr(condition, out);
calls_in_block(then, out);
if let Some(otherwise) = otherwise {
calls_in_block(otherwise, out);
}
}
ts::Statement::For { bound, body, .. } => {
calls_in_expr(bound, out);
calls_in_block(body, out);
}
ts::Statement::While { condition, body } => {
calls_in_expr(condition, out);
calls_in_block(body, out);
}
ts::Statement::ForOf { range, body, .. } => {
calls_in_expr(range, out);
calls_in_block(body, out);
}
ts::Statement::Switch { value, cases } => {
calls_in_expr(value, out);
for case in cases {
for label in &case.labels {
calls_in_expr(label, out);
}
calls_in_block(&case.body, out);
}
}
ts::Statement::Break | ts::Statement::Comment(_) => {}
}
}
#[allow(clippy::too_many_lines)]
fn calls_in_expr(expr: &ts::Expr, out: &mut Vec<String>) {
match expr {
ts::Expr::Call { callee, args } => {
if let ts::Expr::Path(path) = callee.as_ref() {
if path.segments().len() == 1 {
let name = path
.segments()
.first()
.map(|segment| segment.as_str().to_string())
.unwrap_or_default();
if name.starts_with("zd_def_") && !out.iter().any(|seen| seen == &name) {
out.push(name);
}
}
}
calls_in_expr(callee, out);
for arg in args {
calls_in_expr(arg, out);
}
}
ts::Expr::Member { object, .. } => calls_in_expr(object, out),
ts::Expr::Index { object, index } => {
calls_in_expr(object, out);
calls_in_expr(index, out);
}
ts::Expr::Array(values) => {
for value in values {
calls_in_expr(value, out);
}
}
ts::Expr::Object(entries) => {
for (_, value) in entries {
calls_in_expr(value, out);
}
}
ts::Expr::New { args, .. } => {
for arg in args {
calls_in_expr(arg, out);
}
}
ts::Expr::Paren(value)
| ts::Expr::Parenthesised(value)
| ts::Expr::NonNull(value)
| ts::Expr::AsConst(value)
| ts::Expr::Unary { value, .. }
| ts::Expr::As { value, .. } => calls_in_expr(value, out),
ts::Expr::Arrow { body, .. } => calls_in_expr(body, out),
ts::Expr::Binary { lhs, rhs, .. } => {
calls_in_expr(lhs, out);
calls_in_expr(rhs, out);
}
ts::Expr::Ternary {
condition,
then,
otherwise,
} => {
calls_in_expr(condition, out);
calls_in_expr(then, out);
calls_in_expr(otherwise, out);
}
ts::Expr::Literal(_) | ts::Expr::Path(_) | ts::Expr::This | ts::Expr::Undefined => {}
}
}
fn name(text: &str) -> ts::Expr {
ts::Expr::Path(Path::new(&text.split('.').collect::<Vec<_>>()))
}
fn text(value: &str) -> ts::Expr {
ts::Expr::Literal(Literal::Str(value.to_string()))
}
fn call(callee: &str, args: Vec<ts::Expr>) -> ts::Expr {
ts::Expr::Call {
callee: Box::new(name(callee)),
args,
}
}
fn member(base: &str, field: &str) -> ts::Expr {
ts::Expr::Member {
object: Box::new(name(base)),
name: Ident::new(field),
}
}
fn assign(place: ts::Expr, value: ts::Expr) -> ts::Statement {
ts::Statement::Expr(ts::Expr::Binary {
op: "=",
lhs: Box::new(place),
rhs: Box::new(value),
})
}
fn give_back(value: ts::Expr) -> ts::Statement {
ts::Statement::Return(Some(value))
}
const _: Option<MaterialiseError> = None;