Skip to content

Syntax of conditional statements within parsers #1375

Description

@jaehyun1ee

There is a restricted set of statements allowed within a parser block, as illustrated in its grammar production:

parserStatement
    : assignmentOrMethodCallStatement
    | directApplication
    | emptyStatement
    | variableDeclaration
    | constantDeclaration
    | parserBlockStatement
    | conditionalStatement
    ;

At the syntax level, e.g., we disallow exitStatement within a parser. The production rule for parserBlockStatement takes care with nested statements:

parserBlockStatement
    : optAnnotations "{" parserStatements "}"
    ;

blockStatement
    : optAnnotations "{" statOrDeclList "}"
    ;

By using parserBlockStatement instead of blockStatement, we can keep the syntactic restrictions in nested statements within a parser.

With this respect, I believe it would be nice to restrict conditionalStatement as well. Currently, conditionalStatement is defined as:

conditionalStatement
    : IF "(" expression ")" statement
    | IF "(" expression ")" statement ELSE statement
    ;

So, syntactically, parserStatement --> conditionalStatement --> statement production is possible. Thus, as per the current spec, the following program is syntactically valid (though semantically invalid):

parser prs(packet_in p, out H h) {
   state start {
      /* parserStatement */ /* conditionalStatement */ if (true) /* exitStatement */ exit;
      transition accept;
   }
}

To better reflect the parser restrictions at the syntax level, I propose restricting the conditionalStatement in parserStatement as parserConditionalStatement:

parserStatement
    : assignmentOrMethodCallStatement
    | directApplication
    | emptyStatement
    | variableDeclaration
    | constantDeclaration
    | parserBlockStatement
    | parserConditionalStatement
    ;

parserConditionalStatement
    : IF "(" expression ")" parserStatement
    | IF "(" expression ")" parserStatement ELSE parserStatement
    ;

I believe it also better represents the "parser sub-language" explained in section 6. I've tested the proposed production rules by modifying the P4 parser (in P4-SpecTec) and checked that it doesn't break existing tests in p4c/testdata.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions