pyc_editor 0.4.6

A Rust library for reading, modifying, and writing Python .pyc files.
Documentation
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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
use std::collections::{HashMap, VecDeque};

#[cfg(feature = "sir")]
use crate::{
    sir::{AuxVar, SIRExpression, SIRStatement},
    traits::GenericSIRNode,
};

/// The amount of extended_args necessary to represent the arg.
/// This is more efficient than `get_extended_args` as we only calculate the count and the actual values.
pub fn get_extended_args_count(arg: u32) -> u8 {
    if arg <= u8::MAX.into() {
        0
    } else if arg <= u16::MAX.into() {
        1
    } else if arg <= 0xffffff {
        2
    } else {
        3
    }
}

/// Used to represent opargs for opcodes that don't require arguments
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct UnusedArgument(pub u32);

impl From<u32> for UnusedArgument {
    fn from(value: u32) -> Self {
        UnusedArgument(value)
    }
}

/// Used to represent stack operations
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct StackEffect {
    pub pushes: u32,
    pub pops: u32,
}

/// Offsets are for instructions (not bytes)
#[derive(Debug, Clone, PartialEq)]
pub struct ExceptionTableEntry {
    /// Inclusive offset
    pub start: u32,
    /// Exclusive offset
    pub end: u32,
    pub target: u32,
    /// Stack depth at the start of the try block
    pub depth: u32,
    /// Whether to push the index of the last executed instruction
    pub lasti: bool,
}

impl StackEffect {
    /// Creates a StackEffect with equal pushes and pops.
    pub fn balanced(count: u32) -> Self {
        StackEffect {
            pushes: count,
            pops: count,
        }
    }

    /// Creates a StackEffect when only pushing
    pub fn push(count: u32) -> Self {
        StackEffect {
            pushes: count,
            pops: 0,
        }
    }

    /// Creates a StackEffect when only pushing
    pub fn pop(count: u32) -> Self {
        StackEffect {
            pushes: 0,
            pops: count,
        }
    }

    /// For when there is no stack access
    pub fn zero() -> Self {
        StackEffect { pushes: 0, pops: 0 }
    }

    /// Calculates the net total for the stackeffect
    pub fn net_total(&self) -> i32 {
        self.pushes as i32 - self.pops as i32
    }
}

#[macro_export]
macro_rules! define_default_traits {
    ($variant:ident, Instruction) => {
        impl Deref for $crate::$variant::instructions::Instructions {
            type Target = [$crate::$variant::instructions::Instruction];

            /// Allow the user to get a reference slice to the instructions
            fn deref(&self) -> &Self::Target {
                self.0.deref()
            }
        }

        impl DerefMut for $crate::$variant::instructions::Instructions {
            /// Allow the user to get a mutable reference slice for making modifications to existing instructions.
            fn deref_mut(&mut self) -> &mut [$crate::$variant::instructions::Instruction] {
                self.0.deref_mut()
            }
        }

        impl AsRef<[$crate::$variant::instructions::Instruction]>
            for $crate::$variant::instructions::Instructions
        {
            fn as_ref(&self) -> &[$crate::$variant::instructions::Instruction] {
                &self.0
            }
        }

        impl From<$crate::$variant::instructions::Instructions> for Vec<u8> {
            fn from(val: $crate::$variant::instructions::Instructions) -> Self {
                val.to_bytes()
            }
        }

        impl TryFrom<&[u8]> for $crate::$variant::instructions::Instructions {
            type Error = Error;
            fn try_from(code: &[u8]) -> Result<Self, Self::Error> {
                if code.len() % 2 != 0 {
                    return Err(Error::InvalidBytecodeLength);
                }

                let mut instructions = $crate::$variant::instructions::Instructions(
                    Vec::with_capacity(code.len() / 2),
                );

                for chunk in code.chunks(2) {
                    if chunk.len() != 2 {
                        return Err(Error::InvalidBytecodeLength);
                    }
                    let opcode = Opcode::from(chunk[0]);
                    let arg = chunk[1];

                    instructions.append_instruction((opcode, arg).into());
                }

                Ok(instructions)
            }
        }

        impl From<&[Instruction]> for Instructions {
            fn from(value: &[Instruction]) -> Self {
                $crate::$variant::instructions::Instructions::new(value.to_vec())
            }
        }

        impl InstructionsOwned<$crate::$variant::instructions::Instruction>
            for $crate::$variant::instructions::Instructions
        {
            type Instruction = $crate::$variant::instructions::Instruction;

            fn push(&mut self, item: Self::Instruction) {
                self.0.push(item);
            }
        }

        // impl<T> SimpleInstructionAccess<$crate::$variant::instructions::Instruction> for T where
        //     T: Deref<Target = [Instruction]> + AsRef<[Instruction]>
        // {
        // }
    };

    ($variant:ident, ExtInstruction) => {
        impl Deref for $crate::$variant::ext_instructions::ExtInstructions {
            type Target = [$crate::$variant::ext_instructions::ExtInstruction];

            /// Allow the user to get a reference slice to the instructions
            fn deref(&self) -> &Self::Target {
                self.0.deref()
            }
        }

        impl DerefMut for $crate::$variant::ext_instructions::ExtInstructions {
            /// Allow the user to get a mutable reference slice for making modifications to existing instructions.
            fn deref_mut(&mut self) -> &mut [$crate::$variant::ext_instructions::ExtInstruction] {
                self.0.deref_mut()
            }
        }

        impl AsRef<[$crate::$variant::ext_instructions::ExtInstruction]>
            for $crate::$variant::ext_instructions::ExtInstructions
        {
            fn as_ref(&self) -> &[$crate::$variant::ext_instructions::ExtInstruction] {
                &self.0
            }
        }

        impl From<$crate::$variant::ext_instructions::ExtInstructions> for Vec<u8> {
            fn from(val: $crate::$variant::ext_instructions::ExtInstructions) -> Self {
                val.to_bytes()
            }
        }

        impl TryFrom<&[$crate::$variant::instructions::Instruction]>
            for $crate::$variant::ext_instructions::ExtInstructions
        {
            type Error = Error;

            fn try_from(
                value: &[$crate::$variant::instructions::Instruction],
            ) -> Result<Self, Self::Error> {
                $crate::$variant::ext_instructions::ExtInstructions::from_instructions(value)
            }
        }

        impl From<&[$crate::$variant::ext_instructions::ExtInstruction]>
            for $crate::$variant::ext_instructions::ExtInstructions
        {
            fn from(value: &[$crate::$variant::ext_instructions::ExtInstruction]) -> Self {
                $crate::$variant::ext_instructions::ExtInstructions::new(value.to_vec())
            }
        }
    };
}

