diff --git a/p4-16/spec/P4-16-spec.mdk b/p4-16/spec/P4-16-spec.mdk index d9729d8fbf..a09aae52cf 100644 --- a/p4-16/spec/P4-16-spec.mdk +++ b/p4-16/spec/P4-16-spec.mdk @@ -3677,6 +3677,50 @@ tuple, bool> x = { 10, false }; The empty list expression has type `tuple<>` - a tuple with no components. +## Structure-valued expressions { #sec-structure-expressions} + +One can write expressions that evaluate to a structure or header. The +syntax of these expressions is given by: + +~ Begin P4Grammar +expression ... + | '{' kvList '}' + | '(' typeRef ')' expression + ; + +kvList + : kvPair + | kvList "," kvPair + ; + +kvPair + : name "=" expression + ; +~ End P4Grammar + +For a structure-valued expression `typeRef` is the name of a `struct` +or `header` type. The `typeRef` can be omitted if it can be inferred +from context, e.g., when initializing a variable with a `struct` type. +The following example shows a structure-valued expression used in an +equality comparison expression: + +~ Begin P4Example +struct S { + bit<32> a; + bit<32> b; +} + +S s; +... +// Compare s with a structure-valued expression +bool b = s == (S) { a = 1, b = 2 }; +~ End P4Example + +Structure-valued expressions can be used in the right-hand side of +assignments, in comparisons, in field selection expressions, and as +arguments to functions, method or actions. Structure-valued +expressions are not left values. + ## Operations on sets { #sec-set-exprs } Some P4 expressions denote sets of values (`set`, for some type `T`; @@ -3824,28 +3868,9 @@ their corresponding fields are equal. ## Structure initializers { #sec-structure-initializers } -Structures can be initialized using structure initializers, which -specify explicitly the intialized fields. A structure initializer -expression evaluates to a struct; it can be used on the right-hand -side of an initialization of a variable with a struct type. - -~ Begin P4Grammar -expression ... - | '{' kvList '}' - ; - -kvList - : kvPair - | kvList "," kvPair - ; - -kvPair - : name "=" expression - ; -~ End P4Grammar - -The following example shows a structure initialized using a -structure initializer: +Structures can be initialized using structure-valued expression +([#sec-structure-expressions]). The following example shows a +structure initialized using a structure-valued expression: ~ Begin P4Example struct S { @@ -3853,6 +3878,7 @@ struct S { bit<32> b; } const S x = { a = 10, b = 20 }; +const S x = (S){ a = 10, b = 20 }; // equivalent ~ End P4Example The compiler must raise an error if a field name appears more than