p4c icon indicating copy to clipboard operation
p4c copied to clipboard

Experimental: Allow local typedef declarations

Open mihaibudiu opened this issue 3 years ago • 3 comments

This should be discussed by the language design working group. This feature would be useful to make the typeof operator from #3017 much more useful. With this change one can write:

control C(out bit<16> result) {
    apply {
        typedef bit<32> T;
        T x = 5;
        result = x; }}

All standard scoping rules apply to the typedef. No other types can be declared locally, only typedef. This means that there are no issues with types that may not be visible globally - only names that may not be visible globally.

Unfortunately this required a relatively important change in the IR representation, which only supports single inheritance: the replacement of the StatOrDecl abstract class with its base class Node. So now block statements contain a Vector<Node> instead of a Vector<StatOrDecl>. This may require some changes in third-party backends.

mihaibudiu avatar Jan 13 '22 02:01 mihaibudiu

Haven't studied the feature carefully, but to avoid backend chaos, can we write a front-or-midend pass that eliminates these local type definitions?

jnfoster avatar Jan 13 '22 02:01 jnfoster

We already eliminate typedefs. The problem is that the compiler code itself may not typecheck anymore, because for backwards compatibility I have #define StatOrDecl Node, and this means that Vector<StatOrDecl> and Vector<Node> are now the same type. I only had to change a couple of places in the whole compiler and no test broke.

mihaibudiu avatar Jan 13 '22 02:01 mihaibudiu

This was a problem in the toP4 pass which had two overloads: postoder(const IR::Vector<IR::Node>*) and postoder(const IR::Vector<IR::StatOrDecl>*)

mihaibudiu avatar Jan 13 '22 02:01 mihaibudiu