Skip to content

Are @optional parameters allowed in abstract methods? #1383

Description

@shyukahn

A parameter may be annotated with the @optional annotation to state that it is optional, as written in section 6.8.2. Optional parameters. The current spec describes where optional parameters are allowed as the following:

Optional parameters can only appear for arguments of: packages, parser types, control types, extern functions, extern methods, and extern object constructors.

In particular, extern methods may have optional parameters, but should optional parameters be allowed in abstract methods?

P4C allows this, as in these test programs:

For example, issue2273-1.p4 has this extern object declaration with an abstract method apply that has an optional parameter:

extern StackAction<T, U> {
    StackAction(Stack<T> stack);

    @synchronous(push, pop)
    abstract void apply(inout T value, @optional out U rv);
    ...
}

Then in a control block, there are 2 instances of StackAction, write and read:

control ingress(inout headers hdr) {
    Stack<bit<16>>(2048) stack;
    StackAction<bit<16>, bit<16>>(stack) write = {
        void apply(inout bit<16> value) {
            value = hdr.data.h1;
        }
        ...
    };

    StackAction<bit<16>, bit<16>>(stack) read = {
        void apply(inout bit<16> value, out bit<16> rv) {
            rv = value;
        }
        ...
    };
    ...
    apply { ... }
}

Because the parameter rv is optional, the abstract method implementations may or may not include rv. However, this means that the call-site of such methods must know whether the optional parameter is included in the implementation. Note that the target architecture may also call an abstract method, as described in section 11.3.1. Instantiating objects with abstract methods.

Abstract methods may be invoked by users explicitly, or they may be invoked by the target architecture.

For the case above, calling write.apply(value, rv) or read.apply(value) may cause unexpected errors since the arity of parameters and arguments do not match. But it is hard to tell this from the method signature abstract void apply(inout T value, @optional out U rv);.

In this sense, it might be reasonable to disallow optional parameters in an abstract method. If so, I believe it would be better to explicitly mention this in the spec.

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