p4-spec icon indicating copy to clipboard operation
p4-spec copied to clipboard

Arrays of non-header types

Open ChrisDodd opened this issue 1 year ago • 2 comments

P4 uses array syntax for header stacks, which are declared like arrays of a header type and can be indexed with normal (C/java) array indexing syntax, but also support some added special features (push/pop/next/last methods) which work on the header's valid bits.

Should we consider arrays of non-header types? These could not support those special methods, but could be used as normal arrays.

ChrisDodd avatar Oct 21 '24 11:10 ChrisDodd

Discussed in P4 LDWG. We are generally supportive of adding this to the specification.

jonathan-dilorenzo avatar Nov 04 '24 22:11 jonathan-dilorenzo

p4c PR in https://github.com/p4lang/p4c/pull/5115

ChrisDodd avatar Jan 30 '25 01:01 ChrisDodd

One observations is that arrays of externs make a lot of sense -- so much so that externs like Counter, Meter, and Register have them already embedded. With general arrays, it might make more sense to just use arrays, so a counter array would become something like

Counter(CounterType.PACKETS)[1024] ctr;

action count(bit<10> idx) {
    ctr[idx].count();
}

It's not clear how this would work with direct counters -- would need a way to get the entry index for the action.

ChrisDodd avatar May 15 '25 23:05 ChrisDodd

@ChrisDodd ,

This idea might make sense on some architectures.

Overall, with the header stacks and run-time indexing of those we have an "escape hatch": if the index is out-of-bounds the indexing operation is supposed to return an invalid header. This allows us to write safe programs (since in P4 one is always supposed to check header validity before doing anything with that header) while keeping the costs low (it should not be difficult/expensive to return an invalid header if index is out of bounds).

it is not clear to me what will happen with generalized arrays in the same kind of situations. What will be returned if the index is out-of-bounds?

Separately from that, what is the type of the index? Initially with header stacks we didn't worry about that much, since it was always compile-time known. Now, the spec allows variables as indexes but says very little about their types, how things need to be handled, etc. In the example above it is somehow assumed that because the number of entries is 1024, the index has to be bit<10>. I am not sure if that assumption is always right and it will make writing programs trickier: any time array size changes one might be prepared to adjust the index type.

So, a lot of things to think about....

vgurevich avatar May 18 '25 02:05 vgurevich