1use crate::{
2 global::{
3 operators::ModificationOperator,
4 protocol_structures::injected_values::InjectedValueDeclaration,
5 },
6 instruction::type_instruction_codes::{
7 TypeLocalOrShared, TypeMutabilityCode, TypeOwnershipCode,
8 },
9 prelude::*,
10 shared_values::{
11 PointerAddress, ReferenceMutability, RemotePointerAddress,
12 SelfOwnedPointerAddress, SharedContainerMutability,
13 },
14 types::{
15 type_definition::callable::CallableKind,
16 type_definition_with_metadata::TypeMetadata,
17 },
18 values::core_values::{decimal::Decimal, integer::Integer},
19};
20use alloc::string::FromUtf8Error;
21use binrw::{
22 BinRead, BinResult, BinWrite, Endian,
23 io::{Read, Seek, Write},
24 meta::{EndianKind, ReadEndian},
25};
26use core::{fmt::Display, ops::Deref};
27use itertools::Itertools;
28use modular_bitfield::{bitfield, prelude::B4};
29
30#[cfg(feature = "disassembler")]
31mod disassembler_instruction_data;
32use crate::{
33 libs::core::{
34 core_lib_id::CoreLibIdIndex,
35 type_id::{CoreLibBaseTypeId, CoreLibTypeId, CoreLibVariantTypeId},
36 },
37 values::core_values::integer::typed_integer::IntegerTypeVariant,
38};
39#[cfg(feature = "disassembler")]
40pub use disassembler_instruction_data::*;
41
42#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
43#[brw(little)]
44pub struct Int8Data(pub i8);
45
46#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
47#[brw(little)]
48pub struct Int16Data(pub i16);
49
50#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
51#[brw(little)]
52pub struct Int32Data(pub i32);
53
54#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
55#[brw(little)]
56pub struct Int64Data(pub i64);
57
58#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
59#[brw(little)]
60pub struct Int128Data(pub i128);
61
62#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
63#[brw(little)]
64pub struct UInt8Data(pub u8);
65
66#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
67#[brw(little)]
68pub struct UInt16Data(pub u16);
69
70#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
71#[brw(little)]
72pub struct UInt32Data(pub u32);
73
74#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
75#[brw(little)]
76pub struct UInt64Data(pub u64);
77
78#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
79#[brw(little)]
80pub struct UInt128Data(pub u128);
81
82#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
83#[brw(little)]
84pub struct Float32Data(pub f32);
85
86#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
87#[brw(little)]
88pub struct Float64Data(pub f64);
89
90#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
91#[brw(little)]
92pub struct FloatAsInt16Data(pub i16);
93
94#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
95#[brw(little)]
96pub struct FloatAsInt32Data(pub i32);
97
98#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
99#[brw(little)]
100pub struct DecimalData(pub Decimal);
101
102#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
103#[brw(little)]
104pub struct IntegerData(pub Integer);
105
106#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
107#[brw(little)]
108pub struct InstantData(pub i128);
109
110#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
111#[brw(little)]
112pub struct ShortTextDataRaw {
113 pub length: u8,
114 #[br(count = length)]
115 pub text: Vec<u8>,
116}
117#[derive(Clone, Debug, PartialEq)]
118pub struct ShortTextData(pub String);
119impl ShortTextData {
120 pub fn new(text: impl Into<String>) -> Self {
121 ShortTextData(text.into())
122 }
123}
124impl Deref for ShortTextData {
125 type Target = String;
126
127 fn deref(&self) -> &Self::Target {
128 &self.0
129 }
130}
131impl From<&ShortTextData> for ShortTextDataRaw {
132 fn from(value: &ShortTextData) -> Self {
133 let bytes = value.0.as_bytes();
134
135 Self {
136 length: bytes.len() as u8,
137 text: bytes.to_vec(),
138 }
139 }
140}
141
142impl TryFrom<ShortTextDataRaw> for ShortTextData {
143 type Error = FromUtf8Error;
144 fn try_from(raw: ShortTextDataRaw) -> Result<Self, Self::Error> {
145 let string = String::from_utf8(raw.text)?;
146 Ok(ShortTextData(string))
147 }
148}
149
150impl BinWrite for ShortTextData {
151 type Args<'a> = ();
152
153 fn write_options<W: Write + Seek>(
154 &self,
155 writer: &mut W,
156 endian: Endian,
157 _: Self::Args<'_>,
158 ) -> BinResult<()> {
159 let raw = ShortTextDataRaw::from(self);
160 raw.write_options(writer, endian, ())
161 }
162}
163
164impl BinRead for ShortTextData {
165 type Args<'a> = ();
166
167 fn read_options<R: Read + Seek>(
168 reader: &mut R,
169 endian: Endian,
170 _: Self::Args<'_>,
171 ) -> BinResult<Self> {
172 let raw = ShortTextDataRaw::read_options(reader, endian, ())?;
173 raw.try_into().map_err(|_| binrw::Error::AssertFail {
174 pos: reader.stream_position().unwrap_or(0),
175 message: "Invalid UTF-8 string".to_string(),
176 })
177 }
178}
179
180impl ReadEndian for ShortTextData {
181 const ENDIAN: EndianKind = EndianKind::Endian(Endian::Little);
182}
183
184#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
185#[brw(little)]
186pub struct CallableSignatureData {
187 pub name: ShortTextData, pub kind: CallableKind,
189 pub parameter_count: u8,
190 #[br(map = |x: u8| x != 0)]
191 #[bw(map = |b: &bool| if *b { 1u8 } else { 0u8 })]
192 pub requires_async: bool,
193 #[br(map = |x: u8| x != 0)]
194 #[bw(map = |b: &bool| if *b { 1u8 } else { 0u8 })]
195 pub has_rest_parameter: bool,
196 #[br(map = |x: u8| x != 0)]
197 #[bw(map = |b: &bool| if *b { 1u8 } else { 0u8 })]
198 pub has_return_type: bool,
199 #[br(map = |x: u8| x != 0)]
200 #[bw(map = |b: &bool| if *b { 1u8 } else { 0u8 })]
201 pub has_yeet_type: bool,
202 #[br(count = parameter_count)]
203 pub parameter_names: Vec<ShortTextData>,
204 #[br(if(has_rest_parameter))]
205 pub rest_parameter_name: Option<ShortTextData>,
206}
207
208impl Display for CallableSignatureData {
209 fn fmt(
210 &self,
211 formatter: &mut core::fmt::Formatter,
212 ) -> Result<(), core::fmt::Error> {
213 write!(formatter, "[")?;
214 write!(formatter, "kind: {}, ", self.kind)?;
215 write!(formatter, "requires_async: {}, ", self.requires_async)?;
216 write!(
217 formatter,
218 "parameters: [{}], ",
219 self.parameter_names.iter().map(|n| &n.0).join(", ")
220 )?;
221 if let Some(rest) = &self.rest_parameter_name {
222 write!(formatter, ", rest_parameter: {}, ", rest.0)?;
223 }
224 write!(formatter, "has_return_type: {}, ", self.has_return_type)?;
225 write!(formatter, "has_yeet_type: {}", self.has_yeet_type)?;
226 write!(formatter, "]")?;
227 Ok(())
228 }
229}
230
231impl CallableSignatureData {
232 pub fn total_type_count(&self) -> u32 {
234 let mut count = self.parameter_count as u32;
235 if self.has_rest_parameter {
236 count += 1;
237 }
238 if self.has_return_type {
239 count += 1;
240 }
241 if self.has_yeet_type {
242 count += 1;
243 }
244 count
245 }
246}
247
248#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
249#[brw(little)]
250pub struct CallableDeclarationData {
251 pub signature: CallableSignatureData,
252 pub body: InstructionBlockData,
253}
254
255#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
256#[brw(little)]
257pub struct EntityTypeDefinitionData {
258 pub name: ShortTextData,
259}
260
261#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
262#[brw(little)]
263pub struct ClassifiedValueData {
264 #[br(map = |x: u8| x != 0)]
266 #[bw(map = |b: &bool| if *b { 1u8 } else { 0u8 })]
267 pub has_tag: bool,
268 #[br(if(has_tag))]
269 pub(crate) tag: Option<ShortTextData>,
270 #[br(map = |x: u8| x != 0)]
271 #[bw(map = |b: &bool| if *b { 1u8 } else { 0u8 })]
272 pub(crate) tag_value_is_empty: bool,
273
274 #[br(map = |x: u8| x != 0)]
276 #[bw(map = |b: &bool| if *b { 1u8 } else { 0u8 })]
277 pub(crate) is_entity: bool,
278
279 pub impl_count: u32,
281 #[br(count = impl_count)]
282 pub(crate) impls: Vec<PointerAddress>,
283}
284
285impl ClassifiedValueData {
286 pub fn new_tagged(tag: String, tag_value_is_empty: bool) -> Self {
287 Self {
288 has_tag: true,
289 tag: Some(ShortTextData(tag)),
290 tag_value_is_empty,
291 is_entity: false,
292 impl_count: 0,
293 impls: Vec::new(),
294 }
295 }
296
297 pub fn new_entity() -> Self {
298 Self {
299 has_tag: false,
300 tag: None,
301 tag_value_is_empty: false,
302 is_entity: true,
303 impl_count: 0,
304 impls: Vec::new(),
305 }
306 }
307}
308
309#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
310#[brw(little)]
311pub struct CallableData {
312 pub signature: CallableSignatureData,
313 pub body: CallableDataBody,
314}
315
316#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
317#[brw(little)]
318pub struct CallableDataBody {
319 pub injected_value_count: u32,
320 pub length: u32, #[br(count = length)]
322 pub body: Vec<u8>,
323}
324
325impl Display for CallableDataBody {
326 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
327 write!(
328 f,
329 "[length: {}, injected_value_count: {}]",
330 self.length, self.injected_value_count,
331 )
332 }
333}
334
335#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
336#[brw(little)]
337pub struct TextDataRaw {
338 pub length: u32,
339 #[br(count = length)]
340 pub text: Vec<u8>,
341}
342
343#[derive(Clone, Debug, PartialEq)]
344pub struct TextData(pub String);
345
346impl From<String> for TextData {
347 fn from(value: String) -> Self {
348 TextData(value)
349 }
350}
351impl From<&str> for TextData {
352 fn from(value: &str) -> Self {
353 TextData(value.to_string())
354 }
355}
356
357impl From<&TextData> for TextDataRaw {
358 fn from(value: &TextData) -> Self {
359 let bytes = value.0.as_bytes();
360
361 Self {
362 length: bytes.len() as u32,
363 text: bytes.to_vec(),
364 }
365 }
366}
367
368impl TryFrom<TextDataRaw> for TextData {
369 type Error = FromUtf8Error;
370 fn try_from(raw: TextDataRaw) -> Result<Self, Self::Error> {
371 let string = String::from_utf8(raw.text)?;
372 Ok(TextData(string))
373 }
374}
375
376impl BinWrite for TextData {
377 type Args<'a> = ();
378
379 fn write_options<W: Write + Seek>(
380 &self,
381 writer: &mut W,
382 endian: Endian,
383 _: Self::Args<'_>,
384 ) -> BinResult<()> {
385 let raw = TextDataRaw::from(self);
386 raw.write_options(writer, endian, ())
387 }
388}
389
390impl BinRead for TextData {
391 type Args<'a> = ();
392
393 fn read_options<R: Read + Seek>(
394 reader: &mut R,
395 endian: Endian,
396 _: Self::Args<'_>,
397 ) -> BinResult<Self> {
398 let raw = TextDataRaw::read_options(reader, endian, ())?;
399 raw.try_into().map_err(|_| binrw::Error::AssertFail {
400 pos: reader.stream_position().unwrap_or(0),
401 message: "Invalid UTF-8 string".to_string(),
402 })
403 }
404}
405
406impl ReadEndian for TextData {
407 const ENDIAN: EndianKind = EndianKind::Endian(Endian::Little);
408}
409
410#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
411#[brw(little)]
412pub struct ShortListData {
413 pub element_count: u8,
414}
415
416pub fn element_size(core_lib_type_id: CoreLibIdIndex) -> u32 {
420 match CoreLibTypeId::try_from(core_lib_type_id) {
421 Ok(id) => match id {
422 CoreLibTypeId::Base(base_id) => match base_id {
423 CoreLibBaseTypeId::Null => 0,
424 CoreLibBaseTypeId::Boolean => 1,
425 _ => unimplemented!(
426 "Core lib type does not support element size: {}",
427 core_lib_type_id
428 ),
429 },
430 CoreLibTypeId::Variant(variant_id) => match variant_id {
431 CoreLibVariantTypeId::Integer(integer_variant) => {
432 match integer_variant {
433 IntegerTypeVariant::U8 => 1,
434 IntegerTypeVariant::U16 => 2,
435 IntegerTypeVariant::U32 => 4,
436 IntegerTypeVariant::U64 => 8,
437 IntegerTypeVariant::U128 => 16,
438 IntegerTypeVariant::I8 => 1,
439 IntegerTypeVariant::I16 => 2,
440 IntegerTypeVariant::I32 => 4,
441 IntegerTypeVariant::I64 => 8,
442 IntegerTypeVariant::I128 => 16,
443 _ => unimplemented!(
444 "Core lib type does not support element size: {}",
445 core_lib_type_id
446 ),
447 }
448 }
449 _ => unimplemented!(
450 "Core lib type does not support element size: {}",
451 core_lib_type_id
452 ),
453 },
454 },
455 Err(_) => unimplemented!(
456 "Core lib type does not support element size: {}",
457 core_lib_type_id
458 ),
459 }
460}
461
462pub fn calculate_list_size(
463 core_lib_type_id: CoreLibIdIndex,
464 element_count: u32,
465) -> u32 {
466 let element_size = element_size(core_lib_type_id);
467 element_size * element_count
468}
469
470#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
471#[brw(little)]
472pub struct CompactListData {
473 pub element_count: u32,
474 pub core_lib_type: CoreLibIdIndex,
475 #[br(count = calculate_list_size(core_lib_type, element_count))]
476 pub elements: Vec<u8>,
477}
478
479#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
480#[brw(little)]
481pub struct StatementsData {
482 pub statements_count: u32,
483 #[br(map = |x: u8| x != 0)]
484 #[bw(map = |b: &bool| if *b { 1u8 } else { 0u8 })]
485 pub terminated: bool,
486}
487
488#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
489#[brw(little)]
490pub struct UnboundedStatementsData {
491 #[br(map = |x: u8| x != 0)]
492 #[bw(map = |b: &bool| if *b { 1u8 } else { 0u8 })]
493 pub terminated: bool,
494}
495
496#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
497#[brw(little)]
498pub struct ShortStatementsData {
499 pub statements_count: u8,
500 #[br(map = |x: u8| x != 0)]
501 #[bw(map = |b: &bool| if *b { 1u8 } else { 0u8 })]
502 pub terminated: bool,
503}
504
505#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
506#[brw(little)]
507pub struct ListData {
508 pub element_count: u32,
509}
510
511#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
512#[brw(little)]
513pub struct ShortMapData {
514 pub element_count: u8,
515 #[br(map = |x: u8| x != 0)]
516 #[bw(map = |b: &bool| if *b { 1u8 } else { 0u8 })]
517 pub allow_only_text_keys: bool,
518}
519
520#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
521#[brw(little)]
522pub struct MapData {
523 pub element_count: u32,
524 #[br(map = |x: u8| x != 0)]
525 #[bw(map = |b: &bool| if *b { 1u8 } else { 0u8 })]
526 pub allow_only_text_keys: bool,
527}
528
529#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
530#[brw(little)]
531pub struct UnionData {
532 pub element_count: u32,
533}
534
535#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
536#[brw(little)]
537pub struct InstructionCloseAndStore {
538 pub instruction: Int8Data,
539}
540
541#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
542#[brw(little)]
543pub struct GetOrCreateRemoteRefData {
544 pub address: RemotePointerAddress,
545 pub create_block_size: u64,
546}
547
548#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
549#[brw(little)]
550pub struct MoveWithValue {
551 pub mutability: SharedContainerMutability,
552 pub previous_address: SelfOwnedPointerAddress,
553}
554
555#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
556#[brw(little)]
557pub struct SharedRef {
558 pub address: PointerAddress,
559 pub ref_mutability: ReferenceMutability,
560 pub container_mutability: SharedContainerMutability,
561 #[br(map = |x: u8| x != 0)]
562 #[bw(map = |b: &bool| if *b { 1u8 } else { 0u8 })]
563 pub is_debug: bool,
564 }
566
567#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
568#[brw(little)]
569pub struct SharedRefWithValue {
570 pub address: SelfOwnedPointerAddress, pub ref_mutability: ReferenceMutability,
572 pub container_mutability: SharedContainerMutability,
573 #[br(map = |x: u8| x != 0)]
574 #[bw(map = |b: &bool| if *b { 1u8 } else { 0u8 })]
575 pub is_debug: bool,
576}
577
578#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
579#[brw(little)]
580pub struct ModifySharedContainerValue {
581 pub operator: ModificationOperator,
582}
583
584#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
585#[brw(little)]
586pub struct InstructionBlockData {
587 pub length: u32,
588 pub injected_value_count: u32,
589 #[br(count = injected_value_count)]
590 pub injected_values: Vec<InjectedValueDeclaration>,
591 #[br(count = length)]
592 pub body: Vec<u8>,
593}
594
595impl Display for InstructionBlockData {
596 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
597 write!(
598 f,
599 "[length: {}, injected_value_count: {}, injected_values: [{}]]",
600 self.length,
601 self.injected_value_count,
602 self.injected_values
603 .iter()
604 .map(|v| format!("{}", v))
605 .join(", "),
606 )
607 }
608}
609
610#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
611#[brw(little)]
612pub struct SpliceData {
613 pub start_index: u32,
614 pub delete_count: u32,
615 pub insert_count: u32,
616}
617
618#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
619#[brw(little)]
620pub struct JumpData {
621 pub offset: i32,
622}
623
624#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
625#[brw(little)]
626pub struct JumpWithValueData {
627 pub offset: i32,
628 pub value: i32, }
631
632#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
633#[brw(little)]
634pub struct ApplyData {
635 pub arg_count: u8,
636}
637
638#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
639#[brw(little)]
640pub struct CallMethodData {
641 pub method_name: ShortTextData,
642 pub arg_count: u8,
643}
644
645#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
646#[brw(little)]
647pub struct ImplMarkersData {
648 pub impl_count: u8,
649 #[br(count = impl_count)]
650 pub impls: Vec<PointerAddress>,
651}
652
653#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
654#[brw(little)]
655pub struct TaggedTypeData {
656 pub(crate) tag: ShortTextData,
657 #[br(map = |x: u8| x != 0)]
658 #[bw(map = |b: &bool| if *b { 1u8 } else { 0u8 })]
659 pub(crate) has_type: bool,
660}
661impl TaggedTypeData {
662 pub fn new(tag: String, has_type: bool) -> Self {
663 Self {
664 tag: ShortTextData(tag),
665 has_type,
666 }
667 }
668}
669
670#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
671#[brw(little)]
672pub struct IntersectionData {
673 pub(crate) element_count: u32,
674}
675
676#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
677#[brw(little)]
678pub struct ListSliceCollectionData {
679 pub(crate) element_count: u32,
680}
681
682#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
683#[brw(little)]
684pub struct TypeReferenceData {
685 pub address: PointerAddress,
686}
687
688#[bitfield]
689#[derive(BinWrite, BinRead, Clone, Copy, Debug, PartialEq)]
690#[bw(map = |&x| Self::into_bytes(x))]
691#[br(map = Self::from_bytes)]
692#[brw(little)]
693pub struct TypeMetadataBin {
694 pub ownership: TypeOwnershipCode,
695 pub mutability: TypeMutabilityCode,
696 pub type_local_or_shared: TypeLocalOrShared,
697 #[skip]
698 _unused: B4,
699}
700
701impl From<&TypeMetadataBin> for TypeMetadata {
702 fn from(value: &TypeMetadataBin) -> Self {
703 match value.type_local_or_shared() {
704 TypeLocalOrShared::Local => TypeMetadata::Local {
705 mutability: (&value.mutability()).into(),
706 ownership: (&value.ownership()).into(),
707 },
708 TypeLocalOrShared::Shared => TypeMetadata::Shared {
709 mutability: (&value.mutability()).into(),
710 ownership: (&value.ownership()).into(),
711 },
712 }
713 }
714}
715
716impl From<&TypeMetadata> for TypeMetadataBin {
717 fn from(value: &TypeMetadata) -> Self {
718 match value {
719 TypeMetadata::Local {
720 mutability,
721 ownership: reference_mutability,
722 } => Self::new()
723 .with_type_local_or_shared(TypeLocalOrShared::Local)
724 .with_mutability(mutability.into())
725 .with_ownership(reference_mutability.into()),
726 TypeMetadata::Shared {
727 mutability,
728 ownership,
729 } => Self::new()
730 .with_type_local_or_shared(TypeLocalOrShared::Shared)
731 .with_mutability(mutability.into())
732 .with_ownership(ownership.into()),
733 }
734 }
735}