summary refs log tree commit diff stats
path: root/plugins/exec
diff options
context:
space:
mode:
Diffstat (limited to 'plugins/exec')
0 files changed, 0 insertions, 0 deletions
>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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059
// Copyright (C) 2022 Soni L.
// SPDX-License-Identifier: MIT OR Apache-2.0

//! Deserialization-related parts of the VM.

use std::borrow::Cow;
use std::marker::PhantomData;

use indexmap::IndexMap;

use serde::Serialize;
use serde::de::Error as _;
use serde::de::IntoDeserializer as _;

use smallvec::SmallVec;


use super::Frame;
use super::Interpreter;
use super::Pack;
use super::PatternConstants;
use super::PatternElement;
use super::SerdeObject;
use super::Type;
use super::Value;
use crate::errors::MatchError;

/// A `DeserializeSeed` for Datafu input.
///
/// This converts from Serde to Datafu's internal representation (a "pack").
pub(crate) struct Packer<'pat, 'state, O: Serialize> {
    /// The global interpreter state.
    interp: Interpreter<'pat, 'state, O>,
    /// Current call limit.
    call_limit: usize,
    /// Whether we're collecting values.
    collecting: bool,
}

struct FramesMut<'packer, 'pat> {
    frames: &'packer mut Vec<Frame<'pat>>,
}

struct Frames<'packer, 'pat> {
    frames: &'packer Vec<Frame<'pat>>,
}

impl<'packer, 'pat> FramesMut<'packer, 'pat> {
    fn iter_mut<'a>(
        &'a mut self,
    ) -> impl Iterator<Item=&'a mut Frame<'pat>> + DoubleEndedIterator
    where
        'packer: 'a,
    {
        self.frames.iter_mut()
    }

    fn iter_active_mut<'a>(
        &'a mut self,
    ) -> impl Iterator<Item=&'a mut Frame<'pat>> + DoubleEndedIterator
    where
        'packer: 'a,
    {
        self.iter_mut().filter(|frame| {
            frame.active()
        })
    }
}

impl<'packer, 'pat> Frames<'packer, 'pat> {
    fn iter<'a>(
        &'a self,
    ) -> impl Iterator<Item=&'a Frame<'pat>> + DoubleEndedIterator
    where
        'packer: 'a,
    {
        self.frames.iter()
    }

    fn iter_active<'a>(
        &'a self,
    ) -> impl Iterator<Item=&'a Frame<'pat>> + DoubleEndedIterator
    where
        'packer: 'a,
    {
        self.iter().filter(|frame| {
            frame.active()
        })
    }
}