pub fn generate_var_name(
    stack_name: &'static str,
    names: &mut HashMap<&'static str, u32>,
) -> String {
    if names.contains_key(stack_name) {
        *names.get_mut(stack_name).unwrap() += 1;
    } else {
        names.insert(stack_name, 0);
    }

    format!("{}_{}", stack_name, names[stack_name])
}

/// A vector that allows for negative indexes and automatically fills elements with an "empty" value when inserting at an arbitrary index below 0.
#[derive(Debug, Clone)]
pub struct InfiniteVec<T>
where
    T: Clone + std::fmt::Debug,
{
    data: VecDeque<Option<T>>,
    /// This is the offset that indicates where index "0" is really at
    negative_offset: usize,
}

impl<T> Default for InfiniteVec<T>
where
    T: Clone + std::fmt::Debug,
{
    fn default() -> Self {
        Self::new()
    }
}

impl<T> InfiniteVec<T>
where
    T: Clone + std::fmt::Debug,
{
    pub fn new() -> Self {
        InfiniteVec {
            data: vec![].into(),
            negative_offset: 0,
        }
    }

    pub fn from_vec(vec: Vec<T>) -> Self {
        InfiniteVec {
            data: VecDeque::from(vec.into_iter().map(|v| Some(v)).collect::<Vec<_>>()),
            negative_offset: 0,
        }
    }

    pub fn insert(&mut self, index: isize, value: T) {
        let real_index = index + self.negative_offset as isize;

        if real_index < 0 {
            for _ in 0..(real_index.abs() - 1) {
                self.data.push_front(None)
            }

            self.data.push_front(Some(value));

            self.negative_offset += real_index.unsigned_abs();
        } else {
            self.data.insert(real_index as usize, Some(value));
        }
    }

    pub fn push(&mut self, value: T) {
        self.data.push_back(Some(value));
    }

    pub fn get(&self, index: isize) -> Option<&Option<T>> {
        let real_index = index + self.negative_offset as isize;

        if real_index < 0 {
            None
        } else {
            self.data.get(real_index as usize)
        }
    }

    pub fn get_mut(&mut self, index: isize) -> Option<&mut Option<T>> {
        let real_index = index + self.negative_offset as isize;

        if real_index < 0 {
            None
        } else {
            self.data.get_mut(real_index as usize)
        }
    }

    pub fn remove(&mut self, index: isize) -> Option<Option<T>> {
        let real_index = index + self.negative_offset as isize;

        if index < 0 {
            self.negative_offset -= 1;
        }

        self.data.remove(real_index.try_into().unwrap())
    }

    pub fn len(&self) -> usize {
        self.data.len()
    }

    pub fn is_empty(&self) -> bool {
        self.data.is_empty()
    }

    pub fn positive_len(&self) -> usize {
        self.data.len() - self.negative_offset
    }

    pub fn negative_len(&self) -> usize {
        debug_assert!(self.data.len() >= self.negative_offset);

        self.negative_offset
    }

    pub fn collect_negative_indexes(&self) -> Vec<usize> {
        self.data
            .iter()
            .enumerate()
            .take(self.negative_offset)
            .filter_map(|(i, e)| e.as_ref().map(|_| i))
            .collect()
    }

    /// Collects the values with Some() value and their index
    pub fn iter_pairs(&self) -> impl DoubleEndedIterator<Item = (isize, &T)> {
        self.data
            .iter()
            .enumerate()
            .filter(|(_, value)| value.is_some())
            .map(|(i, value)| {
                (
                    i as isize - self.negative_offset as isize,
                    value.as_ref().unwrap(),
                )
            })
    }

    /// Tells us whether negative items were used
    pub fn no_negative_items(&self) -> bool {
        self.negative_offset == 0
    }

    pub fn iter(&self) -> std::collections::vec_deque::Iter<'_, Option<T>> {
        self.data.iter()
    }

    /// Only iter over negative indexed values
    pub fn iter_negative(
        &self,
    ) -> std::iter::Take<std::collections::vec_deque::Iter<'_, Option<T>>> {
        self.data.iter().take(self.negative_offset)
    }
}

