Skip to content

support trait-based for loop iteration #1207

@sbillig

Description

@sbillig

Simple proposal that will suffice for now (ignoring mut):
(from zulip https://fe-lang.zulipchat.com/#narrow/channel/458688-fe-compiler-dev/topic/for-loop.20iteration/with/562861650)

// in core lib
trait Seq<T> {
    fn len(self) -> usize;
    fn get(self, i: usize) -> T; // or just use the core::ops::Index trait for this
}
struct CalldataView<T>
where
  T: Decode,
{
  offset: usize,
  len: usize,
}
impl<T> Seq<T> for CalldataView<T>
where T: Decode
{
  fn len(self) -> usize { self.len }
  fn get(self, i: usize) -> T {
    T::decode_from(ptr: CalldataPtr<T>::new(self.offset + i))
  }
}

fn example() -> u64 {
  let nums = CalldataView<u64>::at_offset(4)
  let mut sum = 0
  for n in nums {
    sum += n
  }
  sum
}
// desugars to:
let len = nums.len() // or Seq::len(nums)
let mut i = 0
while i < len {
  sum += nums.get(i) // or Seq::get(nums, i)
  i += 1
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions