Repository: aptos-labs/aptos-core (language: python)

Issue:
[Bug][Compiler] compiling overflows stack 
# 🐛 Bug

Adding:

```
    public fun borrow<K, V>(self: &OrderedMao<K, V>, key: &K): &V {
        self.find(key).iter_borrow(self)
    }
```
function to the WIP implementation of OrderedMap, makes the compiler (I think) overflow its stack.

Commenting out borrow/borrow_mut in aptos-move/framework/aptos-stdlib/sources/data_structures/ordered_map.move doesn't trigger stack overflow.

## To reproduce

check out [igor/ordered_map](https://github.com/aptos-labs/aptos-core/compare/main...igor/ordered_map) branch, and run:

`cargo run -p aptos --release -- move test --move-2 --filter ordered_map --package-dir aptos-move/framework/aptos-stdlib`

And you'll get:
```
INCLUDING DEPENDENCY MoveStdlib
BUILDING AptosStdlib

thread 'main' has overflowed its stack
fatal runtime error: stack overflow
```


Adding RUST_MIN_STACK=104857600 to the command, doesn't resolve it.


**Code snippet to reproduce**


```move

module aptos_std::ordered_map {
    use std::vector;
    use std::option::{Self, Option};
    use std::error;

    // Trying to do an operation on an Iterator that would go out of bounds
    const EITER_OUT_OF_BOUNDS: u64 = 3;

    /// Individual entry holding (key, value) pair
    struct Entry<K, V> has drop, copy, store {
        key: K,
        value: V,
    }

    /// The OrderedMap datastructure.
    enum OrderedMap<K, V> has drop, copy, store {
        /// sorted-vector based implementation of OrderedMap
        SortedVectorMap {
            /// List of entries, sorted by key.
            entries: vector<Entry<K, V>>,
        }
    }

    /// An iterator pointing to a position between two elements in the
    enum Iterator has copy, drop {
        // TODO: see if it is cleaner/faster to have end-iter be Position { index = len() }
        // and not have a separate variant for it.
        End,
        Position {
            /// The index of the iterator pointing to.
            index: u64,
        },
    }

    /// Returns an iterator pointing to the element that equals to the provided key, or an end
    /// iterator if the key is not found.
    public fun find<K, V>(self: &OrderedMap<K, V>, key: &K): Iterator {
        Iterator::End
    }

    /// Borrows the value given iterator points to.
    /// Note: Requires that the map is not changed after the input iterator is generated.
    public fun iter_borrow<K, V>(self: Iterator, map: &OrderedMap<K, V>): &V {
        assert!(!(self is Iterator::End), error::invalid_argument(EITER_OUT_OF_BOUNDS));
        &map.entries.borrow(self.index).value
    }

    public fun borrow<K, V>(self: &OrderedMao<K, V>, key: &K): &V {
        self.find(key).iter_borrow(self)
    }

    public native fun compare<T>(first: &T, second: &T): Ordering;
}

```

**Stack trace/error message**
```
// Paste the output here
```

## Expected Behavior

A clear and concise description of what you expected to happen.

## System information

**Please complete the following information:**
- Aptos Core Version
- Rust Version
- Computer OS


## Additional context

Add any other context about the problem here.



Discussion / hints:
I managed to reproduce this in lldb-rust.  Here is the stack trace, which suggests that this is in some code I recently modified: 
```
... continue repeating above here...
    frame #18913: [33m0x0000000100e4fddc[0m build-script-build`core::ops::function::impls::_$LT$impl$u20$core..ops..function..FnOnce$LT$A$GT$$u20$for$u20$$RF$mut$u20$F$GT$::call_once::h89cad98ea9975088(self=0x000000016fdde498, args=(&&(move_model::model::Loc, move_model::ty::WideningOrder, move_model::ty::Constraint)) @ 0x000000016fdddbf0) at [36mfunction.rs[0m:[33m305[0m:[33m13[0m
    frame #18914: [33m0x0000000100fd3f2c[0m build-script-build`_$LT$core..iter..adapters..map..Map$LT$I$C$F$GT$$u20$as$u20$core..iter..traits..iterator..Iterator$GT$::next::h187e51fe1bae4562 [inlined] core::option::Option$LT$T$GT$::map::h57bb33e84c8a257d at [36moption.rs[0m:[33m1073[0m:[33m29[0m
    frame #18915: [33m0x0000000100fd3f28[0m build-script-build`_$LT$core..iter..adapters..map..Map$LT$I$C$F$GT$$u20$as$u20$core..iter..traits..iterator..Iterator$GT$::next::h187e51fe1bae4562(self=0x000000016fdde488) at [36mmap.rs[0m:[33m108[0m:[33m26[0m
    frame #18916: [33m0x000000010100f67c[0m build-script-build`itertools::Itertools::join::hee4abf2e04250930(self=0x000000016fdde488, sep=" + ") at [36mlib.rs[0m:[33m2300[0m:[33m15[0m
    frame #18917: [33m0x0000000100e872f0[0m build-script-build`_$LT$move_model..ty..TypeDisplay$u20$as$u20$core..fmt..Display$GT$::fmt::hf004df8883b03586(self=0x000000016fdde8c0, f=0x000000016fdde710) at [36mty.rs[0m:[33m3404[0m:[33m35[0m
    frame #18918: [33m0x00000001023019c8[0m build-script-build`core::fmt::write::hbadb443a71b75f23 [inlined] core::fmt::rt::Argument::fmt::h5ddc0f22b2928899 at [36mrt.rs[0m:[33m142[0m:[33m9[0m [opt]
    frame #18919: [33m0x00000001023019bc[0m build-script-build`core::fmt::write::hbadb443a71b75f23 at [36mmod.rs[0m:[33m1153[0m:[33m17[0m [opt]
    frame #18920: [33m0x000000010216ec24[0m build-script-build`_$LT$$RF$mut$u20$W$u20$as$u20$core..fmt..Write..write_fmt..SpecWriteFmt$GT$::spec_write_fmt::h6b83a459e529679d(self=0x000000016fdde8e8, args=Arguments @ 0x000000016fdde900) at [36mmod.rs[0m:[33m218[0m:[33m21[0m
    frame #18921: [33m0x000000010216c8d0[0m build-script-build`core::fmt::Write::write_fmt::h883aa85270746f47(self=0x000000016fdde8e8, args=<unavailable>) at [36mmod.rs[0m:[33m223[0m:[33m9[0m
    frame #18922: [33m0x000000010100dae0[0m build-script-build`itertools::Itertools::join::h6fcc67e8fcb7b007(self=0x000000016fdde9d8, sep=",") at [36mlib.rs[0m:[33m2306[0m:[33m17[0m
    frame #18923: [33m0x0000000100e78184[0m build-script-build`move_model::ty::Constraint::display::fmt_types::hd52e008eb3ba9a80(ctx=0x000000016fde1680, tys=Iter<move_model::ty::Type> @ 0x000000016fddea00) at [36mty.rs[0m:[33m588[0m:[33m13[0m
    frame #18924: [33m0x0000000100e77f88[0m build-script-build`move_model::ty::Constraint::display::h97c22c5091cba69a(self=0x000000014c308320, display_context=0x000000016fde1680) at [36mty.rs[0m:[33m630[0m:[33m21[0m
    frame #18925: [33m0x0000000100e87690[0m build-script-build`_$LT$move_model..ty..TypeDisplay$u20$as$u20$core..fmt..Display$GT$::fmt::_$u7b$$u7b$closure$u7d$$u7d$::hc8cc3573e380b208((null)=0x0000600003074520) at [36mty.rs[0m:[33m3406[0m:[33m46[0m
    frame #18926: [33m0x0000000100e4fddc[0m build-script-build`core::ops::function::impls::_$LT$impl$u20$core..ops..function..FnOnce$LT$A$GT$$u20$for$u20$$RF$mut$u20$F$GT$::call_once::h89cad98ea9975088(self=0x000000016fddfaa8, args=(&&(move_model::model::Loc, move_model::ty::WideningOrder, move_model::ty::Constraint)) @ 0x000000016fddf200) at [36mfunction.rs[0m:[33m305[0m:[33m13[0m
    frame #18927: [33m0x0000000100fd3f2c[0m build-script-build`_$LT$core..iter..adapters..map..Map$LT$I$C$F$GT$$u20$as$u20$core..iter..traits..iterator..Iterator$GT$::next::h187e51fe1bae4562 [inlined] core::option::Option$LT$T$GT$::map::h57bb33e84c8a257d at [36moption.rs[0m:[33m1073[0m:[33m29[0m
    frame #18928: [33m0x0000000100fd3f28[0m build-script-build`_$LT$core..iter..adapters..map..Map$LT$I$C$F$GT$$u20$as$u20$core..iter..traits..iterator..Iterator$GT$::next::h187e51fe1bae4562(self=0x000000016fddfa98) at [36mmap.rs[0m:[33m108[0m:[33m26[0m
    frame #18929: [33m0x000000010100f67c[0m build-script-build`itertools::Itertools::join::hee4abf2e04250930(self=0x000000016fddfa98, sep=" + ") at [36mlib.rs[0m:[33m2300[0m:[33m15[0m
    frame #18930: [33m0x0000000100e872f0[0m build-script-build`_$LT$move_model..ty..TypeDisplay$u20$as$u20$core..fmt..Display$GT$::fmt::hf004df8883b03586(self=0x000000016fddfed0, f=0x000000016fddfd20) at [36mty.rs[0m:[33m3404[0m:[33m35[0m
    frame #18931: [33m0x00000001023019c8[0m build-script-build`core::fmt::write::hbadb443a71b75f23 [inlined] core::fmt::rt::Argument::fmt::h5ddc0f22b2928899 at [36mrt.rs[0m:[33m142[0m:[33m9[0m [opt]
    frame #18932: [33m0x00000001023019bc[0m build-script-build`core::fmt::write::hbadb443a71b75f23 at [36mmod.rs[0m:[33m1153[0m:[33m17[0m [opt]
    frame #18933: [33m0x000000010216ec24[0m build-script-build`_$LT$$RF$mut$u20$W$u20$as$u20$core..fmt..Write..write_fmt..SpecWriteFmt$GT$::spec_write_fmt::h6b83a459e529679d(self=0x000000016fddfef8, args=Arguments @ 0x000000016fddff10) at [36mmod.rs[0m:[33m218[0m:[33m21[0m
    frame #18934: [33m0x000000010216c8d0[0m build-script-build`core::fmt::Write::write_fmt::h883aa85270746f47(self=0x000000016fddfef8, args=<unavailable>) at [36mmod.rs[0m:[33m223[0m:[33m9[0m
    frame #18935: [33m0x000000010100dae0[0m build-script-build`itertools::Itertools::join::h6fcc67e8fcb7b007(self=0x000000016fddffe8, sep=",") at [36mlib.rs[0m:[33m2306[0m:[33m17[0m
    frame #18936: [33m0x0000000100e78184[0m build-script-build`move_model::ty::Constraint::display::fmt_types::hd52e008eb3ba9a80(ctx=0x000000016fde1680, tys=Iter<move_model::ty::Type> @ 0x000000016fde0010) at [36mty.rs[0m:[33m588[0m:[33m13[0m
    frame #18937: [33m0x0000000100e77f88[0m build-script-build`move_model::ty::Constraint::display::h97c22c5091cba69a(self=0x000000014c308320, display_context=0x000000016fde1680) at [36mty.rs[0m:[33m630[0m:[33m21[0m
    frame #18938: [33m0x0000000100e87690[0m build-script-build`_$LT$move_model..ty..TypeDisplay$u20$as$u20$core..fmt..Display$GT$::fmt::_$u7b$$u7b$closure$u7d$$u7d$::hc8cc3573e380b208((null)=0x0000600003074c00) at [36mty.rs[0m:[33m3406[0m:[33m46[0m
    frame #18939: [33m0x0000000100e4fddc[0m build-script-build`core::ops::function::impls::_$LT$impl$u20$core..ops..function..FnOnce$LT$A$GT$$u20$for$u20$$RF$mut$u20$F$GT$::call_once::h89cad98ea9975088(self=0x000000016fde10b8, args=(&&(move_model::model::Loc, move_model::ty::WideningOrder, move_model::ty::Constraint)) @ 0x000000016fde0810) at [36mfunction.rs[0m:[33m305[0m:[33m13[0m
    frame #18940: [33m0x0000000100fd3f2c[0m build-script-build`_$LT$core..iter..adapters..map..Map$LT$I$C$F$GT$$u20$as$u20$core..iter..traits..iterator..Iterator$GT$::next::h187e51fe1bae4562 [inlined] core::option::Option$LT$T$GT$::map::h57bb33e84c8a257d at [36moption.rs[0m:[33m1073[0m:[33m29[0m
    frame #18941: [33m0x0000000100fd3f28[0m build-script-build`_$LT$core..iter..adapters..map..Map$LT$I$C$F$GT$$u20$as$u20$core..iter..traits..iterator..Iterator$GT$::next::h187e51fe1bae4562(self=0x000000016fde10a8) at [36mmap.rs[0m:[33m108[0m:[33m26[0m
    frame #18942: [33m0x000000010100f67c[0m build-script-build`itertools::Itertools::join::hee4abf2e04250930(self=0x000000016fde10a8, sep=" + ") at [36mlib.rs[0m:[33m2300[0m:[33m15[0m
    frame #18943: [33m0x0000000100e872f0[0m build-script-build`_$LT$move_model..ty..TypeDisplay$u20$as$u20$core..fmt..Display$GT$::fmt::hf004df8883b03586(self=0x000000016fde1670, f=0x000000016fde1330) at [36mty.rs[0m:[33m3404[0m:[33m35[0m
    frame #18944: [33m0x00000001023019c8[0m build-script-build`core::fmt::write::hbadb443a71b75f23 [inlined] core::fmt::rt::Argument::fmt::h5ddc0f22b2928899 at [36mrt.rs[0m:[33m142[0m:[33m9[0m [opt]
    frame #18945: [33m0x00000001023019bc[0m build-script-build`core::fmt::write::hbadb443a71b75f23 at [36mmod.rs[0m:[33m1153[0m:[33m17[0m [opt]
    frame #18946: [33m0x00000001022f9b44[0m build-script-build`alloc::fmt::format::format_inner::hb2f7e8bea7badd53 [inlined] _$LT$$RF$mut$u20$W$u20$as$u20$core..fmt..Write..write_fmt..SpecWriteFmt$GT$::spec_write_fmt::h4ab8cf5f445901c4 at [36mmod.rs[0m:[33m218[0m:[33m21[0m [opt]
    frame #18947: [33m0x00000001022f9b30[0m build-script-build`alloc::fmt::format::format_inner::hb2f7e8bea7badd53 [inlined] core::fmt::Write::write_fmt::h33100cdeee1fd32e at [36mmod.rs[0m:[33m223[0m:[33m9[0m [opt]
    frame #18948: [33m0x00000001022f9b30[0m build-script-build`alloc::fmt::format::format_inner::hb2f7e8bea7badd53 at [36mfmt.rs[0m:[33m633[0m:[33m16[0m [opt]
    frame #18949: [33m0x00000001020bcb48[0m build-script-build`alloc::fmt::format::_$u7b$$u7b$closure$u7d$$u7d$::hbcb3cb7f30bbd70a at [36mfmt.rs[0m:[33m637[0m:[33m34[0m
    frame #18950: [33m0x00000001020b5b1c[0m build-script-build`core::option::Option$LT$T$GT$::map_or_else::h0941f991c39bf72d(self=Option<&str> @ 0x000000016fde1488, default={closure_env#0} @ 0x000000016fde14b0, f=0x00000102ffa9c800) at [36moption.rs[0m:[33m1179[0m:[33m21[0m
    frame #18951: [33m0x0000000100e48334[0m build-script-build`alloc::fmt::format::hf974edaaa92a6a51(args=Arguments @ 0x000000016fde1630) at [36mfmt.rs[0m:[33m637[0m:[33m5[0m
    frame #18952: [33m0x0000000100ea436c[0m build-script-build`move_model::builder::exp_builder::ExpTranslator::finalize_type::h74da270a9ddb88cc(self=0x000000016fde1b60, node_id=NodeId @ 0x000000016fde16f8, ty=0x000000016fde1878, reported_vars=0x000000016fde1800) at [36mexp_builder.rs[0m:[33m422[0m:[33m18[0m
    frame #18953: [33m0x0000000100ea3fa4[0m build-script-build`move_model::builder::exp_builder::ExpTranslator::finalize_types::h7727fcb2b00d4053(self=0x000000016fde1b60) at [36mexp_builder.rs[0m:[33m383[0m:[33m30[0m
    frame #18954: [33m0x0000000100e61190[0m build-script-build`move_model::builder::module_builder::ModuleBuilder::def_ana_fun::hfbafdc95cd2557db(self=0x000000016fde3338, name=0x000000016fde25d8, def=0x000000014d09f328) at [36mmodule_builder.rs[0m:[33m1504[0m:[33m13[0m
    frame #18955: [33m0x0000000100e5e264[0m build-script-build`move_model::builder::module_builder::ModuleBuilder::def_ana::hc3ebdbb701619781(self=0x000000016fde3338, module_def=0x000000016fde3618, compiled_module=0x000000016fde3730) at [36mmodule_builder.rs[0m:[33m1057[0m:[33m13[0m
    frame #18956: [33m0x0000000100e587a4[0m build-script-build`move_model::builder::module_builder::ModuleBuilder::translate::hc769e3f5d2de6bd4(self=0x000000016fde3338, loc=Loc @ 0x000000016fde3600, module_def=ModuleDefinition @ 0x000000016fde3618, compiled_module=Option<move_model::builder::module_builder::BytecodeModule> @ 0x000000016fde3730) at [36mmodule_builder.rs[0m:[33m199[0m:[33m9[0m
    frame #18957: [33m0x0000000100ede360[0m build-script-build`move_model::run_move_checker::h41701539b582feba(env=0x000000016fde53f8, program=Program @ 0x000000016fde95e0) at [36mlib.rs[0m:[33m433[0m:[33m9[0m
    frame #18958: [33m0x0000000100edc3ac[0m build-script-build`move_model::run_model_builder_with_options_and_compilation_flags::h50688f7a4910ab2f(move_sources_targets=size=1, move_sources_deps=size=1, deps=size=1, options=ModelBuilderOptions @ 0x000000016fde53f0, flags=Flags @ 0x000000016fde9d30, known_attributes=0x000000016fdebde8) at [36mlib.rs[0m:[33m406[0m:[33m9[0m
    frame #18959: [33m0x0000000100edb1a0[0m build-script-build`move_model::run_model_builder_in_compiler_mode::h601705a800b9d714(source=PackageInfo @ 0x000000016fdea9e0, source_deps=PackageInfo @ 0x000000016fdeaa40, deps=size=1, skip_attribute_checks=false, known_attributes=0x000000016fdebde8, language_version=V2_0, warn_of_deprecation_use=false, warn_of_deprecation_use_in_aptos_libs=false, compile_test_code=false, compile_verify_code=false) at [36mlib.rs[0m:[33m106[0m:[33m5[0m
    frame #18960: [33m0x00000001009bca20[0m build-script-build`move_compiler_v2::run_checker::h1f9e040f12755472(options=Options @ 0x000000016fdebd58) at [36mlib.rs[0m:[33m178[0m:[33m19[0m
    frame #18961: [33m0x00000001009bcde4[0m build-script-build`move_compiler_v2::run_checker_and_rewriters::h1107a1d6bc9a74de(options=Options @ 0x000000016fded020) at [36mlib.rs[0m:[33m225[0m:[33m19[0m
    frame #18962: [33m0x00000001009bb808[0m build-script-build`move_compiler_v2::run_move_compiler::hbac97fa9db1f5782(error_writer=0x000000016fdede18, options=Options @ 0x000000016fdee818) at [36mlib.rs[0m:[33m96[0m:[33m19[0m
    frame #18963: [33m0x00000001001e46d8[0m build-script-build`move_package::compilation::compiled_package::build_and_report_no_exit_v2_driver::h8750c6b68fe2e4f7(options=Options @ 0x000000016fdef698) at [36mcompiled_package.rs[0m:[33m1134[0m:[33m24[0m
    frame #18964: [33m0x0000000100031978[0m build-script-build`core::ops::function::FnMut::call_mut::h2b9b313a371f07dd + 52
    frame #18965: [33m0x000000010002eda0[0m build-script-build`move_package::compilation::compiled_package::CompiledPackage::build_all::h6101a9665efc50da + 5416
    frame #18966: [33m0x000000010001c410[0m build-script-build`move_package::compilation::build_plan::BuildPlan::compile_with_driver::ha9ad1f61cd64c62e + 540
    frame #18967: [33m0x000000010001bcb0[0m build-script-build`move_package::compilation::build_plan::BuildPlan::compile_no_exit::h1d0caf5a8a76d1ad + 28
    frame #18968: [33m0x0000000100020968[0m build-script-build`move_package::BuildConfig::compile_package_no_exit::hd7ef56ed237b7f9e + 592
    frame #18969: [33m0x000000010004d3f4[0m build-script-build`aptos_framework::built_package::BuiltPackage::build::h44b2421a23a7171d + 1020
    frame #18970: [33m0x000000010002c4c4[0m build-script-build`aptos_framework::release_builder::ReleaseOptions::create_release::h58b966a2617199df + 1616
    frame #18971: [33m0x000000010002be64[0m build-script-build`aptos_framework::aptos::ReleaseTarget::create_release::h1b76fda30b0c3518 + 36
    frame #18972: [33m0x0000000100005010[0m build-script-build`build_script_build::main::h9125cf48ef013eab + 5068
    frame #18973: [33m0x00000001000038e8[0m build-script-build`core::ops::function::FnOnce::call_once::h69cced58f78ef7e3 + 16
    frame #18974: [33m0x00000001000036cc[0m build-script-build`std::sys_common::backtrace::__rust_begin_short_backtrace::h49845b1881852f19 + 12
    frame #18975: [33m0x0000000100003738[0m build-script-build`std::rt::lang_start::_$u7b$$u7b$closure$u7d$$u7d$::hb99f79cbdf1c637e + 20
    frame #18976: [33m0x00000001022d5754[0m build-script-build`std::rt::lang_start_internal::h39923ab4c3913741 [inlined] core::ops::function::impls::_$LT$impl$u20$core..ops..function..FnOnce$LT$A$GT$$u20$for$u20$$RF$F$GT$::call_once::heaba8a29e0324069 at [36mfunction.rs[0m:[33m284[0m:[33m13[0m [opt]
    frame #18977: [33m0x00000001022d574c[0m build-script-build`std::rt::lang_start_internal::h39923ab4c3913741 [inlined] std::panicking::try::do_call::h6e5fac4f4884d97b at [36mpanicking.rs[0m:[33m552[0m:[33m40[0m [opt]
    frame #18978: [33m0x00000001022d574c[0m build-script-build`std::rt::lang_start_internal::h39923ab4c3913741 [inlined] std::panicking::try::h2b98e2f3cf76cd78 at [36mpanicking.rs[0m:[33m516[0m:[33m19[0m [opt]
    frame #18979: [33m0x00000001022d574c[0m build-script-build`std::rt::lang_start_internal::h39923ab4c3913741 [inlined] std::panic::catch_unwind::hba9c97319335c08b at [36mpanic.rs[0m:[33m146[0m:[33m14[0m [opt]
    frame #18980: [33m0x00000001022d574c[0m build-script-build`std::rt::lang_start_internal::h39923ab4c3913741 [inlined] std::rt::lang_start_internal::_$u7b$$u7b$closure$u7d$$u7d$::h18efdcfb68f002e8 at [36mrt.rs[0m:[33m148[0m:[33m48[0m [opt]
    frame #18981: [33m0x00000001022d574c[0m build-script-build`std::rt::lang_start_internal::h39923ab4c3913741 [inlined] std::panicking::try::do_call::ha793e16770aada4d at [36mpanicking.rs[0m:[33m552[0m:[33m40[0m [opt]
    frame #18982: [33m0x00000001022d5748[0m build-script-build`std::rt::lang_start_internal::h39923ab4c3913741 [inlined] std::panicking::try::h8aa812e3e1310d12 at [36mpanicking.rs[0m:[33m516[0m:[33m19[0m [opt]
    frame #18983: [33m0x00000001022d5748[0m build-script-build`std::rt::lang_start_internal::h39923ab4c3913741 [inlined] std::panic::catch_unwind::h38c4879f2623185e at [36mpanic.rs[0m:[33m146[0m:[33m14[0m [opt]
    frame #18984: [33m0x00000001022d5748[0m build-script-build`std::rt::lang_start_internal::h39923ab4c3913741 at [36mrt.rs[0m:[33m148[0m:[33m20[0m [opt]
    frame #18985: [33m0x0000000100003710[0m build-script-build`std::rt::lang_start::h3e11e950ce4f896a + 60
    frame #18986: [33m0x00000001000050f4[0m build-script-build`main + 36
    frame #18987: [33m0x0000000193f620e0[0m dyld`start + 2360
```

Summarizing the stack above:
```
...
ty.rs:588:13
ty.rs:630:21
ty.rs:3406:46
ty.rs:3404:35
ty.rs:588:13
ty.rs:630:21
ty.rs:3406:46
ty.rs:3404:35
exp_builder.rs:422:18
```

It looks like there is a type variable which doesn't have a type yet but is constrained by `Constraint::SomeReceiverFunction` whose display includes the type variable itself.


Fix patch:
diff --git a/third_party/move/move-model/src/builder/exp_builder.rs b/third_party/move/move-model/src/builder/exp_builder.rs
index 651680c20c8d1..5fca751d2e0a2 100644
--- a/third_party/move/move-model/src/builder/exp_builder.rs
+++ b/third_party/move/move-model/src/builder/exp_builder.rs
@@ -420,13 +420,17 @@ impl<'env, 'translator, 'module_translator> ExpTranslator<'env, 'translator, 'mo
         };
         ty.visit(&mut visitor);
         if incomplete {
-            self.error(
-                &loc,
-                &format!(
-                    "unable to infer instantiation of type `{}` (consider providing type arguments or annotating the type)",
-                    ty.display(&self.type_display_context())
-                ),
-            );
+            let displayed_ty = format!("{}", ty.display(&self.type_display_context()));
+            // Skip displaying the error message if there is already an error in the type; we must have another message about it already.
+            if !displayed_ty.contains("*error*") {
+                self.error(
+                    &loc,
+                    &format!(
+                        "unable to infer instantiation of type `{}` (consider providing type arguments or annotating the type)",
+                        displayed_ty
+                    ),
+                );
+            }
         }
         ty
     }
diff --git a/third_party/move/move-model/src/builder/model_builder.rs b/third_party/move/move-model/src/builder/model_builder.rs
index 7faa85f057f97..79586773981db 100644
--- a/third_party/move/move-model/src/builder/model_builder.rs
+++ b/third_party/move/move-model/src/builder/model_builder.rs
@@ -271,6 +271,7 @@ impl<'env> ModelBuilder<'env> {
             display_type_vars: false,
             used_modules: BTreeSet::new(),
             use_module_qualification: false,
+            recursive_vars: None,
         }
     }
 
@@ -399,7 +400,7 @@ impl<'env> ModelBuilder<'env> {
                         &entry.name_loc,
                         &format!(
                             "parameter name `{}` indicates a receiver function but \
-                        the type `{}` {}. Consider using a different name.",
+                             the type `{}` {}. Consider using a different name.",
                             well_known::RECEIVER_PARAM_NAME,
                             base_type.display(&type_ctx()),
                             reason
@@ -413,7 +414,7 @@ impl<'env> ModelBuilder<'env> {
                         if !matches!(ty, Type::TypeParameter(_)) {
                             diag(&format!(
                                 "must only use type parameters \
-                            but instead uses `{}`",
+                                 but instead uses `{}`",
                                 ty.display(&type_ctx())
                             ))
                         } else if !seen.insert(ty) {
@@ -433,7 +434,7 @@ impl<'env> ModelBuilder<'env> {
                         if &entry.module_id != mid {
                             diag(
                                 "is declared outside of this module \
-                            and new receiver functions cannot be added",
+                                 and new receiver functions cannot be added",
                             )
                         } else {
                             // The instantiation must be fully generic.
@@ -456,7 +457,7 @@ impl<'env> ModelBuilder<'env> {
                         {
                             diag(
                                 "is associated with the standard vector module \
-                                and new receiver functions cannot be added",
+                                 and new receiver functions cannot be added",
                             )
                         } else {
                             // See above  for structs
@@ -465,9 +466,12 @@ impl<'env> ModelBuilder<'env> {
                                 .insert(name.symbol, name.clone());
                         }
                     },
+                    Type::Error => {
+                        // Ignore this, there will be a message where the error type is generated.
+                    },
                     _ => diag(
                         "is not suitable for receiver functions. \
-                    Only structs and vectors can have receiver functions",
+                         Only structs and vectors can have receiver functions",
                     ),
                 }
             }
diff --git a/third_party/move/move-model/src/ty.rs b/third_party/move/move-model/src/ty.rs
index 07ee9d11abba8..e19f9172b3868 100644
--- a/third_party/move/move-model/src/ty.rs
+++ b/third_party/move/move-model/src/ty.rs
@@ -3311,6 +3311,8 @@ pub struct TypeDisplayContext<'a> {
     pub used_modules: BTreeSet<ModuleId>,
     /// Whether to use `m::T` for representing types, for stable output in docgen
     pub use_module_qualification: bool,
+    /// Var types that are recursive and should appear as `..` in display
+    pub recursive_vars: Option<BTreeSet<u32>>,
 }
 
 impl<'a> TypeDisplayContext<'a> {
@@ -3324,6 +3326,7 @@ impl<'a> TypeDisplayContext<'a> {
             display_type_vars: false,
             used_modules: BTreeSet::new(),
             use_module_qualification: false,
+            recursive_vars: None,
         }
     }
 
@@ -3347,6 +3350,7 @@ impl<'a> TypeDisplayContext<'a> {
             display_type_vars: false,
             used_modules: BTreeSet::new(),
             use_module_qualification: false,
+            recursive_vars: None,
         }
     }
 
@@ -3356,6 +3360,19 @@ impl<'a> TypeDisplayContext<'a> {
             ..self
         }
     }
+
+    pub fn map_var_to_self(&self, idx: u32) -> Self {
+        Self {
+            recursive_vars: if let Some(existing_set) = &self.recursive_vars {
+                let mut new_set = existing_set.clone();
+                new_set.insert(idx);
+                Some(new_set)
+            } else {
+                Some(BTreeSet::from([idx]))
+            },
+            ..self.clone()
+        }
+    }
 }
 
 /// Helper for type displays.
@@ -3447,6 +3464,11 @@ impl<'a> fmt::Display for TypeDisplay<'a> {
                 }
             },
             Var(idx) => {
+                if let Some(recursive_vars) = &self.context.recursive_vars {
+                    if recursive_vars.contains(idx) {
+                        return f.write_str("..");
+                    }
+                }
                 if let Some(ty) = self.context.subs_opt.and_then(|s| s.subs.get(idx)) {
                     write!(f, "{}", ty.display(self.context))
                 } else if let Some(ctrs) =
@@ -3456,9 +3478,10 @@ impl<'a> fmt::Display for TypeDisplay<'a> {
                     if ctrs.is_empty() {
                         f.write_str(&self.type_var_str(*idx))
                     } else {
+                        let recursive_context = self.context.map_var_to_self(*idx);
                         let out = ctrs
                             .iter()
-                            .map(|(_, _, c)| c.display(self.context).to_string())
+                            .map(|(_, _, c)| c.display(&recursive_context).to_string())
                             .join(" + ");
                         f.write_str(&out)
                     }


Test patch:
diff --git a/third_party/move/move-compiler-v2/tests/checking/receiver/bad_receiver.exp b/third_party/move/move-compiler-v2/tests/checking/receiver/bad_receiver.exp
new file mode 100644
index 0000000000000..aad7cbc7821fd
--- /dev/null
+++ b/third_party/move/move-compiler-v2/tests/checking/receiver/bad_receiver.exp
@@ -0,0 +1,25 @@
+
+Diagnostics:
+error: undeclared receiver function `borrow` for type `vector<Entry<K, V>>`
+   ┌─ tests/checking/receiver/bad_receiver.move:25:10
+   │
+25 │         &map.entries.borrow(self.index).key
+   │          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+error: undeclared receiver function `lower_bound` for type `OrderedMap<K, V>`
+   ┌─ tests/checking/receiver/bad_receiver.move:29:27
+   │
+29 │         let lower_bound = self.lower_bound(key);
+   │                           ^^^^^^^^^^^^^^^^^^^^^
+
+error: type cannot have type arguments
+   ┌─ tests/checking/receiver/bad_receiver.move:39:36
+   │
+39 │     public fun borrow<K, V>(self: &OrderedMao<K, V>, key: &K): &V {
+   │                                    ^^^^^^^^^^
+
+error: undeclared `0x1::ordered_map::OrderedMao`
+   ┌─ tests/checking/receiver/bad_receiver.move:39:36
+   │
+39 │     public fun borrow<K, V>(self: &OrderedMao<K, V>, key: &K): &V {
+   │                                    ^^^^^^^^^^
diff --git a/third_party/move/move-compiler-v2/tests/checking/receiver/bad_receiver.move b/third_party/move/move-compiler-v2/tests/checking/receiver/bad_receiver.move
new file mode 100644
index 0000000000000..da72fd481f0de
--- /dev/null
+++ b/third_party/move/move-compiler-v2/tests/checking/receiver/bad_receiver.move
@@ -0,0 +1,50 @@
+module aptos_std::ordered_map {
+    const EITER_OUT_OF_BOUNDS: u64 = 3;
+
+    struct Entry<K, V> has drop, copy, store {
+        key: K,
+        value: V,
+    }
+
+    enum OrderedMap<K, V> has drop, copy, store {
+        SortedVectorMap {
+            entries: vector<Entry<K, V>>,
+        }
+    }
+
+    enum Iterator has copy, drop {
+        End,
+        Position {
+            index: u64,
+        },
+    }
+
+    public fun iter_borrow_key<K, V>(self: &Iterator, map: &OrderedMap<K, V>): &K {
+        assert!(!(self is Iterator::End), EITER_OUT_OF_BOUNDS);
+
+        &map.entries.borrow(self.index).key
+    }
+
+    public fun find<K, V>(self: &OrderedMap<K, V>, key: &K): Iterator {
+        let lower_bound = self.lower_bound(key);
+        if (lower_bound.iter_is_end(self)) {
+            lower_bound
+        } else if (lower_bound.iter_borrow_key(self) == key) {
+            lower_bound
+        } else {
+            self.new_end_iter()
+        }
+    }
+
+    public fun borrow<K, V>(self: &OrderedMao<K, V>, key: &K): &V {
+        self.find(key).iter_borrow(self)
+    }
+
+    public fun new_end_iter<K, V>(self: &OrderedMap<K, V>): Iterator {
+        Iterator::End
+    }
+
+    public fun iter_is_end<K, V>(self: &Iterator, _map: &OrderedMap<K, V>): bool {
+        self is Iterator::End
+    }
+}