#[derive(Debug, Clone)]
pub struct InfiniteStack<T>
where
    T: Clone + std::fmt::Debug,
{
    pub data: InfiniteVec<T>,
    /// This points to where we currently are in the stack
    pub carrot: isize,
}

impl<T> InfiniteStack<T>
where
    T: Clone + std::fmt::Debug,
{
    pub fn new(stack: InfiniteVec<T>) -> Self {
        InfiniteStack {
            data: stack,
            carrot: 0,
        }
    }

    /// Returns the index of the top of the stack (if there is one)
    pub fn get_tos_index(&self) -> Option<isize> {
        self.data.iter_pairs().last().map(|(i, _)| i)
    }
}

impl<T> From<InfiniteVec<T>> for InfiniteStack<T>
where
    T: Clone + std::fmt::Debug,
{
    fn from(value: InfiniteVec<T>) -> Self {
        InfiniteStack::new(value)
    }
}

impl<T> From<Vec<T>> for InfiniteStack<T>
where
    T: Clone + std::fmt::Debug,
{
    fn from(value: Vec<T>) -> Self {
        InfiniteStack::new(value.into())
    }
}

impl<T> From<Vec<T>> for InfiniteVec<T>
where
    T: Clone + std::fmt::Debug,
{
    fn from(value: Vec<T>) -> Self {
        InfiniteVec {
            data: value.into_iter().map(|e| Some(e)).collect(),
            negative_offset: 0,
        }
    }
}

#[cfg(feature = "dot")]
#[derive(Debug, Clone)]
pub enum BlockKind {
    ExceptionBlock,
    InExceptionRange,
    NormalBlock,
}

#[cfg(feature = "sir")]
pub fn replace_var_in_expression<SIRNode: GenericSIRNode>(
    node: &mut SIRExpression<SIRNode>,
    og_var: &AuxVar,
    new_var: &AuxVar,
) {
    match node {
        SIRExpression::AuxVar(var) => {
            if var == og_var {
                *var = new_var.clone();
            }
        }
        SIRExpression::Call(call) => {
            for var in call.stack_inputs.iter_mut() {
                if var == og_var {
                    *var = new_var.clone();
                }
            }
        }
        SIRExpression::Exception(exc) => {
            for var in exc.stack_inputs.iter_mut() {
                if var == og_var {
                    *var = new_var.clone();
                }
            }
        }
        SIRExpression::PhiNode(values) => {
            for var in values {
                if var == og_var {
                    *var = new_var.clone();
                }
            }
        }
        SIRExpression::GeneratorStart => {}
    }
}

#[cfg(feature = "sir")]
pub fn replace_var_in_statement<SIRNode: GenericSIRNode>(
    node: &mut SIRStatement<SIRNode>,
    og_var: &AuxVar,
    new_var: &AuxVar,
) {
    match node {
        SIRStatement::Assignment(var, value) => {
            if var == og_var {
                *var = new_var.clone();
            }

            replace_var_in_expression(value, og_var, new_var);
        }
        SIRStatement::DisregardCall(call) => {
            for var in call.stack_inputs.iter_mut() {
                if var == og_var {
                    *var = new_var.clone();
                }
            }
        }
        SIRStatement::TupleAssignment(vars, value) => {
            for var in vars.iter_mut() {
                if var == og_var {
                    *var = new_var.clone();
                }
            }

            replace_var_in_expression(value, og_var, new_var);
        }
        SIRStatement::UseVar(var) => {
            if var == og_var {
                *var = new_var.clone();
            }
        }
    }
}

#[cfg(test)]
mod test {
    use crate::utils::InfiniteVec;

    #[test]
    fn test_infinite_vec() {
        let mut infinite_vec = InfiniteVec::new();

        infinite_vec.push(1);
        infinite_vec.insert(-5, 5);

        assert_eq!(
            infinite_vec.iter().collect::<Vec<_>>(),
            [Some(5), None, None, None, None, Some(1)]
                .iter()
                .collect::<Vec<_>>()
        );

        assert_eq!(infinite_vec.get(0).unwrap(), &Some(1));
    }
}