---
# System prepended metadata

title: '`index()`-builtin in Field View'
tags: [shaping-archive]

---

# `index()`-builtin in Field View

###### tags: `shaping-archive`

- Developers:
- Appetite: 1 weeks



## Goal

Add an `index(Dim)` builtin in Field View which returns a field of the domain indices.

## Syntax proposal

```python=
@field_operator
def foo():
    return index(I)
```

returns a field of `I` indices form `start` to (including) `end-1` if the domain is `I:{start,end}`.

## Design

### Lowering

```python=
@field_operator
def foo():
    return index(I)
```

is lowered to
```python!
@fundef
def foo(index):
    return deref(index)
```

and propagated up the call-chain (all stencils calling `foo` itself require the index iterator in its signature).

There are 2 possible strategies:
- add the index iterator to each stencil (e.g. as last argument), in Iterator IR, we might already get rid of unused parameters with current passes (except for the call from the closure, which could be a simple separate pass)
- only add when needed and keep track in the lowering

### Representation on Iterator IR

In Iterator IR we keep the index iterator explicit in the interface of stencils.

The index iterator can be injected in 2 ways:
- it is part of the fencil interface and is injected by the bindings
- a new `make_positional(*dimensions)` (or `make_index`, ...) builtin is introduced which is only valid in the stencil_closure input.

The latter has the advantage that
- no support for index_fields is required in the bindings (-> we don't need to differentiate `Field`s form `IndexField`s)
- fencil and program have the same interface (no additional parameter in the fencil)

Notes:
The Index Iterator has Type `Iterator[DomainLocation, Anywhere, ...]`, i.e. it can be derefed everywhere and returns the position it is currently pointing to.

### GTFN backend

- The index iterator can be created from a positional SID available in GridTools C++, see https://github.com/GridTools/gridtools/blob/master/include/gridtools/stencil/positional.hpp (in unstructured, the dimensions are required to be `dim::horizontal` or `dim::vertical`)
- They can be combined to iterators for multiple dimensions via sid::composite.