impl<'pat, 'state, 'de, O: Serialize> Packer<'pat, 'state, O> {
    /// Creates a new Packer.
    pub(crate) fn new(
        interp: Interpreter<'pat, 'state, O>,
        call_limit: usize,
    ) -> Self {
        Self {
            interp: interp,
            call_limit: call_limit,
            collecting: false,
        }
    }

    fn frames_mut(&mut self) -> FramesMut<'_, 'pat> {
        FramesMut {
            frames: &mut *self.interp.frames,
        }
    }

    fn frames(&mut self) -> Frames<'_, 'pat> {
        Frames {
            frames: &*self.interp.frames,
        }
    }

    /// Steps the VM into the next operation.
    fn step_in<E: serde::de::Error>(&mut self) -> Result<(), E> {
        if self.call_limit > 0 {
            self.call_limit -= 1;
        } else {
            self.interp.error.insert(MatchError::StackOverflow);
            return Err(todo!());
        }
        // iterate up to the *live* length (i.e. the loop is allowed to modify
        // the length).
        // NOTE: we need to use while-let so as to not borrow anything in an
        // iterator. filtering happens on the *result* of the iterator.
        let mut index_iter = 0..;
        while let Some(index) = index_iter.next().filter(|&i| {
            i < self.interp.frames.len()
        }) {
            let frame = &mut self.interp.frames[index];
            if frame.overstep > 0 || !frame.matches {
                // overstepped and non-matching frames
                frame.overstep += 1;
            } else {
                if !frame.next() {
                    // empty/end-of frames
                    // 1 layer of step-in.
                    // step-out will undo this.
                    // this is correct because this branch implies overstep = 0
                    frame.overstep = 1;
                } else if matches!(
                    frame.op(),
                    PatternElement::SubtreeMarker,
                ) {
                    // subtrees!
                    // these are tricky, because the current frame can be moved
                    // in memory. so we have to use indexing every time.
                    // tho first we set it as overstep because it has special
                    // handling.
                    frame.overstep = 1;
                    let mut at = index + 1;
                    while self.interp.frames[index].next() {
                        let op = self.interp.frames[index].op();
                        if let PatternElement::ValueSubtree {
                            index: subtree, ..
                        } = op {
                            let new_frame = Frame {
                                ops: &self.interp.pat.protos[subtree][..],
                                iar: None,
                                overstep: 0,
                                matches: true,
                            };
                            // we want the "newest" frame last, so it is
                            // easier to unwind back.
                            self.interp.frames.insert(at, new_frame);
                            at += 1;
                        } else {
                            unreachable!()
                        }
                    }
                }
            }
        }
        Ok(())
    }

    /// Steps the VM back into the previous operation.
    fn step_out(
        &mut self,
        mut packs: Vec<Pack<'pat, 'de>>,
    ) -> Vec<Pack<'pat, 'de>> {
        // this code attempts to maintain the logical invariant of:
        // self.frames().iter_active().count() == packs.len()
        self.call_limit += 1;
        let mut index_iter = 0..;
        let mut pack_index = packs.len();
        while let Some(index) = index_iter.next().filter(|&i| {
            i < self.interp.frames.len()
        }) {
            // iterate backwards
            let index = self.interp.frames.len() - index - 1;
            let frame = &mut self.interp.frames[index];
            let has_pack = frame.matches;
            if frame.overstep > 0 {
                // handle overstep
                frame.overstep -= 1;
            } else {
                if has_pack {
                    pack_index -= 1;
                }
                // unwind frame
                if frame.prev() {
                    // successfully unwound. do nothing.
                } else {
                    // find parent frame.
                    let mut count = 1;
                    let mut target = index;
                    let mut target_pack = pack_index;
                    let mut target_unwound = false;
                    while count > 0 && target > 0 {
                        target -= 1;
                        match self.interp.frames[target].num_subtrees() {
                            Some((num, _)) if num < count => {
                                if has_pack {
                                    debug_assert!(target_pack > 0);
                                    target_pack -= 1;
                                }
                                count -= num;
                            },
                            Some((num, unwound)) => {
                                if has_pack {
                                    debug_assert!(target_pack > 0);
                                    target_pack -= 1;
                                }
                                target_unwound = unwound;
                                count = 0;
                            },
                            None => {
                                if has_pack {
                                    if self.interp.frames[target].matches {
                                        debug_assert!(target_pack > 0);
                                        target_pack -= 1;
                                    }
                                }
                                count += 1;
                            },
                        }
                    }
                    if count == 0 {
                        let frame = self.interp.frames.remove(target);
                        // TODO what to do with `frame`?
                        if has_pack {
                            // has parent frame
                            let pack = packs.remove(pack_index);
                            if !target_unwound {
                                packs.insert(target_pack, pack);
                            } else {
                                packs[target_pack].merge_from(pack);
                            }
                        }
                    }
                }
            }
        }
        packs
    }
}

impl<'pat, 'state, 'de, O> serde::de::DeserializeSeed<'de>
for &mut Packer<'pat, 'state, O>
where
    O: Serialize,
{
    type Value = (Vec<Pack<'pat, 'de>>, Option<SerdeObject<'de>>);
    fn deserialize<D>(
        mut self,
        deserializer: D,
    ) -> Result<Self::Value, D::Error>
    where
        D: serde::Deserializer<'de>
    {
        if let Err(e) = self.step_in() { return Err(e); }
        let pat = self.interp.pat;
        let target_type = self.frames().iter_active().try_fold(
            Type::IgnoredAny,
            |target_type, frame| {
                Ok(match (target_type, frame.get_type()) {
                    // required type binds stronger than any/ignored_any
                    (Type::IgnoredAny, Some((ty, true))) => ty,
                    (Type::Any, Some((ty, true))) => ty,
                    (ty, Some((Type::IgnoredAny, true))) => ty,
                    (ty, Some((Type::Any, true))) => ty,
                    // prefer owned if any branch prefers owned
                    (Type::String, Some((Type::Str, true))) => {
                        Type::String
                    },
                    (Type::Str, Some((Type::String, true))) => {
                        Type::String
                    },
                    (Type::Bytes, Some((Type::ByteBuf, true))) => {
                        Type::ByteBuf
                    },
                    (Type::ByteBuf, Some((Type::Bytes, true))) => {
                        Type::ByteBuf
                    },
                    // types which are the same are okay
                    (left, Some((right, _))) if left == right => {
                        left
                    },
                    // optional type vs Any/IgnoredAny prefers Any
                    (Type::IgnoredAny, Some((_, false))) => Type::Any,
                    (Type::Any, Some((_, false))) => Type::Any,
                    // types which are not the same are an error because we
                    // only request a specific type if it's actually required
                    (left, Some((right, _))) => {
                        return Err(todo!());
                    },
                    _ => Type::Any,
                })
            },
        );
        let target_type = match target_type {
            Ok(target_type) => target_type,
            Err(e) => {
                self.interp.error.insert(e);
                return Err(D::Error::custom("type conflict"));
            },
        };
        match target_type {
            Type::Any => deserializer.deserialize_any(&mut *self),
            Type::IgnoredAny => {
                deserializer.deserialize_ignored_any(&mut *self)
            },
            Type::Bool => deserializer.deserialize_bool(&mut *self),
            Type::I8 => deserializer.deserialize_i8(&mut *self),
            Type::I16 => deserializer.deserialize_i16(&mut *self),
            Type::I32 => deserializer.deserialize_i32(&mut *self),
            Type::I64 => deserializer.deserialize_i64(&mut *self),
            Type::I128 => deserializer.deserialize_i128(&mut *self),
            Type::U8 => deserializer.deserialize_u8(&mut *self),
            Type::U16 => deserializer.deserialize_u16(&mut *self),
            Type::U32 => deserializer.deserialize_u32(&mut *self),
            Type::U64 => deserializer.deserialize_u64(&mut *self),
            Type::U128 => deserializer.deserialize_u128(&mut *self),
            Type::F32 => deserializer.deserialize_f32(&mut *self),
            Type::F64 => deserializer.deserialize_f64(&mut *self),
            Type::Char => deserializer.deserialize_char(&mut *self),
            Type::Str if !self.collecting => {
                deserializer.deserialize_str(&mut *self)
            },
            Type::Str | Type::String => {
                deserializer.deserialize_string(&mut *self)
            },
            Type::Bytes if !self.collecting => {
                deserializer.deserialize_bytes(&mut *self)
            },
            Type::Bytes | Type::ByteBuf => {
                deserializer.deserialize_byte_buf(&mut *self)
            },
            Type::Option => deserializer.deserialize_option(&mut *self),
            Type::Unit => deserializer.deserialize_unit(&mut *self),
            Type::Seq => deserializer.deserialize_seq(&mut *self),
            Type::Map => deserializer.deserialize_map(&mut *self),
            Type::Identifier => {
                deserializer.deserialize_identifier(&mut *self)
            },
            Type::Tuple(len) => {
                deserializer.deserialize_tuple(len, &mut *self)
            },
            Type::UnitStruct(name) => {
                deserializer.deserialize_unit_struct(name, &mut *self)
            },
            Type::NewtypeStruct(name) => {
                deserializer.deserialize_newtype_struct(name, &mut *self)
            },
            Type::TupleStruct { name, len } => {
                deserializer.deserialize_tuple_struct(name, len, &mut *self)
            },
            Type::Struct { name, fields } => {
                deserializer.deserialize_struct(name, fields, &mut *self)
            },
            Type::Enum { name, variants } => {
                deserializer.deserialize_enum(name, variants, &mut *self)
            },
        }.map(|(packs, obj)| (self.step_out(packs), obj))
    }
}

/// visit method generator for simple values (primitives).
///
/// can generate whole function or just the glue.
macro_rules! vs {
    (fn $visit:ident $obj:ident ($data_type:pat) $rust_type:ty) => {
        fn $visit<E>(mut self, v: $rust_type) -> Result<Self::Value, E>
        where
            E: serde::de::Error,
        {
            vs!(self (v) $obj ($data_type))
        }
    };
    ($this:ident $v:tt $obj:ident ($data_type:pat)) => {
        {
            let pat = $this.interp.pat;
            let mut obj = None;
            if $this.collecting {
                obj = Some(SerdeObject::$obj$v);
            }
            let mut packs = Vec::new();
            let result = {
                $this.frames_mut().iter_active_mut().try_for_each(|frame| {
                    let ty = frame.get_type();
                    match ty {
                        | Some(($data_type, _))
                        | Some((Type::Any, _))
                        | Some((Type::IgnoredAny, _))
                        | None
                        => {},
                        Some((_, false)) => {
                            frame.matches = false;
                            return Ok(());
                        },
                        Some((_, true)) => {
                            return Err(MatchError::ValidationError)
                        },
                    }
                    let mut pack = Pack::default();
                    if let Some(name) = frame.get_name(pat) {
                        let mut map = IndexMap::new();
                        map.insert(name, (Pack::default(), SerdeObject::$obj$v));
                        pack.subpacks.push(map);
                    }
                    packs.push(pack);
                    Ok(())
                })
            };
            match result {
                Err(e) => {
                    $this.interp.error.insert(e);
                    return Err(todo!());
                },
                _ => (),
            }
            Ok((packs, obj))
        }
    };
}

impl<'pat, 'state, 'de, O> serde::de::Visitor<'de>
for &mut Packer<'pat, 'state, O>
where
    O: Serialize,
{
    type Value = (Vec<Pack<'pat, 'de>>, Option<SerdeObject<'de>>);
    fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "unsure")
    }

    vs!(fn visit_bool Bool (Type::Bool) bool);
    vs!(fn visit_i8 I8 (Type::I8) i8);
    vs!(fn visit_i16 I16 (Type::I16) i16);
    vs!(fn visit_i32 I32 (Type::I32) i32);
    vs!(fn visit_i64 I64 (Type::I64) i64);
    vs!(fn visit_i128 I128 (Type::I128) i128);
    vs!(fn visit_u8 U8 (Type::U8) u8);
    vs!(fn visit_u16 U16 (Type::U16) u16);
    vs!(fn visit_u32 U32 (Type::U32) u32);
    vs!(fn visit_u64 U64 (Type::U64) u64);
    vs!(fn visit_u128 U128 (Type::U128) u128);
    vs!(fn visit_f32 F32 (Type::F32) f32);
    vs!(fn visit_f64 F64 (Type::F64) f64);
    vs!(fn visit_char Char (Type::Char) char);

    fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        // no real option but to clone.
        vs!(self (Cow::Owned(v.to_owned())) Str (Type::String | Type::Str))
    }
    fn visit_borrowed_str<E>(self, v: &'de str) -> Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        vs!(self (Cow::Borrowed(v)) Str (Type::String | Type::Str))
    }
    fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        // TODO try to avoid cloning
        self.visit_str(&*v)
    }
    fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        vs!(self (Cow::Owned(v.to_owned())) Bytes (Type::Bytes | Type::ByteBuf))
    }
    fn visit_borrowed_bytes<E>(self, v: &'de [u8]) -> Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        vs!(self (Cow::Borrowed(v)) Bytes (Type::Bytes | Type::ByteBuf))
    }
    fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        // TODO try to avoid cloning
        self.visit_bytes(&*v)
    }
    fn visit_none<E>(self) -> Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        vs!(self {} None (Type::Option))
    }
    fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
    where
        D: serde::de::Deserializer<'de>,
    {
        todo!()
    }
    fn visit_unit<E>(self) -> Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        vs!(self {} Unit (Type::Unit))
    }
    fn visit_newtype_struct<D>(
        self,
        deserializer: D
    ) -> Result<Self::Value, D::Error>
    where
        D: serde::de::Deserializer<'de>,
    {
        todo!()
    }
    fn visit_seq<A>(self, seq: A) -> Result<Self::Value, A::Error>
    where
        A: serde::de::SeqAccess<'de>,
    {
        let mut obj = None;
        if self.collecting {
            obj = Some(SerdeObject::Seq(Vec::new()));
        }
        todo!()
    }
    fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
    where
        A: serde::de::MapAccess<'de>,
    {
        let old_collecting = self.collecting;
        let pat = self.interp.pat;
        let mut collecting = old_collecting;
        let typeck = self.frames_mut().iter_active_mut().try_for_each(|frame| {
            let ty = frame.get_type();
            match ty {
                | Some((Type::Map, _))
                | Some((Type::Any, _))
                | Some((Type::IgnoredAny, _))
                | None
                => {},
                Some((_, false)) => {
                    frame.matches = false;
                    return Ok(());
                },
                Some((_, true)) => {
                    return Err(MatchError::ValidationError)
                },
            }
            if frame.get_name(pat).is_some() {
                collecting = true;
            }
            Ok(())
        });
        match typeck {
            Err(e) => {
                self.interp.error.insert(e);
                return Err(todo!());
            },
            _ => (),
        }
        if let Err(e) = self.step_in() { return Err(e); }
        self.collecting = collecting;
        let mut subframes = Vec::new();
        self.frames().iter_active().for_each(|frame| {
            if let Some(key_subtree) = frame.key_subtree() {
                subframes.push(Frame {
                    ops: &pat.protos[key_subtree],
                    iar: None,
                    overstep: 0,
                    matches: true,
                });
            }
        });
        let mut obj_inner = Vec::new();
        let mut output_packs = Vec::new();
        while let Some(packed_key) = {
            let subinterp = Interpreter {
                pat: pat,
                frames: &mut subframes,
                error: self.interp.error,
            };
            let mut subpacker = Packer {
                interp: subinterp,
                collecting: self.collecting,
                call_limit: self.call_limit,
            };
            map.next_key_seed(&mut subpacker)?
        } {
            self.frames_mut().iter_active_mut().filter(|frame| {
                frame.key_subtree().is_some()
            }).zip(&mut subframes).for_each(|(frame, subframe)| {
                frame.matches = subframe.matches;
                // reset subframe for next iteration
                // NOTE wait to reset subframe.matches when merging packs!!!
                subframe.iar = None;
            });
            self.frames_mut().iter_active_mut().for_each(|frame| {
                // mark every non-subtree key as matching.
                if frame.key_subtree().is_none() {
                    frame.matches = true;
                }
            });
            let packed_value = map.next_value_seed(&mut *self)?;
            if self.collecting {
                obj_inner.push(
                    (packed_key.1.unwrap(), packed_value.1.unwrap()),
                );
            }
            let mut key_packs_per_frame = packed_key.0.into_iter();
            let mut value_packs_per_frame = packed_value.0;
            // whatever is active in self.frames(), if matches, has a pack
            // whatever is in subframes, if matches, has a pack
            // count(active self.frames() with subtree which match) is always
            // smaller than count(subframes which match) because the former
            // gets updated by next_value_seed
            // count(active self.frames() with subtree) == count(subframes)
            // tl;dr: need to figure out which packs produced by subframes line
            // up with which packs produced by self, discarding extra subframes
            // (where the corresponding self frame doesn't match) and accepting
            // extra packs produced by self.
            // NOTE: key_packs_per_frame ~ subframes
            // value_packs_per_frame ~ self
            // keys come first tho (key.merge_from(value))
            let mut iter_subframes = subframes.iter_mut();
            // related to value_packs_per_frame
            let mut pack_index = 0;
            for frame in self.frames().iter_active() {
                // check if this frame has an associated subframe
                let subframe = if frame.key_subtree().is_some() {
                    // if there are more frames with associated subframes
                    // than there are subframes, panic
                    Some(iter_subframes.next().unwrap())
                } else {
                    None
                };
                if frame.matches && subframe.is_some() {
                    // this already implies subframe.matches
                    let key_pack = key_packs_per_frame.next().unwrap();
                    let value_pack = &mut value_packs_per_frame[pack_index];
                    key_pack.merge_into(value_pack);
                    pack_index += 1;
                } else if frame.matches {
                    // value matches but there's no subframe, carry on
                    pack_index += 1;
                } else if !frame.matches && subframe.is_some() {
                    // frame didn't match but there was a subframe
                    let subframe = subframe.unwrap();
                    if subframe.matches {
                        // subframe matched, remove key pack
                        let _ = key_packs_per_frame.next().unwrap();
                    } else {
                        // neither matched, no relevant packs
                        // do reset subframe for next_key_seed tho!
                        subframe.matches = true;
                    }
                } else {
                    // no relevant packs
                }
            }
            if output_packs.is_empty() {
                output_packs = value_packs_per_frame;
            } else {
                for (left, right) in output_packs.iter_mut().zip(
                    value_packs_per_frame,
                ) {
                    left.subpacks.extend(right.subpacks)
                }
            }
        }
        let obj = SerdeObject::Map(obj_inner);
        let mut final_packs = self.step_out(output_packs);
        let mut iter_final_packs = final_packs.iter_mut();
        self.frames_mut().iter_active_mut().zip({
            final_packs.iter_mut()
        }).for_each(|(frame, pack)| {
            let ty = frame.get_type();
            match ty {
                | Some((Type::Map, _))
                | Some((Type::Any, _))
                | Some((Type::IgnoredAny, _))
                | None
                => {
                    frame.matches = true;
                },
                _ => return,
            }
            if let Some(name) = frame.get_name(pat) {
                // we can assume collecting == true
                let old_pack = std::mem::take(pack);
                let mut map = IndexMap::new();
                map.insert(name, (old_pack, obj.clone()));
                pack.subpacks.push(map);
            }
        });
        self.collecting = old_collecting;
        Ok((final_packs, collecting.then(|| obj)))
    }
    fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error>
    where
        A: serde::de::EnumAccess<'de>,
    {
        let mut obj = None;
        if self.collecting {
            obj = Some(SerdeObject::Enum {
                variant: todo!(),
                data: todo!(),
            });
        }
        todo!()
    }
}

