1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
use fuel_asm::Word;
use fuel_crypto::Hasher;
use fuel_tx::{Bytes32, ContractId};
use serde::{Deserialize, Serialize};
use std::hash::Hash;
use std::path::{Path, PathBuf};
use std::{io, iter, slice};

pub mod ident;
pub use ident::*;

pub mod span;
pub use span::*;

pub mod state;

pub type Id = [u8; Bytes32::LEN];
pub type Contract = [u8; ContractId::LEN];

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Position {
    pub line: usize,
    pub col: usize,
}

/// Based on `<https://llvm.org/docs/CoverageMappingFormat.html#source-code-range>`
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Range {
    /// Beginning of the code range
    pub start: Position,
    /// End of the code range (inclusive)
    pub end: Position,
}

impl Range {
    pub const fn is_valid(&self) -> bool {
        self.start.line < self.end.line
            || self.start.line == self.end.line && self.start.col <= self.end.col
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Instruction {
    /// Relative to the `$is`
    pub pc: Word,
    /// Code range that translates to this point
    pub range: Range,
    /// Exit from the current scope?
    pub exit: bool,
}

impl Instruction {
    pub fn to_bytes(&self) -> [u8; 41] {
        let mut bytes = [0u8; 41];

        // Always convert to `u64` to avoid architectural variants of the bytes representation that
        // could lead to arch-dependent unique IDs
        bytes[..8].copy_from_slice(&(self.pc as u64).to_be_bytes());
        bytes[8..16].copy_from_slice(&(self.range.start.line as u64).to_be_bytes());
        bytes[16..24].copy_from_slice(&(self.range.start.col as u64).to_be_bytes());
        bytes[24..32].copy_from_slice(&(self.range.end.line as u64).to_be_bytes());
        bytes[32..40].copy_from_slice(&(self.range.end.col as u64).to_be_bytes());
        bytes[40] = self.exit as u8;

        bytes
    }

    pub fn bytes<'a>(iter: impl Iterator<Item = &'a Self>) -> Vec<u8> {
        // Need to return owned bytes because flatten is not supported by 1.53 for arrays bigger
        // than 32 bytes
        iter.map(Self::to_bytes)
            .fold::<Vec<u8>, _>(vec![], |mut v, b| {
                v.extend(&b);

                v
            })
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Source {
    /// Absolute path to the source file
    path: PathBuf,
}

impl<T> From<T> for Source
where
    T: Into<PathBuf>,
{
    fn from(path: T) -> Self {
        Self { path: path.into() }
    }
}

#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct ConfigTimeConstant {
    pub r#type: String,
    pub value: String,
}
impl AsRef<PathBuf> for Source {
    fn as_ref(&self) -> &PathBuf {
        &self.path
    }
}

impl AsRef<Path> for Source {
    fn as_ref(&self) -> &Path {
        self.path.as_ref()
    }
}

impl AsMut<PathBuf> for Source {
    fn as_mut(&mut self) -> &mut PathBuf {
        &mut self.path
    }
}

impl Source {
    pub fn bytes(&self) -> io::Result<slice::Iter<'_, u8>> {
        Ok(self
            .path
            .as_path()
            .to_str()
            .ok_or_else(|| {
                io::Error::new(
                    io::ErrorKind::Other,
                    "Failed to get the string representation of the path!",
                )
            })?
            .as_bytes()
            .iter())
    }
}

/// Contract call stack frame representation
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct CallFrame {
    /// Deterministic representation of the frame
    id: Id,
    /// Contract that contains the bytecodes of this frame. Currently only scripts are supported
    contract: Contract,
    /// Sway source code that compiles to this frame
    source: Source,
    /// Range of code that represents this frame
    range: Range,
    /// Set of instructions that describes this frame
    program: Vec<Instruction>,
}

impl CallFrame {
    pub fn new(
        contract: ContractId,
        source: Source,
        range: Range,
        program: Vec<Instruction>,
    ) -> io::Result<Self> {
        Context::validate_source(&source)?;
        Context::validate_range(iter::once(&range).chain(program.iter().map(|p| &p.range)))?;

        let contract = Contract::from(contract);

        let id = Context::id_from_repr(
            Instruction::bytes(program.iter())
                .iter()
                .chain(contract.iter())
                .chain(source.bytes()?),
        );

        Ok(Self {
            id,
            contract,
            source,
            range,
            program,
        })
    }

    pub const fn id(&self) -> &Id {
        &self.id
    }

    pub const fn source(&self) -> &Source {
        &self.source
    }

    pub const fn range(&self) -> &Range {
        &self.range
    }

    pub fn program(&self) -> &[Instruction] {
        self.program.as_slice()
    }

    pub fn contract(&self) -> ContractId {
        self.contract.into()
    }
}

/// Transaction script interpreter representation
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct TransactionScript {
    /// Deterministic representation of the script
    id: Id,
    /// Sway source code that compiles to this script
    source: Source,
    /// Range of code that represents this script
    range: Range,
    /// Set of instructions that describes this script
    program: Vec<Instruction>,
}

impl TransactionScript {
    pub fn new(source: Source, range: Range, program: Vec<Instruction>) -> io::Result<Self> {
        Context::validate_source(&source)?;
        Context::validate_range(iter::once(&range).chain(program.iter().map(|p| &p.range)))?;

        let id = Context::id_from_repr(
            Instruction::bytes(program.iter())
                .iter()
                .chain(source.bytes()?),
        );

        Ok(Self {
            id,
            source,
            range,
            program,
        })
    }

    pub const fn id(&self) -> &Id {
        &self.id
    }

    pub const fn source(&self) -> &Source {
        &self.source
    }

    pub const fn range(&self) -> &Range {
        &self.range
    }

    pub fn program(&self) -> &[Instruction] {
        self.program.as_slice()
    }
}

// Representation of a debug context to be mapped from a sway source and consumed by the DAP-sway
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Context {
    CallFrame(CallFrame),
    TransactionScript(TransactionScript),
}

impl From<CallFrame> for Context {
    fn from(frame: CallFrame) -> Self {
        Self::CallFrame(frame)
    }
}

impl From<TransactionScript> for Context {
    fn from(script: TransactionScript) -> Self {
        Self::TransactionScript(script)
    }
}

impl Context {
    pub fn validate_source<P>(path: P) -> io::Result<()>
    where
        P: AsRef<Path>,
    {
        if !path.as_ref().is_absolute() {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "The source path must be absolute!",
            ));
        }

        if !path.as_ref().is_file() {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "The source path must be a valid Sway source file!",
            ));
        }

        if !path.as_ref().exists() {
            return Err(io::Error::new(
                io::ErrorKind::NotFound,
                "The source path must point to an existing file!",
            ));
        }

        Ok(())
    }

    pub fn validate_range<'a>(mut range: impl Iterator<Item = &'a Range>) -> io::Result<()> {
        if !range.any(|r| !r.is_valid()) {
            Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "The provided source range is inconsistent!",
            ))
        } else {
            Ok(())
        }
    }

    pub fn id_from_repr<'a>(bytes: impl Iterator<Item = &'a u8>) -> Id {
        let bytes: Vec<u8> = bytes.copied().collect();

        *Hasher::hash(bytes.as_slice())
    }

    pub const fn id(&self) -> &Id {
        match self {
            Self::CallFrame(t) => t.id(),
            Self::TransactionScript(t) => t.id(),
        }
    }

    pub const fn source(&self) -> &Source {
        match self {
            Self::CallFrame(t) => t.source(),
            Self::TransactionScript(t) => t.source(),
        }
    }

    pub const fn range(&self) -> &Range {
        match self {
            Self::CallFrame(t) => t.range(),
            Self::TransactionScript(t) => t.range(),
        }
    }

    pub fn program(&self) -> &[Instruction] {
        match self {
            Self::CallFrame(t) => t.program(),
            Self::TransactionScript(t) => t.program(),
        }
    }

    pub fn contract(&self) -> Option<ContractId> {
        match self {
            Self::CallFrame(t) => Some(t.contract()),
            _ => None,
        }
    }
}

/// TODO: The types `Function` and `Property` below are copied from `fuels-types` except for the
/// `typeArguments` field of `Property`. Switch back to using fuels-types
/// directly when the `typeArguments` field is added there
///
/// Fuel ABI representation in JSON, originally specified here:
///
/// https://github.com/FuelLabs/fuel-specs/blob/master/specs/protocol/abi.md
///
/// This type may be used by compilers (e.g. Sway) and related tooling to convert an ABI
/// representation into native Rust structs and vice-versa.

pub type JsonABI = Vec<Function>;

#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Function {
    #[serde(rename = "type")]
    pub type_field: String,
    pub inputs: Vec<Property>,
    pub name: String,
    pub outputs: Vec<Property>,
}

#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Property {
    pub name: String,
    #[serde(rename = "type")]
    pub type_field: String,
    pub components: Option<Vec<Property>>, // Used for custom types
    pub type_arguments: Option<Vec<Property>>, // Used for generic types. Not yet supported in fuels-rs.
}

/// Alternative Fuel ABI representation in JSON where the type declarations have associated IDs to
/// help associate type components, type arguments, and type parameters with other types.
#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct JsonABIProgram {
    pub types: Vec<JsonTypeDeclaration>,
    pub functions: Vec<JsonABIFunction>,
}

#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct JsonABIFunction {
    pub inputs: Vec<JsonTypeApplication>,
    pub name: String,
    pub output: JsonTypeApplication,
}

#[derive(Default, Debug, Clone, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct JsonTypeDeclaration {
    pub type_id: usize,
    #[serde(rename = "type")]
    pub type_field: String,
    pub components: Option<Vec<JsonTypeApplication>>,
    pub type_parameters: Option<Vec<usize>>,
}

#[derive(Default, Debug, Clone, Eq, PartialEq, Serialize, Hash, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct JsonTypeApplication {
    pub name: String,
    #[serde(rename = "type")]
    pub type_id: usize,
    pub type_arguments: Option<Vec<JsonTypeApplication>>,
}

// Two type declarations are the same if all their attributes (except for `type_id`) are the same.
// This is useful when trying to merge multiple identical types that have different IDs.
impl Hash for JsonTypeDeclaration {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.type_field.hash(state);
        self.components.hash(state);
        self.type_parameters.hash(state);
    }
}
impl PartialEq for JsonTypeDeclaration {
    fn eq(&self, other: &Self) -> bool {
        self.type_field == other.type_field
            && self.components == other.components
            && self.type_parameters == other.type_parameters
    }
}