GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — RustPython/bytecode/src/lib.rs at main · casey/RustPython Expand file tree/ Copy pathlib.rsMore file actions 1353 lines (1268 loc) · 42.8 KB / Copy pathlib.rsFile metadata and controls1353 lines (1268 loc) · 42.8 KB 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 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 //! Implement python as a virtual machine with bytecodes. This module //! implements bytecode structure. #![doc(html_logo_url = "https://raw.githubusercontent.com/RustPython/RustPython/main/logo.png")] #![doc(html_root_url = "https://docs.rs/rustpython-bytecode/")] use bitflags::bitflags; use bstr::ByteSlice; use itertools::Itertools; use num_bigint::BigInt; use num_complex::Complex64; use serde::{Deserialize, Serialize}; use std::{collections::BTreeSet, fmt, hash}; /// Sourcecode location. #[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] pub struct Location { row: u32, column: u32, } impl Location { /// Creates a new Location object at the given row and column. /// /// # Example /// ``` /// use rustpython_bytecode::Location; /// let loc = Location::new(10, 10); /// ``` pub fn new(row: usize, column: usize) -> Self { let row = row.try_into().expect("Location::row over u32"); let column = column.try_into().expect("Location::column over u32"); Location { row, column } } /// Current row pub fn row(&self) -> usize { self.row as usize } /// Current column pub fn column(&self) -> usize { self.column as usize } } pub trait Constant: Sized { type Name: AsRef<str>; /// Transforms the given Constant to a BorrowedConstant fn borrow_constant(&self) -> BorrowedConstant<Self>; } impl Constant for ConstantData { type Name = String; fn borrow_constant(&self) -> BorrowedConstant<Self> { use BorrowedConstant::*; match self { ConstantData::Integer { value } => Integer { value }, ConstantData::Float { value } => Float { value: *value }, ConstantData::Complex { value } => Complex { value: *value }, ConstantData::Boolean { value } => Boolean { value: *value }, ConstantData::Str { value } => Str { value }, ConstantData::Bytes { value } => Bytes { value }, ConstantData::Code { code } => Code { code }, ConstantData::Tuple { elements } => Tuple { elements: Box::new(elements.iter().map(|e| e.borrow_constant())), }, ConstantData::None => None, ConstantData::Ellipsis => Ellipsis, } } } /// A Constant Bag pub trait ConstantBag: Sized + Copy { type Constant: Constant; fn make_constant<C: Constant>(&self, constant: BorrowedConstant<C>) -> Self::Constant; fn make_name(&self, name: &str) -> <Self::Constant as Constant>::Name; } #[derive(Clone, Copy)] pub struct BasicBag; impl ConstantBag for BasicBag { type Constant = ConstantData; fn make_constant<C: Constant>(&self, constant: BorrowedConstant<C>) -> Self::Constant { constant.to_owned() } fn make_name(&self, name: &str) -> <Self::Constant as Constant>::Name { name.to_owned() } } /// Primary container of a single code object. Each python function has /// a codeobject. Also a module has a codeobject. #[derive(Clone, Serialize, Deserialize)] pub struct CodeObject<C: Constant = ConstantData> { pub instructions: Box<[Instruction]>, pub locations: Box<[Location]>, pub flags: CodeFlags, pub posonlyarg_count: usize, // Number of positional-only arguments pub arg_count: usize, pub kwonlyarg_count: usize, pub source_path: C::Name, pub first_line_number: usize, pub max_stacksize: u32, pub obj_name: C::Name, // Name of the object that created this code object pub cell2arg: Option<Box<[isize]>>, pub constants: Box<[C]>, #[serde(bound( deserialize = "C::Name: serde::Deserialize<'de>", serialize = "C::Name: serde::Serialize" ))] pub names: Box<[C::Name]>, pub varnames: Box<[C::Name]>, pub cellvars: Box<[C::Name]>, pub freevars: Box<[C::Name]>, } bitflags! { #[derive(Serialize, Deserialize)] pub struct CodeFlags: u16 { const NEW_LOCALS = 0x01; const IS_GENERATOR = 0x02; const IS_COROUTINE = 0x04; const HAS_VARARGS = 0x08; const HAS_VARKEYWORDS = 0x10; const IS_OPTIMIZED = 0x20; } } impl CodeFlags { pub const NAME_MAPPING: &'static [(&'static str, CodeFlags)] = &[ ("GENERATOR", CodeFlags::IS_GENERATOR), ("COROUTINE", CodeFlags::IS_COROUTINE), ( "ASYNC_GENERATOR", Self::from_bits_truncate(Self::IS_GENERATOR.bits | Self::IS_COROUTINE.bits), ), ("VARARGS", CodeFlags::HAS_VARARGS), ("VARKEYWORDS", CodeFlags::HAS_VARKEYWORDS), ]; } #[derive(Serialize, Debug, Deserialize, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)] #[repr(transparent)] // XXX: if you add a new instruction that stores a Label, make sure to add it in // Instruction::label_arg{,_mut} pub struct Label(pub u32); impl fmt::Display for Label { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.0.fmt(f) } } /// Transforms a value prior to formatting it. #[derive(Copy, Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ConversionFlag { /// No conversion None, /// Converts by calling `str(<value>)`. Str, /// Converts by calling `ascii(<value>)`. Ascii, /// Converts by calling `repr(<value>)`. Repr, } /// The kind of Raise that occurred. #[derive(Copy, Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum RaiseKind { Reraise, Raise, RaiseCause, } pub type NameIdx = u32; /// A Single bytecode instruction. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub enum Instruction { /// Importing by name ImportName { idx: NameIdx, }, /// Importing without name ImportNameless, /// Import * ImportStar, /// from ... import ... ImportFrom { idx: NameIdx, }, LoadFast(NameIdx), LoadNameAny(NameIdx), LoadGlobal(NameIdx), LoadDeref(NameIdx), LoadClassDeref(NameIdx), StoreFast(NameIdx), StoreLocal(NameIdx), StoreGlobal(NameIdx), StoreDeref(NameIdx), DeleteFast(NameIdx), DeleteLocal(NameIdx), DeleteGlobal(NameIdx), DeleteDeref(NameIdx), LoadClosure(NameIdx), Subscript, StoreSubscript, DeleteSubscript, StoreAttr { idx: NameIdx, }, DeleteAttr { idx: NameIdx, }, LoadConst { /// index into constants vec idx: u32, }, UnaryOperation { op: UnaryOperator, }, BinaryOperation { op: BinaryOperator, }, BinaryOperationInplace { op: BinaryOperator, }, LoadAttr { idx: NameIdx, }, TestOperation { op: TestOperator, }, CompareOperation { op: ComparisonOperator, }, Pop, Rotate2, Rotate3, Duplicate, Duplicate2, GetIter, Continue { target: Label, }, Break, Jump { target: Label, }, /// Pop the top of the stack, and jump if this value is true. JumpIfTrue { target: Label, }, /// Pop the top of the stack, and jump if this value is false. JumpIfFalse { target: Label, }, /// Peek at the top of the stack, and jump if this value is true. /// Otherwise, pop top of stack. JumpIfTrueOrPop { target: Label, }, /// Peek at the top of the stack, and jump if this value is false. /// Otherwise, pop top of stack. JumpIfFalseOrPop { target: Label, }, MakeFunction(MakeFunctionFlags), CallFunctionPositional { nargs: u32, }, CallFunctionKeyword { nargs: u32, }, CallFunctionEx { has_kwargs: bool, }, LoadMethod { idx: NameIdx, }, CallMethodPositional { nargs: u32, }, CallMethodKeyword { nargs: u32, }, CallMethodEx { has_kwargs: bool, }, ForIter { target: Label, }, ReturnValue, YieldValue, YieldFrom, SetupAnnotation, SetupLoop { break_target: Label, }, /// Setup a finally handler, which will be called whenever one of this events occurs: /// - the block is popped /// - the function returns /// - an exception is returned SetupFinally { handler: Label, }, /// Enter a finally block, without returning, excepting, just because we are there. EnterFinally, /// Marker bytecode for the end of a finally sequence. /// When this bytecode is executed, the eval loop does one of those things: /// - Continue at a certain bytecode position /// - Propagate the exception /// - Return from a function /// - Do nothing at all, just continue EndFinally, SetupExcept { handler: Label, }, SetupWith { end: Label, }, WithCleanupStart, WithCleanupFinish, PopBlock, Raise { kind: RaiseKind, }, BuildString { size: u32, }, BuildTuple { unpack: bool, size: u32, }, BuildList { unpack: bool, size: u32, }, BuildSet { unpack: bool, size: u32, }, BuildMap { unpack: bool, for_call: bool, size: u32, }, BuildSlice { /// whether build a slice with a third step argument step: bool, }, ListAppend { i: u32, }, SetAdd { i: u32, }, MapAdd { i: u32, }, PrintExpr, LoadBuildClass, UnpackSequence { size: u32, }, UnpackEx { before: u8, after: u8, }, FormatValue { conversion: ConversionFlag, }, PopException, Reverse { amount: u32, }, GetAwaitable, BeforeAsyncWith, SetupAsyncWith { end: Label, }, GetAIter, GetANext, EndAsyncFor, } static_assertions::assert_eq_size!(Instruction, u64); use self::Instruction::*; bitflags! { #[derive(Serialize, Deserialize)] pub struct MakeFunctionFlags: u8 { const CLOSURE = 0x01; const ANNOTATIONS = 0x02; const KW_ONLY_DEFAULTS = 0x04; const DEFAULTS = 0x08; } } /// A Constant (which usually encapsulates data within it) /// /// # Examples /// ``` /// use rustpython_bytecode::ConstantData; /// let a = ConstantData::Float {value: 120f64}; /// let b = ConstantData::Boolean {value: false}; /// assert_ne!(a, b); /// ``` #[derive(Debug, Clone, Serialize, Deserialize)] pub enum ConstantData { Tuple { elements: Vec<ConstantData> }, Integer { value: BigInt }, Float { value: f64 }, Complex { value: Complex64 }, Boolean { value: bool }, Str { value: String }, Bytes { value: Vec<u8> }, Code { code: Box<CodeObject> }, None, Ellipsis, } impl PartialEq for ConstantData { fn eq(&self, other: &Self) -> bool { use ConstantData::*; match (self, other) { (Integer { value: a }, Integer { value: b }) => a == b, // we want to compare floats *by actual value* - if we have the *exact same* float // already in a constant cache, we want to use that (Float { value: a }, Float { value: b }) => a.to_bits() == b.to_bits(), (Complex { value: a }, Complex { value: b }) => { a.re.to_bits() == b.re.to_bits() && a.im.to_bits() == b.im.to_bits() } (Boolean { value: a }, Boolean { value: b }) => a == b, (Str { value: a }, Str { value: b }) => a == b, (Bytes { value: a }, Bytes { value: b }) => a == b, (Code { code: a }, Code { code: b }) => std::ptr::eq(a.as_ref(), b.as_ref()), (Tuple { elements: a }, Tuple { elements: b }) => a == b, (None, None) => true, (Ellipsis, Ellipsis) => true, _ => false, } } } impl Eq for ConstantData {} impl hash::Hash for ConstantData { fn hash<H: hash::Hasher>(&self, state: &mut H) { use ConstantData::*; std::mem::discriminant(self).hash(state); match self { Integer { value } => value.hash(state), Float { value } => value.to_bits().hash(state), Complex { value } => { value.re.to_bits().hash(state); value.im.to_bits().hash(state); } Boolean { value } => value.hash(state), Str { value } => value.hash(state), Bytes { value } => value.hash(state), Code { code } => std::ptr::hash(code.as_ref(), state), Tuple { elements } => elements.hash(state), None => {} Ellipsis => {} } } } /// A borrowed Constant pub enum BorrowedConstant<'a, C: Constant> { Integer { value: &'a BigInt }, Float { value: f64 }, Complex { value: Complex64 }, Boolean { value: bool }, Str { value: &'a str }, Bytes { value: &'a [u8] }, Code { code: &'a CodeObject<C> }, Tuple { elements: BorrowedTupleIter<'a, C> }, None, Ellipsis, } type BorrowedTupleIter<'a, C> = Box<dyn Iterator<Item = BorrowedConstant<'a, C>> + 'a>; impl<C: Constant> BorrowedConstant<'_, C> { // takes `self` because we need to consume the iterator pub fn fmt_display(self, f: &mut fmt::Formatter) -> fmt::Result { match self { BorrowedConstant::Integer { value } => write!(f, "{}", value), BorrowedConstant::Float { value } => write!(f, "{}", value), BorrowedConstant::Complex { value } => write!(f, "{}", value), BorrowedConstant::Boolean { value } => { write!(f, "{}", if value { "True" } else { "False" }) } BorrowedConstant::Str { value } => write!(f, "{:?}", value), BorrowedConstant::Bytes { value } => write!(f, "b{:?}", value.as_bstr()), BorrowedConstant::Code { code } => write!(f, "{:?}", code), BorrowedConstant::Tuple { elements } => { write!(f, "(")?; let mut first = true; for c in elements { if first { first = false } else { write!(f, ", ")?; } c.fmt_display(f)?; } write!(f, ")") } BorrowedConstant::None => write!(f, "None"), BorrowedConstant::Ellipsis => write!(f, "..."), } } pub fn to_owned(self) -> ConstantData { use ConstantData::*; match self { BorrowedConstant::Integer { value } => Integer { value: value.clone(), }, BorrowedConstant::Float { value } => Float { value }, BorrowedConstant::Complex { value } => Complex { value }, BorrowedConstant::Boolean { value } => Boolean { value }, BorrowedConstant::Str { value } => Str { value: value.to_owned(), }, BorrowedConstant::Bytes { value } => Bytes { value: value.to_owned(), }, BorrowedConstant::Code { code } => Code { code: Box::new(code.map_clone_bag(&BasicBag)), }, BorrowedConstant::Tuple { elements } => Tuple { elements: elements.map(BorrowedConstant::to_owned).collect(), }, BorrowedConstant::None => None, BorrowedConstant::Ellipsis => Ellipsis, } } } /// The possible comparison operators #[derive(Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)] pub enum ComparisonOperator { // be intentional with bits so that we can do eval_ord with just a bitwise and // bits: | Equal | Greater | Less | Less = 0b001, Greater = 0b010, NotEqual = 0b011, Equal = 0b100, LessOrEqual = 0b101, GreaterOrEqual = 0b110, } #[derive(Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)] pub enum TestOperator { In, NotIn, Is, IsNot, /// two exceptions that match? ExceptionMatch, } /// The possible Binary operators /// # Examples /// /// ``` /// use rustpython_bytecode::Instruction::BinaryOperation; /// use rustpython_bytecode::BinaryOperator::Add; /// let op = BinaryOperation {op: Add}; /// ``` #[derive(Debug, Copy, Clone, PartialEq, Serialize, Deserialize)] pub enum BinaryOperator { Power, Multiply, MatrixMultiply, Divide, FloorDivide, Modulo, Add, Subtract, Lshift, Rshift, And, Xor, Or, } /// The possible unary operators #[derive(Debug, Copy, Clone, PartialEq, Serialize, Deserialize)] pub enum UnaryOperator { Not, Invert, Minus, Plus, } /* Maintain a stack of blocks on the VM. pub enum BlockType { Loop, Except, } */ /// Argument structure pub struct Arguments<'a, N: AsRef<str>> { pub posonlyargs: &'a [N], pub args: &'a [N], pub vararg: Option<&'a N>, pub kwonlyargs: &'a [N], pub varkwarg: Option<&'a N>, } impl<N: AsRef<str>> fmt::Debug for Arguments<'_, N> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { macro_rules! fmt_slice { ($x:expr) => { format_args!("[{}]", $x.iter().map(AsRef::as_ref).format(", ")) }; } f.debug_struct("Arguments") .field("posonlyargs", &fmt_slice!(self.posonlyargs)) .field("args", &fmt_slice!(self.posonlyargs)) .field("vararg", &self.vararg.map(N::as_ref)) .field("kwonlyargs", &fmt_slice!(self.kwonlyargs)) .field("varkwarg", &self.varkwarg.map(N::as_ref)) .finish() } } impl<C: Constant> CodeObject<C> { /// Get all arguments of the code object /// like inspect.getargs pub fn arg_names(&self) -> Arguments<C::Name> { let nargs = self.arg_count; let nkwargs = self.kwonlyarg_count; let mut varargspos = nargs + nkwargs; let posonlyargs = &self.varnames[..self.posonlyarg_count]; let args = &self.varnames[..nargs]; let kwonlyargs = &self.varnames[nargs..varargspos]; let vararg = if self.flags.contains(CodeFlags::HAS_VARARGS) { let vararg = &self.varnames[varargspos]; varargspos += 1; Some(vararg) } else { None }; let varkwarg = if self.flags.contains(CodeFlags::HAS_VARKEYWORDS) { Some(&self.varnames[varargspos]) } else { None }; Arguments { posonlyargs, args, vararg, kwonlyargs, varkwarg, } } /// Return the labels targeted by the instructions of this CodeObject pub fn label_targets(&self) -> BTreeSet<Label> { let mut label_targets = BTreeSet::new(); for instruction in &*self.instructions { if let Some(l) = instruction.label_arg() { label_targets.insert(*l); } } label_targets } fn display_inner( &self, f: &mut fmt::Formatter, expand_codeobjects: bool, level: usize, ) -> fmt::Result { let label_targets = self.label_targets(); for (offset, instruction) in self.instructions.iter().enumerate() { let arrow = if label_targets.contains(&Label(offset as u32)) { ">>" } else { " " }; for _ in 0..level { write!(f, " ")?; } write!(f, "{} {:5} ", arrow, offset)?; instruction.fmt_dis( f, &self.constants, &self.names, &self.varnames, &self.cellvars, &self.freevars, expand_codeobjects, level, )?; } Ok(()) } /// Recursively display this CodeObject pub fn display_expand_codeobjects(&self) -> impl fmt::Display + '_ { struct Display<'a, C: Constant>(&'a CodeObject<C>); impl<C: Constant> fmt::Display for Display<'_, C> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.0.display_inner(f, true, 1) } } Display(self) } /// Map this CodeObject to one that holds a Bag::Constant pub fn map_bag<Bag: ConstantBag>(self, bag: Bag) -> CodeObject<Bag::Constant> { let map_names = |names: Box<[C::Name]>| { names .into_vec() .into_iter() .map(|x| bag.make_name(x.as_ref())) .collect::<Box<[_]>>() }; CodeObject { constants: self .constants .into_vec() .into_iter() .map(|x| bag.make_constant(x.borrow_constant())) .collect(), names: map_names(self.names), varnames: map_names(self.varnames), cellvars: map_names(self.cellvars), freevars: map_names(self.freevars), source_path: bag.make_name(self.source_path.as_ref()), obj_name: bag.make_name(self.obj_name.as_ref()), instructions: self.instructions, locations: self.locations, flags: self.flags, posonlyarg_count: self.posonlyarg_count, arg_count: self.arg_count, kwonlyarg_count: self.kwonlyarg_count, first_line_number: self.first_line_number, max_stacksize: self.max_stacksize, cell2arg: self.cell2arg, } } /// Same as `map_bag` but clones `self` pub fn map_clone_bag<Bag: ConstantBag>(&self, bag: &Bag) -> CodeObject<Bag::Constant> { let map_names = |names: &[C::Name]| names.iter().map(|x| bag.make_name(x.as_ref())).collect(); CodeObject { constants: self .constants .iter() .map(|x| bag.make_constant(x.borrow_constant())) .collect(), names: map_names(&self.names), varnames: map_names(&self.varnames), cellvars: map_names(&self.cellvars), freevars: map_names(&self.freevars), source_path: bag.make_name(self.source_path.as_ref()), obj_name: bag.make_name(self.obj_name.as_ref()), instructions: self.instructions.clone(), locations: self.locations.clone(), flags: self.flags, posonlyarg_count: self.posonlyarg_count, arg_count: self.arg_count, kwonlyarg_count: self.kwonlyarg_count, first_line_number: self.first_line_number, max_stacksize: self.max_stacksize, cell2arg: self.cell2arg.clone(), } } } /// Error that occurs during code deserialization #[derive(Debug)] #[non_exhaustive] pub enum CodeDeserializeError { /// Unexpected End Of File Eof, /// Invalid Bytecode Other, } impl fmt::Display for CodeDeserializeError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Self::Eof => f.write_str("unexpected end of data"), Self::Other => f.write_str("invalid bytecode"), } } } impl std::error::Error for CodeDeserializeError {} impl CodeObject<ConstantData> { /// Load a code object from bytes pub fn from_bytes(data: &[u8]) -> Result<Self, CodeDeserializeError> { use lz4_flex::block::DecompressError; let raw_bincode = lz4_flex::decompress_size_prepended(data).map_err(|e| match e { DecompressError::OutputTooSmall { .. } | DecompressError::ExpectedAnotherByte => { CodeDeserializeError::Eof } _ => CodeDeserializeError::Other, })?; let data = bincode::deserialize(&raw_bincode).map_err(|e| match *e { bincode::ErrorKind::Io(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => { CodeDeserializeError::Eof } _ => CodeDeserializeError::Other, })?; Ok(data) } /// Serialize this bytecode to bytes. pub fn to_bytes(&self) -> Vec<u8> { let data = bincode::serialize(&self).expect("CodeObject is not serializable"); lz4_flex::compress_prepend_size(&data) } } impl<C: Constant> fmt::Display for CodeObject<C> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.display_inner(f, false, 1)?; for constant in &*self.constants { if let BorrowedConstant::Code { code } = constant.borrow_constant() { writeln!(f, "\nDisassembly of {:?}", code)?; code.fmt(f)?; } } Ok(()) } } impl Instruction { /// Gets the label stored inside this instruction, if it exists #[inline] pub fn label_arg(&self) -> Option<&Label> { match self { Jump { target: l } | JumpIfTrue { target: l } | JumpIfFalse { target: l } | JumpIfTrueOrPop { target: l } | JumpIfFalseOrPop { target: l } | ForIter { target: l } | SetupFinally { handler: l } | SetupExcept { handler: l } | SetupWith { end: l } | SetupAsyncWith { end: l } | SetupLoop { break_target: l } | Continue { target: l } => Some(l), _ => None, } } /// Gets a mutable reference to the label stored inside this instruction, if it exists #[inline] pub fn label_arg_mut(&mut self) -> Option<&mut Label> { match self { Jump { target: l } | JumpIfTrue { target: l } | JumpIfFalse { target: l } | JumpIfTrueOrPop { target: l } | JumpIfFalseOrPop { target: l } | ForIter { target: l } | SetupFinally { handler: l } | SetupExcept { handler: l } | SetupWith { end: l } | SetupAsyncWith { end: l } | SetupLoop { break_target: l } | Continue { target: l } => Some(l), _ => None, } } /// Whether this is an unconditional branching /// /// # Examples /// /// ``` /// use rustpython_bytecode::{Instruction, Label}; /// let label = Label(0xF); /// let jump_inst = Instruction::Jump {target: label}; /// assert!(jump_inst.unconditional_branch()) /// ``` pub fn unconditional_branch(&self) -> bool { matches!( self, Jump { .. } | Continue { .. } | Break | ReturnValue | Raise { .. } ) } /// What effect this instruction has on the stack /// /// # Examples /// /// ``` /// use rustpython_bytecode::{Instruction, Label, UnaryOperator}; /// let jump_instruction = Instruction::Jump {target: Label(0xF)}; /// let invert_instruction = Instruction::UnaryOperation {op: UnaryOperator::Invert}; /// assert_eq!(jump_instruction.stack_effect(true), 0); /// assert_eq!(invert_instruction.stack_effect(false), 0); /// ``` /// pub fn stack_effect(&self, jump: bool) -> i32 { match self { ImportName { .. } | ImportNameless => -1, ImportStar => -1, ImportFrom { .. } => 1, LoadFast(_) | LoadNameAny(_) | LoadGlobal(_) | LoadDeref(_) | LoadClassDeref(_) => 1, StoreFast(_) | StoreLocal(_) | StoreGlobal(_) | StoreDeref(_) => -1, DeleteFast(_) | DeleteLocal(_) | DeleteGlobal(_) | DeleteDeref(_) => 0, LoadClosure(_) => 1, Subscript => -1, StoreSubscript => -3, DeleteSubscript => -2, LoadAttr { .. } => 0, StoreAttr { .. } => -2, DeleteAttr { .. } => -1, LoadConst { .. } => 1, UnaryOperation { .. } => 0, BinaryOperation { .. } | BinaryOperationInplace { .. } | TestOperation { .. } | CompareOperation { .. } => -1, Pop => -1, Rotate2 | Rotate3 => 0, Duplicate => 1, Duplicate2 => 2, GetIter => 0, Continue { .. } => 0, Break => 0, Jump { .. } => 0, JumpIfTrue { .. } | JumpIfFalse { .. } => -1, JumpIfTrueOrPop { .. } | JumpIfFalseOrPop { .. } => { if jump { 0 } else { -1 } } MakeFunction(flags) => { -2 - flags.contains(MakeFunctionFlags::CLOSURE) as i32 - flags.contains(MakeFunctionFlags::ANNOTATIONS) as i32 - flags.contains(MakeFunctionFlags::KW_ONLY_DEFAULTS) as i32 - flags.contains(MakeFunctionFlags::DEFAULTS) as i32 + 1 } CallFunctionPositional { nargs } => -(*nargs as i32) - 1 + 1, CallMethodPositional { nargs } => -(*nargs as i32) - 3 + 1, CallFunctionKeyword { nargs } => -1 - (*nargs as i32) - 1 + 1, CallMethodKeyword { nargs } => -1 - (*nargs as i32) - 3 + 1, CallFunctionEx { has_kwargs } => -1 - (*has_kwargs as i32) - 1 + 1, CallMethodEx { has_kwargs } => -1 - (*has_kwargs as i32) - 3 + 1, LoadMethod { .. } => -1 + 3, ForIter { .. } => { if jump { -1 } else { 1 } } ReturnValue => -1, YieldValue => 0, YieldFrom => -1, SetupAnnotation | SetupLoop { .. } | SetupFinally { .. } | EnterFinally | EndFinally => 0, SetupExcept { .. } => { if jump { 1 } else { 0 } } SetupWith { .. } => { |
| You are visitor 01402520 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |