1use crate::{
2 core_compiler::value_compiler::append_instruction,
3 global::{
4 operators::AssignmentOperator,
5 protocol_structures::{
6 injected_values::InjectedValueDeclaration,
7 instructions::Instruction,
8 },
9 type_instruction_codes::{
10 TypeLocalOrShared, TypeMutabilityCode, TypeOwnershipCode,
11 },
12 },
13 prelude::*,
14 shared_values::{
15 PointerAddress, ReferenceMutability, RemotePointerAddress,
16 SelfOwnedPointerAddress, SharedContainerMutability,
17 },
18 types::type_definition_with_metadata::TypeMetadata,
19};
20use alloc::string::FromUtf8Error;
21use binrw::{
22 BinRead, BinResult, BinWrite, Endian,
23 io::{Cursor, Read, Seek, Write},
24 meta::{EndianKind, ReadEndian},
25};
26use cfg_if::cfg_if;
27use core::{fmt::Display, ops::AddAssign};
28use modular_bitfield::{bitfield, prelude::B4};
29
30#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
31#[brw(little)]
32pub struct Int8Data(pub i8);
33
34#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
35#[brw(little)]
36pub struct Int16Data(pub i16);
37
38#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
39#[brw(little)]
40pub struct Int32Data(pub i32);
41
42#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
43#[brw(little)]
44pub struct Int64Data(pub i64);
45
46#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
47#[brw(little)]
48pub struct Int128Data(pub i128);
49
50#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
51#[brw(little)]
52pub struct UInt8Data(pub u8);
53
54#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
55#[brw(little)]
56pub struct UInt16Data(pub u16);
57
58#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
59#[brw(little)]
60pub struct UInt32Data(pub u32);
61
62#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
63#[brw(little)]
64pub struct UInt64Data(pub u64);
65
66#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
67#[brw(little)]
68pub struct UInt128Data(pub u128);
69
70#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
71#[brw(little)]
72pub struct Float32Data(pub f32);
73
74#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
75#[brw(little)]
76pub struct Float64Data(pub f64);
77
78#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
79#[brw(little)]
80pub struct FloatAsInt16Data(pub i16);
81
82#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
83#[brw(little)]
84pub struct FloatAsInt32Data(pub i32);
85
86#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
87#[brw(little)]
88pub struct ShortTextDataRaw {
89 pub length: u8,
90 #[br(count = length)]
91 pub text: Vec<u8>,
92}
93#[derive(Clone, Debug, PartialEq)]
94pub struct ShortTextData(pub String);
95
96impl From<&ShortTextData> for ShortTextDataRaw {
97 fn from(value: &ShortTextData) -> Self {
98 let bytes = value.0.as_bytes();
99
100 Self {
101 length: bytes.len() as u8,
102 text: bytes.to_vec(),
103 }
104 }
105}
106
107impl TryFrom<ShortTextDataRaw> for ShortTextData {
108 type Error = FromUtf8Error;
109 fn try_from(raw: ShortTextDataRaw) -> Result<Self, Self::Error> {
110 let string = String::from_utf8(raw.text)?;
111 Ok(ShortTextData(string))
112 }
113}
114
115impl BinWrite for ShortTextData {
116 type Args<'a> = ();
117
118 fn write_options<W: Write + Seek>(
119 &self,
120 writer: &mut W,
121 endian: Endian,
122 _: Self::Args<'_>,
123 ) -> BinResult<()> {
124 let raw = ShortTextDataRaw::from(self);
125 raw.write_options(writer, endian, ())
126 }
127}
128
129impl BinRead for ShortTextData {
130 type Args<'a> = ();
131
132 fn read_options<R: Read + Seek>(
133 reader: &mut R,
134 endian: Endian,
135 _: Self::Args<'_>,
136 ) -> BinResult<Self> {
137 let raw = ShortTextDataRaw::read_options(reader, endian, ())?;
138 raw.try_into().map_err(|_| binrw::Error::AssertFail {
139 pos: reader.stream_position().unwrap_or(0),
140 message: "Invalid UTF-8 string".to_string(),
141 })
142 }
143}
144
145impl ReadEndian for ShortTextData {
146 const ENDIAN: EndianKind = EndianKind::Endian(Endian::Little);
147}
148
149#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
150#[brw(little)]
151pub struct TaggedValue {
152 pub(crate) tag: ShortTextData,
153 #[br(map = |x: u8| x != 0)]
154 #[bw(map = |b: &bool| if *b { 1u8 } else { 0u8 })]
155 pub(crate) is_empty: bool,
156}
157
158#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
159#[brw(little)]
160pub struct TextDataRaw {
161 pub length: u32,
162 #[br(count = length)]
163 pub text: Vec<u8>,
164}
165
166#[derive(Clone, Debug, PartialEq)]
167pub struct TextData(pub String);
168
169impl From<String> for TextData {
170 fn from(value: String) -> Self {
171 TextData(value)
172 }
173}
174impl From<&str> for TextData {
175 fn from(value: &str) -> Self {
176 TextData(value.to_string())
177 }
178}
179
180impl From<&TextData> for TextDataRaw {
181 fn from(value: &TextData) -> Self {
182 let bytes = value.0.as_bytes();
183
184 Self {
185 length: bytes.len() as u32,
186 text: bytes.to_vec(),
187 }
188 }
189}
190
191impl TryFrom<TextDataRaw> for TextData {
192 type Error = FromUtf8Error;
193 fn try_from(raw: TextDataRaw) -> Result<Self, Self::Error> {
194 let string = String::from_utf8(raw.text)?;
195 Ok(TextData(string))
196 }
197}
198
199impl BinWrite for TextData {
200 type Args<'a> = ();
201
202 fn write_options<W: Write + Seek>(
203 &self,
204 writer: &mut W,
205 endian: Endian,
206 _: Self::Args<'_>,
207 ) -> BinResult<()> {
208 let raw = TextDataRaw::from(self);
209 raw.write_options(writer, endian, ())
210 }
211}
212
213impl BinRead for TextData {
214 type Args<'a> = ();
215
216 fn read_options<R: Read + Seek>(
217 reader: &mut R,
218 endian: Endian,
219 _: Self::Args<'_>,
220 ) -> BinResult<Self> {
221 let raw = TextDataRaw::read_options(reader, endian, ())?;
222 raw.try_into().map_err(|_| binrw::Error::AssertFail {
223 pos: reader.stream_position().unwrap_or(0),
224 message: "Invalid UTF-8 string".to_string(),
225 })
226 }
227}
228
229impl ReadEndian for TextData {
230 const ENDIAN: EndianKind = EndianKind::Endian(Endian::Little);
231}
232
233#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
234#[brw(little)]
235pub struct ShortListData {
236 pub element_count: u8,
237}
238
239#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
240#[brw(little)]
241pub struct StatementsData {
242 pub statements_count: u32,
243 #[br(map = |x: u8| x != 0)]
244 #[bw(map = |b: &bool| if *b { 1u8 } else { 0u8 })]
245 pub terminated: bool,
246}
247
248#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
249#[brw(little)]
250pub struct UnboundedStatementsData {
251 #[br(map = |x: u8| x != 0)]
252 #[bw(map = |b: &bool| if *b { 1u8 } else { 0u8 })]
253 pub terminated: bool,
254}
255
256#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
257#[brw(little)]
258pub struct ShortStatementsData {
259 pub statements_count: u8,
260 #[br(map = |x: u8| x != 0)]
261 #[bw(map = |b: &bool| if *b { 1u8 } else { 0u8 })]
262 pub terminated: bool,
263}
264
265#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
266#[brw(little)]
267pub struct ListData {
268 pub element_count: u32,
269}
270
271#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
272#[brw(little)]
273pub struct ShortMapData {
274 pub element_count: u8,
275}
276
277#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
278#[brw(little)]
279pub struct MapData {
280 pub element_count: u32,
281}
282
283#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
284#[brw(little)]
285pub struct InstructionCloseAndStore {
286 pub instruction: Int8Data,
287}
288
289#[derive(
290 BinRead, BinWrite, Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord,
291)]
292#[brw(little)]
293pub struct StackIndex(pub u32);
294
295impl Display for StackIndex {
296 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
297 write!(f, "\\{}", self.0)
298 }
299}
300
301impl AddAssign<u32> for StackIndex {
302 fn add_assign(&mut self, rhs: u32) {
303 self.0 += rhs;
304 }
305}
306
307#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
308#[brw(little)]
309pub struct GetOrCreateRemoteRefData {
310 pub address: RemotePointerAddress,
311 pub create_block_size: u64,
312}
313
314#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
315#[brw(little)]
316pub struct PerformMoves {
317 pub pointer_count: u32,
318 #[br(count = pointer_count)]
319 pub pointers: Vec<(u8, SelfOwnedPointerAddress)>, }
321
322#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
323#[brw(little)]
324pub struct SharedRef {
325 pub address: PointerAddress,
326 pub ref_mutability: ReferenceMutability,
327 pub container_mutability: SharedContainerMutability,
328}
329
330#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
331#[brw(little)]
332pub struct SharedRefWithValue {
333 pub address: SelfOwnedPointerAddress, pub ref_mutability: ReferenceMutability,
335 pub container_mutability: SharedContainerMutability,
336}
337
338#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
339#[brw(little)]
340pub struct ModifySharedContainerValue {
341 pub operator: AssignmentOperator,
342}
343
344#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
345#[brw(little)]
346pub struct ModifyStackValue {
347 pub index: StackIndex,
348 pub operator: AssignmentOperator,
349}
350
351#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
352#[brw(little)]
353pub struct Move {
354 pub pointer_count: u32,
355 #[br(count = pointer_count)]
356 pub address_mappings:
357 Vec<(SelfOwnedPointerAddress, SelfOwnedPointerAddress)>,
358}
359
360#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
361#[brw(little)]
362pub struct InstructionBlockData {
363 pub length: u32,
364 pub injected_value_count: u32,
365 #[br(count = injected_value_count)]
366 pub injected_values: Vec<InjectedValueDeclaration>,
367 #[br(count = length)]
368 pub body: Vec<u8>,
369}
370
371cfg_if! {
372 if #[cfg(feature = "disassembler")]{
373 use crate::disassembler::InstructionTree;
374
375 #[derive(Clone, Debug, PartialEq)]
376 pub struct InstructionBlockDataDebugTree {
377 pub length: u32,
378 pub injected_variable_count: u32,
379 pub injected_values: Vec<InjectedValueDeclaration>,
380 pub body: InstructionTree<Instruction>,
381 }
382
383 #[derive(Clone, Debug, PartialEq)]
384 pub struct InstructionBlockDataDebugFlat {
385 pub length: u32,
386 pub injected_variable_count: u32,
387 pub injected_values: Vec<InjectedValueDeclaration>,
388 pub body: Vec<Instruction>,
389 }
390
391 impl From<&InstructionBlockDataDebugTree> for InstructionBlockDataDebugFlat {
392 fn from(instruction_block_data: &InstructionBlockDataDebugTree) -> Self {
393 InstructionBlockDataDebugFlat {
394 length: instruction_block_data.length,
395 injected_variable_count: instruction_block_data.injected_variable_count,
396 injected_values: instruction_block_data.injected_values.clone(),
397 body: instruction_block_data.body.flatten(),
398 }
399 }
400 }
401
402 impl From<&InstructionBlockDataDebugFlat> for InstructionBlockData {
403 fn from(value: &InstructionBlockDataDebugFlat) -> Self {
404 let mut cursor = Cursor::new(Vec::new());
405 for instruction in &value.body {
406 append_instruction(&mut cursor, instruction.clone());
407 }
408 Self {
409 length: value.length,
410 injected_value_count: value.injected_variable_count,
411 injected_values: value.injected_values.clone(),
412 body: cursor.into_inner(),
413 }
414 }
415 }
416
417 impl BinWrite for InstructionBlockDataDebugFlat {
418 type Args<'a> = ();
419
420 fn write_options<W: Write + Seek>(
421 &self,
422 writer: &mut W,
423 endian: Endian,
424 _: Self::Args<'_>,
425 ) -> BinResult<()> {
426 let raw = InstructionBlockData::from(self);
427 raw.write_options(writer, endian, ())
428 }
429 }
430
431 impl BinWrite for InstructionBlockDataDebugTree {
432 type Args<'a> = ();
433 fn write_options<W: Write + Seek>(
434 &self,
435 writer: &mut W,
436 endian: Endian,
437 _: Self::Args<'_>,
438 ) -> BinResult<()> {
439 let raw = InstructionBlockData::from(&InstructionBlockDataDebugFlat::from(self));
440 raw.write_options(writer, endian, ())
441 }
442 }
443
444 }
445}
446
447#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
448#[brw(little)]
449pub struct ApplyData {
450 pub arg_count: u16,
451}
452
453#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
454#[brw(little)]
455pub struct ImplTypeData {
456 pub impl_count: u8,
457 #[br(count = impl_count)]
458 pub impls: Vec<PointerAddress>,
459}
460
461#[derive(BinRead, BinWrite, Clone, Debug, PartialEq)]
462#[brw(little)]
463pub struct TypeReferenceData {
464 pub address: PointerAddress,
465}
466
467#[bitfield]
468#[derive(BinWrite, BinRead, Clone, Copy, Debug, PartialEq)]
469#[bw(map = |&x| Self::into_bytes(x))]
470#[br(map = Self::from_bytes)]
471#[brw(little)]
472pub struct TypeMetadataBin {
473 pub ownership: TypeOwnershipCode,
474 pub mutability: TypeMutabilityCode,
475 pub type_local_or_shared: TypeLocalOrShared,
476 _unused: B4,
477}
478
479impl From<&TypeMetadataBin> for TypeMetadata {
480 fn from(value: &TypeMetadataBin) -> Self {
481 match value.type_local_or_shared() {
482 TypeLocalOrShared::Local => TypeMetadata::Local {
483 mutability: (&value.mutability()).into(),
484 ownership: (&value.ownership()).into(),
485 },
486 TypeLocalOrShared::Shared => TypeMetadata::Shared {
487 mutability: (&value.mutability()).into(),
488 ownership: (&value.ownership()).into(),
489 },
490 }
491 }
492}
493
494impl From<&TypeMetadata> for TypeMetadataBin {
495 fn from(value: &TypeMetadata) -> Self {
496 match value {
497 TypeMetadata::Local {
498 mutability,
499 ownership: reference_mutability,
500 } => Self::new()
501 .with_type_local_or_shared(TypeLocalOrShared::Local)
502 .with_mutability(mutability.into())
503 .with_ownership(reference_mutability.into()),
504 TypeMetadata::Shared {
505 mutability,
506 ownership,
507 } => Self::new()
508 .with_type_local_or_shared(TypeLocalOrShared::Shared)
509 .with_mutability(mutability.into())
510 .with_ownership(ownership.into()),
511 }
512 }
513}