/// A `Deserializer` for Datafu output.
///
/// This converts from Datafu's internal representation (a "pack") into the
/// desired output type.
pub struct Unpacker<'pat, 'de> {
    pack: Pack<'pat, 'de>,
    call_limit: usize,
}

impl<'pat, 'de> Unpacker<'pat, 'de> {
    /// Unpacks a Datafu "pack".
    pub fn new(pack: Pack<'pat, 'de>, call_limit: usize) -> Self {
        Self {
            pack, call_limit,
        }
    }
}

impl<'pat, 'de> serde::Deserializer<'de> for Unpacker<'pat, 'de> {
    // TODO datafu errors
    type Error = serde::de::value::Error;
    fn deserialize_any<V>(self, _: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de> { todo!() }
    fn deserialize_bool<V>(self, _: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de> { todo!() }
    fn deserialize_i8<V>(self, _: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de> { todo!() }
    fn deserialize_i16<V>(self, _: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de> { todo!() }
    fn deserialize_i32<V>(self, _: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de> { todo!() }
    fn deserialize_i64<V>(self, _: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de> { todo!() }
    fn deserialize_u8<V>(self, _: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de> { todo!() }
    fn deserialize_u16<V>(self, _: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de> { todo!() }
    fn deserialize_u32<V>(self, _: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de> { todo!() }
    fn deserialize_u64<V>(self, _: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de> { todo!() }
    fn deserialize_f32<V>(self, _: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de> { todo!() }
    fn deserialize_f64<V>(self, _: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de> { todo!() }
    fn deserialize_char<V>(self, _: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de> { todo!() }
    fn deserialize_str<V>(self, _: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de> { todo!() }
    fn deserialize_string<V>(self, _: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de> { todo!() }
    fn deserialize_bytes<V>(self, _: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de> { todo!() }
    fn deserialize_byte_buf<V>(self, _: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de> { todo!() }
    fn deserialize_option<V>(self, _: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de> { todo!() }
    fn deserialize_unit<V>(self, _: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de> { todo!() }
    fn deserialize_unit_struct<V>(self, _: &'static str, _: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de> { todo!() }
    fn deserialize_newtype_struct<V>(self, _: &'static str, _: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de> { todo!() }
    fn deserialize_seq<V>(self, _: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de> { todo!() }
    fn deserialize_tuple<V>(self, _: usize, _: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de> { todo!() }
    fn deserialize_tuple_struct<V>(self, _: &'static str, _: usize, _: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de> { todo!() }
    fn deserialize_map<V>(self, _: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de> { todo!() }
    fn deserialize_struct<V>(
        self,
        _: &'static str,
        fields: &'static [&'static str],
        visitor: V,
    ) -> Result<V::Value, Self::Error>
    where
        V: serde::de::Visitor<'de>,
    {
        todo!()
    }
    fn deserialize_enum<V>(self, _: &'static str, _: &'static [&'static str], _: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de> { todo!() }
    fn deserialize_identifier<V>(self, _: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de> { todo!() }
    fn deserialize_ignored_any<V>(self, _: V) -> Result<V::Value, Self::Error> where V: serde::de::Visitor<'de> { todo!() }
}

/// Deserializes a SerdeObject
pub(crate) struct SerdeObjectDeserializer<'de, E> {
    pub(crate) obj: SerdeObject<'de>,
    pub(crate) value: Option<SerdeObject<'de>>,
    pub(crate) _e: PhantomData<fn() -> E>,
}

impl<'de, E> serde::de::Deserializer<'de> for SerdeObjectDeserializer<'de, E>
where
    E: serde::de::Error,
{
    type Error = E;
    fn deserialize_any<V>(self, v: V) -> Result<V::Value, Self::Error>
    where
        V: serde::de::Visitor<'de>,
    {
        match self.obj {
            SerdeObject::Bool(x) => v.visit_bool(x),
            SerdeObject::I8(x) => v.visit_i8(x),
            SerdeObject::I16(x) => v.visit_i16(x),
            SerdeObject::I32(x) => v.visit_i32(x),
            SerdeObject::I64(x) => v.visit_i64(x),
            SerdeObject::I128(x) => v.visit_i128(x),
            SerdeObject::U8(x) => v.visit_u8(x),
            SerdeObject::U16(x) => v.visit_u16(x),
            SerdeObject::U32(x) => v.visit_u32(x),
            SerdeObject::U64(x) => v.visit_u64(x),
            SerdeObject::U128(x) => v.visit_u128(x),
            SerdeObject::F32(x) => v.visit_f32(x),
            SerdeObject::F64(x) => v.visit_f64(x),
            SerdeObject::Char(x) => v.visit_char(x),
            SerdeObject::Str(Cow::Owned(x)) => v.visit_string(x),
            SerdeObject::Str(Cow::Borrowed(x)) => v.visit_borrowed_str(x),
            SerdeObject::Bytes(Cow::Owned(x)) => v.visit_byte_buf(x),
            SerdeObject::Bytes(Cow::Borrowed(x)) => v.visit_borrowed_bytes(x),
            SerdeObject::Some(x) => v.visit_some(x.into_deserializer()),
            SerdeObject::None => v.visit_none(),
            SerdeObject::Unit => v.visit_unit(),
            SerdeObject::Seq(x) => todo!(),
            SerdeObject::Map(x) => todo!(),
            SerdeObject::NewtypeStruct(x) => {
                v.visit_newtype_struct(x.into_deserializer())
            },
            SerdeObject::Enum { variant, data } => todo!(),
        }
    }
    fn deserialize_ignored_any<V>(self, v: V) -> Result<V::Value, Self::Error>
    where
        V: serde::de::Visitor<'de>,
    {
        drop(self);
        v.visit_unit()
    }
    serde::forward_to_deserialize_any! {
        bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
        bytes byte_buf option unit unit_struct newtype_struct seq tuple
        tuple_struct map struct enum identifier
    }
}

#[cfg(test)]
mod tests {
    use super::Packer;
    use super::super::PatternConstants;
    use crate::vm::MAX_CALLS;
    use crate::vm::Interpreter;
    use crate::vm::Type;
    use crate::vm::Value;
    use crate::vm::PatternElement;
    use crate::vm::SerdeObject;
    use crate::vm::Frame;
    use serde_json::Deserializer as JsonDeserializer;
    use serde::de::DeserializeSeed as _;

    #[test]
    #[should_panic]
    fn test_broken() {
        // broken pattern, should never be emitted by parser. make sure it's
        // not accepted.
        let consts = PatternConstants::<()>::default();
        let mut err = Default::default();
        let mut frames = Default::default();
        let interp = Interpreter::new(&consts, &mut err, &mut frames);
        let _ = Packer::new(interp, MAX_CALLS);
    }

    #[test]
    fn test_empty_create() {
        // test creating the parser with an empty pattern.
        let mut consts = PatternConstants::<()>::default();
        consts.protos.push(Vec::new());
        let mut err = Default::default();
        let mut frames = Default::default();
        let interp = Interpreter::new(&consts, &mut err, &mut frames);
        let _ = Packer::new(interp, MAX_CALLS);
    }

    #[test]
    fn test_empty_match() {
        // test matching something with an empty pattern.
        let mut consts = PatternConstants::<()>::default();
        consts.protos.push(Vec::new());
        let mut der = JsonDeserializer::from_str("{}");
        let mut err = Default::default();
        let mut frames = Default::default();
        let interp = Interpreter::new(&consts, &mut err, &mut frames);
        let pack = Packer::new(interp, MAX_CALLS).deserialize(&mut der).unwrap();
    }

    #[test]
    fn test_simple_match() {
        // test matching a simple value
        let mut consts = PatternConstants::<()>::default();
        consts.strings.push("hello".into());
        consts.protos.push(vec![
            PatternElement::Value {
                name: Some(0),
                value: Some(Value::Type {
                    ty: Type::U64,
                    skippable: false,
                }),
            },
        ]);
        let mut der = JsonDeserializer::from_str("3");
        let mut err = Default::default();
        let mut frames = Default::default();
        let interp = Interpreter::new(&consts, &mut err, &mut frames);
        let packed = Packer::new(interp, MAX_CALLS).deserialize(&mut der);
        let (packs, obj) = packed.unwrap();
        assert!(obj.is_none());
        assert_eq!(packs[0].subpacks[0]["hello"].1, SerdeObject::U64(3));
    }

    #[test]
    fn test_simple_error() {
        // test a value that doesn't match (serde_json error)
        let mut consts = PatternConstants::<()>::default();
        consts.strings.push("hello".into());
        consts.protos.push(vec![
            PatternElement::Value {
                name: Some(0),
                value: Some(Value::Type {
                    ty: Type::U64,
                    skippable: false,
                }),
            },
        ]);
        let mut der = JsonDeserializer::from_str("\"hello\"");
        let mut err = Default::default();
        let mut frames = Default::default();
        let interp = Interpreter::new(&consts, &mut err, &mut frames);
        let packed = Packer::new(interp, MAX_CALLS).deserialize(&mut der);
        dbg!(&packed);
        // error produced by serde_json
        assert!(packed.is_err());
    }

    #[test]
    fn test_basic_multiframe() {
        // test multiple frames (matching and non-matching)
        let mut consts = PatternConstants::<()>::default();
        consts.strings.push("a".into());
        consts.strings.push("b".into());
        consts.protos.push(vec![
            PatternElement::Value {
                name: Some(0),
                value: Some(Value::Type {
                    ty: Type::U64,
                    skippable: true,
                }),
            },
        ]);
        consts.protos.push(vec![
            PatternElement::Value {
                name: Some(1),
                value: Some(Value::Type {
                    ty: Type::Bool,
                    skippable: true,
                }),
            },
        ]);
        let mut der = JsonDeserializer::from_str(r#"10"#);
        let mut err = Default::default();
        let mut frames: Vec<_> = Default::default();
        frames.push(Frame {
            ops: &consts.protos[0],
            iar: None,
            matches: true,
            overstep: 0,
        });
        frames.push(Frame {
            ops: &consts.protos[1],
            iar: None,
            matches: true,
            overstep: 0,
        });
        let interp = Interpreter {
            pat: &consts,
            error: &mut err,
            frames: &mut frames,
        };
        let packed = Packer::new(interp, MAX_CALLS).deserialize(&mut der);
        let (packs, obj) = packed.unwrap();
        assert!(obj.is_none());
        assert_eq!(
            packs[0].subpacks[0]["a"].1,
            SerdeObject::U64(10),
        );
        assert_eq!(packs.len(), 1);
        assert!(frames[0].matches);
        assert!(!frames[1].matches);
    }

    #[test]
    fn test_map() {
        let mut consts = PatternConstants::<()>::default();
        consts.strings.push("key".into());
        consts.strings.push("value".into());
        consts.protos.push(vec![
            PatternElement::Value {
                name: Some(0),
                value: None,
            },
        ]);
        consts.protos.push(vec![
            PatternElement::Value {
                name: None,
                value: Some(Value::Type {
                    ty: Type::Map,
                    skippable: false,
                }),
            },
            PatternElement::Tag {
                key_subtree: Some(0),
            },
            PatternElement::Value {
                name: Some(1),
                value: Some(Value::Type {
                    ty: Type::U64,
                    skippable: false,
                }),
            },
        ]);
        let mut der = JsonDeserializer::from_str(r#"{"hello": 0, "world": 1}"#);
        let mut err = Default::default();
        let mut frames = Default::default();
        let interp = Interpreter::new(&consts, &mut err, &mut frames);
        let packed = Packer::new(interp, MAX_CALLS).deserialize(&mut der);
        let (packs, obj) = packed.unwrap();
        assert!(obj.is_none());
        assert_eq!(
            packs[0].subpacks[0]["key"].1,
            SerdeObject::Str("hello".into()),
        );
        assert_eq!(
            packs[0].subpacks[0]["value"].1,
            SerdeObject::U64(0),
        );
        assert_eq!(
            packs[0].subpacks[1]["key"].1,
            SerdeObject::Str("world".into()),
        );
        assert_eq!(
            packs[0].subpacks[1]["value"].1,
            SerdeObject::U64(1),
        );
    }
}